From 0fca7169d3cd21e4256cd261ab7317304e903b7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=9B=D1=83=D1=85?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2?= Date: Wed, 4 Sep 2024 17:31:16 +0300 Subject: [PATCH] Define code style and format all source file using clang-format-14 except those placed in 3rdparty directories. --- .clang-format | 41 + .github/workflows/cmake.yml | 13 + console/main.cpp | 90 +- demo_r1/main.cpp | 4 +- demo_r1/mainwindow.cpp | 215 ++- demo_r1/mainwindow.h | 19 +- demo_r2/main.cpp | 3 +- demo_r2/mainwindow.cpp | 92 +- demo_r2/mainwindow.h | 46 +- designer/designersettingmanager.cpp | 19 +- designer/designersettingmanager.h | 10 +- designer/main.cpp | 27 +- designer_plugin/lrdesignerplugin.cpp | 11 +- designer_plugin/lrdesignerplugin.h | 9 +- include/lrcallbackdatasourceintf.h | 21 +- include/lrdatasourceintf.h | 28 +- include/lrdatasourcemanagerintf.h | 25 +- include/lrglobal.cpp | 45 +- include/lrglobal.h | 213 ++- include/lrpreparedpagesintf.h | 10 +- include/lrpreviewreportwidget.h | 45 +- include/lrrenderengine.h | 71 +- include/lrreportdesignwindowintrerface.h | 4 +- include/lrreportengine.h | 154 +- include/lrscriptenginemanagerintf.h | 54 +- limereport/bands/lrdataband.cpp | 136 +- limereport/bands/lrdataband.h | 79 +- limereport/bands/lrgroupbands.cpp | 170 +- limereport/bands/lrgroupbands.h | 43 +- limereport/bands/lrpagefooter.cpp | 84 +- limereport/bands/lrpagefooter.h | 21 +- limereport/bands/lrpageheader.cpp | 58 +- limereport/bands/lrpageheader.h | 16 +- limereport/bands/lrreportfooter.cpp | 41 +- limereport/bands/lrreportfooter.h | 15 +- limereport/bands/lrreportheader.cpp | 51 +- limereport/bands/lrreportheader.h | 17 +- limereport/bands/lrsubdetailband.cpp | 111 +- limereport/bands/lrsubdetailband.h | 59 +- limereport/bands/lrtearoffband.cpp | 35 +- limereport/bands/lrtearoffband.h | 12 +- limereport/base/lrattribsabstractfactory.h | 71 +- limereport/base/lrsimpleabstractfactory.h | 92 +- limereport/base/lrsingleton.h | 27 +- limereport/databrowser/lrconnectiondialog.cpp | 100 +- limereport/databrowser/lrconnectiondialog.h | 18 +- limereport/databrowser/lrdatabrowser.cpp | 719 ++++---- limereport/databrowser/lrdatabrowser.h | 67 +- limereport/databrowser/lrdatabrowsertree.cpp | 23 +- limereport/databrowser/lrdatabrowsertree.h | 25 +- limereport/databrowser/lrsqleditdialog.cpp | 139 +- limereport/databrowser/lrsqleditdialog.h | 46 +- limereport/databrowser/lrvariabledialog.cpp | 84 +- limereport/databrowser/lrvariabledialog.h | 23 +- .../dialogdesigner/lrdialogdesigner.cpp | 205 +-- limereport/dialogdesigner/lrdialogdesigner.h | 33 +- limereport/exporters/lrpdfexporter.cpp | 30 +- limereport/exporters/lrpdfexporter.h | 31 +- limereport/items/charts/lrgridlineschart.cpp | 46 +- limereport/items/charts/lrgridlineschart.h | 10 +- .../items/charts/lrhorizontalbarchart.cpp | 62 +- .../items/charts/lrhorizontalbarchart.h | 10 +- limereport/items/charts/lrlineschart.cpp | 105 +- limereport/items/charts/lrlineschart.h | 18 +- limereport/items/charts/lrpiechart.cpp | 129 +- limereport/items/charts/lrpiechart.h | 15 +- .../items/charts/lrverticalbarchart.cpp | 96 +- limereport/items/charts/lrverticalbarchart.h | 16 +- .../items/editors/lrfonteditorwidget.cpp | 99 +- limereport/items/editors/lrfonteditorwidget.h | 53 +- .../items/editors/lritemeditorwidget.cpp | 31 +- limereport/items/editors/lritemeditorwidget.h | 24 +- .../editors/lritemsaligneditorwidget.cpp | 131 +- .../items/editors/lritemsaligneditorwidget.h | 21 +- .../editors/lritemsborderseditorwidget.cpp | 91 +- .../editors/lritemsborderseditorwidget.h | 41 +- .../editors/lrtextalignmenteditorwidget.cpp | 167 +- .../editors/lrtextalignmenteditorwidget.h | 47 +- limereport/items/lrabstractlayout.cpp | 254 ++- limereport/items/lrabstractlayout.h | 42 +- limereport/items/lralignpropitem.cpp | 129 +- limereport/items/lralignpropitem.h | 45 +- limereport/items/lrbarcodeitem.cpp | 275 ++- limereport/items/lrbarcodeitem.h | 229 +-- limereport/items/lrbordereditor.cpp | 114 +- limereport/items/lrbordereditor.h | 19 +- limereport/items/lrborderframeeditor.cpp | 134 +- limereport/items/lrborderframeeditor.h | 36 +- limereport/items/lrchartaxiseditor.cpp | 35 +- limereport/items/lrchartaxiseditor.h | 14 +- limereport/items/lrchartitem.cpp | 871 +++++----- limereport/items/lrchartitem.h | 217 ++- limereport/items/lrchartitemeditor.cpp | 143 +- limereport/items/lrchartitemeditor.h | 32 +- limereport/items/lreditableimageitemintf.h | 9 +- limereport/items/lrhorizontallayout.cpp | 153 +- limereport/items/lrhorizontallayout.h | 24 +- limereport/items/lrimageitem.cpp | 312 ++-- limereport/items/lrimageitem.h | 60 +- limereport/items/lrimageitemeditor.cpp | 25 +- limereport/items/lrimageitemeditor.h | 12 +- limereport/items/lrlayoutmarker.cpp | 43 +- limereport/items/lrlayoutmarker.h | 21 +- limereport/items/lrpageeditor.cpp | 73 +- limereport/items/lrpageeditor.h | 16 +- limereport/items/lrshapeitem.cpp | 123 +- limereport/items/lrshapeitem.h | 48 +- limereport/items/lrsimpletagparser.cpp | 164 +- limereport/items/lrsimpletagparser.h | 62 +- limereport/items/lrsubitemparentpropitem.cpp | 88 +- limereport/items/lrsubitemparentpropitem.h | 33 +- limereport/items/lrsvgitem.cpp | 159 +- limereport/items/lrsvgitem.h | 33 +- limereport/items/lrtextitem.cpp | 823 +++++---- limereport/items/lrtextitem.h | 99 +- limereport/items/lrtextitemeditor.cpp | 80 +- limereport/items/lrtextitemeditor.h | 46 +- limereport/items/lrverticallayout.cpp | 116 +- limereport/items/lrverticallayout.h | 19 +- limereport/lraboutdialog.cpp | 16 +- limereport/lraboutdialog.h | 13 +- limereport/lraxisdata.cpp | 171 +- limereport/lraxisdata.h | 9 +- limereport/lrbanddesignintf.cpp | 768 ++++----- limereport/lrbanddesignintf.h | 261 +-- limereport/lrbandsmanager.cpp | 59 +- limereport/lrbandsmanager.h | 22 +- limereport/lrbasedesignintf.cpp | 1189 ++++++------- limereport/lrbasedesignintf.h | 476 ++--- limereport/lrcallbackdatasourceintf.h | 21 +- limereport/lrcollection.h | 30 +- limereport/lrcolorindicator.cpp | 31 +- limereport/lrcolorindicator.h | 10 +- limereport/lrdatadesignintf.cpp | 712 ++++---- limereport/lrdatadesignintf.h | 380 ++-- limereport/lrdatasourceintf.h | 28 +- limereport/lrdatasourcemanager.cpp | 1253 +++++++------- limereport/lrdatasourcemanager.h | 253 +-- limereport/lrdatasourcemanagerintf.h | 25 +- limereport/lrdesignelementsfactory.h | 32 +- limereport/lrdesignerplugininterface.h | 18 +- limereport/lrexporterintf.h | 13 +- limereport/lrexportersfactory.h | 27 +- limereport/lrfactoryinitializer.cpp | 573 +++--- limereport/lrfactoryinitializer.h | 10 +- limereport/lrglobal.cpp | 125 +- limereport/lrglobal.h | 213 ++- limereport/lrgraphicsviewzoom.cpp | 108 +- limereport/lrgraphicsviewzoom.h | 29 +- limereport/lrgroupfunctions.cpp | 161 +- limereport/lrgroupfunctions.h | 126 +- limereport/lritemdesignintf.cpp | 75 +- limereport/lritemdesignintf.h | 69 +- limereport/lritemscontainerdesignitf.cpp | 130 +- limereport/lritemscontainerdesignitf.h | 61 +- limereport/lrpagedesignintf.cpp | 1531 +++++++++-------- limereport/lrpagedesignintf.h | 943 +++++----- limereport/lrpageinitintf.h | 2 +- limereport/lrpageitemdesignintf.cpp | 718 ++++---- limereport/lrpageitemdesignintf.h | 205 ++- limereport/lrpreparedpages.cpp | 33 +- limereport/lrpreparedpages.h | 15 +- limereport/lrpreparedpagesintf.h | 10 +- limereport/lrpreviewreportwidget.cpp | 314 ++-- limereport/lrpreviewreportwidget.h | 45 +- limereport/lrpreviewreportwidget_p.h | 28 +- limereport/lrpreviewreportwindow.cpp | 275 ++- limereport/lrpreviewreportwindow.h | 46 +- limereport/lrreportdesignwidget.cpp | 679 ++++---- limereport/lrreportdesignwidget.h | 112 +- limereport/lrreportdesignwindow.cpp | 918 +++++----- limereport/lrreportdesignwindow.h | 72 +- limereport/lrreportdesignwindowintrerface.h | 4 +- limereport/lrreportengine.cpp | 1299 +++++++------- limereport/lrreportengine.h | 154 +- limereport/lrreportengine_p.h | 364 ++-- limereport/lrreportrender.cpp | 1257 +++++++------- limereport/lrreportrender.h | 244 +-- limereport/lrreporttranslation.cpp | 117 +- limereport/lrreporttranslation.h | 42 +- limereport/lrscriptenginemanager.cpp | 1232 +++++++------ limereport/lrscriptenginemanager.h | 508 +++--- limereport/lrscriptenginemanagerintf.h | 54 +- limereport/lrsettingdialog.cpp | 98 +- limereport/lrsettingdialog.h | 16 +- limereport/lrsimplecrypt.cpp | 133 +- limereport/lrsimplecrypt.h | 7 +- limereport/lrvariablesholder.cpp | 121 +- limereport/lrvariablesholder.h | 94 +- .../editors/lrbuttonlineeditor.cpp | 85 +- .../editors/lrbuttonlineeditor.h | 29 +- .../editors/lrcheckboxeditor.cpp | 74 +- .../editors/lrcheckboxeditor.h | 20 +- .../objectinspector/editors/lrcoloreditor.cpp | 59 +- .../objectinspector/editors/lrcoloreditor.h | 36 +- .../editors/lrcomboboxeditor.cpp | 71 +- .../editors/lrcomboboxeditor.h | 37 +- .../objectinspector/editors/lrfonteditor.cpp | 47 +- .../objectinspector/editors/lrfonteditor.h | 15 +- .../objectinspector/editors/lrimageeditor.cpp | 23 +- .../objectinspector/editors/lrimageeditor.h | 12 +- .../objectinspector/editors/lrsvgeditor.cpp | 31 +- .../objectinspector/editors/lrsvgeditor.h | 14 +- .../editors/lrtextitempropertyeditor.cpp | 22 +- .../editors/lrtextitempropertyeditor.h | 16 +- .../lrbasedesignobjectmodel.cpp | 19 +- .../objectinspector/lrbasedesignobjectmodel.h | 12 +- .../lrobjectinspectorwidget.cpp | 182 +- .../objectinspector/lrobjectinspectorwidget.h | 49 +- .../objectinspector/lrobjectitemmodel.cpp | 323 ++-- .../objectinspector/lrobjectitemmodel.h | 99 +- .../objectinspector/lrobjectpropitem.cpp | 181 +- limereport/objectinspector/lrobjectpropitem.h | 219 +-- .../objectinspector/lrpropertydelegate.cpp | 197 ++- .../objectinspector/lrpropertydelegate.h | 39 +- .../propertyItems/lraxispropitem.cpp | 52 +- .../propertyItems/lraxispropitem.h | 28 +- .../propertyItems/lrboolpropitem.cpp | 80 +- .../propertyItems/lrboolpropitem.h | 27 +- .../propertyItems/lrcolorpropitem.cpp | 64 +- .../propertyItems/lrcolorpropitem.h | 25 +- .../propertyItems/lrcontentpropitem.cpp | 37 +- .../propertyItems/lrcontentpropitem.h | 24 +- .../propertyItems/lrdatasourcepropitem.cpp | 159 +- .../propertyItems/lrdatasourcepropitem.h | 38 +- .../propertyItems/lrenumpropitem.cpp | 80 +- .../propertyItems/lrenumpropitem.h | 46 +- .../propertyItems/lrflagspropitem.cpp | 126 +- .../propertyItems/lrflagspropitem.h | 43 +- .../propertyItems/lrfontpropitem.cpp | 134 +- .../propertyItems/lrfontpropitem.h | 94 +- .../propertyItems/lrgroupfieldpropitem.cpp | 63 +- .../propertyItems/lrgroupfieldpropitem.h | 22 +- .../propertyItems/lrimagepropitem.cpp | 38 +- .../propertyItems/lrimagepropitem.h | 23 +- .../propertyItems/lrintpropitem.cpp | 74 +- .../propertyItems/lrintpropitem.h | 23 +- .../propertyItems/lrmarginpropitem.cpp | 87 +- .../propertyItems/lrmarginpropitem.h | 21 +- .../propertyItems/lrqrealpropitem.cpp | 47 +- .../propertyItems/lrqrealpropitem.h | 21 +- .../propertyItems/lrrectproptem.cpp | 283 +-- .../propertyItems/lrrectproptem.h | 44 +- .../propertyItems/lrseriespropitem.cpp | 39 +- .../propertyItems/lrseriespropitem.h | 29 +- .../propertyItems/lrstringpropitem.cpp | 52 +- .../propertyItems/lrstringpropitem.h | 20 +- .../propertyItems/lrsvgpropitem.cpp | 37 +- .../propertyItems/lrsvgpropitem.h | 21 +- limereport/objectsbrowser/lrobjectbrowser.cpp | 271 ++- limereport/objectsbrowser/lrobjectbrowser.h | 48 +- limereport/scriptbrowser/lrscriptbrowser.cpp | 120 +- limereport/scriptbrowser/lrscriptbrowser.h | 28 +- limereport/scripteditor/lrcodeeditor.cpp | 155 +- limereport/scripteditor/lrcodeeditor.h | 57 +- limereport/scripteditor/lrcompletermodel.cpp | 113 +- limereport/scripteditor/lrcompletermodel.h | 72 +- limereport/scripteditor/lrscripteditor.cpp | 304 ++-- limereport/scripteditor/lrscripteditor.h | 46 +- .../scripteditor/lrscripthighlighter.cpp | 291 ++-- limereport/scripteditor/lrscripthighlighter.h | 48 +- limereport/serializators/lrserializatorintf.h | 12 +- limereport/serializators/lrstorageintf.h | 19 +- .../lrxmlbasetypesserializators.cpp | 311 ++-- .../lrxmlbasetypesserializators.h | 160 +- .../serializators/lrxmlqrectserializator.cpp | 71 +- .../serializators/lrxmlqrectserializator.h | 29 +- limereport/serializators/lrxmlreader.cpp | 197 +-- limereport/serializators/lrxmlreader.h | 72 +- .../serializators/lrxmlserializatorsfactory.h | 22 +- limereport/serializators/lrxmlwriter.cpp | 236 +-- limereport/serializators/lrxmlwriter.h | 38 +- .../languageselectdialog.cpp | 15 +- .../translationeditor/languageselectdialog.h | 10 +- .../translationeditor/translationeditor.cpp | 171 +- .../translationeditor/translationeditor.h | 24 +- lrdview/MainWindow.cpp | 148 +- lrdview/MainWindow.h | 19 +- lrdview/SettingDialog.cpp | 32 +- lrdview/SettingDialog.h | 8 +- lrdview/XmlModel.cpp | 46 +- lrdview/XmlModel.h | 15 +- lrdview/main.cpp | 5 +- tests/tst_callbackdstest.cpp | 280 +-- tools/check_code_style.sh | 11 + 285 files changed, 19120 insertions(+), 17875 deletions(-) create mode 100644 .clang-format create mode 100755 tools/check_code_style.sh diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..f3b2be0 --- /dev/null +++ b/.clang-format @@ -0,0 +1,41 @@ +--- +BasedOnStyle: WebKit +Language: Cpp +AlignAfterOpenBracket: Align +AllowShortEnumsOnASingleLine: false +BreakInheritanceList: AfterColon +BreakConstructorInitializers: AfterColon +SpaceBeforeCtorInitializerColon: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +AllowAllConstructorInitializersOnNextLine: false +SpaceBeforeInheritanceColon: false +PointerAlignment: Left +ReflowComments: true +FixNamespaceComments: true +SortIncludes: true +SortUsingDeclarations: true +IncludeBlocks: Regroup +# regular expressions are matched against the filename of an include (including the <> or “”) in order: +# topmost: main header file (the one that has the same name as .cpp-file) and ui_XXX.h, if exists +# second group: local header files (i.e. "something.h") +# third group: external header files (i.e. ) +# fourth group: Qt toolkit headers (actually, anything that starts with a 'Q') +# last group: all other external header files +# headers in all groups are sorted by name +IncludeCategories: + - Regex: '"ui_.*' + Priority: 0 + - Regex: '^".*' + Priority: 1 + - Regex: '^' + Priority: 2 + - Regex: '^ -#include -#include -#include +#include #include #include #include -#include -#include "../limereport/version.h" +#include + +#include +#include #ifdef _WIN32 - #include - #include +#include +#include #endif -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QApplication a(argc, argv); QApplication::setApplicationVersion(LIMEREPORT_VERSION_STR); @@ -23,63 +25,69 @@ int main(int argc, char *argv[]) QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); - QCommandLineOption sourceOption(QStringList() << "s" << "source", - QCoreApplication::translate("main", "Limereport pattern file name"), - QCoreApplication::translate("main", "source")); + QCommandLineOption sourceOption( + QStringList() << "s" + << "source", + QCoreApplication::translate("main", "Limereport pattern file name"), + QCoreApplication::translate("main", "source")); parser.addOption(sourceOption); - QCommandLineOption destinationOption(QStringList() << "d" << "destination", - QCoreApplication::translate("main", "Output file name"), - QCoreApplication::translate("main", "destination")); + QCommandLineOption destinationOption(QStringList() << "d" + << "destination", + QCoreApplication::translate("main", "Output file name"), + QCoreApplication::translate("main", "destination")); parser.addOption(destinationOption); - QCommandLineOption variablesOption(QStringList() << "p" << "param", - QCoreApplication::translate("main", "Report parameter (can be more than one)"), - QCoreApplication::translate("main", "param_name=param_value")); + QCommandLineOption variablesOption( + QStringList() << "p" + << "param", + QCoreApplication::translate("main", "Report parameter (can be more than one)"), + QCoreApplication::translate("main", "param_name=param_value")); parser.addOption(variablesOption); parser.process(a); LimeReport::ReportEngine report; - if (parser.value(sourceOption).isEmpty()){ - std::cerr<<"Error! Report file is not specified !! \n"; + if (parser.value(sourceOption).isEmpty()) { + std::cerr << "Error! Report file is not specified !! \n"; return 1; } - if (!report.loadFromFile(parser.value(sourceOption))){ - std::cerr<<"Error! Report file \""+parser.value(sourceOption).toStdString()+"\" not found \n"; + if (!report.loadFromFile(parser.value(sourceOption))) { + std::cerr << "Error! Report file \"" + parser.value(sourceOption).toStdString() + + "\" not found \n"; return 1; } - if (!parser.values(variablesOption).isEmpty()){ - foreach(QString var, parser.values(variablesOption)){ + if (!parser.values(variablesOption).isEmpty()) { + foreach (QString var, parser.values(variablesOption)) { QStringList varItem = var.split("="); if (varItem.size() == 2) - report.dataManager()->setReportVariable(varItem.at(0),varItem.at(1)); + report.dataManager()->setReportVariable(varItem.at(0), varItem.at(1)); } } - if (parser.value(destinationOption).isEmpty()){ + if (parser.value(destinationOption).isEmpty()) { report.printToPDF(QFileInfo(parser.value(sourceOption)).baseName()); } else { report.printToPDF(parser.value(destinationOption)); } #else - std::cerr<<"This demo intended for Qt 5.2 and higher\n"; + std::cerr << "This demo intended for Qt 5.2 and higher\n"; #endif -// QUuid uid = QUuid::createUuid(); -// QString uidStr = uid.toString()+".pdf"; -// report.printToPDF(uidStr); -// QFile in(uidStr); -// QFile out; -// out.open(stdout, QFile::WriteOnly); -// in.open(QIODevice::ReadOnly); -//#ifdef _WIN32 -// _setmode(fileno(stdout),O_BINARY); -//#endif -// QByteArray buffer = in.readAll(); -// fwrite(buffer,1,buffer.size(),stdout); -// in.close(); -// in.remove(); + // QUuid uid = QUuid::createUuid(); + // QString uidStr = uid.toString()+".pdf"; + // report.printToPDF(uidStr); + // QFile in(uidStr); + // QFile out; + // out.open(stdout, QFile::WriteOnly); + // in.open(QIODevice::ReadOnly); + //#ifdef _WIN32 + // _setmode(fileno(stdout),O_BINARY); + //#endif + // QByteArray buffer = in.readAll(); + // fwrite(buffer,1,buffer.size(),stdout); + // in.close(); + // in.remove(); return 0; - //return a.exec(); + // return a.exec(); } diff --git a/demo_r1/main.cpp b/demo_r1/main.cpp index 72c8163..af16117 100644 --- a/demo_r1/main.cpp +++ b/demo_r1/main.cpp @@ -28,10 +28,10 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "mainwindow.h" + #include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QApplication a(argc, argv); MainWindow w; diff --git a/demo_r1/mainwindow.cpp b/demo_r1/mainwindow.cpp index a7ea5c8..a5ce92b 100644 --- a/demo_r1/mainwindow.cpp +++ b/demo_r1/mainwindow.cpp @@ -29,85 +29,94 @@ ****************************************************************************/ #include "mainwindow.h" #include "ui_mainwindow.h" + +#include #include #include +#include +#include #include #include -#include + #include -#include -#include -#include +#include #ifdef BUILD_WITH_EASY_PROFILER #include "easy/profiler.h" #else -# define EASY_BLOCK(...) -# define EASY_END_BLOCK -# define EASY_PROFILER_ENABLE +#define EASY_BLOCK(...) +#define EASY_END_BLOCK +#define EASY_PROFILER_ENABLE #endif -MainWindow::MainWindow(QWidget *parent) : +MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), - ui(new Ui::MainWindow), m_progressDialog(0), m_customers(0), m_orders(0) + ui(new Ui::MainWindow), + m_progressDialog(0), + m_customers(0), + m_orders(0) { ui->setupUi(this); report = new LimeReport::ReportEngine(this); connect(report, SIGNAL(renderStarted()), this, SLOT(renderStarted())); - connect(report, SIGNAL(renderPageFinished(int)), - this, SLOT(renderPageFinished(int))); + connect(report, SIGNAL(renderPageFinished(int)), this, SLOT(renderPageFinished(int))); connect(report, SIGNAL(renderFinished()), this, SLOT(renderFinished())); - QFile dbFile(QApplication::applicationDirPath()+"/demo_reports/northwind.db"); - if (dbFile.exists()){ + QFile dbFile(QApplication::applicationDirPath() + "/demo_reports/northwind.db"); + if (dbFile.exists()) { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(dbFile.fileName()); - if (m_db.open()){ + if (m_db.open()) { QSqlQueryModel* customersModel = new QSqlQueryModel(); customersModel->setQuery("select * from customers", m_db); - report->dataManager()->addModel("external_customers_data",customersModel,true); + report->dataManager()->addModel("external_customers_data", customersModel, true); QSqlQueryModel* ordersModel = new QSqlQueryModel(); - ordersModel->setQuery("Select * from orders",m_db); - report->dataManager()->addModel("external_orders_data",ordersModel,true); - m_customers = new QSqlQuery("Select * from customers limit 10",m_db); + ordersModel->setQuery("Select * from orders", m_db); + report->dataManager()->addModel("external_orders_data", ordersModel, true); + m_customers = new QSqlQuery("Select * from customers limit 10", m_db); m_customers->first(); m_orders = new QSqlQuery(m_db); m_orders->prepare("Select * from orders where CustomerID = :id"); int index = m_customers->record().indexOf("CustomerID"); - m_orders->bindValue(":id",m_customers->value(index)); + m_orders->bindValue(":id", m_customers->value(index)); m_orders->exec(); } } - LimeReport::ICallbackDatasource * callbackDatasource = report->dataManager()->createCallbackDatasource("master"); - connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - this, SLOT(slotGetCallbackData(LimeReport::CallbackInfo,QVariant&))); - connect(callbackDatasource, SIGNAL(changePos(const LimeReport::CallbackInfo::ChangePosType&,bool&)), - this, SLOT(slotChangePos(const LimeReport::CallbackInfo::ChangePosType&,bool&))); + LimeReport::ICallbackDatasource* callbackDatasource + = report->dataManager()->createCallbackDatasource("master"); + connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), this, + SLOT(slotGetCallbackData(LimeReport::CallbackInfo, QVariant&))); + connect(callbackDatasource, + SIGNAL(changePos(const LimeReport::CallbackInfo::ChangePosType&, bool&)), this, + SLOT(slotChangePos(const LimeReport::CallbackInfo::ChangePosType&, bool&))); callbackDatasource = report->dataManager()->createCallbackDatasource("detail"); - connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - this, SLOT(slotGetCallbackChildData(LimeReport::CallbackInfo,QVariant&))); - connect(callbackDatasource, SIGNAL(changePos(const LimeReport::CallbackInfo::ChangePosType&,bool&)), - this, SLOT(slotChangeChildPos(const LimeReport::CallbackInfo::ChangePosType&,bool&))); + connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), this, + SLOT(slotGetCallbackChildData(LimeReport::CallbackInfo, QVariant&))); + connect(callbackDatasource, + SIGNAL(changePos(const LimeReport::CallbackInfo::ChangePosType&, bool&)), this, + SLOT(slotChangeChildPos(const LimeReport::CallbackInfo::ChangePosType&, bool&))); callbackDatasource = report->dataManager()->createCallbackDatasource("oneSlotDS"); - connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - this, SLOT(slotOneSlotDS(LimeReport::CallbackInfo,QVariant&))); + connect(callbackDatasource, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), this, + SLOT(slotOneSlotDS(LimeReport::CallbackInfo, QVariant&))); QStringList simpleData; - simpleData << "value1" << "value2" << "value3"; + simpleData << "value1" + << "value2" + << "value3"; QStringListModel* stringListModel = new QStringListModel(); stringListModel->setStringList(simpleData); - report->dataManager()->addModel("string_list",stringListModel,true); + report->dataManager()->addModel("string_list", stringListModel, true); QStringList strList; - strList<<"value1"<<"value2"; - //QScriptValue value = qScriptValueFromSequence(report->scriptManager()->scriptEngine(),strList); - //report->scriptManager()->scriptEngine()->globalObject().setProperty("test_list",value); - - + strList << "value1" + << "value2"; + // QScriptValue value = + // qScriptValueFromSequence(report->scriptManager()->scriptEngine(),strList); + // report->scriptManager()->scriptEngine()->globalObject().setProperty("test_list",value); } MainWindow::~MainWindow() @@ -122,8 +131,9 @@ void MainWindow::on_pushButton_clicked() EASY_PROFILER_ENABLE; EASY_BLOCK("design report"); report->dataManager()->clearUserVariables(); - if (!ui->leVariableName->text().isEmpty() && !ui->leVariableValue->text().isEmpty()){ - report->dataManager()->setReportVariable(ui->leVariableName->text(), ui->leVariableValue->text()); + if (!ui->leVariableName->text().isEmpty() && !ui->leVariableValue->text().isEmpty()) { + report->dataManager()->setReportVariable(ui->leVariableName->text(), + ui->leVariableValue->text()); } report->setShowProgressDialog(false); report->designReport(); @@ -135,27 +145,30 @@ void MainWindow::on_pushButton_clicked() void MainWindow::on_pushButton_2_clicked() { - QString fileName = QFileDialog::getOpenFileName(this,"Select report file",QApplication::applicationDirPath()+"/demo_reports/","*.lrxml"); + QString fileName = QFileDialog::getOpenFileName( + this, "Select report file", QApplication::applicationDirPath() + "/demo_reports/", + "*.lrxml"); if (!fileName.isEmpty()) { EASY_PROFILER_ENABLE; EASY_BLOCK("Load file"); report->loadFromFile(fileName); EASY_END_BLOCK; EASY_BLOCK("Set report variable"); - if (!ui->leVariableName->text().isEmpty() && !ui->leVariableValue->text().isEmpty()){ - report->dataManager()->setReportVariable(ui->leVariableName->text(), ui->leVariableValue->text()); + if (!ui->leVariableName->text().isEmpty() && !ui->leVariableValue->text().isEmpty()) { + report->dataManager()->setReportVariable(ui->leVariableName->text(), + ui->leVariableValue->text()); } EASY_END_BLOCK; #ifdef BUILD_WITH_EASY_PROFILER profiler::dumpBlocksToFile("test.prof"); #endif -// QPrinter* printer = new QPrinter; -// QPrintDialog dialog(printer); -// if (dialog.exec()){ -// QMap printers; -// printers.insert("default",printer); -// report->printReport(printers); -// } + // QPrinter* printer = new QPrinter; + // QPrintDialog dialog(printer); + // if (dialog.exec()){ + // QMap printers; + // printers.insert("default",printer); + // report->printReport(printers); + // } report->setShowProgressDialog(true); report->previewReport(); } @@ -163,10 +176,10 @@ void MainWindow::on_pushButton_2_clicked() void MainWindow::renderStarted() { - if (report->isShowProgressDialog()){ + if (report->isShowProgressDialog()) { m_currentPage = 0; - m_progressDialog = new QProgressDialog(tr("Start render"),tr("Cancel"),0,0,this); - //m_progressDialog->setWindowModality(Qt::WindowModal); + m_progressDialog = new QProgressDialog(tr("Start render"), tr("Cancel"), 0, 0, this); + // m_progressDialog->setWindowModality(Qt::WindowModal); connect(m_progressDialog, SIGNAL(canceled()), report, SLOT(cancelRender())); QApplication::processEvents(); m_progressDialog->show(); @@ -175,22 +188,22 @@ void MainWindow::renderStarted() void MainWindow::renderPageFinished(int renderedPageCount) { - if (m_progressDialog){ - m_progressDialog->setLabelText(QString::number(renderedPageCount)+tr(" page rendered")); + if (m_progressDialog) { + m_progressDialog->setLabelText(QString::number(renderedPageCount) + tr(" page rendered")); m_progressDialog->setValue(renderedPageCount); } } void MainWindow::renderFinished() { - if (m_progressDialog){ + if (m_progressDialog) { m_progressDialog->close(); delete m_progressDialog; } m_progressDialog = 0; } -void MainWindow::prepareData(QSqlQuery* ds, LimeReport::CallbackInfo info, QVariant &data) +void MainWindow::prepareData(QSqlQuery* ds, LimeReport::CallbackInfo info, QVariant& data) { switch (info.dataType) { case LimeReport::CallbackInfo::ColumnCount: @@ -210,67 +223,81 @@ void MainWindow::prepareData(QSqlQuery* ds, LimeReport::CallbackInfo info, QVari case LimeReport::CallbackInfo::ColumnData: data = ds->value(ds->record().indexOf(info.columnName)); break; - default: break; + default: + break; } } -void MainWindow::slotGetCallbackData(LimeReport::CallbackInfo info, QVariant &data) +void MainWindow::slotGetCallbackData(LimeReport::CallbackInfo info, QVariant& data) { - if (!m_customers) return; + if (!m_customers) + return; prepareData(m_customers, info, data); } -void MainWindow::slotChangePos(const LimeReport::CallbackInfo::ChangePosType &type, bool &result) +void MainWindow::slotChangePos(const LimeReport::CallbackInfo::ChangePosType& type, bool& result) { QSqlQuery* ds = m_customers; - if (!ds) return; - if (type == LimeReport::CallbackInfo::First) {result = ds->first();} - else {result = ds->next();} - if (result){ - m_orders->bindValue(":id",m_customers->value(m_customers->record().indexOf("CustomerID"))); + if (!ds) + return; + if (type == LimeReport::CallbackInfo::First) { + result = ds->first(); + } else { + result = ds->next(); + } + if (result) { + m_orders->bindValue(":id", m_customers->value(m_customers->record().indexOf("CustomerID"))); m_orders->exec(); } } -void MainWindow::slotGetCallbackChildData(LimeReport::CallbackInfo info, QVariant &data) +void MainWindow::slotGetCallbackChildData(LimeReport::CallbackInfo info, QVariant& data) { - if (!m_orders) return ; + if (!m_orders) + return; prepareData(m_orders, info, data); } -void MainWindow::slotChangeChildPos(const LimeReport::CallbackInfo::ChangePosType &type, bool &result) +void MainWindow::slotChangeChildPos(const LimeReport::CallbackInfo::ChangePosType& type, + bool& result) { QSqlQuery* ds = m_orders; - if (!ds) return; - if (type == LimeReport::CallbackInfo::First) result = ds->first(); - else result = ds->next(); + if (!ds) + return; + if (type == LimeReport::CallbackInfo::First) + result = ds->first(); + else + result = ds->next(); } -void MainWindow::slotOneSlotDS(LimeReport::CallbackInfo info, QVariant &data) +void MainWindow::slotOneSlotDS(LimeReport::CallbackInfo info, QVariant& data) { QStringList columns; - columns << "Name" << "Value" << "Image"; + columns << "Name" + << "Value" + << "Image"; switch (info.dataType) { - case LimeReport::CallbackInfo::RowCount: - data = 4; - break; - case LimeReport::CallbackInfo::ColumnCount: - data = columns.size(); - break; -// case LimeReport::CallbackInfo::IsEmpty: -// data = false; -// break; - case LimeReport::CallbackInfo::ColumnHeaderData: { - data = columns.at(info.index); - break; - } - case LimeReport::CallbackInfo::ColumnData: - if (info.columnName == "Image") - data = QImage(":/report//images/logo32"); - else { - data = info.columnName+" "+QString::number(info.index); - } - break; - default: break; + case LimeReport::CallbackInfo::RowCount: + data = 4; + break; + case LimeReport::CallbackInfo::ColumnCount: + data = columns.size(); + break; + // case LimeReport::CallbackInfo::IsEmpty: + // data = false; + // break; + case LimeReport::CallbackInfo::ColumnHeaderData: { + data = columns.at(info.index); + break; + } + case LimeReport::CallbackInfo::ColumnData: + if (info.columnName == "Image") + data = QImage(":/report//images/logo32"); + else { + data = info.columnName + " " + QString::number(info.index); } + break; + default: + break; + } } diff --git a/demo_r1/mainwindow.h b/demo_r1/mainwindow.h index 271a907..0a5e621 100644 --- a/demo_r1/mainwindow.h +++ b/demo_r1/mainwindow.h @@ -30,22 +30,22 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H +#include "lrreportengine.h" + #include #include #include #include -#include "lrreportengine.h" namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ +class MainWindow: public QMainWindow { Q_OBJECT public: - explicit MainWindow(QWidget *parent = 0); + explicit MainWindow(QWidget* parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); @@ -58,11 +58,13 @@ private slots: void slotGetCallbackChildData(LimeReport::CallbackInfo info, QVariant& data); void slotChangeChildPos(const LimeReport::CallbackInfo::ChangePosType& type, bool& result); void slotOneSlotDS(LimeReport::CallbackInfo info, QVariant& data); + private: - void prepareData(QSqlQuery* ds, LimeReport::CallbackInfo info, QVariant &data); + void prepareData(QSqlQuery* ds, LimeReport::CallbackInfo info, QVariant& data); + private: - Ui::MainWindow *ui; - LimeReport::ReportEngine *report; + Ui::MainWindow* ui; + LimeReport::ReportEngine* report; QProgressDialog* m_progressDialog; int m_currentPage; QSqlDatabase m_db; @@ -73,9 +75,6 @@ private: int m_currentOrderRecord; QSqlQuery* m_customers; QSqlQuery* m_orders; - }; - - #endif // MAINWINDOW_H diff --git a/demo_r2/main.cpp b/demo_r2/main.cpp index dac3ecc..59d74fd 100644 --- a/demo_r2/main.cpp +++ b/demo_r2/main.cpp @@ -1,7 +1,8 @@ #include "mainwindow.h" + #include -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QApplication a(argc, argv); diff --git a/demo_r2/mainwindow.cpp b/demo_r2/mainwindow.cpp index 47c7149..ea2d0f0 100644 --- a/demo_r2/mainwindow.cpp +++ b/demo_r2/mainwindow.cpp @@ -1,17 +1,16 @@ #include "mainwindow.h" #include "ui_mainwindow.h" -#include -#include + #include +#include +#include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include #else #include #endif -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow) +MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); @@ -20,20 +19,22 @@ MainWindow::MainWindow(QWidget *parent) : m_pageNavigator = new QSpinBox(this); m_pageNavigator->setPrefix(tr("Page :")); - ui->toolBar->insertWidget(ui->actionZoom_Out,m_scalePercent); - ui->toolBar->insertWidget(ui->actionNext_Page,m_pageNavigator); - connect(m_scalePercent, SIGNAL(currentIndexChanged(QString)), this, SLOT(scaleComboboxChanged(QString))); + ui->toolBar->insertWidget(ui->actionZoom_Out, m_scalePercent); + ui->toolBar->insertWidget(ui->actionNext_Page, m_pageNavigator); + connect(m_scalePercent, SIGNAL(currentIndexChanged(QString)), this, + SLOT(scaleComboboxChanged(QString))); connect(m_pageNavigator, SIGNAL(valueChanged(int)), this, SLOT(slotPageNavigatorChanged(int))); ui->groupBox_2->layout()->addWidget(m_preview); - buildReportsTree(QApplication::applicationDirPath()+"/demo_reports/", ui->treeWidget); + buildReportsTree(QApplication::applicationDirPath() + "/demo_reports/", ui->treeWidget); connect(ui->actionZoomIn, SIGNAL(triggered()), m_preview, SLOT(zoomIn())); connect(ui->actionZoom_Out, SIGNAL(triggered()), m_preview, SLOT(zoomOut())); connect(ui->actionFirst_Page, SIGNAL(triggered()), m_preview, SLOT(firstPage())); connect(ui->actionPrior_Page, SIGNAL(triggered()), m_preview, SLOT(priorPage())); connect(ui->actionNext_Page, SIGNAL(triggered()), m_preview, SLOT(nextPage())); connect(ui->actionLast_Page, SIGNAL(triggered()), m_preview, SLOT(lastPage())); - connect(m_preview,SIGNAL(scalePercentChanged(int)), this, SLOT(slotScalePercentChanged(int))); - //connect(ui->cbScalePercent, SIGNAL(currentIndexChanged(QString)), this, SLOT(scaleComboboxChanged(QString))); + connect(m_preview, SIGNAL(scalePercentChanged(int)), this, SLOT(slotScalePercentChanged(int))); + // connect(ui->cbScalePercent, SIGNAL(currentIndexChanged(QString)), this, + // SLOT(scaleComboboxChanged(QString))); connect(ui->actionFit_Width, SIGNAL(triggered()), m_preview, SLOT(fitWidth())); connect(ui->actionFit_Page, SIGNAL(triggered()), m_preview, SLOT(fitPage())); connect(m_preview, SIGNAL(pagesSet(int)), this, SLOT(slotPagesSet(int))); @@ -45,44 +46,40 @@ MainWindow::MainWindow(QWidget *parent) : initPercentCombobox(); enableUI(false); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - QDesktopWidget *desktop = QApplication::desktop(); + QDesktopWidget* desktop = QApplication::desktop(); int screenWidth = desktop->screenGeometry().width(); int screenHeight = desktop->screenGeometry().height(); #else - QScreen *screen = QGuiApplication::primaryScreen(); + QScreen* screen = QGuiApplication::primaryScreen(); int screenWidth = screen->geometry().width(); int screenHeight = screen->geometry().height(); #endif - int x = screenWidth*0.1; - int y = screenHeight*0.1; + int x = screenWidth * 0.1; + int y = screenHeight * 0.1; - resize(screenWidth*0.8, screenHeight*0.8); + resize(screenWidth * 0.8, screenHeight * 0.8); move(x, y); - if (ui->treeWidget->topLevelItemCount()>0){ + if (ui->treeWidget->topLevelItemCount() > 0) { int index = 0; - while (indextreeWidget->topLevelItemCount()){ - if (ui->treeWidget->topLevelItem(index)->childCount()>0) + while (index < ui->treeWidget->topLevelItemCount()) { + if (ui->treeWidget->topLevelItem(index)->childCount() > 0) ++index; else { - m_report.loadFromFile(ui->treeWidget->topLevelItem(index)->data(0,Qt::UserRole).toString()); + m_report.loadFromFile( + ui->treeWidget->topLevelItem(index)->data(0, Qt::UserRole).toString()); ui->treeWidget->setCurrentItem(ui->treeWidget->topLevelItem(index)); break; } } - } - m_preview->refreshPages(); - + m_preview->refreshPages(); } -MainWindow::~MainWindow() -{ - delete ui; -} +MainWindow::~MainWindow() { delete ui; } void MainWindow::enableUI(bool value) { @@ -104,21 +101,21 @@ void MainWindow::enableUI(bool value) void MainWindow::slotScalePercentChanged(int percent) { - //ui->cbScalePercent->setEditText(QString("%1%").arg(percent)); + // ui->cbScalePercent->setEditText(QString("%1%").arg(percent)); m_scalePercent->setEditText(QString("%1%").arg(percent)); } void MainWindow::scaleComboboxChanged(QString text) { - m_preview->setScalePercent(text.remove(text.count()-1,1).toInt()); + m_preview->setScalePercent(text.remove(text.count() - 1, 1).toInt()); } void MainWindow::slotPagesSet(int pagesCount) { -// ui->sbPageNavigator->setSuffix(tr(" of %1").arg(pagesCount)); -// ui->sbPageNavigator->setMinimum(1); -// ui->sbPageNavigator->setMaximum(pagesCount); -// ui->sbPageNavigator->setValue(1); + // ui->sbPageNavigator->setSuffix(tr(" of %1").arg(pagesCount)); + // ui->sbPageNavigator->setMinimum(1); + // ui->sbPageNavigator->setMaximum(pagesCount); + // ui->sbPageNavigator->setValue(1); m_pageNavigator->setSuffix(tr(" of %1").arg(pagesCount)); m_pageNavigator->setMinimum(1); @@ -127,35 +124,29 @@ void MainWindow::slotPagesSet(int pagesCount) enableUI(true); } -void MainWindow::slotPageChanged(int page) -{ - m_pageNavigator->setValue(page); -} +void MainWindow::slotPageChanged(int page) { m_pageNavigator->setValue(page); } -void MainWindow::slotPageNavigatorChanged(int page) -{ - m_preview->pageNavigatorChanged(page); -} +void MainWindow::slotPageNavigatorChanged(int page) { m_preview->pageNavigatorChanged(page); } -void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem *item, int ) +void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem* item, int) { - if (!m_report.isBusy()){ - m_report.loadFromFile(item->data(0,Qt::UserRole).toString()); + if (!m_report.isBusy()) { + m_report.loadFromFile(item->data(0, Qt::UserRole).toString()); m_preview->refreshPages(); } } void MainWindow::initPercentCombobox() { - for (int i = 10; i<310; i+=10){ -// ui->cbScalePercent->addItem(QString("%1%").arg(i)); + for (int i = 10; i < 310; i += 10) { + // ui->cbScalePercent->addItem(QString("%1%").arg(i)); m_scalePercent->addItem(QString("%1%").arg(i)); } -// ui->cbScalePercent->setCurrentIndex(4); + // ui->cbScalePercent->setCurrentIndex(4); m_scalePercent->setCurrentIndex(4); } -//void MainWindow::on_sbPageNavigator_valueChanged(int arg1) +// void MainWindow::on_sbPageNavigator_valueChanged(int arg1) //{ // m_preview->pageNavigatorChanged(arg1); //} @@ -166,7 +157,4 @@ void MainWindow::slotDesignReport() m_preview->refreshPages(); } -void MainWindow::slotOneToOne() -{ - m_preview->setScalePercent(100); -} +void MainWindow::slotOneToOne() { m_preview->setScalePercent(100); } diff --git a/demo_r2/mainwindow.h b/demo_r2/mainwindow.h index ceab608..feb1f1c 100644 --- a/demo_r2/mainwindow.h +++ b/demo_r2/mainwindow.h @@ -1,25 +1,26 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include -#include -#include -#include -#include #include +#include +#include +#include #include +#include + +#include namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ +class MainWindow: public QMainWindow { Q_OBJECT public: - explicit MainWindow(QWidget *parent = 0); + explicit MainWindow(QWidget* parent = 0); ~MainWindow(); + private: void enableUI(bool value); private slots: @@ -28,35 +29,36 @@ private slots: void slotPagesSet(int pagesCount); void slotPageChanged(int page); void slotPageNavigatorChanged(int page); - void on_treeWidget_itemClicked(QTreeWidgetItem *item, int); - //void on_sbPageNavigator_valueChanged(int arg1); + void on_treeWidget_itemClicked(QTreeWidgetItem* item, int); + // void on_sbPageNavigator_valueChanged(int arg1); void slotDesignReport(); void slotOneToOne(); + private: - template< typename T > - void buildReportsTree(const QString &path, T* parentItem) + template void buildReportsTree(const QString& path, T* parentItem) { QDir reportsDir(path); QStringList items = reportsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); - foreach( QString dir, items){ + foreach (QString dir, items) { QTreeWidgetItem* listItem = new QTreeWidgetItem(parentItem); - listItem->setText(0,dir); - listItem->setIcon(0,QIcon(":/images/images/folder.png")); - buildReportsTree(reportsDir.path()+"/"+dir, listItem); + listItem->setText(0, dir); + listItem->setIcon(0, QIcon(":/images/images/folder.png")); + buildReportsTree(reportsDir.path() + "/" + dir, listItem); } QStringList nameFilters; - nameFilters <<"*.lrxml"; + nameFilters << "*.lrxml"; items = reportsDir.entryList(nameFilters, QDir::Files); - foreach( QString file, items){ + foreach (QString file, items) { QTreeWidgetItem* listItem = new QTreeWidgetItem(parentItem); - listItem->setIcon(0,QIcon(":/images/images/report.png")); - listItem->setText(0,file); - listItem->setData(0,Qt::UserRole,reportsDir.path()+"/"+file); + listItem->setIcon(0, QIcon(":/images/images/report.png")); + listItem->setText(0, file); + listItem->setData(0, Qt::UserRole, reportsDir.path() + "/" + file); } } void initPercentCombobox(); + private: - Ui::MainWindow *ui; + Ui::MainWindow* ui; LimeReport::ReportEngine m_report; LimeReport::PreviewReportWidget* m_preview; QComboBox* m_scalePercent; diff --git a/designer/designersettingmanager.cpp b/designer/designersettingmanager.cpp index f523c6c..e9c88d0 100644 --- a/designer/designersettingmanager.cpp +++ b/designer/designersettingmanager.cpp @@ -1,21 +1,19 @@ #include "designersettingmanager.h" + #include -DesignerSettingManager::DesignerSettingManager(QObject *parent) : QObject(parent) +DesignerSettingManager::DesignerSettingManager(QObject* parent): QObject(parent) { - m_setting = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_setting = new QSettings("LimeReport", QCoreApplication::applicationName()); } -DesignerSettingManager::~DesignerSettingManager() -{ - delete m_setting; -} +DesignerSettingManager::~DesignerSettingManager() { delete m_setting; } void DesignerSettingManager::getAvailableLanguages(QList* languages) { languages->append(QLocale::Russian); languages->append(QLocale::English); -// languages->append(QLocale::Arabic); + // languages->append(QLocale::Arabic); languages->append(QLocale::French); languages->append(QLocale::Chinese); languages->append(QLocale::Spanish); @@ -27,8 +25,8 @@ QLocale::Language DesignerSettingManager::getCurrentDefaultLanguage() m_setting->beginGroup("ReportDesigner"); QVariant v = m_setting->value("DesignerLanguage"); m_setting->endGroup(); - if (v.isValid()){ - return static_cast(v.toInt()) ; + if (v.isValid()) { + return static_cast(v.toInt()); } else { return QLocale::system().language(); } @@ -36,7 +34,8 @@ QLocale::Language DesignerSettingManager::getCurrentDefaultLanguage() void DesignerSettingManager::currentDefaultLanguageChanged(QLocale::Language language) { - QMessageBox::information(0, tr("Warning") , tr("The language will change after the application is restarted")); + QMessageBox::information(0, tr("Warning"), + tr("The language will change after the application is restarted")); m_setting->beginGroup("ReportDesigner"); m_setting->setValue("DesignerLanguage", (int)language); m_setting->endGroup(); diff --git a/designer/designersettingmanager.h b/designer/designersettingmanager.h index e1226fe..78ce61a 100644 --- a/designer/designersettingmanager.h +++ b/designer/designersettingmanager.h @@ -1,21 +1,21 @@ #ifndef DESIGNERSETTINGMANAGER_H #define DESIGNERSETTINGMANAGER_H -#include -#include #include +#include +#include #include -class DesignerSettingManager : public QObject -{ +class DesignerSettingManager: public QObject { Q_OBJECT public: - explicit DesignerSettingManager(QObject *parent = 0); + explicit DesignerSettingManager(QObject* parent = 0); ~DesignerSettingManager(); public slots: void getAvailableLanguages(QList* languages); QLocale::Language getCurrentDefaultLanguage(); void currentDefaultLanguageChanged(QLocale::Language language); + private: QSettings* m_setting; }; diff --git a/designer/main.cpp b/designer/main.cpp index 485de4a..d859dfd 100644 --- a/designer/main.cpp +++ b/designer/main.cpp @@ -1,10 +1,12 @@ -#include -#include -#include -#include #include "designersettingmanager.h" -int main(int argc, char *argv[]) +#include +#include +#include + +#include + +int main(int argc, char* argv[]) { QApplication a(argc, argv); @@ -21,29 +23,31 @@ int main(int argc, char *argv[]) QString designerTranslation = QLocale(manager.getCurrentDefaultLanguage()).name(); - if (limeReportTranslator.load("limereport_"+designerTranslation, translationPath)){ + if (limeReportTranslator.load("limereport_" + designerTranslation, translationPath)) { static_cast(qtBaseTranslator.load("qtbase_" + designerTranslation, translationPath)); - static_cast(qtDesignerTranslator.load("designer_"+designerTranslation,translationPath)); + static_cast( + qtDesignerTranslator.load("designer_" + designerTranslation, translationPath)); a.installTranslator(&qtBaseTranslator); a.installTranslator(&qtDesignerTranslator); a.installTranslator(&limeReportTranslator); - Qt::LayoutDirection layoutDirection = QLocale(manager.getCurrentDefaultLanguage()).textDirection(); + Qt::LayoutDirection layoutDirection + = QLocale(manager.getCurrentDefaultLanguage()).textDirection(); a.setLayoutDirection(layoutDirection); } LimeReport::ReportEngine report; report.setPreviewLayoutDirection(layoutDirection); - if (a.arguments().count()>1){ + if (a.arguments().count() > 1) { report.loadFromFile(a.arguments().at(1)); } QObject::connect(&report, SIGNAL(getAvailableDesignerLanguages(QList*)), &manager, SLOT(getAvailableLanguages(QList*))); - QObject::connect(&report, SIGNAL(getCurrentDefaultDesignerLanguage()), - &manager, SLOT(getCurrentDefaultLanguage())); + QObject::connect(&report, SIGNAL(getCurrentDefaultDesignerLanguage()), &manager, + SLOT(getCurrentDefaultLanguage())); QObject::connect(&report, SIGNAL(currentDefaultDesignerLanguageChanged(QLocale::Language)), &manager, SLOT(currentDefaultLanguageChanged(QLocale::Language))); @@ -52,4 +56,3 @@ int main(int argc, char *argv[]) report.designReport(); return a.exec(); } - diff --git a/designer_plugin/lrdesignerplugin.cpp b/designer_plugin/lrdesignerplugin.cpp index 96b6f4a..23e55e9 100644 --- a/designer_plugin/lrdesignerplugin.cpp +++ b/designer_plugin/lrdesignerplugin.cpp @@ -1,12 +1,14 @@ #include "lrdesignerplugin.h" -#include #include "lrreportdesignwindow.h" -ReportDesignerFactoryPlugin::~ReportDesignerFactoryPlugin() { -} +#include -LimeReport::ReportDesignWindowInterface* ReportDesignerFactoryPlugin::getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, QWidget* parent, QSettings* settings) +ReportDesignerFactoryPlugin::~ReportDesignerFactoryPlugin() { } + +LimeReport::ReportDesignWindowInterface* +ReportDesignerFactoryPlugin::getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, + QWidget* parent, QSettings* settings) { return new LimeReport::ReportDesignWindow(report, parent, settings); } @@ -14,4 +16,3 @@ LimeReport::ReportDesignWindowInterface* ReportDesignerFactoryPlugin::getDesigne #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(LimeReportPluginInterface, ReportDesignerFactoryPlugin) #endif - diff --git a/designer_plugin/lrdesignerplugin.h b/designer_plugin/lrdesignerplugin.h index d23f147..bf275dd 100644 --- a/designer_plugin/lrdesignerplugin.h +++ b/designer_plugin/lrdesignerplugin.h @@ -2,18 +2,21 @@ #define LRDESIGNERPLUGIN_H #include + #include -class ReportDesignerFactoryPlugin : public QObject, public LimeReportDesignerPluginInterface { +class ReportDesignerFactoryPlugin: public QObject, public LimeReportDesignerPluginInterface { Q_OBJECT #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "ru.limereport.DersignerFactoryInterface") #endif - Q_INTERFACES( LimeReportDesignerPluginInterface ) + Q_INTERFACES(LimeReportDesignerPluginInterface) public: ~ReportDesignerFactoryPlugin(); - LimeReport::ReportDesignWindowInterface* getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, QWidget* parent, QSettings* settings); + LimeReport::ReportDesignWindowInterface* + getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, QWidget* parent, + QSettings* settings); }; #endif diff --git a/include/lrcallbackdatasourceintf.h b/include/lrcallbackdatasourceintf.h index e59c71c..d37e502 100644 --- a/include/lrcallbackdatasourceintf.h +++ b/include/lrcallbackdatasourceintf.h @@ -3,22 +3,31 @@ #include namespace LimeReport { -struct CallbackInfo{ - enum DataType{IsEmpty, HasNext, ColumnHeaderData, ColumnData, ColumnCount, RowCount}; - enum ChangePosType{First, Next}; +struct CallbackInfo { + enum DataType { + IsEmpty, + HasNext, + ColumnHeaderData, + ColumnData, + ColumnCount, + RowCount + }; + enum ChangePosType { + First, + Next + }; DataType dataType; int index; QString columnName; }; -class ICallbackDatasource :public QObject{ +class ICallbackDatasource: public QObject { Q_OBJECT signals: void getCallbackData(const LimeReport::CallbackInfo& info, QVariant& data); void changePos(const LimeReport::CallbackInfo::ChangePosType& type, bool& result); }; -} +} // namespace LimeReport #endif // LRVIRTUALDATASOURCEINTF - diff --git a/include/lrdatasourceintf.h b/include/lrdatasourceintf.h index 481787c..5633a8a 100644 --- a/include/lrdatasourceintf.h +++ b/include/lrdatasourceintf.h @@ -1,14 +1,17 @@ #ifndef LRDATASOURCEINTF_H #define LRDATASOURCEINTF_H -#include #include +#include namespace LimeReport { class IDataSource { public: - enum DatasourceMode{DESIGN_MODE,RENDER_MODE}; + enum DatasourceMode { + DESIGN_MODE, + RENDER_MODE + }; typedef QSharedPointer Ptr; - virtual ~IDataSource() {} + virtual ~IDataSource() { } virtual bool next() = 0; virtual bool hasNext() = 0; virtual bool prior() = 0; @@ -18,12 +21,16 @@ public: virtual bool eof() = 0; virtual QVariant data(const QString& columnName) = 0; virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex) = 0; - virtual QVariant dataByRowIndex(const QString &columnName, int rowIndex, int roleName) = 0; - virtual QVariant dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName) = 0; - virtual QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData) = 0; + virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex, int roleName) = 0; + virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex, + const QString& roleName) + = 0; + virtual QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData) + = 0; virtual int columnCount() = 0; virtual QString columnNameByIndex(int columnIndex) = 0; - virtual QVariant headerData(const QString &columnName, const QString &roleName) = 0; + virtual QVariant headerData(const QString& columnName, const QString& roleName) = 0; virtual int columnIndexByName(QString name) = 0; virtual bool isInvalid() const = 0; virtual QString lastError() = 0; @@ -32,8 +39,9 @@ public: class IDataSourceHolder { public: - virtual ~IDataSourceHolder(){} - virtual IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE) = 0; + virtual ~IDataSourceHolder() { } + virtual IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE) + = 0; virtual QString lastError() const = 0; virtual bool isInvalid() const = 0; virtual bool isOwned() const = 0; @@ -47,5 +55,3 @@ public: } // namespace LimeReport #endif // LRDATASOURCEINTF_H - - diff --git a/include/lrdatasourcemanagerintf.h b/include/lrdatasourcemanagerintf.h index 0ff4a55..056555b 100644 --- a/include/lrdatasourcemanagerintf.h +++ b/include/lrdatasourcemanagerintf.h @@ -31,34 +31,36 @@ #define LRDATASOURCEMANAGERINTF_H #include "lrcallbackdatasourceintf.h" -#include "lrglobal.h" #include "lrdatasourceintf.h" +#include "lrglobal.h" class QVariant; class QString; class QAbstractItemModel; -namespace LimeReport{ +namespace LimeReport { -class IDbCredentialsProvider{ +class IDbCredentialsProvider { public: - virtual ~IDbCredentialsProvider(){} + virtual ~IDbCredentialsProvider() { } virtual QString getUserName(const QString& connectionName) = 0; virtual QString getPassword(const QString& connectionName) = 0; }; -class IDataSourceManager{ +class IDataSourceManager { public: - virtual ~IDataSourceManager(){} + virtual ~IDataSourceManager() { } virtual void setReportVariable(const QString& name, const QVariant& value) = 0; - virtual void setDefaultDatabasePath(const QString &defaultDatabasePath) = 0; + virtual void setDefaultDatabasePath(const QString& defaultDatabasePath) = 0; virtual void deleteVariable(const QString& name) = 0; virtual bool containsVariable(const QString& variableName) = 0; virtual QVariant variable(const QString& variableName) = 0; - virtual bool addModel(const QString& name, QAbstractItemModel *model, bool owned) = 0; - virtual void addCSV(const QString& name, const QString& csvText, const QString& separator, bool firstRowIsHeader) = 0; + virtual bool addModel(const QString& name, QAbstractItemModel* model, bool owned) = 0; + virtual void addCSV(const QString& name, const QString& csvText, const QString& separator, + bool firstRowIsHeader) + = 0; virtual void removeModel(const QString& name) = 0; virtual bool containsDatasource(const QString& dataSourceName) = 0; - virtual void clearUserVariables()=0; + virtual void clearUserVariables() = 0; virtual ICallbackDatasource* createCallbackDatasource(const QString& name) = 0; virtual void registerDbCredentialsProvider(IDbCredentialsProvider* provider) = 0; virtual QStringList variableNames() = 0; @@ -69,6 +71,5 @@ public: virtual IDataSourceHolder* dataSourceHolder(const QString& name) = 0; }; -} +} // namespace LimeReport #endif // LRDATASOURCEMANAGERINTF_H - diff --git a/include/lrglobal.cpp b/include/lrglobal.cpp index 07c5d8e..df1992b 100644 --- a/include/lrglobal.cpp +++ b/include/lrglobal.cpp @@ -27,18 +27,21 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include #include "lrglobal.h" +#include +#include + namespace LimeReport { QString extractClassName(QString className) { - int startPos=className.lastIndexOf("::"); - if(startPos==-1) startPos=0; - else startPos+=2; - return className.right(className.length()-startPos); + int startPos = className.lastIndexOf("::"); + if (startPos == -1) + startPos = 0; + else + startPos += 2; + return className.right(className.length() - startPos); } bool ReportSettings::suppressAbsentFieldsAndVarsWarnings() const @@ -46,31 +49,34 @@ bool ReportSettings::suppressAbsentFieldsAndVarsWarnings() const return m_suppressAbsentFieldsAndVarsWarnings; } -void ReportSettings::setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings) +void ReportSettings::setSuppressAbsentFieldsAndVarsWarnings( + bool suppressAbsentFieldsAndVarsWarnings) { m_suppressAbsentFieldsAndVarsWarnings = suppressAbsentFieldsAndVarsWarnings; } -QString escapeSimbols(const QString &value) +QString escapeSimbols(const QString& value) { QString result = value; - result.replace("\"","\\\""); - result.replace('\n',"\\n"); + result.replace("\"", "\\\""); + result.replace('\n', "\\n"); return result; } -QString replaceHTMLSymbols(const QString &value) +QString replaceHTMLSymbols(const QString& value) { QString result = value; - result.replace("<","<"); - result.replace(">",">"); + result.replace("<", "<"); + result.replace(">", ">"); return result; } #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) -QVector normalizeCaptures(const QRegExp& reg){ +QVector normalizeCaptures(const QRegExp& reg) +{ #else -QVector normalizeCaptures(const QRegularExpressionMatch ®){ +QVector normalizeCaptures(const QRegularExpressionMatch& reg) +{ #endif QVector result; foreach (QString cap, reg.capturedTexts()) { @@ -80,13 +86,14 @@ QVector normalizeCaptures(const QRegularExpressionMatch ®){ return result; } -bool isColorDark(QColor color){ - qreal darkness = 1-(0.299*color.red() + 0.587*color.green() + 0.114*color.blue())/255; - if(darkness<0.5){ +bool isColorDark(QColor color) +{ + qreal darkness = 1 - (0.299 * color.red() + 0.587 * color.green() + 0.114 * color.blue()) / 255; + if (darkness < 0.5) { return false; } else { return true; } } -} //namespace LimeReport +} // namespace LimeReport diff --git a/include/lrglobal.h b/include/lrglobal.h index ed8b86a..c7ef2a2 100644 --- a/include/lrglobal.h +++ b/include/lrglobal.h @@ -30,23 +30,25 @@ #ifndef LRGLOBAL_H #define LRGLOBAL_H #include "qglobal.h" -#include + #include #include #include +#include + #if defined(LIMEREPORT_EXPORTS) -# define LIMEREPORT_EXPORT Q_DECL_EXPORT -#elif defined (LIMEREPORT_IMPORTS) -# define LIMEREPORT_EXPORT Q_DECL_IMPORT +#define LIMEREPORT_EXPORT Q_DECL_EXPORT +#elif defined(LIMEREPORT_IMPORTS) +#define LIMEREPORT_EXPORT Q_DECL_IMPORT #else -# define LIMEREPORT_EXPORT /**/ +#define LIMEREPORT_EXPORT /**/ #endif namespace LimeReport { #ifdef __GNUC__ -#define VARIABLE_IS_NOT_USED __attribute__ ((unused)) +#define VARIABLE_IS_NOT_USED __attribute__((unused)) #else #define VARIABLE_IS_NOT_USED #endif @@ -55,12 +57,12 @@ namespace LimeReport { Q_NAMESPACE #endif -namespace Const{ +namespace Const { int const DEFAULT_GRID_STEP = 1; int const RESIZE_HANDLE_SIZE = 5; int const SELECTION_PEN_SIZE = 1; - int const MINIMUM_ITEM_WIDTH = 2*RESIZE_HANDLE_SIZE; - int const MINIMUM_ITEM_HEIGHT = 2*RESIZE_HANDLE_SIZE; + int const MINIMUM_ITEM_WIDTH = 2 * RESIZE_HANDLE_SIZE; + int const MINIMUM_ITEM_HEIGHT = 2 * RESIZE_HANDLE_SIZE; double const RESIZE_ZONE_OPACITY = 0.5; double const SELECTED_RESIZE_ZONE_OPACITY = 0.6; Qt::GlobalColor const RESIZE_ZONE_COLOR = Qt::green; @@ -80,15 +82,21 @@ namespace Const{ const qreal BAND_NAME_TEXT_OPACITY = 0.6; const qreal SELECTION_OPACITY = 0.3; const QString FIELD_RX = "\\$D\\s*\\{\\s*([^{}]*)\\s*\\}"; - const QString VARIABLE_RX = "\\$V\\s*\\{\\s*(?:([^\\{\\},]*)|(?:([^\\{\\}]*)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; - const QString NAMED_VARIABLE_RX = "\\$V\\s*\\{\\s*(?:(%1)|(?:(%1)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; - const QString SCRIPT_RX = "\\$S\\s*\\{(.*)\\}"; - const QString GROUP_FUNCTION_PARAM_RX = "\\(\\s*((?:(?:\\\")|(?:))(?:(?:\\$(?:(?:D\\{\\s*\\w*..*\\})|(?:V\\{\\s*\\w*\\s*\\})|(?:S\\{.+\\})))|(?:\\w*))(?:(?:\\\")|(?:)))(?:(?:\\s*,\\s*(?:\\\"(\\w*)\\\"))|(?:))(?:(?:\\s*,\\s*(?:(\\w*)))|(?:))\\)"; + const QString VARIABLE_RX = "\\$V\\s*\\{\\s*(?:([^\\{\\},]*)|(?:([^\\{\\}]*)\\s*,\\s*([^\\{" + "\\}]*)))\\s*\\}"; + const QString NAMED_VARIABLE_RX + = "\\$V\\s*\\{\\s*(?:(%1)|(?:(%1)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; + const QString SCRIPT_RX = "\\$S\\s*\\{(.*)\\}"; + const QString GROUP_FUNCTION_PARAM_RX + = "\\(\\s*((?:(?:\\\")|(?:))(?:(?:\\$(?:(?:D\\{\\s*\\w*..*\\})|" + "(?:V\\{\\s*\\w*\\s*\\})|(?:S\\{.+\\})))|(?:\\w*))(?:(?:\\\")" + "|(?:)))(?:(?:\\s*,\\s*(?:\\\"(\\w*)\\\"))|(?:))(?:(?:\\s*," + "\\s*(?:(\\w*)))|(?:))\\)"; const int DATASOURCE_INDEX = 3; const int VALUE_INDEX = 2; const int EXPRESSION_ARGUMENT_INDEX = 1; - const QString GROUP_FUNCTION_RX = "(%1\\s*"+GROUP_FUNCTION_PARAM_RX+")"; + const QString GROUP_FUNCTION_RX = "(%1\\s*" + GROUP_FUNCTION_PARAM_RX + ")"; const QString GROUP_FUNCTION_NAME_RX = "%1\\s*\\((.*[^\\)])\\)"; const int SCENE_MARGIN = 50; const QString FUNCTION_MANAGER_NAME = "LimeReport"; @@ -100,104 +108,135 @@ namespace Const{ const char SCRIPT_SIGN = 'S'; const char FIELD_SIGN = 'D'; const char VARIABLE_SIGN = 'V'; -} - QString extractClassName(QString className); - QString escapeSimbols(const QString& value); - QString replaceHTMLSymbols(const QString &value); +} // namespace Const +QString extractClassName(QString className); +QString escapeSimbols(const QString& value); +QString replaceHTMLSymbols(const QString& value); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - QVector normalizeCaptures(const QRegularExpressionMatch ®); +QVector normalizeCaptures(const QRegularExpressionMatch& reg); #else - QVector normalizeCaptures(const QRegExp ®); +QVector normalizeCaptures(const QRegExp& reg); #endif - bool isColorDark(QColor color); +bool isColorDark(QColor color); - enum ExpandType {EscapeSymbols, NoEscapeSymbols, ReplaceHTMLSymbols}; - enum RenderPass {FirstPass = 1, SecondPass = 2}; - enum ArrangeType {AsNeeded, Force}; - enum ScaleType {FitWidth, FitPage, OneToOne, Percents}; - enum PreviewHint{ShowAllPreviewBars = 0, - HidePreviewToolBar = 1, - HidePreviewMenuBar = 2, - HidePreviewStatusBar = 4, - HideAllPreviewBar = 7, - PreviewBarsUserSetting = 8}; +enum ExpandType { + EscapeSymbols, + NoEscapeSymbols, + ReplaceHTMLSymbols +}; +enum RenderPass { + FirstPass = 1, + SecondPass = 2 +}; +enum ArrangeType { + AsNeeded, + Force +}; +enum ScaleType { + FitWidth, + FitPage, + OneToOne, + Percents +}; +enum PreviewHint { + ShowAllPreviewBars = 0, + HidePreviewToolBar = 1, + HidePreviewMenuBar = 2, + HidePreviewStatusBar = 4, + HideAllPreviewBar = 7, + PreviewBarsUserSetting = 8 +}; - Q_DECLARE_FLAGS(PreviewHints, PreviewHint) - Q_FLAGS(PreviewHints) +Q_DECLARE_FLAGS(PreviewHints, PreviewHint) +Q_FLAGS(PreviewHints) - class LIMEREPORT_EXPORT ReportError : public std::runtime_error{ - public: - ReportError(const QString& message); - }; +class LIMEREPORT_EXPORT ReportError: public std::runtime_error { +public: + ReportError(const QString& message); +}; - class LIMEREPORT_EXPORT ReportSettings{ - public: +class LIMEREPORT_EXPORT ReportSettings { +public: #ifdef DEFAULT_ITEM_PADDING - ReportSettings():m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(DEFAULT_ITEM_PADDING){} + ReportSettings(): + m_suppressAbsentFieldsAndVarsWarnings(false), + m_baseItemPadding(DEFAULT_ITEM_PADDING) + { + } #else - ReportSettings():m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(0){} + ReportSettings(): m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(0) { } #endif - void setDefaultValues(){ - m_suppressAbsentFieldsAndVarsWarnings = false; + void setDefaultValues() + { + m_suppressAbsentFieldsAndVarsWarnings = false; #ifdef DEFAULT_ITEM_PADDING - m_baseItemPadding = DEFAULT_ITEM_PADDING; + m_baseItemPadding = DEFAULT_ITEM_PADDING; #else - m_baseItemPadding = 0; + m_baseItemPadding = 0; #endif + } + bool suppressAbsentFieldsAndVarsWarnings() const; + void setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings); + int baseItemPadding() const; + void setBaseItemPadding(int newBaseTextItemPadding); - } - bool suppressAbsentFieldsAndVarsWarnings() const; - void setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings); - int baseItemPadding() const; - void setBaseItemPadding(int newBaseTextItemPadding); - private: - bool m_suppressAbsentFieldsAndVarsWarnings; - int m_baseItemPadding; - }; +private: + bool m_suppressAbsentFieldsAndVarsWarnings; + int m_baseItemPadding; +}; - class LIMEREPORT_EXPORT IExternalPainter{ - public: - virtual void paintByExternalPainter(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem* options) = 0; - virtual ~IExternalPainter(); - }; +class LIMEREPORT_EXPORT IExternalPainter { +public: + virtual void paintByExternalPainter(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem* options) + = 0; + virtual ~IExternalPainter(); +}; - class LIMEREPORT_EXPORT IPainterProxy{ - public: - virtual void setExternalPainter(IExternalPainter* externalPainter) = 0; - virtual ~IPainterProxy(); - }; +class LIMEREPORT_EXPORT IPainterProxy { +public: + virtual void setExternalPainter(IExternalPainter* externalPainter) = 0; + virtual ~IPainterProxy(); +}; #if QT_VERSION < 0x050000 - typedef QStyleOptionViewItemV4 StyleOptionViewItem; +typedef QStyleOptionViewItemV4 StyleOptionViewItem; #else - typedef QStyleOptionViewItem StyleOptionViewItem; +typedef QStyleOptionViewItem StyleOptionViewItem; #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - QRegularExpression getRegEx(QString expression); - QRegularExpression getVariableRegEx(); - QRegularExpression getFieldRegEx(); - QRegularExpression getScriptRegEx(); - QRegularExpression getGroupFunctionRegEx(QString functionName); - QRegularExpression getGroupFunctionNameRegEx(QString functionName); - QRegularExpression getNamedVariableRegEx(QString variableName); +QRegularExpression getRegEx(QString expression); +QRegularExpression getVariableRegEx(); +QRegularExpression getFieldRegEx(); +QRegularExpression getScriptRegEx(); +QRegularExpression getGroupFunctionRegEx(QString functionName); +QRegularExpression getGroupFunctionNameRegEx(QString functionName); +QRegularExpression getNamedVariableRegEx(QString variableName); #endif - - class LIMEREPORT_EXPORT Enums - { - public: - enum VariableDataType {Undefined, String, Bool, Int, Real, Date, Time, DateTime}; -#if QT_VERSION >= 0x050500 - Q_ENUM(VariableDataType) -#else - Q_ENUMS(VariableDataType) -#endif - private: - Enums(){} - Q_GADGET +class LIMEREPORT_EXPORT Enums { +public: + enum VariableDataType { + Undefined, + String, + Bool, + Int, + Real, + Date, + Time, + DateTime }; +#if QT_VERSION >= 0x050500 + Q_ENUM(VariableDataType) +#else + Q_ENUMS(VariableDataType) +#endif +private: + Enums() { } + Q_GADGET +}; - typedef Enums::VariableDataType VariableDataType; +typedef Enums::VariableDataType VariableDataType; } // namespace LimeReport diff --git a/include/lrpreparedpagesintf.h b/include/lrpreparedpagesintf.h index a079a9a..1c96ede 100644 --- a/include/lrpreparedpagesintf.h +++ b/include/lrpreparedpagesintf.h @@ -2,16 +2,16 @@ #define LRPREPAREDPAGESINTF_H #include "lrglobal.h" namespace LimeReport { -class LIMEREPORT_EXPORT IPreparedPages{ +class LIMEREPORT_EXPORT IPreparedPages { public: - virtual ~IPreparedPages(){}; + virtual ~IPreparedPages() {}; virtual bool loadFromFile(const QString& fileName) = 0; virtual bool loadFromString(const QString data) = 0; virtual bool loadFromByteArray(QByteArray* data) = 0; virtual bool saveToFile(const QString& fileName) = 0; - virtual QString saveToString() = 0; - virtual QByteArray saveToByteArray() = 0; + virtual QString saveToString() = 0; + virtual QByteArray saveToByteArray() = 0; virtual void clear() = 0; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRPREPAREDPAGESINTF_H diff --git a/include/lrpreviewreportwidget.h b/include/lrpreviewreportwidget.h index 9a9eab7..c9b4377 100644 --- a/include/lrpreviewreportwidget.h +++ b/include/lrpreviewreportwidget.h @@ -1,16 +1,17 @@ #ifndef LRPREVIEWREPORTWIDGET_H #define LRPREVIEWREPORTWIDGET_H -#include -#include -#include #include "lrglobal.h" #include "lrpreparedpagesintf.h" +#include +#include +#include + namespace LimeReport { namespace Ui { -class PreviewReportWidget; + class PreviewReportWidget; } class PreviewReportWidgetPrivate; @@ -18,29 +19,30 @@ class ReportEnginePrivate; class ReportEngine; class PageDesignIntf; -class LIMEREPORT_EXPORT PreviewReportWidget : public QWidget -{ +class LIMEREPORT_EXPORT PreviewReportWidget: public QWidget { Q_OBJECT friend class ReportEnginePrivate; friend class PreviewReportWindow; friend class PreviewReportWidgetPrivate; + public: - explicit PreviewReportWidget(ReportEngine *report, QWidget *parent = 0); + explicit PreviewReportWidget(ReportEngine* report, QWidget* parent = 0); ~PreviewReportWidget(); QList aviableExporters(); - bool exportReport(QString exporterName, const QMap& params = QMap()); + bool exportReport(QString exporterName, + const QMap& params = QMap()); ScaleType scaleType() const; - int scalePercent() const; - void setScaleType(const ScaleType &scaleType, int percent = 0); + int scalePercent() const; + void setScaleType(const ScaleType& scaleType, int percent = 0); void setPreviewPageBackgroundColor(QColor color); QColor previewPageBackgroundColor(); - QPrinter *defaultPrinter() const; - void setDefaultPrinter(QPrinter *defaultPrinter); + QPrinter* defaultPrinter() const; + void setDefaultPrinter(QPrinter* defaultPrinter); void startInsertTextItem(); void activateItemSelectionMode(); void deleteSelectedItems(); void activateCurrentPage(); - void resize(ScaleType scaleType, int percent=0); + void resize(ScaleType scaleType, int percent = 0); public slots: void refreshPages(); @@ -59,8 +61,9 @@ public slots: void setScalePercent(int percent); void fitWidth(); void fitPage(); + protected: - void resizeEvent(QResizeEvent *); + void resizeEvent(QResizeEvent*); signals: void pageChanged(int page); void scalePercentChanged(int percent); @@ -72,20 +75,22 @@ private slots: void reportEngineDestroyed(QObject* object); void slotZoomed(double); void resizeDone(); + private: void initPreview(); void setErrorsMesagesVisible(bool visible); - void setErrorMessages(const QStringList &value); + void setErrorMessages(const QStringList& value); void emitPageSet(); + private: - Ui::PreviewReportWidget *ui; + Ui::PreviewReportWidget* ui; PreviewReportWidgetPrivate* d_ptr; ScaleType m_scaleType; - int m_scalePercent; - QTimer m_resizeTimer; - QColor m_previewPageBackgroundColor; + int m_scalePercent; + QTimer m_resizeTimer; + QColor m_previewPageBackgroundColor; QPrinter* m_defaultPrinter; - void printPages(QPrinter *printer); + void printPages(QPrinter* printer); bool m_scaleChanging; }; diff --git a/include/lrrenderengine.h b/include/lrrenderengine.h index ccbecd4..97a424a 100644 --- a/include/lrrenderengine.h +++ b/include/lrrenderengine.h @@ -1,26 +1,28 @@ #ifndef LRRENDERENGINE_H #define LRRENDERENGINE_H -#include -#include -#include - -#include "lrglobal.h" #include "lrdatasourcemanagerintf.h" -#include "lrscriptenginemanagerintf.h" +#include "lrglobal.h" #include "lrpreviewreportwidget.h" +#include "lrscriptenginemanagerintf.h" -namespace LimeReport{ +#include +#include +#include -class PrintRange{ +namespace LimeReport { + +class PrintRange { public: - int fromPage() const { return m_fromPage;} - int toPage() const { return m_toPage;} - QPrintDialog::PrintRange rangeType() const { return m_rangeType;} - PrintRange(QAbstractPrintDialog::PrintRange rangeType=QPrintDialog::AllPages, int fromPage=0, int toPage=0); - void setRangeType(QAbstractPrintDialog::PrintRange rangeType){ m_rangeType=rangeType;} - void setFromPage(int fromPage){ m_fromPage = fromPage;} - void setToPage(int toPage){ m_toPage = toPage;} + int fromPage() const { return m_fromPage; } + int toPage() const { return m_toPage; } + QPrintDialog::PrintRange rangeType() const { return m_rangeType; } + PrintRange(QAbstractPrintDialog::PrintRange rangeType = QPrintDialog::AllPages, + int fromPage = 0, int toPage = 0); + void setRangeType(QAbstractPrintDialog::PrintRange rangeType) { m_rangeType = rangeType; } + void setFromPage(int fromPage) { m_fromPage = fromPage; } + void setToPage(int toPage) { m_toPage = toPage; } + private: QPrintDialog::PrintRange m_rangeType; int m_fromPage; @@ -32,34 +34,36 @@ class PageDesignIntf; class PageItemDesignIntf; class PreviewReportWidget; -typedef QList< QSharedPointer > ReportPages; +typedef QList> ReportPages; class RenderEnginePrivate; -class LIMEREPORT_EXPORT RenderEngine: public QObject{ +class LIMEREPORT_EXPORT RenderEngine: public QObject { Q_OBJECT friend class PreviewReportWidget; + public: - static void setSettings(QSettings *value){m_settings=value;} + static void setSettings(QSettings* value) { m_settings = value; } + public: - explicit RenderEngine(QObject *parent = 0); - explicit RenderEngine(RenderEnginePrivate* dd, QObject *parent = 0); + explicit RenderEngine(QObject* parent = 0); + explicit RenderEngine(RenderEnginePrivate* dd, QObject* parent = 0); ~RenderEngine(); - bool printReport(QPrinter *printer=0); - bool printPages(ReportPages pages, QPrinter *printer); - void printToFile(const QString& fileName); - PageDesignIntf *createPreviewScene(QObject *parent = 0); - bool printToPDF(const QString& fileName); - void previewReport(PreviewHints hints = PreviewBarsUserSetting); + bool printReport(QPrinter* printer = 0); + bool printPages(ReportPages pages, QPrinter* printer); + void printToFile(const QString& fileName); + PageDesignIntf* createPreviewScene(QObject* parent = 0); + bool printToPDF(const QString& fileName); + void previewReport(PreviewHints hints = PreviewBarsUserSetting); IDataSourceManager* dataManager(); IScriptEngineManager* scriptManager(); - bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); - bool loadFromByteArray(QByteArray *data); - bool loadFromString(const QString& data); + bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); + bool loadFromByteArray(QByteArray* data); + bool loadFromString(const QString& data); QString reportFileName(); - void setReportFileName(const QString& fileName); + void setReportFileName(const QString& fileName); QString lastError(); - PreviewReportWidget *createPreviewWidget(QWidget *parent = 0); + PreviewReportWidget* createPreviewWidget(QWidget* parent = 0); void setPreviewWindowTitle(const QString& title); void setPreviewWindowIcon(const QIcon& icon); void setResultEditable(bool value); @@ -70,7 +74,7 @@ public: bool setReportLanguage(QLocale::Language language); Qt::LayoutDirection previewLayoutDirection(); void setPreviewLayoutDirection(const Qt::LayoutDirection& previewLayoutDirection); - QSettings* settings(){ return m_settings;} + QSettings* settings() { return m_settings; } signals: void renderStarted(); void renderFinished(); @@ -78,11 +82,14 @@ signals: void onLoad(bool& loaded); public slots: void cancelRender(); + protected: QObject* d_ptr; + private: static QSettings* m_settings; void init(); + private: Q_DECLARE_PRIVATE(RenderEngine) }; diff --git a/include/lrreportdesignwindowintrerface.h b/include/lrreportdesignwindowintrerface.h index 858881e..beae8d6 100644 --- a/include/lrreportdesignwindowintrerface.h +++ b/include/lrreportdesignwindowintrerface.h @@ -6,9 +6,9 @@ namespace LimeReport { -class ReportDesignWindowInterface: public QMainWindow{ +class ReportDesignWindowInterface: public QMainWindow { public: - ReportDesignWindowInterface(QWidget* parent = 0): QMainWindow(parent){} + ReportDesignWindowInterface(QWidget* parent = 0): QMainWindow(parent) { } virtual bool checkNeedToSave() = 0; virtual void showModal() = 0; virtual void showNonModal() = 0; diff --git a/include/lrreportengine.h b/include/lrreportengine.h index a8716e8..fa244e6 100644 --- a/include/lrreportengine.h +++ b/include/lrreportengine.h @@ -31,61 +31,74 @@ #define LRREPORTDESIGNINTF_H #include -#include #include +#include //#include -#include "lrglobal.h" #include "lrdatasourcemanagerintf.h" -#include "lrscriptenginemanagerintf.h" +#include "lrglobal.h" +#include "lrpreparedpagesintf.h" #include "lrpreviewreportwidget.h" #include "lrreportdesignwindowintrerface.h" -#include "lrpreparedpagesintf.h" +#include "lrscriptenginemanagerintf.h" class QPrinter; class QGraphicsScene; namespace LimeReport { -class PrintRange{ +class PrintRange { public: - int fromPage() const { return m_fromPage;} - int toPage() const { return m_toPage;} - QPrintDialog::PrintRange rangeType() const { return m_rangeType;} - PrintRange(QAbstractPrintDialog::PrintRange rangeType=QPrintDialog::AllPages, int fromPage=0, int toPage=0); - void setRangeType(QAbstractPrintDialog::PrintRange rangeType){ m_rangeType=rangeType;} - void setFromPage(int fromPage){ m_fromPage = fromPage;} - void setToPage(int toPage){ m_toPage = toPage;} + int fromPage() const { return m_fromPage; } + int toPage() const { return m_toPage; } + QPrintDialog::PrintRange rangeType() const { return m_rangeType; } + PrintRange(QAbstractPrintDialog::PrintRange rangeType = QPrintDialog::AllPages, + int fromPage = 0, int toPage = 0); + void setRangeType(QAbstractPrintDialog::PrintRange rangeType) { m_rangeType = rangeType; } + void setFromPage(int fromPage) { m_fromPage = fromPage; } + void setToPage(int toPage) { m_toPage = toPage; } + private: QPrintDialog::PrintRange m_rangeType; int m_fromPage; int m_toPage; }; -class LIMEREPORT_EXPORT ItemGeometry{ +class LIMEREPORT_EXPORT ItemGeometry { public: - enum Type{Millimeters, Pixels}; - ItemGeometry(qreal x, qreal y, qreal width, qreal height, Qt::Alignment anchor, Type type = Millimeters) - :m_x(x), m_y(y), m_width(width), m_height(height), m_type(type), m_anchor(anchor){} - ItemGeometry(): m_x(0), m_y(0), m_width(0), m_height(0), m_type(Millimeters){} + enum Type { + Millimeters, + Pixels + }; + ItemGeometry(qreal x, qreal y, qreal width, qreal height, Qt::Alignment anchor, + Type type = Millimeters): + m_x(x), + m_y(y), + m_width(width), + m_height(height), + m_type(type), + m_anchor(anchor) + { + } + ItemGeometry(): m_x(0), m_y(0), m_width(0), m_height(0), m_type(Millimeters) { } qreal x() const; - void setX(const qreal &x); + void setX(const qreal& x); qreal y() const; - void setY(const qreal &y); + void setY(const qreal& y); qreal width() const; - void setWidth(const qreal &width); + void setWidth(const qreal& width); qreal height() const; - void setHeight(const qreal &height); + void setHeight(const qreal& height); Type type() const; - void setType(const Type &type); + void setType(const Type& type); Qt::Alignment anchor() const; - void setAnchor(const Qt::Alignment &anchor); + void setAnchor(const Qt::Alignment& anchor); private: qreal m_x; @@ -96,42 +109,47 @@ private: Qt::Alignment m_anchor; }; -class LIMEREPORT_EXPORT WatermarkSetting{ +class LIMEREPORT_EXPORT WatermarkSetting { public: - WatermarkSetting(const QString& text, const ItemGeometry& geometry, const QFont& font) - : m_text(text), m_font(font), m_opacity(50), m_geometry(geometry), m_color(QColor(Qt::black)){} - WatermarkSetting(): m_font(QFont()), m_opacity(50), m_geometry(ItemGeometry()){} + WatermarkSetting(const QString& text, const ItemGeometry& geometry, const QFont& font): + m_text(text), + m_font(font), + m_opacity(50), + m_geometry(geometry), + m_color(QColor(Qt::black)) + { + } + WatermarkSetting(): m_font(QFont()), m_opacity(50), m_geometry(ItemGeometry()) { } QString text() const; - void setText(const QString &text); + void setText(const QString& text); QFont font() const; - void setFont(const QFont &font); + void setFont(const QFont& font); int opacity() const; - void setOpacity(const int &opacity); + void setOpacity(const int& opacity); ItemGeometry geometry() const; - void setGeometry(const ItemGeometry &geometry); + void setGeometry(const ItemGeometry& geometry); QColor color() const; - void setColor(const QColor &color); + void setColor(const QColor& color); private: QString m_text; - QFont m_font; - int m_opacity; + QFont m_font; + int m_opacity; ItemGeometry m_geometry; QColor m_color; }; -class ItemBuilder{ +class ItemBuilder { virtual void setProperty(QString name, QVariant value) = 0; virtual QVariant property(QString name) = 0; virtual void setGeometry(ItemGeometry geometry) = 0; - virtual ItemGeometry geometry() = 0; + virtual ItemGeometry geometry() = 0; }; - class DataSourceManager; class ReportEnginePrivate; class PageDesignIntf; @@ -140,47 +158,50 @@ class ReportDesignWidget; class PreviewReportWidget; class PreparedPages; -typedef QList< QSharedPointer > ReportPages; +typedef QList> ReportPages; -class LIMEREPORT_EXPORT ReportEngine : public QObject{ +class LIMEREPORT_EXPORT ReportEngine: public QObject { Q_OBJECT friend class ReportDesignWidget; friend class PreviewReportWidget; friend class TranslationEditor; + public: - static void setSettings(QSettings *value){m_settings=value;} + static void setSettings(QSettings* value) { m_settings = value; } + public: - explicit ReportEngine(QObject *parent = 0); + explicit ReportEngine(QObject* parent = 0); ~ReportEngine(); - bool printReport(QPrinter *printer=0); - bool printReport(QMap printers, bool printToAllPrinters = false); - bool printPages(ReportPages pages, QPrinter *printer); - void printToFile(const QString& fileName); - QGraphicsScene* createPreviewScene(QObject *parent = 0); - bool printToPDF(const QString& fileName); - bool exportReport(QString exporterName, const QString &fileName = "", const QMap& params = QMap()); - void previewReport(PreviewHints hints = PreviewBarsUserSetting); - void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); - void designReport(); + bool printReport(QPrinter* printer = 0); + bool printReport(QMap printers, bool printToAllPrinters = false); + bool printPages(ReportPages pages, QPrinter* printer); + void printToFile(const QString& fileName); + QGraphicsScene* createPreviewScene(QObject* parent = 0); + bool printToPDF(const QString& fileName); + bool exportReport(QString exporterName, const QString& fileName = "", + const QMap& params = QMap()); + void previewReport(PreviewHints hints = PreviewBarsUserSetting); + void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); + void designReport(); ReportDesignWindowInterface* getDesignerWindow(); - void setShowProgressDialog(bool value); - bool isShowProgressDialog(); + void setShowProgressDialog(bool value); + bool isShowProgressDialog(); IDataSourceManager* dataManager(); IScriptEngineManager* scriptManager(); - bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); - bool loadFromByteArray(QByteArray *data); - bool loadFromString(const QString& data); + bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); + bool loadFromByteArray(QByteArray* data); + bool loadFromString(const QString& data); QString reportFileName(); - void setReportFileName(const QString& fileName); - bool saveToFile(const QString& fileName); - QByteArray saveToByteArray(); + void setReportFileName(const QString& fileName); + bool saveToFile(const QString& fileName); + QByteArray saveToByteArray(); QString saveToString(); QString lastError(); void setCurrentReportsDir(const QString& dirName); bool setDefaultExportDir(const QString& dirName); void setReportName(const QString& name); QString reportName(); - PreviewReportWidget *createPreviewWidget(QWidget *parent = 0); + PreviewReportWidget* createPreviewWidget(QWidget* parent = 0); void setPreviewWindowTitle(const QString& title); void setPreviewWindowIcon(const QIcon& icon); void setPreviewPageBackgroundColor(QColor color); @@ -201,8 +222,8 @@ public: QList designerLanguages(); QLocale::Language currentDesignerLanguage(); ScaleType previewScaleType(); - int previewScalePercent(); - void setPreviewScaleType(const ScaleType &previewScaleType, int percent = 0); + int previewScalePercent(); + void setPreviewScaleType(const ScaleType& previewScaleType, int percent = 0); void addWatermark(const WatermarkSetting& watermarkSetting); void clearWatermarks(); IPreparedPages* preparedPages(); @@ -234,14 +255,17 @@ signals: void currentDefaultDesignerLanguageChanged(QLocale::Language); QLocale::Language getCurrentDefaultDesignerLanguage(); - void externalPaint(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem*); + void externalPaint(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem*); public slots: void cancelRender(); void cancelPrinting(); + protected: - ReportEnginePrivate * const d_ptr; - ReportEngine(ReportEnginePrivate &dd, QObject * parent=0); + ReportEnginePrivate* const d_ptr; + ReportEngine(ReportEnginePrivate& dd, QObject* parent = 0); + private: Q_DECLARE_PRIVATE(ReportEngine) static QSettings* m_settings; diff --git a/include/lrscriptenginemanagerintf.h b/include/lrscriptenginemanagerintf.h index 573f748..055e771 100644 --- a/include/lrscriptenginemanagerintf.h +++ b/include/lrscriptenginemanagerintf.h @@ -32,15 +32,15 @@ #include "qglobal.h" #if QT_VERSION >= 0x050600 - #ifndef USE_QTSCRIPTENGINE - #ifndef USE_QJSENGINE - #define USE_QJSENGINE - #endif - #endif +#ifndef USE_QTSCRIPTENGINE +#ifndef USE_QJSENGINE +#define USE_QJSENGINE +#endif +#endif #else - #ifndef USE_QTSCRIPTENGINE - #define USE_QTSCRIPTENGINE - #endif +#ifndef USE_QTSCRIPTENGINE +#define USE_QTSCRIPTENGINE +#endif #endif #ifdef USE_QJSENGINE @@ -49,38 +49,38 @@ #include #endif -namespace LimeReport{ +namespace LimeReport { #ifdef USE_QJSENGINE - typedef QJSEngine ScriptEngineType; - typedef QJSValue ScriptValueType; - template - static inline QJSValue getJSValue(QJSEngine &e, T *p) - { - QJSValue res = e.newQObject(p); - QQmlEngine::setObjectOwnership(p, QQmlEngine::CppOwnership); - return res; - } +typedef QJSEngine ScriptEngineType; +typedef QJSValue ScriptValueType; +template static inline QJSValue getJSValue(QJSEngine& e, T* p) +{ + QJSValue res = e.newQObject(p); + QQmlEngine::setObjectOwnership(p, QQmlEngine::CppOwnership); + return res; +} #else - typedef QScriptEngine ScriptEngineType; - typedef QScriptValue ScriptValueType; +typedef QScriptEngine ScriptEngineType; +typedef QScriptValue ScriptValueType; #endif -class IScriptEngineManager{ +class IScriptEngineManager { public: virtual ScriptEngineType* scriptEngine() = 0; #ifdef USE_QTSCRIPTENGINE virtual bool addFunction(const QString& name, ScriptEngineType::FunctionSignature function, - const QString& category="", const QString& description="") = 0; + const QString& category = "", const QString& description = "") + = 0; #endif - virtual bool addFunction(const QString &name, const QString& script, - const QString &category="", const QString &description="") = 0; + virtual bool addFunction(const QString& name, const QString& script, + const QString& category = "", const QString& description = "") + = 0; virtual const QString& lastError() const = 0; virtual ScriptValueType moveQObjectToScript(QObject* object, const QString objectName) = 0; - virtual ~IScriptEngineManager(){} - + virtual ~IScriptEngineManager() { } }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRSCRIPTENGINEMANAGERINTF_H diff --git a/limereport/bands/lrdataband.cpp b/limereport/bands/lrdataband.cpp index 9e81ba1..29189ea 100644 --- a/limereport/bands/lrdataband.cpp +++ b/limereport/bands/lrdataband.cpp @@ -28,6 +28,7 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrdataband.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" @@ -35,56 +36,51 @@ const QString xmlTag = "Data"; const QString xmlTagHeader = "DataHeader"; const QString xmlTagFooter = "DataFooter"; -namespace{ +namespace { -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataBand(owner,parent); +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataBand(owner, parent); } -LimeReport::BaseDesignIntf * createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataHeaderBand(owner,parent); +LimeReport::BaseDesignIntf* createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataHeaderBand(owner, parent); } -LimeReport::BaseDesignIntf * createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataFooterBand(owner,parent); +LimeReport::BaseDesignIntf* createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataFooterBand(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Data"),LimeReport::Const::bandTAG), - createBand - ); -bool VARIABLE_IS_NOT_USED registredHeader = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTagHeader, - LimeReport::ItemAttribs(QObject::tr("DataHeader"),LimeReport::Const::bandTAG), - createHeader - ); -bool VARIABLE_IS_NOT_USED registredFooter = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTagFooter, - LimeReport::ItemAttribs(QObject::tr("DataFooter"),LimeReport::Const::bandTAG), - createFooter - ); + xmlTag, LimeReport::ItemAttribs(QObject::tr("Data"), LimeReport::Const::bandTAG), createBand); +bool VARIABLE_IS_NOT_USED registredHeader + = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTagHeader, + LimeReport::ItemAttribs(QObject::tr("DataHeader"), LimeReport::Const::bandTAG), + createHeader); +bool VARIABLE_IS_NOT_USED registredFooter + = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTagFooter, + LimeReport::ItemAttribs(QObject::tr("DataFooter"), LimeReport::Const::bandTAG), + createFooter); -} +} // namespace namespace LimeReport { -DataBand::DataBand(QObject *owner, QGraphicsItem *parent) - : DataBandDesignIntf(LimeReport::BandDesignIntf::Data,xmlTag,owner,parent) { - setBandTypeText(tr("Data")); - setFixedPos(false); - setMarkerColor(bandColor()); -} - -bool DataBand::isUnique() const +DataBand::DataBand(QObject* owner, QGraphicsItem* parent): + DataBandDesignIntf(LimeReport::BandDesignIntf::Data, xmlTag, owner, parent) { - return false; + setBandTypeText(tr("Data")); + setFixedPos(false); + setMarkerColor(bandColor()); } -QColor DataBand::bandColor() const -{ - return QColor(Qt::darkGreen); -} +bool DataBand::isUnique() const { return false; } -void DataBand::preparePopUpMenu(QMenu &menu) +QColor DataBand::bandColor() const { return QColor(Qt::darkGreen); } + +void DataBand::preparePopUpMenu(QMenu& menu) { BandDesignIntf::preparePopUpMenu(menu); @@ -111,52 +107,49 @@ void DataBand::preparePopUpMenu(QMenu &menu) currAction = menu.addAction(tr("Start new page")); currAction->setCheckable(true); currAction->setChecked(startNewPage()); - - - } -void DataBand::processPopUpAction(QAction *action) +void DataBand::processPopUpAction(QAction* action) { BandDesignIntf::processPopUpAction(action); - if (action->text().compare(tr("Keep footer together")) == 0){ - setProperty("keepFooterTogether",action->isChecked()); + if (action->text().compare(tr("Keep footer together")) == 0) { + setProperty("keepFooterTogether", action->isChecked()); } - if (action->text().compare(tr("Keep subdetail together")) == 0){ - setProperty("keepSubdetailTogether",action->isChecked()); + if (action->text().compare(tr("Keep subdetail together")) == 0) { + setProperty("keepSubdetailTogether", action->isChecked()); } - if (action->text().compare(tr("Slice last row")) == 0){ - setProperty("sliceLastRow",action->isChecked()); + if (action->text().compare(tr("Slice last row")) == 0) { + setProperty("sliceLastRow", action->isChecked()); } - if (action->text().compare(tr("Use alternate background color")) == 0){ - setProperty("useAlternateBackgroundColor",action->isChecked()); + if (action->text().compare(tr("Use alternate background color")) == 0) { + setProperty("useAlternateBackgroundColor", action->isChecked()); } - if (action->text().compare(tr("Start new page")) == 0){ - setProperty("startNewPage",action->isChecked()); + if (action->text().compare(tr("Start new page")) == 0) { + setProperty("startNewPage", action->isChecked()); } - if (action->text().compare(tr("Start from new page")) == 0){ - setProperty("startFromNewPage",action->isChecked()); + if (action->text().compare(tr("Start from new page")) == 0) { + setProperty("startFromNewPage", action->isChecked()); } } -BaseDesignIntf *DataBand::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* DataBand::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new DataBand(owner,parent); + return new DataBand(owner, parent); } -DataHeaderBand::DataHeaderBand(QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(BandDesignIntf::DataHeader,xmlTagHeader,owner,parent) +DataHeaderBand::DataHeaderBand(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::DataHeader, xmlTagHeader, owner, parent) { setBandTypeText(tr("DataHeader")); setMarkerColor(bandColor()); } -void DataHeaderBand::preparePopUpMenu(QMenu &menu) +void DataHeaderBand::preparePopUpMenu(QMenu& menu) { BandDesignIntf::preparePopUpMenu(menu); QAction* currAction = menu.addAction(tr("Reprint on each page")); @@ -172,30 +165,30 @@ void DataHeaderBand::preparePopUpMenu(QMenu &menu) currAction->setChecked(printAlways()); } -void DataHeaderBand::processPopUpAction(QAction *action) +void DataHeaderBand::processPopUpAction(QAction* action) { BandDesignIntf::processPopUpAction(action); - if (action->text().compare(tr("Reprint on each page")) == 0){ - setProperty("reprintOnEachPage",action->isChecked()); + if (action->text().compare(tr("Reprint on each page")) == 0) { + setProperty("reprintOnEachPage", action->isChecked()); } - if (action->text().compare(tr("Repeat on each row")) == 0){ - setProperty("repeatOnEachRow",action->isChecked()); + if (action->text().compare(tr("Repeat on each row")) == 0) { + setProperty("repeatOnEachRow", action->isChecked()); } - if (action->text().compare(tr("Print always")) == 0){ - setProperty("printAlways",action->isChecked()); + if (action->text().compare(tr("Print always")) == 0) { + setProperty("printAlways", action->isChecked()); } } -DataFooterBand::DataFooterBand(QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(BandDesignIntf::DataFooter,xmlTagFooter,owner,parent) +DataFooterBand::DataFooterBand(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::DataFooter, xmlTagFooter, owner, parent) { setBandTypeText(tr("DataFooter")); setMarkerColor(bandColor()); } -void DataFooterBand::preparePopUpMenu(QMenu &menu) +void DataFooterBand::preparePopUpMenu(QMenu& menu) { BandDesignIntf::preparePopUpMenu(menu); QAction* currAction = menu.addAction(tr("Print always")); @@ -203,13 +196,12 @@ void DataFooterBand::preparePopUpMenu(QMenu &menu) currAction->setChecked(printAlways()); } -void DataFooterBand::processPopUpAction(QAction *action) +void DataFooterBand::processPopUpAction(QAction* action) { BandDesignIntf::processPopUpAction(action); - if (action->text().compare(tr("Print always")) == 0){ - setProperty("printAlways",action->isChecked()); + if (action->text().compare(tr("Print always")) == 0) { + setProperty("printAlways", action->isChecked()); } } -} - +} // namespace LimeReport diff --git a/limereport/bands/lrdataband.h b/limereport/bands/lrdataband.h index ba0395c..a663454 100644 --- a/limereport/bands/lrdataband.h +++ b/limereport/bands/lrdataband.h @@ -32,77 +32,88 @@ #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -class DataBand : public DataBandDesignIntf -{ +class DataBand: public DataBandDesignIntf { Q_OBJECT Q_PROPERTY(bool keepSubdetailTogether READ tryToKeepTogether WRITE setTryToKeepTogether) Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) Q_PROPERTY(bool keepFooterTogether READ keepFooterTogether WRITE setKeepFooterTogether) Q_PROPERTY(bool sliceLastRow READ sliceLastRow WRITE setSliceLastRow) Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool startNewPage READ startNewPage WRITE setStartNewPage) Q_PROPERTY(bool startFromNewPage READ startFromNewPage WRITE setStartFromNewPage) - Q_PROPERTY(QColor alternateBackgroundColor READ alternateBackgroundColor WRITE setAlternateBackgroundColor) - Q_PROPERTY(bool useAlternateBackgroundColor READ useAlternateBackgroundColor WRITE setUseAlternateBackgroundColor) + Q_PROPERTY(QColor alternateBackgroundColor READ alternateBackgroundColor WRITE + setAlternateBackgroundColor) + Q_PROPERTY(bool useAlternateBackgroundColor READ useAlternateBackgroundColor WRITE + setUseAlternateBackgroundColor) public: - DataBand(QObject* owner = 0, QGraphicsItem* parent=0); + DataBand(QObject* owner = 0, QGraphicsItem* parent = 0); bool isUnique() const; - bool isData() const {return true;} + bool isData() const { return true; } + protected: QColor bandColor() const; - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); }; -class DataHeaderBand : public BandDesignIntf -{ +class DataHeaderBand: public BandDesignIntf { Q_OBJECT Q_PROPERTY(bool reprintOnEachPage READ reprintOnEachPage WRITE setReprintOnEachPage) Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool printAlways READ printAlways WRITE setPrintAlways) Q_PROPERTY(bool repeatOnEachRow READ repeatOnEachRow WRITE setRepeatOnEachRow) public: - DataHeaderBand(QObject* owner=0, QGraphicsItem* parent=0); - bool isUnique() const {return false;} - bool isHeader() const {return true;} - QColor bandColor() const {return QColor(Qt::darkGreen);} + DataHeaderBand(QObject* owner = 0, QGraphicsItem* parent = 0); + bool isUnique() const { return false; } + bool isHeader() const { return true; } + QColor bandColor() const { return QColor(Qt::darkGreen); } + protected: - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0){ - return new DataHeaderBand(owner,parent); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0) + { + return new DataHeaderBand(owner, parent); } }; -class DataFooterBand : public BandDesignIntf -{ +class DataFooterBand: public BandDesignIntf { Q_OBJECT Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool printAlways READ printAlways WRITE setPrintAlways) public: - DataFooterBand(QObject* owner=0, QGraphicsItem* parent=0); - bool isUnique() const {return false;} - bool isFooter() const {return true;} - QColor bandColor() const{return QColor(Qt::darkGreen);} + DataFooterBand(QObject* owner = 0, QGraphicsItem* parent = 0); + bool isUnique() const { return false; } + bool isFooter() const { return true; } + QColor bandColor() const { return QColor(Qt::darkGreen); } + protected: - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0){ - return new DataFooterBand(owner,parent); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0) + { + return new DataFooterBand(owner, parent); } }; -} +} // namespace LimeReport #endif // LRDATABAND_H diff --git a/limereport/bands/lrgroupbands.cpp b/limereport/bands/lrgroupbands.cpp index 569e0df..bb2ab03 100644 --- a/limereport/bands/lrgroupbands.cpp +++ b/limereport/bands/lrgroupbands.cpp @@ -28,131 +28,130 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrgroupbands.h" -#include "lrglobal.h" + #include "lrdatasourcemanager.h" +#include "lrglobal.h" const QString xmlTagHeader = QLatin1String("GroupHeader"); const QString xmlTagFooter = QLatin1String("GroupFooter"); -namespace{ +namespace { -LimeReport::BaseDesignIntf* createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::GroupBandHeader(owner,parent); +LimeReport::BaseDesignIntf* createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::GroupBandHeader(owner, parent); } -bool VARIABLE_IS_NOT_USED registredHeader = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTagHeader, - LimeReport::ItemAttribs(QObject::tr("GroupHeader"),LimeReport::Const::bandTAG), - createHeader - ); +bool VARIABLE_IS_NOT_USED registredHeader + = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTagHeader, + LimeReport::ItemAttribs(QObject::tr("GroupHeader"), LimeReport::Const::bandTAG), + createHeader); -LimeReport::BaseDesignIntf * createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::GroupBandFooter(owner,parent); +LimeReport::BaseDesignIntf* createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::GroupBandFooter(owner, parent); } -bool VARIABLE_IS_NOT_USED registredFooter = LimeReport::DesignElementsFactory::instance().registerCreator( +bool VARIABLE_IS_NOT_USED registredFooter + = LimeReport::DesignElementsFactory::instance().registerCreator( xmlTagFooter, - LimeReport::ItemAttribs(QObject::tr("GroupFooter"),LimeReport::Const::bandTAG), - createFooter - ); + LimeReport::ItemAttribs(QObject::tr("GroupFooter"), LimeReport::Const::bandTAG), + createFooter); -} +} // namespace -namespace LimeReport{ +namespace LimeReport { -GroupBandHeader::GroupBandHeader(QObject *owner, QGraphicsItem *parent) - : BandDesignIntf(BandDesignIntf::GroupHeader, xmlTagHeader, owner,parent), - m_groupFiledName(""), m_groupStarted(false), m_resetPageNumber(false) +GroupBandHeader::GroupBandHeader(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::GroupHeader, xmlTagHeader, owner, parent), + m_groupFiledName(""), + m_groupStarted(false), + m_resetPageNumber(false) { setBandTypeText(tr("GroupHeader")); setFixedPos(false); setMarkerColor(bandColor()); } -bool GroupBandHeader::isUnique() const -{ - return false; -} +bool GroupBandHeader::isUnique() const { return false; } -//bool GroupBandHeader::tryToKeepTogether() +// bool GroupBandHeader::tryToKeepTogether() //{ // return m_tryToKeepTogether; //} -BaseDesignIntf *GroupBandHeader::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* GroupBandHeader::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { return new GroupBandHeader(owner, parent); } void GroupBandHeader::startGroup(DataSourceManager* dataManager) { - m_groupStarted=true; + m_groupStarted = true; - QString lineVar = QLatin1String("line_")+objectName().toLower(); - dataManager->setReportVariable(lineVar,1); + QString lineVar = QLatin1String("line_") + objectName().toLower(); + dataManager->setReportVariable(lineVar, 1); QString datasourceName = findDataSourceName(parentBand()); - if (dataManager->containsDatasource(datasourceName)){ + if (dataManager->containsDatasource(datasourceName)) { IDataSource* ds = dataManager->dataSource(datasourceName); - if (ds && ds->columnIndexByName(m_groupFiledName)!=-1) - m_groupFieldValue=ds->data(m_groupFiledName); + if (ds && ds->columnIndexByName(m_groupFiledName) != -1) + m_groupFieldValue = ds->data(m_groupFiledName); } - if (!m_condition.isEmpty()) m_conditionValue = calcCondition(dataManager); + if (!m_condition.isEmpty()) + m_conditionValue = calcCondition(dataManager); } -QColor GroupBandHeader::bandColor() const +QColor GroupBandHeader::bandColor() const { return QColor(Qt::darkBlue); } + +QString GroupBandHeader::findDataSourceName(BandDesignIntf* parentBand) { - return QColor(Qt::darkBlue); -} - -QString GroupBandHeader::findDataSourceName(BandDesignIntf* parentBand){ - if (!parentBand) return ""; + if (!parentBand) + return ""; if (!parentBand->datasourceName().isEmpty()) return parentBand->datasourceName(); else return findDataSourceName(parentBand->parentBand()); - } -QString GroupBandHeader::condition() const +QString GroupBandHeader::condition() const { return m_condition; } + +void GroupBandHeader::setCondition(const QString& condition) { m_condition = condition; } + +QString GroupBandHeader::calcCondition(DataSourceManager* dataManager) { - return m_condition; -} - -void GroupBandHeader::setCondition(const QString &condition) -{ - m_condition = condition; -} - -QString GroupBandHeader::calcCondition(DataSourceManager* dataManager){ QString result = m_condition; - if (!m_condition.isEmpty()){ - result=expandUserVariables(result, FirstPass, NoEscapeSymbols, dataManager); - result=expandScripts(result, dataManager); - result=expandDataFields(result, NoEscapeSymbols, dataManager); + if (!m_condition.isEmpty()) { + result = expandUserVariables(result, FirstPass, NoEscapeSymbols, dataManager); + result = expandScripts(result, dataManager); + result = expandDataFields(result, NoEscapeSymbols, dataManager); } return result; } bool GroupBandHeader::isNeedToClose(DataSourceManager* dataManager) { - if (!m_groupStarted) return false; - if ((m_groupFiledName.isNull() || m_groupFiledName.isEmpty()) && condition().isEmpty()){ + if (!m_groupStarted) + return false; + if ((m_groupFiledName.isNull() || m_groupFiledName.isEmpty()) && condition().isEmpty()) { dataManager->putError(tr("Group field not found")); return false; } - if (!m_condition.isEmpty()){ + if (!m_condition.isEmpty()) { return m_conditionValue != calcCondition(dataManager); } else { QString datasourceName = findDataSourceName(parentBand()); - if (dataManager->containsDatasource(datasourceName)){ + if (dataManager->containsDatasource(datasourceName)) { IDataSource* ds = dataManager->dataSource(datasourceName); - if (ds){ - if (ds->data(m_groupFiledName).isNull() && m_groupFieldValue.isNull()) return false; - if (!ds->data(m_groupFiledName).isValid()) return false; - return ds->data(m_groupFiledName)!=m_groupFieldValue; + if (ds) { + if (ds->data(m_groupFiledName).isNull() && m_groupFieldValue.isNull()) + return false; + if (!ds->data(m_groupFiledName).isValid()) + return false; + return ds->data(m_groupFiledName) != m_groupFieldValue; } } else { dataManager->putError(tr("Datasource \"%1\" not found!").arg(datasourceName)); @@ -164,62 +163,47 @@ bool GroupBandHeader::isNeedToClose(DataSourceManager* dataManager) bool GroupBandHeader::isStarted() { - return m_groupStarted;//!m_groupFieldValue.isNull(); + return m_groupStarted; //! m_groupFieldValue.isNull(); } void GroupBandHeader::closeGroup() { - m_groupFieldValue=QVariant(); - m_conditionValue=""; - m_groupStarted=false; + m_groupFieldValue = QVariant(); + m_conditionValue = ""; + m_groupStarted = false; } -int GroupBandHeader::index() -{ - return bandIndex(); -} +int GroupBandHeader::index() { return bandIndex(); } -bool GroupBandHeader::startNewPage() const -{ - return BandDesignIntf::startNewPage(); -} +bool GroupBandHeader::startNewPage() const { return BandDesignIntf::startNewPage(); } void GroupBandHeader::setStartNewPage(bool startNewPage) { BandDesignIntf::setStartNewPage(startNewPage); } -bool GroupBandHeader::resetPageNumber() const -{ - return m_resetPageNumber; -} +bool GroupBandHeader::resetPageNumber() const { return m_resetPageNumber; } void GroupBandHeader::setResetPageNumber(bool resetPageNumber) { m_resetPageNumber = resetPageNumber; } -GroupBandFooter::GroupBandFooter(QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(BandDesignIntf::GroupFooter, xmlTagFooter, owner,parent) +GroupBandFooter::GroupBandFooter(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::GroupFooter, xmlTagFooter, owner, parent) { setBandTypeText(tr("GroupFooter")); setFixedPos(false); setMarkerColor(bandColor()); } -bool GroupBandFooter::isUnique() const +bool GroupBandFooter::isUnique() const { return false; } + +QColor GroupBandFooter::bandColor() const { return QColor(Qt::darkBlue); } + +BaseDesignIntf* GroupBandFooter::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return false; + return new GroupBandFooter(owner, parent); } -QColor GroupBandFooter::bandColor() const -{ - return QColor(Qt::darkBlue); -} - -BaseDesignIntf *GroupBandFooter::createSameTypeItem(QObject *owner, QGraphicsItem *parent) -{ - return new GroupBandFooter(owner,parent); -} - -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/bands/lrgroupbands.h b/limereport/bands/lrgroupbands.h index 62b9b16..c3d4afe 100644 --- a/limereport/bands/lrgroupbands.h +++ b/limereport/bands/lrgroupbands.h @@ -33,61 +33,64 @@ #include "lrbanddesignintf.h" #include "lrdesignelementsfactory.h" -namespace LimeReport{ +namespace LimeReport { -class GroupBandHeader : public BandDesignIntf, public IGroupBand{ +class GroupBandHeader: public BandDesignIntf, public IGroupBand { Q_OBJECT Q_PROPERTY(QString groupFieldName READ groupFieldName WRITE setGroupFieldName) - Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable ) + Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) Q_PROPERTY(bool keepGroupTogether READ tryToKeepTogether WRITE setTryToKeepTogether) Q_PROPERTY(bool startNewPage READ startNewPage WRITE setStartNewPage) Q_PROPERTY(bool resetPageNumber READ resetPageNumber WRITE setResetPageNumber) Q_PROPERTY(bool reprintOnEachPage READ reprintOnEachPage WRITE setReprintOnEachPage) Q_PROPERTY(QString condition READ condition WRITE setCondition) public: - GroupBandHeader(QObject* owner = 0, QGraphicsItem* parent=0); + GroupBandHeader(QObject* owner = 0, QGraphicsItem* parent = 0); virtual bool isUnique() const; - QVariant groupFieldValue(){return m_groupFieldValue;} - void setGroupFieldValue(QVariant value){m_groupFieldValue=value;} - QString groupFieldName(){return m_groupFiledName;} - void setGroupFieldName(QString fieldName){m_groupFiledName=fieldName;} + QVariant groupFieldValue() { return m_groupFieldValue; } + void setGroupFieldValue(QVariant value) { m_groupFieldValue = value; } + QString groupFieldName() { return m_groupFiledName; } + void setGroupFieldName(QString fieldName) { m_groupFiledName = fieldName; } QColor bandColor() const; bool startNewPage() const; void setStartNewPage(bool startNewPage); bool resetPageNumber() const; void setResetPageNumber(bool resetPageNumber); - bool isHeader() const{return true;} - bool isGroupHeader() const {return true;} + bool isHeader() const { return true; } + bool isGroupHeader() const { return true; } QString condition() const; - void setCondition(const QString &condition); + void setCondition(const QString& condition); + private: - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); void startGroup(DataSourceManager* dataManager); - bool isNeedToClose(DataSourceManager *dataManager); + bool isNeedToClose(DataSourceManager* dataManager); bool isStarted(); void closeGroup(); int index(); - QString findDataSourceName(BandDesignIntf *parentBand); - QString calcCondition(DataSourceManager *dataManager); + QString findDataSourceName(BandDesignIntf* parentBand); + QString calcCondition(DataSourceManager* dataManager); + private: QVariant m_groupFieldValue; QString m_groupFiledName; bool m_groupStarted; - //bool m_startNewPage; + // bool m_startNewPage; bool m_resetPageNumber; QString m_condition; QString m_conditionValue; }; -class GroupBandFooter : public BandDesignIntf{ +class GroupBandFooter: public BandDesignIntf { Q_OBJECT public: - GroupBandFooter(QObject* owner = 0, QGraphicsItem* parent=0); + GroupBandFooter(QObject* owner = 0, QGraphicsItem* parent = 0); virtual bool isUnique() const; QColor bandColor() const; - virtual bool isFooter() const{return true;} + virtual bool isFooter() const { return true; } + private: - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); }; } // namespace LimeReport diff --git a/limereport/bands/lrpagefooter.cpp b/limereport/bands/lrpagefooter.cpp index 0cb7091..59683ce 100644 --- a/limereport/bands/lrpagefooter.cpp +++ b/limereport/bands/lrpagefooter.cpp @@ -28,46 +28,45 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrpagefooter.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" #include "lrpagedesignintf.h" -const QString xmlTag ="PageFooter"; +const QString xmlTag = "PageFooter"; -namespace{ -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::PageFooter(owner,parent); +namespace { +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::PageFooter(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Page Footer"),LimeReport::Const::bandTAG), - createBand - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Page Footer"), LimeReport::Const::bandTAG), + createBand); +} // namespace -namespace LimeReport{ +namespace LimeReport { -PageFooter::PageFooter(QObject *owner, QGraphicsItem *parent) - : BandDesignIntf(LimeReport::BandDesignIntf::PageFooter,xmlTag,owner,parent), - m_printOnFirstPage(true), m_printOnLastPage(true), m_removeGap(false) +PageFooter::PageFooter(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(LimeReport::BandDesignIntf::PageFooter, xmlTag, owner, parent), + m_printOnFirstPage(true), + m_printOnLastPage(true), + m_removeGap(false) { - setBandTypeText( tr("Page Footer") ); - setMarkerColor(bandColor()); - setAutoHeight(false); + setBandTypeText(tr("Page Footer")); + setMarkerColor(bandColor()); + setAutoHeight(false); } -BaseDesignIntf *PageFooter::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* PageFooter::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new PageFooter(owner,parent); + return new PageFooter(owner, parent); } -QColor PageFooter::bandColor() const -{ - return QColor(246,120,12); -} +QColor PageFooter::bandColor() const { return QColor(246, 120, 12); } -void PageFooter::preparePopUpMenu(QMenu &menu) +void PageFooter::preparePopUpMenu(QMenu& menu) { QAction* action = menu.addAction(tr("Print on first page")); action->setCheckable(true); @@ -76,57 +75,44 @@ void PageFooter::preparePopUpMenu(QMenu &menu) action = menu.addAction(tr("Print on last page")); action->setCheckable(true); action->setChecked(printOnLastPage()); - } -void PageFooter::processPopUpAction(QAction *action) +void PageFooter::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Print on first page")) == 0){ - page()->setPropertyToSelectedItems("printOnFirstPage",action->isChecked()); + if (action->text().compare(tr("Print on first page")) == 0) { + page()->setPropertyToSelectedItems("printOnFirstPage", action->isChecked()); } - if (action->text().compare(tr("Print on last page")) == 0){ - page()->setPropertyToSelectedItems("printOnLastPage",action->isChecked()); + if (action->text().compare(tr("Print on last page")) == 0) { + page()->setPropertyToSelectedItems("printOnLastPage", action->isChecked()); } BandDesignIntf::processPopUpAction(action); } -bool PageFooter::removeGap() const -{ - return m_removeGap; -} +bool PageFooter::removeGap() const { return m_removeGap; } -void PageFooter::setRemoveGap(bool removeGap) -{ - m_removeGap = removeGap; -} +void PageFooter::setRemoveGap(bool removeGap) { m_removeGap = removeGap; } -bool PageFooter::printOnFirstPage() const -{ - return m_printOnFirstPage; -} +bool PageFooter::printOnFirstPage() const { return m_printOnFirstPage; } void PageFooter::setPrintOnFirstPage(bool printOnFirstPage) { - if (m_printOnFirstPage != printOnFirstPage){ + if (m_printOnFirstPage != printOnFirstPage) { bool oldValue = m_printOnFirstPage; m_printOnFirstPage = printOnFirstPage; update(); - notify("printOnFirstPage",oldValue,printOnFirstPage); + notify("printOnFirstPage", oldValue, printOnFirstPage); } } -bool PageFooter::printOnLastPage() const -{ - return m_printOnLastPage; -} +bool PageFooter::printOnLastPage() const { return m_printOnLastPage; } void PageFooter::setPrintOnLastPage(bool printOnLastPage) { - if (m_printOnLastPage != printOnLastPage){ + if (m_printOnLastPage != printOnLastPage) { bool oldValue = m_printOnLastPage; m_printOnLastPage = printOnLastPage; update(); - notify("printOnLastPage",oldValue,printOnLastPage); + notify("printOnLastPage", oldValue, printOnLastPage); } } diff --git a/limereport/bands/lrpagefooter.h b/limereport/bands/lrpagefooter.h index ce3ca59..8f5c91b 100644 --- a/limereport/bands/lrpagefooter.h +++ b/limereport/bands/lrpagefooter.h @@ -32,19 +32,19 @@ #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" + #include -namespace LimeReport{ -class PageFooter : public BandDesignIntf -{ +namespace LimeReport { +class PageFooter: public BandDesignIntf { Q_OBJECT Q_PROPERTY(bool printOnFirstPage READ printOnFirstPage WRITE setPrintOnFirstPage) Q_PROPERTY(bool printOnLastPage READ printOnLastPage WRITE setPrintOnLastPage) Q_PROPERTY(bool removeGap READ removeGap WRITE setRemoveGap) public: - PageFooter(QObject* owner = 0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); - virtual bool isFooter() const {return true;} + PageFooter(QObject* owner = 0, QGraphicsItem* parent = 0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + virtual bool isFooter() const { return true; } bool printOnLastPage() const; void setPrintOnLastPage(bool printOnLastPage); bool printOnFirstPage() const; @@ -53,14 +53,15 @@ public: void setRemoveGap(bool removeGap); protected: - QColor bandColor() const; - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + QColor bandColor() const; + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: bool m_printOnFirstPage; bool m_printOnLastPage; bool m_removeGap; }; -} +} // namespace LimeReport #endif // LRPAGEFOOTER_H diff --git a/limereport/bands/lrpageheader.cpp b/limereport/bands/lrpageheader.cpp index 7a08599..1c2b1f7 100644 --- a/limereport/bands/lrpageheader.cpp +++ b/limereport/bands/lrpageheader.cpp @@ -28,64 +28,54 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrpageheader.h" -#include "lrdesignelementsfactory.h" + #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" -#include "lrpageitemdesignintf.h" +#include "lrdesignelementsfactory.h" #include "lrglobal.h" +#include "lrpageitemdesignintf.h" -const QString xmlTag ="PageHeader"; +const QString xmlTag = "PageHeader"; -namespace{ +namespace { -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::PageHeader(owner,parent); +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::PageHeader(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Page Header"),LimeReport::Const::bandTAG), - createBand - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Page Header"), LimeReport::Const::bandTAG), + createBand); +} // namespace -namespace LimeReport{ +namespace LimeReport { -PageHeader::PageHeader(QObject* owner, QGraphicsItem *parent) -: BandDesignIntf(LimeReport::BandDesignIntf::PageHeader,xmlTag,owner,parent), - m_printOnFirstPage(true), m_printOnLastPage(true) { +PageHeader::PageHeader(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(LimeReport::BandDesignIntf::PageHeader, xmlTag, owner, parent), + m_printOnFirstPage(true), + m_printOnLastPage(true) +{ setBandTypeText(tr("Page Header")); setMarkerColor(bandColor()); } -BaseDesignIntf *PageHeader::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* PageHeader::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new PageHeader(owner,parent); + return new PageHeader(owner, parent); } -QColor PageHeader::bandColor() const -{ - return QColor(246,120,12); -} +QColor PageHeader::bandColor() const { return QColor(246, 120, 12); } -bool PageHeader::printOnLastPage() const -{ - return m_printOnLastPage; -} +bool PageHeader::printOnLastPage() const { return m_printOnLastPage; } -void PageHeader::setPrintOnLastPage(bool printOnLastPage) -{ - m_printOnLastPage = printOnLastPage; -} +void PageHeader::setPrintOnLastPage(bool printOnLastPage) { m_printOnLastPage = printOnLastPage; } -bool PageHeader::printOnFirstPage() const -{ - return m_printOnFirstPage; -} +bool PageHeader::printOnFirstPage() const { return m_printOnFirstPage; } void PageHeader::setPrintOnFirstPage(bool printOnFirstPage) { m_printOnFirstPage = printOnFirstPage; } -} +} // namespace LimeReport diff --git a/limereport/bands/lrpageheader.h b/limereport/bands/lrpageheader.h index d0607cd..00cf2cf 100644 --- a/limereport/bands/lrpageheader.h +++ b/limereport/bands/lrpageheader.h @@ -30,29 +30,31 @@ #ifndef LRPAGEHEADER_H #define LRPAGEHEADER_H -#include #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" +#include + namespace LimeReport { -class PageHeader : public LimeReport::BandDesignIntf -{ +class PageHeader: public LimeReport::BandDesignIntf { Q_OBJECT Q_PROPERTY(bool printOnFirstPage READ printOnFirstPage WRITE setPrintOnFirstPage) Q_PROPERTY(bool printOnLastPage READ printOnLastPage WRITE setPrintOnLastPage) public: - PageHeader(QObject* owner = 0, QGraphicsItem* parent=0); + PageHeader(QObject* owner = 0, QGraphicsItem* parent = 0); bool printOnFirstPage() const; void setPrintOnFirstPage(bool printOnFirstPage); bool printOnLastPage() const; void setPrintOnLastPage(bool printOnLastPage); - bool isHeader() const{return true;} + bool isHeader() const { return true; } + protected: - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); QColor bandColor() const; + private: bool m_printOnFirstPage; bool m_printOnLastPage; }; -} +} // namespace LimeReport #endif // LRPAGEHEADER_H diff --git a/limereport/bands/lrreportfooter.cpp b/limereport/bands/lrreportfooter.cpp index 41c50e0..18a41b7 100644 --- a/limereport/bands/lrreportfooter.cpp +++ b/limereport/bands/lrreportfooter.cpp @@ -28,44 +28,39 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrreportfooter.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" -const QString xmlTag ="ReportFooter"; +const QString xmlTag = "ReportFooter"; -namespace{ +namespace { -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::ReportFooter(owner,parent); +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::ReportFooter(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Report Footer"),LimeReport::Const::bandTAG), - createBand - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Report Footer"), LimeReport::Const::bandTAG), + createBand); +} // namespace -namespace LimeReport{ +namespace LimeReport { -ReportFooter::ReportFooter(QObject *owner, QGraphicsItem *parent) - : BandDesignIntf(LimeReport::BandDesignIntf::ReportFooter,xmlTag,owner,parent) { +ReportFooter::ReportFooter(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(LimeReport::BandDesignIntf::ReportFooter, xmlTag, owner, parent) +{ setBandTypeText(tr("Report Footer")); setMarkerColor(bandColor()); } -BaseDesignIntf *ReportFooter::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* ReportFooter::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new ReportFooter(owner,parent); + return new ReportFooter(owner, parent); } -QColor ReportFooter::bandColor() const -{ - return QColor(152,69,167); -} +QColor ReportFooter::bandColor() const { return QColor(152, 69, 167); } -bool ReportFooter::isFooter() const -{ - return true; -} +bool ReportFooter::isFooter() const { return true; } -} +} // namespace LimeReport diff --git a/limereport/bands/lrreportfooter.h b/limereport/bands/lrreportfooter.h index 5ffcc0c..164f3c6 100644 --- a/limereport/bands/lrreportfooter.h +++ b/limereport/bands/lrreportfooter.h @@ -30,22 +30,23 @@ #ifndef LRREPORTFOOTER_H #define LRREPORTFOOTER_H -#include #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" -namespace LimeReport{ -class ReportFooter : public BandDesignIntf -{ +#include + +namespace LimeReport { +class ReportFooter: public BandDesignIntf { Q_OBJECT Q_PROPERTY(int maxScalePercent READ maxScalePercent WRITE setMaxScalePercent) Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) public: - ReportFooter(QObject* owner=0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + ReportFooter(QObject* owner = 0, QGraphicsItem* parent = 0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + protected: QColor bandColor() const; bool isFooter() const; }; -} +} // namespace LimeReport #endif // LRREPORTFOOTER_H diff --git a/limereport/bands/lrreportheader.cpp b/limereport/bands/lrreportheader.cpp index af8e924..c24b03e 100644 --- a/limereport/bands/lrreportheader.cpp +++ b/limereport/bands/lrreportheader.cpp @@ -28,50 +28,45 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrreportheader.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" -const QString xmlTag ="ReportHeader"; +const QString xmlTag = "ReportHeader"; -namespace{ -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::ReportHeader(owner,parent); +namespace { +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::ReportHeader(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Report Header"),LimeReport::Const::bandTAG), - createBand - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Report Header"), LimeReport::Const::bandTAG), + createBand); +} // namespace namespace LimeReport { -ReportHeader::ReportHeader(QObject *owner, QGraphicsItem *parent) - : BandDesignIntf(LimeReport::BandDesignIntf::ReportHeader,xmlTag,owner,parent), m_printBeforePageHeader(false) { - setBandTypeText(tr("Report Header")); - setMarkerColor(bandColor()); -} -BaseDesignIntf *ReportHeader::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +ReportHeader::ReportHeader(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(LimeReport::BandDesignIntf::ReportHeader, xmlTag, owner, parent), + m_printBeforePageHeader(false) { - return new ReportHeader(owner,parent); + setBandTypeText(tr("Report Header")); + setMarkerColor(bandColor()); +} +BaseDesignIntf* ReportHeader::createSameTypeItem(QObject* owner, QGraphicsItem* parent) +{ + return new ReportHeader(owner, parent); } -QColor ReportHeader::bandColor() const -{ - return QColor(152,69,167); -} +QColor ReportHeader::bandColor() const { return QColor(152, 69, 167); } -bool ReportHeader::printBeforePageHeader() const -{ - return m_printBeforePageHeader; -} +bool ReportHeader::printBeforePageHeader() const { return m_printBeforePageHeader; } void ReportHeader::setPrintBeforePageHeader(bool printBeforePageHeader) { - if (m_printBeforePageHeader != printBeforePageHeader){ + if (m_printBeforePageHeader != printBeforePageHeader) { m_printBeforePageHeader = printBeforePageHeader; - notify("printBeforePageHeader",!m_printBeforePageHeader,m_printBeforePageHeader); + notify("printBeforePageHeader", !m_printBeforePageHeader, m_printBeforePageHeader); } } -} - +} // namespace LimeReport diff --git a/limereport/bands/lrreportheader.h b/limereport/bands/lrreportheader.h index 4a85b3b..58eefdd 100644 --- a/limereport/bands/lrreportheader.h +++ b/limereport/bands/lrreportheader.h @@ -30,25 +30,26 @@ #ifndef LRREPORTHEADER_H #define LRREPORTHEADER_H -#include #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" -namespace LimeReport{ -class ReportHeader : public LimeReport::BandDesignIntf -{ +#include + +namespace LimeReport { +class ReportHeader: public LimeReport::BandDesignIntf { Q_OBJECT Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) Q_PROPERTY(bool printBeforePageHeader READ printBeforePageHeader WRITE setPrintBeforePageHeader) public: - ReportHeader(QObject* owner = 0, QGraphicsItem *parent=0); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + ReportHeader(QObject* owner = 0, QGraphicsItem* parent = 0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); bool printBeforePageHeader() const; void setPrintBeforePageHeader(bool printBeforePageHeader); - bool isHeader() const {return true;} + bool isHeader() const { return true; } + protected: QColor bandColor() const; bool m_printBeforePageHeader; }; -} +} // namespace LimeReport #endif // LRREPORTHEADER_H diff --git a/limereport/bands/lrsubdetailband.cpp b/limereport/bands/lrsubdetailband.cpp index 3e74d7c..b21acf0 100644 --- a/limereport/bands/lrsubdetailband.cpp +++ b/limereport/bands/lrsubdetailband.cpp @@ -28,55 +28,56 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrsubdetailband.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" - const QString xmlTagBand = QLatin1String("SubDetail"); const QString xmlTagHeader = QLatin1String("SubDetailHeader"); const QString xmlTagFooter = QLatin1String("SubDetailFooter"); const QColor BAND_COLOR = Qt::red; -namespace{ +namespace { -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailBand(owner,parent); +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailBand(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTagBand, - LimeReport::ItemAttribs(QObject::tr("SubDetail"),LimeReport::Const::bandTAG), - createBand - ); + xmlTagBand, LimeReport::ItemAttribs(QObject::tr("SubDetail"), LimeReport::Const::bandTAG), + createBand); -LimeReport::BaseDesignIntf * createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailHeaderBand(owner,parent); +LimeReport::BaseDesignIntf* createHeader(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailHeaderBand(owner, parent); } -bool VARIABLE_IS_NOT_USED registredHeader = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTagHeader, - LimeReport::ItemAttribs(QObject::tr("SubDetailHeader"),LimeReport::Const::bandTAG), - createHeader - ); +bool VARIABLE_IS_NOT_USED registredHeader + = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTagHeader, + LimeReport::ItemAttribs(QObject::tr("SubDetailHeader"), LimeReport::Const::bandTAG), + createHeader); -LimeReport::BaseDesignIntf * createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailFooterBand(owner,parent); +LimeReport::BaseDesignIntf* createFooter(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailFooterBand(owner, parent); } -bool VARIABLE_IS_NOT_USED registredFooter = LimeReport::DesignElementsFactory::instance().registerCreator( +bool VARIABLE_IS_NOT_USED registredFooter + = LimeReport::DesignElementsFactory::instance().registerCreator( xmlTagFooter, - LimeReport::ItemAttribs(QObject::tr("SubDetailFooter"),LimeReport::Const::bandTAG), - createFooter - ); + LimeReport::ItemAttribs(QObject::tr("SubDetailFooter"), LimeReport::Const::bandTAG), + createFooter); } // namespace -namespace LimeReport{ +namespace LimeReport { -//SubDetailBand +// SubDetailBand -SubDetailBand::SubDetailBand(QObject *owner, QGraphicsItem *parent) - : DataBandDesignIntf(BandDesignIntf::SubDetailBand, xmlTagBand, owner,parent) +SubDetailBand::SubDetailBand(QObject* owner, QGraphicsItem* parent): + DataBandDesignIntf(BandDesignIntf::SubDetailBand, xmlTagBand, owner, parent) { setBandTypeText(tr("SubDetail")); setFixedPos(false); @@ -93,62 +94,46 @@ bool SubDetailBand::isHasFooter() const return isConnectedToBand(BandDesignIntf::SubDetailFooter); } -BaseDesignIntf *SubDetailBand::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* SubDetailBand::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new SubDetailBand(owner,parent); + return new SubDetailBand(owner, parent); } -QColor SubDetailBand::bandColor() const -{ - return BAND_COLOR; -} +QColor SubDetailBand::bandColor() const { return BAND_COLOR; } -//SubDetailHeaderBand +// SubDetailHeaderBand -SubDetailHeaderBand::SubDetailHeaderBand(QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(BandDesignIntf::SubDetailHeader,xmlTagHeader,owner,parent) +SubDetailHeaderBand::SubDetailHeaderBand(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::SubDetailHeader, xmlTagHeader, owner, parent) { setBandTypeText(tr("SubDetailHeader")); setMarkerColor(bandColor()); } -bool SubDetailHeaderBand::isUnique() const +bool SubDetailHeaderBand::isUnique() const { return false; } + +QColor SubDetailHeaderBand::bandColor() const { return BAND_COLOR; } + +BaseDesignIntf* SubDetailHeaderBand::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return false; + return new SubDetailHeaderBand(owner, parent); } -QColor SubDetailHeaderBand::bandColor() const -{ - return BAND_COLOR; -} +// SubDetailFooterBand -BaseDesignIntf *SubDetailHeaderBand::createSameTypeItem(QObject *owner, QGraphicsItem *parent) -{ - return new SubDetailHeaderBand(owner,parent); -} - -//SubDetailFooterBand - -SubDetailFooterBand::SubDetailFooterBand(QObject *owner, QGraphicsItem *parent) - : BandDesignIntf(BandDesignIntf::SubDetailFooter,xmlTagFooter,owner,parent) +SubDetailFooterBand::SubDetailFooterBand(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(BandDesignIntf::SubDetailFooter, xmlTagFooter, owner, parent) { setMarkerColor(bandColor()); } -bool SubDetailFooterBand::isUnique() const +bool SubDetailFooterBand::isUnique() const { return false; } + +QColor SubDetailFooterBand::bandColor() const { return BAND_COLOR; } + +BaseDesignIntf* SubDetailFooterBand::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return false; + return new SubDetailFooterBand(owner, parent); } -QColor SubDetailFooterBand::bandColor() const -{ - return BAND_COLOR; -} - -BaseDesignIntf *SubDetailFooterBand::createSameTypeItem(QObject *owner, QGraphicsItem *parent) -{ - return new SubDetailFooterBand(owner,parent); -} - - -} +} // namespace LimeReport diff --git a/limereport/bands/lrsubdetailband.h b/limereport/bands/lrsubdetailband.h index b50b1c2..2e91971 100644 --- a/limereport/bands/lrsubdetailband.h +++ b/limereport/bands/lrsubdetailband.h @@ -33,64 +33,73 @@ #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" -namespace LimeReport{ +namespace LimeReport { -class SubDetailBand : public DataBandDesignIntf -{ +class SubDetailBand: public DataBandDesignIntf { Q_OBJECT Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool keepFooterTogether READ keepFooterTogether WRITE setKeepFooterTogether) - Q_PROPERTY(QColor alternateBackgroundColor READ alternateBackgroundColor WRITE setAlternateBackgroundColor) - Q_PROPERTY(bool useAlternateBackgroundColor READ useAlternateBackgroundColor WRITE setUseAlternateBackgroundColor) + Q_PROPERTY(QColor alternateBackgroundColor READ alternateBackgroundColor WRITE + setAlternateBackgroundColor) + Q_PROPERTY(bool useAlternateBackgroundColor READ useAlternateBackgroundColor WRITE + setUseAlternateBackgroundColor) public: - SubDetailBand(QObject* owner = 0, QGraphicsItem* parent=0); - bool isUnique() const {return false;} - int bandNestingLevel(){ return 1;} + SubDetailBand(QObject* owner = 0, QGraphicsItem* parent = 0); + bool isUnique() const { return false; } + int bandNestingLevel() { return 1; } bool isHasHeader() const; bool isHasFooter() const; + private: - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + protected: virtual QColor bandColor() const; }; -class SubDetailHeaderBand : public BandDesignIntf -{ +class SubDetailHeaderBand: public BandDesignIntf { Q_OBJECT Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool printAlways READ printAlways WRITE setPrintAlways) public: - SubDetailHeaderBand(QObject* owner = 0, QGraphicsItem* parent=0); + SubDetailHeaderBand(QObject* owner = 0, QGraphicsItem* parent = 0); bool isUnique() const; - bool isHeader() const {return true;} - int bandNestingLevel(){ return 1;} + bool isHeader() const { return true; } + int bandNestingLevel() { return 1; } + protected: QColor bandColor() const; + private: - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); }; -class SubDetailFooterBand : public BandDesignIntf -{ +class SubDetailFooterBand: public BandDesignIntf { Q_OBJECT Q_PROPERTY(int columnsCount READ columnsCount WRITE setColumnsCount) Q_PROPERTY(bool splittable READ isSplittable WRITE setSplittable) - Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE setColumnsFillDirection) + Q_PROPERTY(BandColumnsLayoutType columnsFillDirection READ columnsFillDirection WRITE + setColumnsFillDirection) Q_PROPERTY(bool printAlways READ printAlways WRITE setPrintAlways) public: - SubDetailFooterBand(QObject* owner = 0, QGraphicsItem* parent=0); + SubDetailFooterBand(QObject* owner = 0, QGraphicsItem* parent = 0); virtual bool isUnique() const; - bool isFooter() const{return true;} - int bandNestingLevel(){ return 1;} + bool isFooter() const { return true; } + int bandNestingLevel() { return 1; } + protected: QColor bandColor() const; + private: - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + private: }; -} +} // namespace LimeReport #endif // LRSUBDETAILBAND_H diff --git a/limereport/bands/lrtearoffband.cpp b/limereport/bands/lrtearoffband.cpp index 6f854ab..f954cb2 100644 --- a/limereport/bands/lrtearoffband.cpp +++ b/limereport/bands/lrtearoffband.cpp @@ -1,37 +1,34 @@ #include "lrtearoffband.h" + #include "lrdesignelementsfactory.h" #include "lrglobal.h" -const QString xmlTag ="TearOffBand"; +const QString xmlTag = "TearOffBand"; -namespace{ -LimeReport::BaseDesignIntf * createBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::TearOffBand(owner,parent); +namespace { +LimeReport::BaseDesignIntf* createBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::TearOffBand(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("Tear-off Band"),LimeReport::Const::bandTAG), - createBand - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Tear-off Band"), LimeReport::Const::bandTAG), + createBand); +} // namespace -namespace LimeReport{ +namespace LimeReport { -TearOffBand::TearOffBand(QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(LimeReport::BandDesignIntf::TearOffBand,xmlTag,owner,parent) +TearOffBand::TearOffBand(QObject* owner, QGraphicsItem* parent): + BandDesignIntf(LimeReport::BandDesignIntf::TearOffBand, xmlTag, owner, parent) { setBandTypeText(tr("Tear-off Band")); setMarkerColor(bandColor()); } -BaseDesignIntf *TearOffBand::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* TearOffBand::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new TearOffBand(owner,parent); + return new TearOffBand(owner, parent); } -QColor TearOffBand::bandColor() const -{ - return QColor(200,200,200); -} +QColor TearOffBand::bandColor() const { return QColor(200, 200, 200); } -} // namedpace LimeReport +} // namespace LimeReport diff --git a/limereport/bands/lrtearoffband.h b/limereport/bands/lrtearoffband.h index 5c8c17c..53bc78f 100644 --- a/limereport/bands/lrtearoffband.h +++ b/limereport/bands/lrtearoffband.h @@ -4,16 +4,16 @@ namespace LimeReport { -class TearOffBand : public BandDesignIntf -{ +class TearOffBand: public BandDesignIntf { Q_OBJECT public: - TearOffBand(QObject* owner = 0, QGraphicsItem *parent=0); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + TearOffBand(QObject* owner = 0, QGraphicsItem* parent = 0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + protected: QColor bandColor() const; - bool isUnique() const {return true;} - bool isFooter() const{ return true;} + bool isUnique() const { return true; } + bool isFooter() const { return true; } }; } // namespace LimeReport diff --git a/limereport/base/lrattribsabstractfactory.h b/limereport/base/lrattribsabstractfactory.h index a6b76dc..4f9068c 100644 --- a/limereport/base/lrattribsabstractfactory.h +++ b/limereport/base/lrattribsabstractfactory.h @@ -30,54 +30,61 @@ #ifndef LRATTRIBABSTRACTFACTORY_H #define LRATTRIBABSTRACTFACTORY_H -#include "lrsingleton.h" #include "lrglobal.h" -#include +#include "lrsingleton.h" + #include #include -namespace LimeReport{ +#include -template -< - typename AbstractProduct, - typename IdentifierType, - typename ProductCreator, - typename Attribs -> -class AttribsAbstractFactory - : public Singleton< AttribsAbstractFactory< AbstractProduct,IdentifierType,ProductCreator,Attribs > > -{ +namespace LimeReport { + +template +class AttribsAbstractFactory: + public Singleton< + AttribsAbstractFactory> { private: - typedef QMap FactoryMap; - typedef QMap AliasMap; - friend class Singleton< AttribsAbstractFactory< AbstractProduct,IdentifierType,ProductCreator,Attribs > >; + typedef QMap FactoryMap; + typedef QMap AliasMap; + friend class Singleton< + AttribsAbstractFactory>; + public: - bool registerCreator(const IdentifierType& id, Attribs attribs, ProductCreator creator){ - if (m_factoryMap.contains(id)) return true; - return (m_factoryMap.insert(id,creator).value() == creator) && - (m_attribsMap.insert(id,attribs).value() == attribs); + bool registerCreator(const IdentifierType& id, Attribs attribs, ProductCreator creator) + { + if (m_factoryMap.contains(id)) + return true; + return (m_factoryMap.insert(id, creator).value() == creator) + && (m_attribsMap.insert(id, attribs).value() == attribs); } - bool unregisterCreator(const IdentifierType& id){ + bool unregisterCreator(const IdentifierType& id) + { return (m_factoryMap.remove(id) == 1) && (m_attribsMap.remove(id) == 1); } - ProductCreator objectCreator(const IdentifierType& id){ - if (m_factoryMap.contains(id)){ + ProductCreator objectCreator(const IdentifierType& id) + { + if (m_factoryMap.contains(id)) { return m_factoryMap[id]; - } else return 0; + } else + return 0; } - QString attribs(const IdentifierType& id){ - if (m_attribsMap.contains(id)){ + QString attribs(const IdentifierType& id) + { + if (m_attribsMap.contains(id)) { return m_attribsMap.value(id); - } else return ""; + } else + return ""; } - const FactoryMap& map(){return m_factoryMap;} - const AliasMap& attribsMap(){return m_attribsMap;} - int mapElementCount(){return m_factoryMap.count();} -private: + const FactoryMap& map() { return m_factoryMap; } + const AliasMap& attribsMap() { return m_attribsMap; } + int mapElementCount() { return m_factoryMap.count(); } + +private: FactoryMap m_factoryMap; AliasMap m_attribsMap; }; -} +} // namespace LimeReport #endif // LRATTRIBABSTRACTFACTORY_H diff --git a/limereport/base/lrsimpleabstractfactory.h b/limereport/base/lrsimpleabstractfactory.h index 3406ee0..32e9b16 100644 --- a/limereport/base/lrsimpleabstractfactory.h +++ b/limereport/base/lrsimpleabstractfactory.h @@ -30,74 +30,76 @@ #ifndef LRSIMPLEABSTRACTFACTORY_H #define LRSIMPLEABSTRACTFACTORY_H -#include "lrsingleton.h" #include "lrglobal.h" -#include +#include "lrsingleton.h" + #include #include #include -namespace LimeReport{ -template -< - typename AbstractProduct, - typename IdentifierType, - typename ProductCreator -> -class SimpleAbstractFactory - : public Singleton< SimpleAbstractFactory< AbstractProduct,IdentifierType,ProductCreator > > -{ +#include +namespace LimeReport { + +template +class SimpleAbstractFactory: + public Singleton> { private: - typedef QHash FactoryMap; - friend class Singleton< SimpleAbstractFactory< AbstractProduct,IdentifierType,ProductCreator > >; + typedef QHash FactoryMap; + friend class Singleton>; + public: - bool registerCreator(const IdentifierType& id, ProductCreator creator){ - return (m_factoryMap.insert(id,creator).value()==creator); + bool registerCreator(const IdentifierType& id, ProductCreator creator) + { + return (m_factoryMap.insert(id, creator).value() == creator); } - bool unregisterCreator(const IdentifierType& id){ - return (m_factoryMap.remove(id)==1); - } - ProductCreator objectCreator(const IdentifierType& id){ - if (m_factoryMap.contains(id)){ + bool unregisterCreator(const IdentifierType& id) { return (m_factoryMap.remove(id) == 1); } + ProductCreator objectCreator(const IdentifierType& id) + { + if (m_factoryMap.contains(id)) { return m_factoryMap[id]; } else { return 0; } } - const FactoryMap& map(){return m_factoryMap;} - int mapElementCount(){return m_factoryMap.count();} + const FactoryMap& map() { return m_factoryMap; } + int mapElementCount() { return m_factoryMap.count(); } + private: FactoryMap m_factoryMap; }; -template -< - typename AbstractProduct, - typename IdentifierType, - typename ProductCreator, - typename Attribs -> -class AttribAbstractFactory : public SimpleAbstractFactory< AbstractProduct,IdentifierType,ProductCreator >{ - typedef SimpleAbstractFactory< AbstractProduct,IdentifierType,ProductCreator > SimpleFactory; - typedef QMap AliasMap; - friend class Singleton >; -public : - bool registerCreator(const IdentifierType &id, Attribs attribs, ProductCreator creator){ - return SimpleFactory::registerCreator(id,creator) && (m_attribsMap.insert(id,attribs).value()==attribs); +template +class AttribAbstractFactory: + public SimpleAbstractFactory { + typedef SimpleAbstractFactory SimpleFactory; + typedef QMap AliasMap; + friend class Singleton< + AttribAbstractFactory>; + +public: + bool registerCreator(const IdentifierType& id, Attribs attribs, ProductCreator creator) + { + return SimpleFactory::registerCreator(id, creator) + && (m_attribsMap.insert(id, attribs).value() == attribs); } - bool unregisterCreator(const IdentifierType &id){ - return SimpleFactory::unregisterCreator(id)&&(m_attribsMap.remove(id)==1); + bool unregisterCreator(const IdentifierType& id) + { + return SimpleFactory::unregisterCreator(id) && (m_attribsMap.remove(id) == 1); } - QString attribs(const IdentifierType& id){ - if (m_attribsMap.contains(id)){ + QString attribs(const IdentifierType& id) + { + if (m_attribsMap.contains(id)) { return m_attribsMap.value(id); - } else return ""; + } else + return ""; } - const AliasMap& attribsMap(){return m_attribsMap;} + const AliasMap& attribsMap() { return m_attribsMap; } + private: AliasMap m_attribsMap; }; -} +} // namespace LimeReport -#endif //LRSIMPLEABSTRACTFACTORY_H +#endif // LRSIMPLEABSTRACTFACTORY_H diff --git a/limereport/base/lrsingleton.h b/limereport/base/lrsingleton.h index 87c5255..bf63866 100644 --- a/limereport/base/lrsingleton.h +++ b/limereport/base/lrsingleton.h @@ -32,28 +32,27 @@ #include -namespace LimeReport{ +namespace LimeReport { -template -class Singleton -{ +template class Singleton { public: - static T& instance(){ - if (0==inst){ + static T& instance() + { + if (0 == inst) { inst = new T(); - ::atexit( destroy ); - } else {}; + ::atexit(destroy); + } else { + }; return *inst; } + private: static T* inst; + private: - static void destroy() { - delete inst; - } + static void destroy() { delete inst; } }; -template -T* Singleton< T >::inst =0; -} +template T* Singleton::inst = 0; +} // namespace LimeReport #endif // LRSINGLETON_H diff --git a/limereport/databrowser/lrconnectiondialog.cpp b/limereport/databrowser/lrconnectiondialog.cpp index a4bf8b6..bc5f49a 100644 --- a/limereport/databrowser/lrconnectiondialog.cpp +++ b/limereport/databrowser/lrconnectiondialog.cpp @@ -29,111 +29,118 @@ ****************************************************************************/ #include "lrconnectiondialog.h" #include "ui_lrconnectiondialog.h" + #include "lrglobal.h" + +#include +#include +#include #include #include -#include -#include + #include -#include -namespace LimeReport{ +namespace LimeReport { -ConnectionDialog::ConnectionDialog(LimeReport::IConnectionController *conControl, LimeReport::ConnectionDesc* connectionDesc, QWidget *parent) : +ConnectionDialog::ConnectionDialog(LimeReport::IConnectionController* conControl, + LimeReport::ConnectionDesc* connectionDesc, QWidget* parent): QDialog(parent), - ui(new Ui::ConnectionDialog), m_connection(connectionDesc), m_controller(conControl), m_savedConnectionName("") + ui(new Ui::ConnectionDialog), + m_connection(connectionDesc), + m_controller(conControl), + m_savedConnectionName("") { ui->setupUi(this); - setAttribute(Qt::WA_DeleteOnClose,true); - m_changeMode=m_connection!=0; + setAttribute(Qt::WA_DeleteOnClose, true); + m_changeMode = m_connection != 0; } -ConnectionDialog::~ConnectionDialog() -{ - delete ui; -} +ConnectionDialog::~ConnectionDialog() { delete ui; } void ConnectionDialog::init() { - ui->cbbDrivers->addItems(QSqlDatabase::drivers()); - ui->cbbUseDefaultConnection->setEnabled(!m_controller->containsDefaultConnection()); + ui->cbbDrivers->addItems(QSqlDatabase::drivers()); + ui->cbbUseDefaultConnection->setEnabled(!m_controller->containsDefaultConnection()); } -void ConnectionDialog::showEvent(QShowEvent *) -{ - connectionToUI(); -} +void ConnectionDialog::showEvent(QShowEvent*) { connectionToUI(); } void ConnectionDialog::slotAccept() { try { checkFieldsFill(); - if (ui->cbAutoConnect->isChecked()) checkConnection(); - if (!m_connection){ + if (ui->cbAutoConnect->isChecked()) + checkConnection(); + if (!m_connection) { m_controller->addConnectionDesc(uiToConnection()); } else { m_controller->changeConnectionDesc(uiToConnection(m_connection)); } close(); - } - catch(LimeReport::ReportError &exception){ - QMessageBox::critical(this,tr("Error"),exception.what()); + } catch (LimeReport::ReportError& exception) { + QMessageBox::critical(this, tr("Error"), exception.what()); } } void ConnectionDialog::slotCheckConnection() { - try{ + try { checkConnection(); - QMessageBox::information(this,tr("Connection"),tr("Connection succsesfully established!")); - } catch(LimeReport::ReportError &exception) { - QMessageBox::critical(this,tr("Error"),exception.what()); + QMessageBox::information(this, tr("Connection"), + tr("Connection succsesfully established!")); + } catch (LimeReport::ReportError& exception) { + QMessageBox::critical(this, tr("Error"), exception.what()); } } void ConnectionDialog::checkFieldsFill() { - if (ui->leConnectionName->text().isEmpty()){throw LimeReport::ReportError(tr("Connection Name is empty"));} - if (!m_changeMode&&QSqlDatabase::connectionNames().contains(ui->leConnectionName->text())) { - throw LimeReport::ReportError(tr("Connection with name ")+ui->leConnectionName->text()+tr(" already exists! ")); + if (ui->leConnectionName->text().isEmpty()) { + throw LimeReport::ReportError(tr("Connection Name is empty")); + } + if (!m_changeMode && QSqlDatabase::connectionNames().contains(ui->leConnectionName->text())) { + throw LimeReport::ReportError(tr("Connection with name ") + ui->leConnectionName->text() + + tr(" already exists! ")); } } bool ConnectionDialog::checkConnection() { QScopedPointer con(uiToConnection()); - if (!m_controller->checkConnectionDesc(con.data())){ + if (!m_controller->checkConnectionDesc(con.data())) { throw LimeReport::ReportError(m_controller->lastError()); } return true; } -ConnectionDesc *ConnectionDialog::uiToConnection(LimeReport::ConnectionDesc* conDesc) +ConnectionDesc* ConnectionDialog::uiToConnection(LimeReport::ConnectionDesc* conDesc) { LimeReport::ConnectionDesc* result; if (conDesc) result = conDesc; else result = new LimeReport::ConnectionDesc(); - result ->setName(ConnectionDesc::connectionNameForReport(ui->leConnectionName->text())); - result ->setHost(ui->leServerName->text()); + result->setName(ConnectionDesc::connectionNameForReport(ui->leConnectionName->text())); + result->setHost(ui->leServerName->text()); if (!ui->lePort->text().isEmpty()) result->setPort(ui->lePort->text()); - result ->setDriver(ui->cbbDrivers->currentText()); - result ->setUserName(ui->leUserName->text()); - result ->setPassword(ui->lePassword->text()); - result ->setDatabaseName(ui->leDataBase->text()); - result ->setAutoconnect(ui->cbAutoConnect->isChecked()); + result->setDriver(ui->cbbDrivers->currentText()); + result->setUserName(ui->leUserName->text()); + result->setPassword(ui->lePassword->text()); + result->setDatabaseName(ui->leDataBase->text()); + result->setAutoconnect(ui->cbAutoConnect->isChecked()); result->setKeepDBCredentials(!ui->cbbKeepCredentials->isChecked()); - return result ; + return result; } void ConnectionDialog::connectionToUI() { init(); - if (!m_connection) return; + if (!m_connection) + return; ui->leConnectionName->setText(ConnectionDesc::connectionNameForUser(m_connection->name())); - ui->cbbUseDefaultConnection->setChecked(m_connection->name().compare(QSqlDatabase::defaultConnection) == 0); + ui->cbbUseDefaultConnection->setChecked( + m_connection->name().compare(QSqlDatabase::defaultConnection) == 0); ui->leDataBase->setText(m_connection->databaseName()); ui->leServerName->setText(m_connection->host()); ui->leUserName->setText(m_connection->userName()); @@ -151,7 +158,7 @@ void ConnectionDialog::on_toolButton_clicked() void ConnectionDialog::on_cbbUseDefaultConnection_toggled(bool checked) { - if (checked){ + if (checked) { m_savedConnectionName = ui->leConnectionName->text(); ui->leConnectionName->setText(tr("defaultConnection")); ui->leConnectionName->setEnabled(false); @@ -166,10 +173,3 @@ void ConnectionDialog::on_toolButton_2_toggled(bool checked) } } // namespace LimeReport - - - - - - - diff --git a/limereport/databrowser/lrconnectiondialog.h b/limereport/databrowser/lrconnectiondialog.h index e9ece7c..c81c44f 100644 --- a/limereport/databrowser/lrconnectiondialog.h +++ b/limereport/databrowser/lrconnectiondialog.h @@ -30,27 +30,29 @@ #ifndef LRCONNECTIONDIALOG_H #define LRCONNECTIONDIALOG_H -#include #include "lrdatadesignintf.h" -namespace LimeReport{ +#include + +namespace LimeReport { namespace Ui { class ConnectionDialog; } -class ConnectionDialog : public QDialog -{ +class ConnectionDialog: public QDialog { Q_OBJECT public: - explicit ConnectionDialog(LimeReport::IConnectionController* conControl, LimeReport::ConnectionDesc* connectionDesc=0, QWidget *parent = 0); + explicit ConnectionDialog(LimeReport::IConnectionController* conControl, + LimeReport::ConnectionDesc* connectionDesc = 0, QWidget* parent = 0); ~ConnectionDialog(); + protected: - void showEvent(QShowEvent *); + void showEvent(QShowEvent*); void init(); void checkFieldsFill(); bool checkConnection(); - ConnectionDesc* uiToConnection(LimeReport::ConnectionDesc *conDesc = 0); + ConnectionDesc* uiToConnection(LimeReport::ConnectionDesc* conDesc = 0); void connectionToUI(); signals: void conectionRegistred(LimeReport::ConnectionDesc* connectionDesc); @@ -63,7 +65,7 @@ private slots: void on_toolButton_2_toggled(bool checked); private: - Ui::ConnectionDialog *ui; + Ui::ConnectionDialog* ui; ConnectionDesc* m_connection; bool m_changeMode; IConnectionController* m_controller; diff --git a/limereport/databrowser/lrdatabrowser.cpp b/limereport/databrowser/lrdatabrowser.cpp index b91605f..5d49aa3 100644 --- a/limereport/databrowser/lrdatabrowser.cpp +++ b/limereport/databrowser/lrdatabrowser.cpp @@ -27,41 +27,46 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "ui_lrdatabrowser.h" -#include "lrdatabrowser.h" -#include "lrsqleditdialog.h" #include "lrconnectiondialog.h" +#include "lrdatabrowser.h" #include "lrreportengine_p.h" +#include "lrsqleditdialog.h" #include "lrvariabledialog.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -DataBrowser::DataBrowser(QWidget *parent) : +namespace LimeReport { + +DataBrowser::DataBrowser(QWidget* parent): QWidget(parent), - ui(new Ui::DataBrowser), m_report(0), m_closingWindows(false), m_settings(0), m_ownedSettings(false) + ui(new Ui::DataBrowser), + m_report(0), + m_closingWindows(false), + m_settings(0), + m_ownedSettings(false) { ui->setupUi(this); - connect(ui->addConnection,SIGNAL(clicked()),this,SLOT(slotAddConnection())); - connect(ui->deleteConection,SIGNAL(clicked()),this,SLOT(slotDeleteConnection())); - connect(ui->addDataSource,SIGNAL(clicked()),this,SLOT(slotAddDataSource())); - connect(ui->viewDataSource,SIGNAL(clicked()),this,SLOT(slotViewDatasource())); - connect(ui->editDataSource,SIGNAL(clicked()),this,SLOT(slotEditDatasource())); - connect(ui->deleteDataSource,SIGNAL(clicked()),this,SLOT(slotDeleteDatasource())); - connect(ui->changeConnection,SIGNAL(clicked()),this,SLOT(slotChangeConnection())); - connect(ui->pbConnect,SIGNAL(clicked()),this,SLOT(slotChangeConnectionState())); + connect(ui->addConnection, SIGNAL(clicked()), this, SLOT(slotAddConnection())); + connect(ui->deleteConection, SIGNAL(clicked()), this, SLOT(slotDeleteConnection())); + connect(ui->addDataSource, SIGNAL(clicked()), this, SLOT(slotAddDataSource())); + connect(ui->viewDataSource, SIGNAL(clicked()), this, SLOT(slotViewDatasource())); + connect(ui->editDataSource, SIGNAL(clicked()), this, SLOT(slotEditDatasource())); + connect(ui->deleteDataSource, SIGNAL(clicked()), this, SLOT(slotDeleteDatasource())); + connect(ui->changeConnection, SIGNAL(clicked()), this, SLOT(slotChangeConnection())); + connect(ui->pbConnect, SIGNAL(clicked()), this, SLOT(slotChangeConnectionState())); int margin = Const::DOCKWIDGET_MARGINS; ui->verticalLayout_2->setContentsMargins(margin, margin, margin, margin); @@ -76,28 +81,25 @@ DataBrowser::~DataBrowser() if (m_settings && m_ownedSettings) delete m_settings; } -QSize DataBrowser::sizeHint() const -{ - return QSize(100,200); -} +QSize DataBrowser::sizeHint() const { return QSize(100, 200); } void DataBrowser::slotAddConnection() { - ConnectionDialog *connectionEdit = new ConnectionDialog(this,0,this); - connectionEdit->setAttribute(Qt::WA_DeleteOnClose,true); + ConnectionDialog* connectionEdit = new ConnectionDialog(this, 0, this); + connectionEdit->setAttribute(Qt::WA_DeleteOnClose, true); #ifdef Q_OS_MAC connectionEdit->setWindowModality(Qt::WindowModal); #else connectionEdit->setWindowModality(Qt::ApplicationModal); #endif - //connect(connectionEdit,SIGNAL(finished(int)),this,SLOT(slotConnectionEditFinished(int))); - //connect(connectionEdit,SIGNAL(conectionRegistred(QString)),this,SLOT(slotConnectionRegistred(QString))); + // connect(connectionEdit,SIGNAL(finished(int)),this,SLOT(slotConnectionEditFinished(int))); + // connect(connectionEdit,SIGNAL(conectionRegistred(QString)),this,SLOT(slotConnectionRegistred(QString))); connectionEdit->exec(); } void DataBrowser::slotSQLEditingFinished(SQLEditResult result) { - if (result.dialogMode==SQLEditDialog::AddMode) { + if (result.dialogMode == SQLEditDialog::AddMode) { addDatasource(result); } else { applyChanges(result); @@ -107,16 +109,12 @@ void DataBrowser::slotSQLEditingFinished(SQLEditResult result) void DataBrowser::slotDeleteConnection() { - if (!getConnectionName(NameForUser).isEmpty()){ - if ( - QMessageBox::critical( - this, - tr("Attention"), - tr("Do you really want to delete \"%1\" connection?").arg(getConnectionName(NameForUser)), - QMessageBox::Ok|QMessageBox::No, - QMessageBox::No - ) == QMessageBox::Ok - ){ + if (!getConnectionName(NameForUser).isEmpty()) { + if (QMessageBox::critical(this, tr("Attention"), + tr("Do you really want to delete \"%1\" connection?") + .arg(getConnectionName(NameForUser)), + QMessageBox::Ok | QMessageBox::No, QMessageBox::No) + == QMessageBox::Ok) { m_report->dataManager()->removeConnection(getConnectionName(NameForReport)); updateDataTree(); } @@ -125,8 +123,9 @@ void DataBrowser::slotDeleteConnection() void DataBrowser::slotAddDataSource() { - SQLEditDialog *sqlEdit = new SQLEditDialog(this,m_report->dataManager(),SQLEditDialog::AddMode); - sqlEdit->setAttribute(Qt::WA_DeleteOnClose,true); + SQLEditDialog* sqlEdit + = new SQLEditDialog(this, m_report->dataManager(), SQLEditDialog::AddMode); + sqlEdit->setAttribute(Qt::WA_DeleteOnClose, true); #ifdef Q_OS_MAC sqlEdit->setWindowModality(Qt::WindowModal); #else @@ -135,7 +134,8 @@ void DataBrowser::slotAddDataSource() sqlEdit->setSettings(settings()); sqlEdit->setDataSources(m_report->dataManager()); sqlEdit->setDefaultConnection(getConnectionName(NameForReport)); - connect(sqlEdit,SIGNAL(signalSqlEditingFinished(SQLEditResult)),this,SLOT(slotSQLEditingFinished(SQLEditResult))); + connect(sqlEdit, SIGNAL(signalSqlEditingFinished(SQLEditResult)), this, + SLOT(slotSQLEditingFinished(SQLEditResult))); sqlEdit->exec(); } @@ -144,46 +144,49 @@ void DataBrowser::updateDataTree() QString selectedText = ""; int selectedType = 0; - if (ui->dataTree->selectedItems().count()==1){ + if (ui->dataTree->selectedItems().count() == 1) { selectedType = ui->dataTree->selectedItems().at(0)->type(); selectedText = ui->dataTree->selectedItems().at(0)->text(0); } initConnections(); - foreach(QString dataSourceName, m_report->datasourcesNames()){ + foreach (QString dataSourceName, m_report->datasourcesNames()) { - QTreeWidgetItem *item=new QTreeWidgetItem(QStringList(dataSourceName),DataBrowserTree::Table); - QTreeWidgetItem *parentItem = findByNameAndType( - ConnectionDesc::connectionNameForUser(m_report->dataManager()->connectionName(dataSourceName)), - DataBrowserTree::Connection - ); - if (parentItem){ + QTreeWidgetItem* item + = new QTreeWidgetItem(QStringList(dataSourceName), DataBrowserTree::Table); + QTreeWidgetItem* parentItem + = findByNameAndType(ConnectionDesc::connectionNameForUser( + m_report->dataManager()->connectionName(dataSourceName)), + DataBrowserTree::Connection); + if (parentItem) { parentItem->addChild(item); - if (!parentItem->isExpanded()) ui->dataTree->expandItem(parentItem); + if (!parentItem->isExpanded()) + ui->dataTree->expandItem(parentItem); } else { ui->dataTree->addTopLevelItem(item); } - try{ + try { IDataSource* datasource = m_report->dataManager()->dataSource(dataSourceName); - if (datasource){ - fillFields(item,datasource); + if (datasource) { + fillFields(item, datasource); if (!datasource->isInvalid()) - item->setIcon(0,QIcon(":/databrowser/images/table_good")); + item->setIcon(0, QIcon(":/databrowser/images/table_good")); else - item->setIcon(0,QIcon(":/databrowser/images/table_error")); + item->setIcon(0, QIcon(":/databrowser/images/table_error")); - } else item->setIcon(0,QIcon(":/databrowser/images/table_error")); + } else + item->setIcon(0, QIcon(":/databrowser/images/table_error")); - } catch(ReportError& /*exception*/) { - item->setIcon(0,QIcon(":/databrowser/images/table_error")); - //qDebug()<setIcon(0, QIcon(":/databrowser/images/table_error")); + // qDebug()<setSelected(true); ui->dataTree->setCurrentItem(selectedItem); } @@ -192,39 +195,43 @@ void DataBrowser::updateDataTree() void DataBrowser::updateVariablesTree() { ui->variablesTree->clear(); - QTreeWidgetItem *reportVariables = new QTreeWidgetItem(QStringList(tr("Report variables")),DataBrowserTree::Category); - reportVariables->setIcon(0,QIcon(":/report/images/folder")); - QTreeWidgetItem *systemVariables =new QTreeWidgetItem(QStringList(tr("System variables")),DataBrowserTree::Category); - systemVariables->setIcon(0,QIcon(":/report/images/folder")); - QTreeWidgetItem *externalVariables = new QTreeWidgetItem(QStringList(tr("External variables")),DataBrowserTree::Category); - externalVariables->setIcon(0,QIcon(":/report/images/folder")); + QTreeWidgetItem* reportVariables + = new QTreeWidgetItem(QStringList(tr("Report variables")), DataBrowserTree::Category); + reportVariables->setIcon(0, QIcon(":/report/images/folder")); + QTreeWidgetItem* systemVariables + = new QTreeWidgetItem(QStringList(tr("System variables")), DataBrowserTree::Category); + systemVariables->setIcon(0, QIcon(":/report/images/folder")); + QTreeWidgetItem* externalVariables + = new QTreeWidgetItem(QStringList(tr("External variables")), DataBrowserTree::Category); + externalVariables->setIcon(0, QIcon(":/report/images/folder")); ui->variablesTree->addTopLevelItem(reportVariables); ui->variablesTree->addTopLevelItem(systemVariables); ui->variablesTree->addTopLevelItem(externalVariables); - foreach(QString variableName,m_report->dataManager()->variableNames()){ + foreach (QString variableName, m_report->dataManager()->variableNames()) { QStringList values; - values<dataManager()->variableIsSystem(variableName))? - "": - " ["+m_report->dataManager()->variable(variableName).toString()+"]" - ) - <setIcon(0,QIcon(":/databrowser/images/value")); - if (m_report->dataManager()->variableIsSystem(variableName)){ - systemVariables->addChild(item); + values << variableName + + ((m_report->dataManager()->variableIsSystem(variableName)) + ? "" + : " [" + m_report->dataManager()->variable(variableName).toString() + "]") + << variableName; + QTreeWidgetItem* item = new QTreeWidgetItem(values, DataBrowserTree::Variable); + item->setIcon(0, QIcon(":/databrowser/images/value")); + if (m_report->dataManager()->variableIsSystem(variableName)) { + systemVariables->addChild(item); } else { reportVariables->addChild(item); } } - foreach(QString variableName,m_report->dataManager()->userVariableNames()){ - if (!m_report->dataManager()->variableNames().contains(variableName)){ + foreach (QString variableName, m_report->dataManager()->userVariableNames()) { + if (!m_report->dataManager()->variableNames().contains(variableName)) { QStringList values; - values<dataManager()->variable(variableName).toString()+"]" - <setIcon(0,QIcon(":/databrowser/images/value")); + values << variableName + " [" + + m_report->dataManager()->variable(variableName).toString() + "]" + << variableName; + QTreeWidgetItem* item = new QTreeWidgetItem(values, DataBrowserTree::ExternalVariable); + item->setIcon(0, QIcon(":/databrowser/images/value")); externalVariables->addChild(item); } } @@ -237,8 +244,8 @@ void DataBrowser::updateVariablesTree() void DataBrowser::closeAllDataWindows() { m_closingWindows = true; - QMap::iterator it = m_dataWindows.begin(); - for(;it!=m_dataWindows.end();){ + QMap::iterator it = m_dataWindows.begin(); + for (; it != m_dataWindows.end();) { (*it)->close(); delete (*it); it = m_dataWindows.erase(it); @@ -246,47 +253,51 @@ void DataBrowser::closeAllDataWindows() m_closingWindows = false; } -void DataBrowser::setSettings(QSettings *value, bool owned) +void DataBrowser::setSettings(QSettings* value, bool owned) { - if (m_settings && m_ownedSettings) delete m_settings; - m_settings=value; + if (m_settings && m_ownedSettings) + delete m_settings; + m_settings = value; m_ownedSettings = owned; } -QSettings *DataBrowser::settings() +QSettings* DataBrowser::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_settings = new QSettings("LimeReport", QCoreApplication::applicationName()); m_ownedSettings = true; return m_settings; } } -void DataBrowser::slotDatasourcesChanged() -{ - updateDataTree(); -} +void DataBrowser::slotDatasourcesChanged() { updateDataTree(); } -void DataBrowser::fillFields(QTreeWidgetItem *parentItem, LimeReport::IDataSource *dataSource) +void DataBrowser::fillFields(QTreeWidgetItem* parentItem, LimeReport::IDataSource* dataSource) { - if (!dataSource) return; - for (int i=0;icolumnCount();i++){ - QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(dataSource->columnNameByIndex(i)),DataBrowserTree::Row); - item->setIcon(0,QIcon(":/databrowser/images/field")); + if (!dataSource) + return; + for (int i = 0; i < dataSource->columnCount(); i++) { + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(dataSource->columnNameByIndex(i)), + DataBrowserTree::Row); + item->setIcon(0, QIcon(":/databrowser/images/field")); parentItem->addChild(item); } - parentItem->sortChildren(0,Qt::AscendingOrder); + parentItem->sortChildren(0, Qt::AscendingOrder); } -QTreeWidgetItem * DataBrowser::findByNameAndType(QString name, int itemType) +QTreeWidgetItem* DataBrowser::findByNameAndType(QString name, int itemType) { - if (name.isEmpty()) return 0; - QListitems = ui->dataTree->findItems(name,Qt::MatchContains | Qt::MatchRecursive); - if (!items.isEmpty()){ - for (int i=0;itype()==itemType)/* && (items.at(0)->text(0)==name)*/){ return items.at(i);} + if (name.isEmpty()) + return 0; + QList items + = ui->dataTree->findItems(name, Qt::MatchContains | Qt::MatchRecursive); + if (!items.isEmpty()) { + for (int i = 0; i < items.count(); i++) { + if ((items.at(i)->type() == itemType) /* && (items.at(0)->text(0)==name)*/) { + return items.at(i); + } } } return 0; @@ -294,23 +305,26 @@ QTreeWidgetItem * DataBrowser::findByNameAndType(QString name, int itemType) void DataBrowser::slotViewDatasource() { - QString datasourceName=getDatasourceName(); - if (!datasourceName.isEmpty()){ + QString datasourceName = getDatasourceName(); + if (!datasourceName.isEmpty()) { showDataWindow(datasourceName); } } QString DataBrowser::getDatasourceName() { - if (ui->dataTree->currentItem()){ - if (ui->dataTree->currentItem()->type() == DataBrowserTree::Table) return ui->dataTree->currentItem()->text(0); - if (ui->dataTree->currentItem()->type() == DataBrowserTree::Row) return ui->dataTree->currentItem()->parent()->text(0); + if (ui->dataTree->currentItem()) { + if (ui->dataTree->currentItem()->type() == DataBrowserTree::Table) + return ui->dataTree->currentItem()->text(0); + if (ui->dataTree->currentItem()->type() == DataBrowserTree::Row) + return ui->dataTree->currentItem()->parent()->text(0); }; return QString(); } -QTreeWidgetItem* findConnectionItem(QTreeWidgetItem* item){ - if (item->type() == DataBrowserTree::Connection){ +QTreeWidgetItem* findConnectionItem(QTreeWidgetItem* item) +{ + if (item->type() == DataBrowserTree::Connection) { return item; } else { if (item->parent()) @@ -322,8 +336,8 @@ QTreeWidgetItem* findConnectionItem(QTreeWidgetItem* item){ QString DataBrowser::getConnectionName(NameType nameType) { - if (ui->dataTree->currentItem()){ - QTreeWidgetItem * ci = findConnectionItem(ui->dataTree->currentItem()); + if (ui->dataTree->currentItem()) { + QTreeWidgetItem* ci = findConnectionItem(ui->dataTree->currentItem()); if (ci) { switch (nameType) { case NameForUser: @@ -331,19 +345,17 @@ QString DataBrowser::getConnectionName(NameType nameType) case NameForReport: return ConnectionDesc::connectionNameForReport(ci->text(0)); } - } - else return QString(); + } else + return QString(); }; return QString(); } QString DataBrowser::getVariable() { - if( - ui->variablesTree->currentItem() && - (ui->variablesTree->currentItem()->type() == DataBrowserTree::Variable || - ui->variablesTree->currentItem()->type() == DataBrowserTree::ExternalVariable) - ){ + if (ui->variablesTree->currentItem() + && (ui->variablesTree->currentItem()->type() == DataBrowserTree::Variable + || ui->variablesTree->currentItem()->type() == DataBrowserTree::ExternalVariable)) { return ui->variablesTree->currentItem()->text(1); } return QString(); @@ -351,46 +363,45 @@ QString DataBrowser::getVariable() void DataBrowser::slotEditDatasource() { - if (!getDatasourceName().isEmpty()){ - closeDataWindow(getDatasourceName()); - SQLEditDialog *sqlEdit = new SQLEditDialog(this,m_report->dataManager(),SQLEditDialog::EditMode); - sqlEdit->setAttribute(Qt::WA_DeleteOnClose); + if (!getDatasourceName().isEmpty()) { + closeDataWindow(getDatasourceName()); + SQLEditDialog* sqlEdit + = new SQLEditDialog(this, m_report->dataManager(), SQLEditDialog::EditMode); + sqlEdit->setAttribute(Qt::WA_DeleteOnClose); #ifdef Q_OS_MAC - sqlEdit->setWindowModality(Qt::WindowModal); + sqlEdit->setWindowModality(Qt::WindowModal); #else - sqlEdit->setWindowModality(Qt::ApplicationModal); + sqlEdit->setWindowModality(Qt::ApplicationModal); #endif - sqlEdit->setSettings(settings()); - sqlEdit->setDataSources(m_report->dataManager(),getDatasourceName()); - connect(sqlEdit,SIGNAL(signalSqlEditingFinished(SQLEditResult)),this,SLOT(slotSQLEditingFinished(SQLEditResult))); - sqlEdit->exec(); + sqlEdit->setSettings(settings()); + sqlEdit->setDataSources(m_report->dataManager(), getDatasourceName()); + connect(sqlEdit, SIGNAL(signalSqlEditingFinished(SQLEditResult)), this, + SLOT(slotSQLEditingFinished(SQLEditResult))); + sqlEdit->exec(); } } void DataBrowser::slotDeleteDatasource() { - QString datasourceName=getDatasourceName(); - QTreeWidgetItem *item = findByNameAndType(datasourceName, DataBrowserTree::Table); - if (item){ - if ( - QMessageBox::critical( - this, - tr("Attention"), - tr("Do you really want to delete \"%1\" datasource?").arg(datasourceName), - QMessageBox::Ok|QMessageBox::No, - QMessageBox::No - ) == QMessageBox::Ok - ){ + QString datasourceName = getDatasourceName(); + QTreeWidgetItem* item = findByNameAndType(datasourceName, DataBrowserTree::Table); + if (item) { + if (QMessageBox::critical( + this, tr("Attention"), + tr("Do you really want to delete \"%1\" datasource?").arg(datasourceName), + QMessageBox::Ok | QMessageBox::No, QMessageBox::No) + == QMessageBox::Ok) { removeDatasource(datasourceName); } } } -void DataBrowser::setReportEditor(LimeReport::ReportDesignWidget *report) +void DataBrowser::setReportEditor(LimeReport::ReportDesignWidget* report) { - m_report=report; - connect(m_report,SIGNAL(cleared()),this,SLOT(slotClear())); - connect(m_report->dataManager(), SIGNAL(datasourcesChanged()), this, SLOT(slotDatasourcesChanged())); + m_report = report; + connect(m_report, SIGNAL(cleared()), this, SLOT(slotClear())); + connect(m_report->dataManager(), SIGNAL(datasourcesChanged()), this, + SLOT(slotDatasourcesChanged())); updateDataTree(); updateVariablesTree(); } @@ -398,7 +409,8 @@ void DataBrowser::setReportEditor(LimeReport::ReportDesignWidget *report) void DataBrowser::slotClear() { ui->dataTree->clear(); - foreach(QDockWidget* window,m_dataWindows.values()) window->close(); + foreach (QDockWidget* window, m_dataWindows.values()) + window->close(); updateDataTree(); updateVariablesTree(); } @@ -406,110 +418,107 @@ void DataBrowser::slotClear() void DataBrowser::initConnections() { ui->dataTree->clear(); - QListitems; + QList items; QStringList connections = QSqlDatabase::connectionNames(); - foreach(QString connectionName, m_report->dataManager()->connectionNames()){ - if (!connections.contains(connectionName,Qt::CaseInsensitive)){ + foreach (QString connectionName, m_report->dataManager()->connectionNames()) { + if (!connections.contains(connectionName, Qt::CaseInsensitive)) { connections.append(connectionName); } } std::sort(connections.begin(), connections.end()); foreach (QString connectionName, connections) { - QTreeWidgetItem *item=new QTreeWidgetItem( - ui->dataTree, - QStringList(ConnectionDesc::connectionNameForUser(connectionName)), - DataBrowserTree::Connection - ); - if (!m_report->dataManager()->connectionNames().contains(ConnectionDesc::connectionNameForReport(connectionName), Qt::CaseInsensitive)) - { - item->setIcon(0,QIcon(":/databrowser/images/database_connected")); + QTreeWidgetItem* item = new QTreeWidgetItem( + ui->dataTree, QStringList(ConnectionDesc::connectionNameForUser(connectionName)), + DataBrowserTree::Connection); + if (!m_report->dataManager()->connectionNames().contains( + ConnectionDesc::connectionNameForReport(connectionName), Qt::CaseInsensitive)) { + item->setIcon(0, QIcon(":/databrowser/images/database_connected")); } else { if (m_report->dataManager()->isConnectionConnected(connectionName)) - item->setIcon(0,QIcon(":/databrowser/images/database_connected")); + item->setIcon(0, QIcon(":/databrowser/images/database_connected")); else - item->setIcon(0,QIcon(":/databrowser/images/database_disconnected")); + item->setIcon(0, QIcon(":/databrowser/images/database_disconnected")); } items.append(item); } + // foreach (QString connectionName, connections) { + // QTreeWidgetItem *item=new QTreeWidgetItem( + // ui->dataTree, + // QStringList(ConnectionDesc::connectionNameForUser(connectionName)), + // DataBrowserTree::Connection + // ); + // item->setIcon(0,QIcon(":/databrowser/images/database_connected")); + // } -// foreach (QString connectionName, connections) { -// QTreeWidgetItem *item=new QTreeWidgetItem( -// ui->dataTree, -// QStringList(ConnectionDesc::connectionNameForUser(connectionName)), -// DataBrowserTree::Connection -// ); -// item->setIcon(0,QIcon(":/databrowser/images/database_connected")); -// } - -// connections = m_report->dataManager()->connectionNames(); -// std::sort(connections); -// foreach(QString connectionName,connectionName){ -// if (!QSqlDatabase::contains(connectionName)){ -// QTreeWidgetItem *item=new QTreeWidgetItem( -// ui->dataTree, -// QStringList(ConnectionDesc::connectionNameForUser(connectionName)), -// DataBrowserTree::Connection -// ); -// if (m_report->dataManager()->isConnectionConnected(connectionName)) -// item->setIcon(0,QIcon(":/databrowser/images/database_connected")); -// else -// item->setIcon(0,QIcon(":/databrowser/images/database_disconnected")); -// items.append(item); -// } -// } - ui->dataTree->insertTopLevelItems(0,items); + // connections = m_report->dataManager()->connectionNames(); + // std::sort(connections); + // foreach(QString connectionName,connectionName){ + // if (!QSqlDatabase::contains(connectionName)){ + // QTreeWidgetItem *item=new QTreeWidgetItem( + // ui->dataTree, + // QStringList(ConnectionDesc::connectionNameForUser(connectionName)), + // DataBrowserTree::Connection + // ); + // if (m_report->dataManager()->isConnectionConnected(connectionName)) + // item->setIcon(0,QIcon(":/databrowser/images/database_connected")); + // else + // item->setIcon(0,QIcon(":/databrowser/images/database_disconnected")); + // items.append(item); + // } + // } + ui->dataTree->insertTopLevelItems(0, items); } -QDockWidget *DataBrowser::createDataWindow(QString datasourceName) +QDockWidget* DataBrowser::createDataWindow(QString datasourceName) { - QDockWidget *window = new QDockWidget("Table: "+datasourceName); - QTableView *tableView = new QTableView(window); - //TODO: exception or message ? + QDockWidget* window = new QDockWidget("Table: " + datasourceName); + QTableView* tableView = new QTableView(window); + // TODO: exception or message ? try { IDataSourceHolder* holder = m_report->dataManager()->dataSourceHolder(datasourceName); - if (holder) holder->update(); + if (holder) + holder->update(); IDataSource* datasource = m_report->dataManager()->dataSource(datasourceName); - if (datasource){ + if (datasource) { tableView->setModel(datasource->model()); } } catch (ReportError& exception) { - qDebug()<setWidget(tableView); window->setAttribute(Qt::WA_DeleteOnClose); - connect(window,SIGNAL(destroyed()),this,SLOT(slotDataWindowClosed())); + connect(window, SIGNAL(destroyed()), this, SLOT(slotDataWindowClosed())); if (!m_dataWindows.isEmpty()) - m_mainWindow->tabifyDockWidget(m_dataWindows.values().at(0),window); + m_mainWindow->tabifyDockWidget(m_dataWindows.values().at(0), window); else - m_mainWindow->addDockWidget(Qt::BottomDockWidgetArea,window); + m_mainWindow->addDockWidget(Qt::BottomDockWidgetArea, window); - m_dataWindows.insert(datasourceName,window); + m_dataWindows.insert(datasourceName, window); return window; } -QDockWidget *DataBrowser::dataWindow(QString datasourceName) +QDockWidget* DataBrowser::dataWindow(QString datasourceName) { - if (m_dataWindows.contains(datasourceName)){ + if (m_dataWindows.contains(datasourceName)) { return m_dataWindows.value(datasourceName); - } else return createDataWindow(datasourceName); + } else + return createDataWindow(datasourceName); } -void DataBrowser::setMainWindow(QMainWindow *mainWindow) -{ - m_mainWindow=mainWindow; -} +void DataBrowser::setMainWindow(QMainWindow* mainWindow) { m_mainWindow = mainWindow; } void DataBrowser::slotDataWindowClosed() { - if (isClosingWindows()) return; - for (int i=0;idataManager()->connectionByName(getConnectionName(NameForReport)), - this - ); - connectionEdit->setAttribute(Qt::WA_DeleteOnClose,true); + if (!getConnectionName(NameForUser).isEmpty()) { + ConnectionDialog* connectionEdit = new ConnectionDialog( + this, m_report->dataManager()->connectionByName(getConnectionName(NameForReport)), + this); + connectionEdit->setAttribute(Qt::WA_DeleteOnClose, true); #ifdef Q_OS_MAC connectionEdit->setWindowModality(Qt::WindowModal); #else connectionEdit->setWindowModality(Qt::ApplicationModal); #endif - //connect(connectionEdit,SIGNAL(finished(int)),this,SLOT(slotConnectionEditFinished(int))); + // connect(connectionEdit,SIGNAL(finished(int)),this,SLOT(slotConnectionEditFinished(int))); connectionEdit->exec(); } } @@ -537,14 +544,14 @@ void DataBrowser::slotChangeConnection() void DataBrowser::slotChangeConnectionState() { QString connectionName = getConnectionName(NameForReport); - if (!connectionName.isEmpty()){ - if (!m_report->dataManager()->isConnectionConnected(connectionName)){ + if (!connectionName.isEmpty()) { + if (!m_report->dataManager()->isConnectionConnected(connectionName)) { setCursor(Qt::WaitCursor); - //try { - if (!m_report->dataManager()->connectConnection(connectionName)){ - //} catch(std::runtime_error &exception) { - QMessageBox::critical(this,tr("Attention"),m_report->dataManager()->lastError()); - //} + // try { + if (!m_report->dataManager()->connectConnection(connectionName)) { + //} catch(std::runtime_error &exception) { + QMessageBox::critical(this, tr("Attention"), m_report->dataManager()->lastError()); + //} } updateDataTree(); setCursor(Qt::ArrowCursor); @@ -555,19 +562,20 @@ void DataBrowser::slotChangeConnectionState() } } -void DataBrowser::slotVariableEditorAccept(const QString &variable) +void DataBrowser::slotVariableEditorAccept(const QString& variable) { updateVariablesTree(); - QList items = ui->variablesTree->findItems(variable, Qt::MatchContains | Qt::MatchRecursive); - if (!items.isEmpty()){ + QList items + = ui->variablesTree->findItems(variable, Qt::MatchContains | Qt::MatchRecursive); + if (!items.isEmpty()) { ui->variablesTree->setCurrentItem(items.at(0)); } } void DataBrowser::showDataWindow(QString datasourceName) { - QDockWidget *window = dataWindow(datasourceName); - if (window){ + QDockWidget* window = dataWindow(datasourceName); + if (window) { window->show(); window->raise(); } @@ -589,8 +597,8 @@ void DataBrowser::addQuery(SQLEditResult result) { try { m_report->dataManager()->addQuery(result.datasourceName, result.sql, result.connectionName); - } catch(ReportError &exception){ - qDebug()<dataManager()->removeDatasource(result.oldDatasourceName); addQuery(result); - } catch(ReportError &exception){ - qDebug()<dataManager()->addSubQuery(result.datasourceName, result.sql, result.connectionName, result.masterDatasource); - } catch(ReportError &exception){ - qDebug()<dataManager()->addSubQuery(result.datasourceName, result.sql, + result.connectionName, result.masterDatasource); + } catch (ReportError& exception) { + qDebug() << exception.what(); } } @@ -618,17 +627,18 @@ void DataBrowser::changeSubQuery(SQLEditResult result) try { m_report->dataManager()->removeDatasource(result.oldDatasourceName); addSubQuery(result); - } catch(ReportError &exception){ - qDebug()<dataManager()->addProxy(result.datasourceName,result.masterDatasource,result.childDataSource,result.fieldMap); - } catch(ReportError &exception){ - qDebug()<dataManager()->addProxy(result.datasourceName, result.masterDatasource, + result.childDataSource, result.fieldMap); + } catch (ReportError& exception) { + qDebug() << exception.what(); } } @@ -637,22 +647,18 @@ void DataBrowser::changeProxy(SQLEditResult result) try { m_report->dataManager()->removeDatasource(result.oldDatasourceName); addProxy(result); - } catch(ReportError &exception){ - qDebug()<dataManager()->addCSV( - result.datasourceName, - result.csv, - result.separator, - result.firstRowIsHeader - ); - } catch(ReportError &exception){ - qDebug()<dataManager()->addCSV(result.datasourceName, result.csv, result.separator, + result.firstRowIsHeader); + } catch (ReportError& exception) { + qDebug() << exception.what(); } } @@ -661,38 +667,42 @@ void DataBrowser::changeCSV(SQLEditResult result) try { m_report->dataManager()->removeDatasource(result.oldDatasourceName); addCSV(result); - } catch(ReportError &exception){ - qDebug()<dataManager()->isQuery(datasourceName)) return SQLEditResult::Query; - if (m_report->dataManager()->isSubQuery(datasourceName)) return SQLEditResult::SubQuery; - if (m_report->dataManager()->isProxy(datasourceName)) return SQLEditResult::SubProxy; - if (m_report->dataManager()->isCSV(datasourceName)) return SQLEditResult::CSVText; + if (m_report->dataManager()->isQuery(datasourceName)) + return SQLEditResult::Query; + if (m_report->dataManager()->isSubQuery(datasourceName)) + return SQLEditResult::SubQuery; + if (m_report->dataManager()->isProxy(datasourceName)) + return SQLEditResult::SubProxy; + if (m_report->dataManager()->isCSV(datasourceName)) + return SQLEditResult::CSVText; return SQLEditResult::Undefined; } - void DataBrowser::applyChanges(SQLEditResult result) { - if (result.resultMode == currentDatasourceType(result.oldDatasourceName)){ - switch(result.resultMode){ - case SQLEditResult::Query: - changeQuery(result); - break; - case SQLEditResult::SubQuery: - changeSubQuery(result); - break; - case SQLEditResult::SubProxy: - changeProxy(result); - break; - case SQLEditResult::CSVText: - changeCSV(result); - break; - default: break; + if (result.resultMode == currentDatasourceType(result.oldDatasourceName)) { + switch (result.resultMode) { + case SQLEditResult::Query: + changeQuery(result); + break; + case SQLEditResult::SubQuery: + changeSubQuery(result); + break; + case SQLEditResult::SubProxy: + changeProxy(result); + break; + case SQLEditResult::CSVText: + changeCSV(result); + break; + default: + break; } } else { removeDatasource(result.oldDatasourceName); @@ -704,81 +714,81 @@ void DataBrowser::applyChanges(SQLEditResult result) void DataBrowser::addDatasource(SQLEditResult result) { switch (result.resultMode) { - case SQLEditResult::Query: - addQuery(result); - break; - case SQLEditResult::SubQuery: - addSubQuery(result); - break; - case SQLEditResult::SubProxy: - addProxy(result); - break; - case SQLEditResult::CSVText: - addCSV(result); - break; - default: - break; + case SQLEditResult::Query: + addQuery(result); + break; + case SQLEditResult::SubQuery: + addSubQuery(result); + break; + case SQLEditResult::SubProxy: + addProxy(result); + break; + case SQLEditResult::CSVText: + addCSV(result); + break; + default: + break; } activateItem(result.datasourceName, DataBrowserTree::Table); } -void DataBrowser::activateItem(const QString& name, DataBrowserTree::NodeType type){ +void DataBrowser::activateItem(const QString& name, DataBrowserTree::NodeType type) +{ QTreeWidgetItem* item = findByNameAndType(name, type); if (item) item->treeWidget()->setCurrentItem(item); } -void DataBrowser::addConnectionDesc(ConnectionDesc *connection) +void DataBrowser::addConnectionDesc(ConnectionDesc* connection) { m_report->dataManager()->addConnectionDesc(connection); updateDataTree(); activateItem(connection->name(), DataBrowserTree::Connection); } -void DataBrowser::changeConnectionDesc(ConnectionDesc *connection) +void DataBrowser::changeConnectionDesc(ConnectionDesc* connection) { - if (connection->autoconnect()) m_report->dataManager()->connectConnection(connection->name()); + if (connection->autoconnect()) + m_report->dataManager()->connectConnection(connection->name()); updateDataTree(); activateItem(connection->name(), DataBrowserTree::Connection); } -bool DataBrowser::checkConnectionDesc(ConnectionDesc *connection) +bool DataBrowser::checkConnectionDesc(ConnectionDesc* connection) { bool result = m_report->dataManager()->checkConnectionDesc(connection); - if (!result) setLastError(m_report->dataManager()->lastError()); + if (!result) + setLastError(m_report->dataManager()->lastError()); return result; } bool DataBrowser::containsDefaultConnection() { - bool result = m_report->dataManager()->connectionByName(QSqlDatabase::defaultConnection) || - QSqlDatabase::contains(QSqlDatabase::defaultConnection); + bool result = m_report->dataManager()->connectionByName(QSqlDatabase::defaultConnection) + || QSqlDatabase::contains(QSqlDatabase::defaultConnection); return result; } -QString DataBrowser::lastError() const -{ - return m_lastError; -} +QString DataBrowser::lastError() const { return m_lastError; } -void DataBrowser::setLastError(const QString &lastError) -{ - m_lastError = lastError; -} +void DataBrowser::setLastError(const QString& lastError) { m_lastError = lastError; } -void DataBrowser::on_dataTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) +void DataBrowser::on_dataTree_currentItemChanged(QTreeWidgetItem* current, + QTreeWidgetItem* previous) { Q_UNUSED(previous) - if (current&&(current->type() == DataBrowserTree::Connection)) { - bool internalConnection = m_report->dataManager()->connectionByName(ConnectionDesc::connectionNameForReport(current->text(0))); - if (m_report->dataManager()->isConnectionConnected(ConnectionDesc::connectionNameForReport(current->text(0)))){ + if (current && (current->type() == DataBrowserTree::Connection)) { + bool internalConnection = m_report->dataManager()->connectionByName( + ConnectionDesc::connectionNameForReport(current->text(0))); + if (m_report->dataManager()->isConnectionConnected( + ConnectionDesc::connectionNameForReport(current->text(0)))) { ui->pbConnect->setIcon(QIcon(":/databrowser/images/plug-connect.png")); } else { ui->pbConnect->setIcon(QIcon(":/databrowser/images/plug-disconnect.png")); } ui->editDataSource->setEnabled(false); ui->deleteDataSource->setEnabled(false); - ui->viewDataSource->setEnabled(false); + ui->viewDataSource->setEnabled(false); ui->pbConnect->setEnabled(internalConnection); ui->changeConnection->setEnabled(internalConnection); ui->deleteConection->setEnabled(internalConnection); @@ -788,13 +798,15 @@ void DataBrowser::on_dataTree_currentItemChanged(QTreeWidgetItem *current, QTree ui->deleteConection->setEnabled(false); ui->pbConnect->setEnabled(false); IDataSourceHolder* holder = m_report->dataManager()->dataSourceHolder(getDatasourceName()); - if (holder){ + if (holder) { ui->viewDataSource->setEnabled(!holder->isInvalid()); ui->editDataSource->setEnabled(holder->isEditable()); ui->deleteDataSource->setEnabled(holder->isRemovable()); - if (!holder->lastError().isEmpty()){ + if (!holder->lastError().isEmpty()) { ui->errorMessage->setEnabled(true); - } else {ui->errorMessage->setEnabled(false);} + } else { + ui->errorMessage->setEnabled(false); + } } } } @@ -808,15 +820,14 @@ void LimeReport::DataBrowser::on_addVariable_clicked() dialog.setWindowModality(Qt::ApplicationModal); #endif dialog.setVariableContainer(m_report->dataManager()); - connect(&dialog,SIGNAL(signalVariableAccepted(QString)),this,SLOT(slotVariableEditorAccept(QString))); + connect(&dialog, SIGNAL(signalVariableAccepted(QString)), this, + SLOT(slotVariableEditorAccept(QString))); dialog.exec(); - } void DataBrowser::on_editVariable_clicked() { - if (!getVariable().isEmpty()) - { + if (!getVariable().isEmpty()) { LRVariableDialog dialog(this); #ifdef Q_OS_MAC dialog.setWindowModality(Qt::WindowModal); @@ -826,7 +837,8 @@ void DataBrowser::on_editVariable_clicked() dialog.setVariableContainer(m_report->dataManager()); QString varName = getVariable(); dialog.setVariableName(varName); - connect(&dialog,SIGNAL(signalVariableAccepted(QString)),this,SLOT(slotVariableEditorAccept(QString))); + connect(&dialog, SIGNAL(signalVariableAccepted(QString)), this, + SLOT(slotVariableEditorAccept(QString))); dialog.exec(); } } @@ -834,33 +846,36 @@ void DataBrowser::on_editVariable_clicked() void DataBrowser::on_deleteVariable_clicked() { QString varName = getVariable(); - if (!varName.isEmpty()){ - if (QMessageBox::critical(this,tr("Attention"),QString(tr("Do you really want to delete variable \"%1\"?")).arg(varName), - QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel - )==QMessageBox::Ok){ + if (!varName.isEmpty()) { + if (QMessageBox::critical( + this, tr("Attention"), + QString(tr("Do you really want to delete variable \"%1\"?")).arg(varName), + QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) + == QMessageBox::Ok) { m_report->dataManager()->deleteVariable(varName); updateVariablesTree(); } } } -void DataBrowser::on_variablesTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) +void DataBrowser::on_variablesTree_currentItemChanged(QTreeWidgetItem* current, + QTreeWidgetItem* previous) { Q_UNUSED(previous) - if (current){ - if (m_report->dataManager()->containsVariable(current->text(1))){ - if (m_report->dataManager()->variableType(current->text(1)) == VarDesc::Report){ + if (current) { + if (m_report->dataManager()->containsVariable(current->text(1))) { + if (m_report->dataManager()->variableType(current->text(1)) == VarDesc::Report) { ui->editVariable->setEnabled(true); ui->deleteVariable->setEnabled(true); } else { ui->editVariable->setEnabled(false); ui->deleteVariable->setEnabled(false); } - if (m_report->dataManager()->variableType(current->text(1)) == VarDesc::User){ - ui->varToReport->setEnabled(true); - } else { - ui->varToReport->setEnabled(false); - } + if (m_report->dataManager()->variableType(current->text(1)) == VarDesc::User) { + ui->varToReport->setEnabled(true); + } else { + ui->varToReport->setEnabled(false); + } } else { ui->editVariable->setEnabled(false); ui->deleteVariable->setEnabled(false); @@ -871,39 +886,41 @@ void DataBrowser::on_variablesTree_currentItemChanged(QTreeWidgetItem *current, void DataBrowser::on_errorMessage_clicked() { - if(!getDatasourceName().isEmpty()&&m_report->dataManager()->dataSourceHolder(getDatasourceName())){ - QMessageBox::critical(this,tr("Error"),m_report->dataManager()->dataSourceHolder(getDatasourceName())->lastError()); + if (!getDatasourceName().isEmpty() + && m_report->dataManager()->dataSourceHolder(getDatasourceName())) { + QMessageBox::critical( + this, tr("Error"), + m_report->dataManager()->dataSourceHolder(getDatasourceName())->lastError()); } } void DataBrowser::on_varToReport_clicked() { QString varName = getVariable(); - if (!varName.isEmpty()){ - m_report->dataManager()->addVariable(varName,m_report->dataManager()->variable(varName), VarDesc::Report); + if (!varName.isEmpty()) { + m_report->dataManager()->addVariable(varName, m_report->dataManager()->variable(varName), + VarDesc::Report); ui->varToReport->setEnabled(false); updateVariablesTree(); } - } -void DataBrowser::on_variablesTree_itemDoubleClicked(QTreeWidgetItem *item, int ) +void DataBrowser::on_variablesTree_itemDoubleClicked(QTreeWidgetItem* item, int) { - if (item){ + if (item) { QString varName = item->text(1); - if ( - !varName.isEmpty() && - (m_report->dataManager()->variableType(varName) == VarDesc::Report) - ){ + if (!varName.isEmpty() + && (m_report->dataManager()->variableType(varName) == VarDesc::Report)) { LRVariableDialog dialog(this); - #ifdef Q_OS_MAC +#ifdef Q_OS_MAC dialog.setWindowModality(Qt::WindowModal); - #else +#else dialog.setWindowModality(Qt::ApplicationModal); - #endif +#endif dialog.setVariableContainer(m_report->dataManager()); dialog.setVariableName(varName); - connect(&dialog,SIGNAL(signalVariableAccepted(QString)),this,SLOT(slotVariableEditorAccept(QString))); + connect(&dialog, SIGNAL(signalVariableAccepted(QString)), this, + SLOT(slotVariableEditorAccept(QString))); dialog.exec(); } } diff --git a/limereport/databrowser/lrdatabrowser.h b/limereport/databrowser/lrdatabrowser.h index edab5ef..ac3dc86 100644 --- a/limereport/databrowser/lrdatabrowser.h +++ b/limereport/databrowser/lrdatabrowser.h @@ -30,27 +30,25 @@ #ifndef LRDATABROWSER_H #define LRDATABROWSER_H -#include -#include -#include -#include - +#include "lrdatabrowsertree.h" #include "lrreportdesignwidget.h" #include "lrsqleditdialog.h" -#include "lrdatabrowsertree.h" -namespace LimeReport{ +#include +#include +#include +#include + +namespace LimeReport { namespace Ui { class DataBrowser; } -class DataBrowser : public QWidget, public IConnectionController -{ +class DataBrowser: public QWidget, public IConnectionController { Q_OBJECT public: - - explicit DataBrowser(QWidget *parent = 0); + explicit DataBrowser(QWidget* parent = 0); ~DataBrowser(); QSize sizeHint() const; void setReportEditor(LimeReport::ReportDesignWidget* report); @@ -62,7 +60,7 @@ public: void setSettings(QSettings* value, bool owned = false); QSettings* settings(); QString lastError() const; - void setLastError(const QString &lastError); + void setLastError(const QString& lastError); private slots: void slotDatasourcesChanged(); @@ -77,24 +75,27 @@ private slots: void slotDataWindowClosed(); void slotChangeConnection(); void slotChangeConnectionState(); - void slotVariableEditorAccept(const QString &variable); - void on_dataTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + void slotVariableEditorAccept(const QString& variable); + void on_dataTree_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous); void on_editVariable_clicked(); void on_deleteVariable_clicked(); void on_addVariable_clicked(); - void on_variablesTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + void on_variablesTree_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous); void on_errorMessage_clicked(); void on_varToReport_clicked(); - void on_variablesTree_itemDoubleClicked(QTreeWidgetItem *item, int); + void on_variablesTree_itemDoubleClicked(QTreeWidgetItem* item, int); private: - enum NameType{NameForUser, NameForReport}; + enum NameType { + NameForUser, + NameForReport + }; QString getDatasourceName(); QString getConnectionName(NameType nameType); QString getVariable(); - bool isClosingWindows() const {return m_closingWindows;} - QTreeWidgetItem * findByNameAndType(QString name, int itemType); - void fillFields(QTreeWidgetItem *parentItem, LimeReport::IDataSource *dataSource); + bool isClosingWindows() const { return m_closingWindows; } + QTreeWidgetItem* findByNameAndType(QString name, int itemType); + void fillFields(QTreeWidgetItem* parentItem, LimeReport::IDataSource* dataSource); QDockWidget* createDataWindow(QString datasourceName); void closeDataWindow(QString datasourceName); QDockWidget* dataWindow(QString datasourceName); @@ -113,22 +114,22 @@ private: void applyChanges(SQLEditResult result); void addDatasource(SQLEditResult result); - void addConnectionDesc(ConnectionDesc *connection); - void changeConnectionDesc(ConnectionDesc *connection); - bool checkConnectionDesc(ConnectionDesc *connection); + void addConnectionDesc(ConnectionDesc* connection); + void changeConnectionDesc(ConnectionDesc* connection); + bool checkConnectionDesc(ConnectionDesc* connection); bool containsDefaultConnection(); - void activateItem(const QString &name, DataBrowserTree::NodeType type); + void activateItem(const QString& name, DataBrowserTree::NodeType type); private: - Ui::DataBrowser* ui; - ReportDesignWidget* m_report; - QMap m_dataWindows; - QMainWindow* m_mainWindow; - bool m_closingWindows; - QSettings* m_settings; - bool m_ownedSettings; - QString m_lastError; + Ui::DataBrowser* ui; + ReportDesignWidget* m_report; + QMap m_dataWindows; + QMainWindow* m_mainWindow; + bool m_closingWindows; + QSettings* m_settings; + bool m_ownedSettings; + QString m_lastError; }; -} +} // namespace LimeReport #endif // LRDATABROWSER_H diff --git a/limereport/databrowser/lrdatabrowsertree.cpp b/limereport/databrowser/lrdatabrowsertree.cpp index 53934f3..4aaa289 100644 --- a/limereport/databrowser/lrdatabrowsertree.cpp +++ b/limereport/databrowser/lrdatabrowsertree.cpp @@ -28,29 +28,30 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrdatabrowsertree.h" + #include #include namespace LimeReport { -DataBrowserTree::DataBrowserTree(QWidget *parent) : - QTreeWidget(parent){} +DataBrowserTree::DataBrowserTree(QWidget* parent): QTreeWidget(parent) { } -#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) -QMimeData *DataBrowserTree::mimeData(const QList &items) const +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +QMimeData* DataBrowserTree::mimeData(const QList& items) const #else -QMimeData *DataBrowserTree::mimeData(const QList items) const +QMimeData* DataBrowserTree::mimeData(const QList items) const #endif { QMimeData* result = QTreeWidget::mimeData(items); - if (items.at(0)->type()==Row){ - result->setText("field:$D{"+items.at(0)->parent()->text(0)+"."+items.at(0)->data(0,Qt::DisplayRole).toString()+"}"); + if (items.at(0)->type() == Row) { + result->setText("field:$D{" + items.at(0)->parent()->text(0) + "." + + items.at(0)->data(0, Qt::DisplayRole).toString() + "}"); } - if (items.at(0)->type()==Variable){ - result->setText("variable:$V{"+items.at(0)->text(0)+"}"); + if (items.at(0)->type() == Variable) { + result->setText("variable:$V{" + items.at(0)->text(0) + "}"); } - if (items.at(0)->type()==ExternalVariable){ - result->setText("variable:$V{"+items.at(0)->text(0)+"}"); + if (items.at(0)->type() == ExternalVariable) { + result->setText("variable:$V{" + items.at(0)->text(0) + "}"); } return result; } diff --git a/limereport/databrowser/lrdatabrowsertree.h b/limereport/databrowser/lrdatabrowsertree.h index eb03791..04b5321 100644 --- a/limereport/databrowser/lrdatabrowsertree.h +++ b/limereport/databrowser/lrdatabrowsertree.h @@ -32,24 +32,29 @@ #include -namespace LimeReport{ +namespace LimeReport { - -class DataBrowserTree : public QTreeWidget -{ +class DataBrowserTree: public QTreeWidget { Q_OBJECT public: - enum NodeType{Connection, Table, Row, Category, Variable, ExternalVariable}; - explicit DataBrowserTree(QWidget *parent = 0); + enum NodeType { + Connection, + Table, + Row, + Category, + Variable, + ExternalVariable + }; + explicit DataBrowserTree(QWidget* parent = 0); + protected: -#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) - virtual QMimeData *mimeData(const QList &items) const; +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + virtual QMimeData* mimeData(const QList& items) const; #else - virtual QMimeData *mimeData(const QList items) const; + virtual QMimeData* mimeData(const QList items) const; #endif public slots: - }; } // namespace LimeReport diff --git a/limereport/databrowser/lrsqleditdialog.cpp b/limereport/databrowser/lrsqleditdialog.cpp index 92e5b3a..c11b99e 100644 --- a/limereport/databrowser/lrsqleditdialog.cpp +++ b/limereport/databrowser/lrsqleditdialog.cpp @@ -28,18 +28,26 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrsqleditdialog.h" -#include "lrreportengine_p.h" #include "ui_lrsqleditdialog.h" +#include "lrreportengine_p.h" + #include #include #include namespace LimeReport { -SQLEditDialog::SQLEditDialog(QWidget *parent, LimeReport::DataSourceManager *dataSources, SQLDialogMode dialogMode) - : QDialog(parent), ui(new Ui::SQLEditDialog), m_datasources(dataSources), m_dialogMode(dialogMode), - m_oldDatasourceName(""), m_settings(0), m_ownedSettings(false) { +SQLEditDialog::SQLEditDialog(QWidget* parent, LimeReport::DataSourceManager* dataSources, + SQLDialogMode dialogMode): + QDialog(parent), + ui(new Ui::SQLEditDialog), + m_datasources(dataSources), + m_dialogMode(dialogMode), + m_oldDatasourceName(""), + m_settings(0), + m_ownedSettings(false) +{ ui->setupUi(this); m_masterDatasources = new QCompleter(this); ui->leMaster->setCompleter(m_masterDatasources); @@ -62,13 +70,15 @@ SQLEditDialog::SQLEditDialog(QWidget *parent, LimeReport::DataSourceManager *dat connect(ui->pbHidePreview, SIGNAL(pressed()), this, SLOT(slotHidePreview())); } -SQLEditDialog::~SQLEditDialog() { +SQLEditDialog::~SQLEditDialog() +{ delete ui; if (m_settings && m_ownedSettings) delete m_settings; } -QSettings *SQLEditDialog::settings() { +QSettings* SQLEditDialog::settings() +{ if (m_settings) { return m_settings; } else { @@ -78,14 +88,16 @@ QSettings *SQLEditDialog::settings() { } } -void SQLEditDialog::setSettings(QSettings *value, bool owned) { +void SQLEditDialog::setSettings(QSettings* value, bool owned) +{ if (m_settings && m_ownedSettings) delete m_settings; m_settings = value; m_ownedSettings = owned; } -void SQLEditDialog::accept() { +void SQLEditDialog::accept() +{ SQLEditResult result; if (ui->tabWidget->currentIndex() == 1) { @@ -99,7 +111,8 @@ void SQLEditDialog::accept() { result.resultMode = SQLEditResult::SubProxy; } - result.connectionName = ConnectionDesc::connectionNameForReport(ui->cbbConnection->currentText()); + result.connectionName + = ConnectionDesc::connectionNameForReport(ui->cbbConnection->currentText()); result.datasourceName = ui->leDatasourceName->text(); result.sql = ui->sqlText->toPlainText(); result.csv = ui->csvText->toPlainText(); @@ -114,10 +127,12 @@ void SQLEditDialog::accept() { if (ui->fieldsMap->rowCount() > 0) { for (int i = 0; i < ui->fieldsMap->rowCount(); ++i) { LimeReport::FieldsCorrelation fieldsCorrelation; - fieldsCorrelation.master = - ui->fieldsMap->item(i, 0) ? ui->fieldsMap->item(i, 0)->data(Qt::DisplayRole).toString() : ""; - fieldsCorrelation.detail = - ui->fieldsMap->item(i, 1) ? ui->fieldsMap->item(i, 1)->data(Qt::DisplayRole).toString() : ""; + fieldsCorrelation.master = ui->fieldsMap->item(i, 0) + ? ui->fieldsMap->item(i, 0)->data(Qt::DisplayRole).toString() + : ""; + fieldsCorrelation.detail = ui->fieldsMap->item(i, 1) + ? ui->fieldsMap->item(i, 1)->data(Qt::DisplayRole).toString() + : ""; result.fieldMap.append(fieldsCorrelation); } } @@ -126,22 +141,24 @@ void SQLEditDialog::accept() { check(); emit signalSqlEditingFinished(result); QDialog::accept(); - } catch (LimeReport::ReportError &exception) { + } catch (LimeReport::ReportError& exception) { QMessageBox::critical(this, tr("Error"), exception.what()); } } -void SQLEditDialog::showEvent(QShowEvent *) { +void SQLEditDialog::showEvent(QShowEvent*) +{ ui->lblInfo->setVisible(false); initConnections(); readSettings(); } -void SQLEditDialog::closeEvent(QCloseEvent *) { writeSetting(); } +void SQLEditDialog::closeEvent(QCloseEvent*) { writeSetting(); } -void SQLEditDialog::hideEvent(QHideEvent *) { writeSetting(); } +void SQLEditDialog::hideEvent(QHideEvent*) { writeSetting(); } -void SQLEditDialog::check() { +void SQLEditDialog::check() +{ if (ui->leDatasourceName->text().isEmpty()) throw LimeReport::ReportError(tr("Datasource Name is empty!")); if (ui->sqlText->toPlainText().isEmpty() && (!ui->rbProxy)) @@ -149,20 +166,23 @@ void SQLEditDialog::check() { if (m_dialogMode == AddMode) { if (m_datasources->containsDatasource(ui->leDatasourceName->text())) { throw LimeReport::ReportError( - QString(tr("Datasource with name: \"%1\" already exists!")).arg(ui->leDatasourceName->text())); + QString(tr("Datasource with name: \"%1\" already exists!")) + .arg(ui->leDatasourceName->text())); } } } -void SQLEditDialog::initConnections() { +void SQLEditDialog::initConnections() +{ foreach (QString connectionName, QSqlDatabase::connectionNames()) { ui->cbbConnection->addItem(QIcon(":/databrowser/images/plug-connect.png"), ConnectionDesc::connectionNameForUser(connectionName)); } foreach (QString connectionName, m_datasources->connectionNames()) { - connectionName = - (connectionName.compare(QSqlDatabase::defaultConnection) == 0) ? tr("defaultConnection") : connectionName; + connectionName = (connectionName.compare(QSqlDatabase::defaultConnection) == 0) + ? tr("defaultConnection") + : connectionName; if (ui->cbbConnection->findText(connectionName, Qt::MatchExactly) == -1) ui->cbbConnection->addItem(QIcon(":/databrowser/images/plug-disconnect.png"), ConnectionDesc::connectionNameForUser(connectionName)); @@ -170,12 +190,15 @@ void SQLEditDialog::initConnections() { ui->cbbConnection->setCurrentIndex(ui->cbbConnection->findText(m_defaultConnection)); if (!m_oldDatasourceName.isEmpty()) { - ui->cbbConnection->setCurrentIndex(ui->cbbConnection->findText( - ConnectionDesc::connectionNameForUser(m_datasources->connectionName(m_oldDatasourceName)))); + ui->cbbConnection->setCurrentIndex( + ui->cbbConnection->findText(ConnectionDesc::connectionNameForUser( + m_datasources->connectionName(m_oldDatasourceName)))); } } -void SQLEditDialog::setDataSources(LimeReport::DataSourceManager *dataSources, QString datasourceName) { +void SQLEditDialog::setDataSources(LimeReport::DataSourceManager* dataSources, + QString datasourceName) +{ m_datasources = dataSources; if (!datasourceName.isEmpty()) { ui->cbSubdetail->setEnabled(true); @@ -191,11 +214,11 @@ void SQLEditDialog::setDataSources(LimeReport::DataSourceManager *dataSources, Q } if (dataSources->isProxy(datasourceName)) { initProxyMode(); - LimeReport::ProxyDesc *proxyDesc = dataSources->proxyByName(datasourceName); + LimeReport::ProxyDesc* proxyDesc = dataSources->proxyByName(datasourceName); ui->leChild->setText(proxyDesc->child()); ui->leMaster->setText(proxyDesc->master()); int curIndex = 0; - foreach (LimeReport::FieldMapDesc *fields, *proxyDesc->fieldsMap()) { + foreach (LimeReport::FieldMapDesc* fields, *proxyDesc->fieldsMap()) { ui->fieldsMap->setRowCount(curIndex + 1); ui->fieldsMap->setItem(curIndex, 0, new QTableWidgetItem(fields->master())); ui->fieldsMap->setItem(curIndex, 1, new QTableWidgetItem(fields->detail())); @@ -205,24 +228,27 @@ void SQLEditDialog::setDataSources(LimeReport::DataSourceManager *dataSources, Q if (dataSources->isCSV(datasourceName)) { ui->csvText->setPlainText(dataSources->csvByName(datasourceName)->csvText()); ui->leSeparator->setText(dataSources->csvByName(datasourceName)->separator()); - ui->cbUseFirstRowAsHeader->setChecked(dataSources->csvByName(datasourceName)->firstRowIsHeader()); + ui->cbUseFirstRowAsHeader->setChecked( + dataSources->csvByName(datasourceName)->firstRowIsHeader()); initCSVMode(); } } } -void SQLEditDialog::setDefaultConnection(QString defaultConnection) { +void SQLEditDialog::setDefaultConnection(QString defaultConnection) +{ m_defaultConnection = ConnectionDesc::connectionNameForUser(defaultConnection); } -void SQLEditDialog::slotDataSourceNameEditing() { +void SQLEditDialog::slotDataSourceNameEditing() +{ if (m_dialogMode == AddMode) { QPalette palette = ui->leDatasourceName->palette(); if (m_datasources->containsDatasource(ui->leDatasourceName->text())) { palette.setColor(QPalette::Text, Qt::red); ui->leDatasourceName->setPalette(palette); - ui->lblInfo->setText( - QString(tr("Datasource with name %1 already exist")).arg(ui->leDatasourceName->text())); + ui->lblInfo->setText(QString(tr("Datasource with name %1 already exist")) + .arg(ui->leDatasourceName->text())); ui->lblInfo->setVisible(true); } else { palette.setColor(QPalette::Text, QApplication::palette().text().color()); @@ -232,9 +258,11 @@ void SQLEditDialog::slotDataSourceNameEditing() { } } -void SQLEditDialog::on_cbSubdetail_clicked(bool checked) { +void SQLEditDialog::on_cbSubdetail_clicked(bool checked) +{ if (checked) { - m_masterDatasources->setModel(new QStringListModel(m_datasources->dataSourceNames(), m_datasources)); + m_masterDatasources->setModel( + new QStringListModel(m_datasources->dataSourceNames(), m_datasources)); } ui->leMaster->setEnabled(checked); ui->rbProxy->setEnabled(checked); @@ -247,19 +275,25 @@ void SQLEditDialog::on_cbSubdetail_clicked(bool checked) { initQueryMode(); } -void SQLEditDialog::on_rbProxy_clicked(bool checked) { +void SQLEditDialog::on_rbProxy_clicked(bool checked) +{ if (checked) initProxyMode(); } -void SQLEditDialog::on_rbSubQuery_clicked(bool checked) { +void SQLEditDialog::on_rbSubQuery_clicked(bool checked) +{ if (checked) initSubQueryMode(); } -void SQLEditDialog::on_pbAddField_clicked() { ui->fieldsMap->setRowCount(ui->fieldsMap->rowCount() + 1); } +void SQLEditDialog::on_pbAddField_clicked() +{ + ui->fieldsMap->setRowCount(ui->fieldsMap->rowCount() + 1); +} -void SQLEditDialog::initQueryMode() { +void SQLEditDialog::initQueryMode() +{ ui->gbSQL->setVisible(true); ui->gbFieldsMap->setVisible(false); ui->pnlChildDatasource->setVisible(false); @@ -272,7 +306,8 @@ void SQLEditDialog::initQueryMode() { ui->tabWidget->addTab(ui->csvTab, tr("CSV")); } -void SQLEditDialog::initSubQueryMode() { +void SQLEditDialog::initSubQueryMode() +{ ui->gbSQL->setVisible(true); ui->gbFieldsMap->setVisible(false); ui->pnlChildDatasource->setVisible(false); @@ -286,7 +321,8 @@ void SQLEditDialog::initSubQueryMode() { ui->tabWidget->removeTab(1); } -void SQLEditDialog::initProxyMode() { +void SQLEditDialog::initProxyMode() +{ ui->gbSQL->setVisible(false); ui->gbFieldsMap->setVisible(true); ui->pnlChildDatasource->setVisible(true); @@ -303,14 +339,15 @@ void SQLEditDialog::initProxyMode() { void SQLEditDialog::initCSVMode() { ui->tabWidget->setCurrentWidget(ui->csvTab); } -void SQLEditDialog::slotPreviewData() { +void SQLEditDialog::slotPreviewData() +{ if (ui->cbbConnection->currentText().isEmpty()) { QMessageBox::critical(this, tr("Attention"), tr("Connection is not specified")); return; } - m_previewModel = - m_datasources->previewSQL(ConnectionDesc::connectionNameForReport(ui->cbbConnection->currentText()), - ui->sqlText->toPlainText(), ui->leMaster->text()); + m_previewModel = m_datasources->previewSQL( + ConnectionDesc::connectionNameForReport(ui->cbbConnection->currentText()), + ui->sqlText->toPlainText(), ui->leMaster->text()); if (m_previewModel) { ui->tvPreview->setModel(m_previewModel.data()); ui->gbDataPreview->setVisible(true); @@ -325,7 +362,8 @@ void SQLEditDialog::slotPreviewData() { void SQLEditDialog::slotHidePreview() { hidePreview(); } -void SQLEditDialog::writeSetting() { +void SQLEditDialog::writeSetting() +{ if (settings() != 0) { settings()->beginGroup("SQLEditor"); settings()->setValue("Geometry", saveGeometry()); @@ -333,7 +371,8 @@ void SQLEditDialog::writeSetting() { } } -void SQLEditDialog::readSettings() { +void SQLEditDialog::readSettings() +{ if (settings() == 0) return; settings()->beginGroup("SQLEditor"); @@ -344,12 +383,16 @@ void SQLEditDialog::readSettings() { settings()->endGroup(); } -void SQLEditDialog::hidePreview() { +void SQLEditDialog::hidePreview() +{ ui->gbDataPreview->setVisible(false); ui->pbPreview->setText(tr("Preview")); ui->pbHidePreview->setVisible(false); } -void SQLEditDialog::on_pbDelField_clicked() { ui->fieldsMap->removeRow(ui->fieldsMap->currentRow()); } +void SQLEditDialog::on_pbDelField_clicked() +{ + ui->fieldsMap->removeRow(ui->fieldsMap->currentRow()); +} } // namespace LimeReport diff --git a/limereport/databrowser/lrsqleditdialog.h b/limereport/databrowser/lrsqleditdialog.h index 8f3e29a..cb5eb42 100644 --- a/limereport/databrowser/lrsqleditdialog.h +++ b/limereport/databrowser/lrsqleditdialog.h @@ -30,15 +30,17 @@ #ifndef LRSQLEDITDIALOG_H #define LRSQLEDITDIALOG_H -#include -#include -#include -#include -#include "lrreportengine_p.h" -#include "lrdatasourcemanager.h" #include "lrdatadesignintf.h" +#include "lrdatasourcemanager.h" +#include "lrreportengine_p.h" -namespace LimeReport{ +#include +#include +#include + +#include + +namespace LimeReport { namespace Ui { class SQLEditDialog; @@ -46,22 +48,26 @@ namespace Ui { struct SQLEditResult; -class SQLEditDialog : public QDialog -{ +class SQLEditDialog: public QDialog { Q_OBJECT public: - enum SQLDialogMode {AddMode,EditMode}; - explicit SQLEditDialog(QWidget *parent, LimeReport::DataSourceManager* dataSources,SQLDialogMode dialogMode); - void setDataSources(LimeReport::DataSourceManager *dataSources,QString datasourceName=""); + enum SQLDialogMode { + AddMode, + EditMode + }; + explicit SQLEditDialog(QWidget* parent, LimeReport::DataSourceManager* dataSources, + SQLDialogMode dialogMode); + void setDataSources(LimeReport::DataSourceManager* dataSources, QString datasourceName = ""); void setDefaultConnection(QString defaultConnection); ~SQLEditDialog(); QSettings* settings(); void setSettings(QSettings* value, bool owned = false); signals: void signalSqlEditingFinished(SQLEditResult result); + protected: - void showEvent(QShowEvent *); + void showEvent(QShowEvent*); void closeEvent(QCloseEvent*); void hideEvent(QHideEvent*); void check(); @@ -80,12 +86,14 @@ private slots: void initCSVMode(); void slotPreviewData(); void slotHidePreview(); + private: void writeSetting(); void readSettings(); void hidePreview(); + private: - Ui::SQLEditDialog *ui; + Ui::SQLEditDialog* ui; LimeReport::DataSourceManager* m_datasources; SQLDialogMode m_dialogMode; QString m_oldDatasourceName; @@ -96,8 +104,14 @@ private: QSharedPointer m_previewModel; }; -struct SQLEditResult{ - enum ResultMode{Query, SubQuery, SubProxy, CSVText, Undefined}; +struct SQLEditResult { + enum ResultMode { + Query, + SubQuery, + SubProxy, + CSVText, + Undefined + }; QString connectionName; QString datasourceName; QString oldDatasourceName; diff --git a/limereport/databrowser/lrvariabledialog.cpp b/limereport/databrowser/lrvariabledialog.cpp index cb8f2d0..beb5323 100644 --- a/limereport/databrowser/lrvariabledialog.cpp +++ b/limereport/databrowser/lrvariabledialog.cpp @@ -29,13 +29,16 @@ ****************************************************************************/ #include "lrvariabledialog.h" #include "ui_lrvariabledialog.h" + #include "lrglobal.h" #include "lrvariablesholder.h" -#include + #include #include -LRVariableDialog::LRVariableDialog(QWidget *parent) : +#include + +LRVariableDialog::LRVariableDialog(QWidget* parent): QDialog(parent), ui(new Ui::LRVariableDialog), m_variableName(""), @@ -45,43 +48,45 @@ LRVariableDialog::LRVariableDialog(QWidget *parent) : { ui->setupUi(this); - static int enumIndex = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); + static int enumIndex + = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); QMetaEnum enumerator = LimeReport::Enums::staticMetaObject.enumerator(enumIndex); - for (int i = 0; icbbType->addItem(enumerator.key(i)); } - //ui->cbbType->setVisible(false); - //ui->lblType->setVisible(false); + // ui->cbbType->setVisible(false); + // ui->lblType->setVisible(false); } -LRVariableDialog::~LRVariableDialog() +LRVariableDialog::~LRVariableDialog() { delete ui; } + +void LRVariableDialog::setVariableContainer(LimeReport::IVariablesContainer* value) { - delete ui; + m_variablesContainer = value; } -void LRVariableDialog::setVariableContainer(LimeReport::IVariablesContainer *value) +void LRVariableDialog::setVariableName(const QString& value) { - m_variablesContainer=value; + m_variableName = value; + m_changeMode = true; + m_oldVariableName = value; } -void LRVariableDialog::setVariableName(const QString &value) -{ - m_variableName=value; - m_changeMode=true; - m_oldVariableName=value; -} - -void LRVariableDialog::showEvent(QShowEvent *) +void LRVariableDialog::showEvent(QShowEvent*) { ui->leName->setText(m_variableName); - static int enumIndex = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); + static int enumIndex + = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); QMetaEnum enumerator = LimeReport::Enums::staticMetaObject.enumerator(enumIndex); - if (!m_variableName.isEmpty()&&m_variablesContainer&&m_variablesContainer->containsVariable(m_variableName)){ + if (!m_variableName.isEmpty() && m_variablesContainer + && m_variablesContainer->containsVariable(m_variableName)) { ui->leValue->setPlainText(m_variablesContainer->variable(m_variableName).toString()); #if QT_VERSION < 0x050000 - ui->cbbType->setCurrentIndex(ui->cbbType->findText(enumerator.valueToKey(m_variablesContainer->variableDataType(m_variableName)))); + ui->cbbType->setCurrentIndex(ui->cbbType->findText( + enumerator.valueToKey(m_variablesContainer->variableDataType(m_variableName)))); #else - ui->cbbType->setCurrentText(enumerator.valueToKey(m_variablesContainer->variableDataType(m_variableName))); + ui->cbbType->setCurrentText( + enumerator.valueToKey(m_variablesContainer->variableDataType(m_variableName))); #endif ui->cbbMandatory->setChecked(m_variablesContainer->variableIsMandatory(m_variableName)); } @@ -89,35 +94,36 @@ void LRVariableDialog::showEvent(QShowEvent *) void LRVariableDialog::accept() { - try{ - static int enumIndex = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); + try { + static int enumIndex + = LimeReport::Enums::staticMetaObject.indexOfEnumerator("VariableDataType"); QMetaEnum enumerator = LimeReport::Enums::staticMetaObject.enumerator(enumIndex); - if (m_variablesContainer&&!ui->leName->text().isEmpty()){ - if (m_changeMode){ - if (m_oldVariableName==ui->leName->text()){ - m_variablesContainer->changeVariable(m_oldVariableName,value()); + if (m_variablesContainer && !ui->leName->text().isEmpty()) { + if (m_changeMode) { + if (m_oldVariableName == ui->leName->text()) { + m_variablesContainer->changeVariable(m_oldVariableName, value()); } else { m_variablesContainer->deleteVariable(m_oldVariableName); - m_variablesContainer->addVariable(ui->leName->text(),value(), LimeReport::VarDesc::Report); + m_variablesContainer->addVariable(ui->leName->text(), value(), + LimeReport::VarDesc::Report); } } else { - m_variablesContainer->addVariable(ui->leName->text(),value(), LimeReport::VarDesc::Report); + m_variablesContainer->addVariable(ui->leName->text(), value(), + LimeReport::VarDesc::Report); } - m_variablesContainer->setVarableMandatory(ui->leName->text(),ui->cbbMandatory->isChecked()); + m_variablesContainer->setVarableMandatory(ui->leName->text(), + ui->cbbMandatory->isChecked()); m_variablesContainer->setVariableDataType( ui->leName->text(), - LimeReport::VariableDataType(enumerator.keysToValue(ui->cbbType->currentText().toLatin1())) - ); + LimeReport::VariableDataType( + enumerator.keysToValue(ui->cbbType->currentText().toLatin1()))); emit signalVariableAccepted(ui->leName->text()); QDialog::accept(); } - } catch (LimeReport::ReportError &exception){ - QMessageBox::critical(this,tr("Attention"),exception.what()); + } catch (LimeReport::ReportError& exception) { + QMessageBox::critical(this, tr("Attention"), exception.what()); } } -QVariant LRVariableDialog::value() -{ - return ui->leValue->toPlainText(); -} +QVariant LRVariableDialog::value() { return ui->leValue->toPlainText(); } diff --git a/limereport/databrowser/lrvariabledialog.h b/limereport/databrowser/lrvariabledialog.h index 61211a7..6699fd1 100644 --- a/limereport/databrowser/lrvariabledialog.h +++ b/limereport/databrowser/lrvariabledialog.h @@ -30,32 +30,35 @@ #ifndef LRVARIABLEDIALOG_H #define LRVARIABLEDIALOG_H -#include #include "lrvariablesholder.h" +#include + namespace Ui { class LRVariableDialog; } -class LRVariableDialog : public QDialog -{ +class LRVariableDialog: public QDialog { Q_OBJECT - + public: - explicit LRVariableDialog(QWidget *parent = 0); + explicit LRVariableDialog(QWidget* parent = 0); ~LRVariableDialog(); - void setVariableContainer(LimeReport::IVariablesContainer *value); - void setVariableName(const QString &value); + void setVariableContainer(LimeReport::IVariablesContainer* value); + void setVariableName(const QString& value); + protected: - void showEvent(QShowEvent *); + void showEvent(QShowEvent*); private slots: void accept(); signals: - void signalVariableAccepted(const QString &variable); + void signalVariableAccepted(const QString& variable); + private: QVariant value(); + private: - Ui::LRVariableDialog *ui; + Ui::LRVariableDialog* ui; QString m_variableName; LimeReport::IVariablesContainer* m_variablesContainer; bool m_changeMode; diff --git a/limereport/dialogdesigner/lrdialogdesigner.cpp b/limereport/dialogdesigner/lrdialogdesigner.cpp index 740b6a6..da1530c 100644 --- a/limereport/dialogdesigner/lrdialogdesigner.cpp +++ b/limereport/dialogdesigner/lrdialogdesigner.cpp @@ -1,20 +1,17 @@ #include "lrdialogdesigner.h" -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #if HAVE_QT5 @@ -22,15 +19,17 @@ #endif #if HAVE_QT4 #include "qdesigner_integration_p.h" + #include #endif #include "pluginmanager_p.h" #include "widgethost.h" + #include -namespace LimeReport{ +namespace LimeReport { -DialogDesignerManager::DialogDesignerManager(QObject *parent) : QObject(parent) +DialogDesignerManager::DialogDesignerManager(QObject* parent): QObject(parent) { QDesignerComponents::initializeResources(); m_formEditor = QDesignerComponents::createFormEditor(this); @@ -43,20 +42,21 @@ DialogDesignerManager::DialogDesignerManager(QObject *parent) : QObject(parent) m_editWidgetsAction->setCheckable(true); m_editWidgetsAction->setChecked(true); connect(m_editWidgetsAction, SIGNAL(triggered()), this, SLOT(slotEditWidgets())); - connect(m_formEditor->formWindowManager(), SIGNAL(activeFormWindowChanged(QDesignerFormWindowInterface*)), - this, SLOT(slotActiveFormWindowChanged(QDesignerFormWindowInterface*)) ); + connect(m_formEditor->formWindowManager(), + SIGNAL(activeFormWindowChanged(QDesignerFormWindowInterface*)), this, + SLOT(slotActiveFormWindowChanged(QDesignerFormWindowInterface*))); m_modes = new QActionGroup(this); m_modes->setExclusive(true); m_modes->addAction(m_editWidgetsAction); - foreach ( QObject* o, QPluginLoader::staticInstances() << m_formEditor->pluginManager()->instances() ) - { - if ( QDesignerFormEditorPluginInterface* fep = qobject_cast( o ) ) - { - if ( !fep->isInitialized() ) - fep->initialize( m_formEditor ); - fep->action()->setCheckable( true ); + foreach (QObject* o, + QPluginLoader::staticInstances() << m_formEditor->pluginManager()->instances()) { + if (QDesignerFormEditorPluginInterface* fep + = qobject_cast(o)) { + if (!fep->isInitialized()) + fep->initialize(m_formEditor); + fep->action()->setCheckable(true); fep->action()->setIcon(QIcon(iconPathByName(fep->action()->objectName()))); m_modes->addAction(fep->action()); } @@ -68,54 +68,57 @@ DialogDesignerManager::DialogDesignerManager(QObject *parent) : QObject(parent) m_formEditor->setWidgetBox(m_widgetBox); m_formEditor->setTopLevel(m_widgetBox); m_designerToolWindows.append(m_widgetBox); - connect(m_widgetBox, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_widgetBox, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*))); m_objectInspector = QDesignerComponents::createObjectInspector(m_formEditor, 0); m_objectInspector->setWindowTitle(tr("Object Inspector")); m_objectInspector->setObjectName(QLatin1String("ObjectInspector")); m_formEditor->setObjectInspector(m_objectInspector); m_designerToolWindows.append(m_objectInspector); - connect(m_objectInspector, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_objectInspector, SIGNAL(destroyed(QObject*)), this, + SLOT(slotObjectDestroyed(QObject*))); m_propertyEditor = QDesignerComponents::createPropertyEditor(m_formEditor, 0); m_propertyEditor->setWindowTitle(tr("Property Editor")); m_propertyEditor->setObjectName(QLatin1String("PropertyEditor")); m_formEditor->setPropertyEditor(m_propertyEditor); m_designerToolWindows.append(m_propertyEditor); - connect(m_propertyEditor, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_propertyEditor, SIGNAL(destroyed(QObject*)), this, + SLOT(slotObjectDestroyed(QObject*))); m_signalSlotEditor = QDesignerComponents::createSignalSlotEditor(m_formEditor, 0); m_signalSlotEditor->setWindowTitle(tr("Signals && Slots Editor")); m_signalSlotEditor->setObjectName(QLatin1String("SignalsAndSlotsEditor")); m_designerToolWindows.append(m_signalSlotEditor); - connect(m_signalSlotEditor, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_signalSlotEditor, SIGNAL(destroyed(QObject*)), this, + SLOT(slotObjectDestroyed(QObject*))); m_resourcesEditor = QDesignerComponents::createResourceEditor(m_formEditor, 0); m_resourcesEditor->setWindowTitle(tr("Resource Editor")); m_resourcesEditor->setObjectName(QLatin1String("ResourceEditor")); m_designerToolWindows.append(m_resourcesEditor); - connect(m_resourcesEditor, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_resourcesEditor, SIGNAL(destroyed(QObject*)), this, + SLOT(slotObjectDestroyed(QObject*))); m_actionEditor = QDesignerComponents::createActionEditor(m_formEditor, 0); m_actionEditor->setWindowTitle(tr("Action Editor")); m_actionEditor->setObjectName("ActionEditor"); m_formEditor->setActionEditor(m_actionEditor); m_designerToolWindows.append(m_actionEditor); - connect(m_actionEditor, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*)) ); + connect(m_actionEditor, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*))); #if QT_VERSION < 0x050000 - m_designerIntegration = new qdesigner_internal::QDesignerIntegration(m_formEditor,this); + m_designerIntegration = new qdesigner_internal::QDesignerIntegration(m_formEditor, this); #else - m_designerIntegration = new QDesignerIntegration(m_formEditor,this); + m_designerIntegration = new QDesignerIntegration(m_formEditor, this); #endif m_formEditor->setIntegration(m_designerIntegration); - } DialogDesignerManager::~DialogDesignerManager() { - for (int i = 0; isetIconSize(QSize(16,16)); + tb->setIconSize(QSize(16, 16)); m_formEditor->formWindowManager()->actionCopy()->setIcon(QIcon(":/report/images/copy")); tb->addAction(m_formEditor->formWindowManager()->actionCopy()); m_formEditor->formWindowManager()->actionPaste()->setIcon(QIcon(":/report/images/paste")); @@ -145,15 +148,17 @@ void DialogDesignerManager::initToolBar(QToolBar *tb) tb->addAction(m_formEditor->formWindowManager()->actionSplitHorizontal()); tb->addAction(m_formEditor->formWindowManager()->actionSplitVertical()); tb->addAction(m_formEditor->formWindowManager()->actionGridLayout()); - m_formEditor->formWindowManager()->actionFormLayout()->setIcon(QIcon(":/images/images/editform.png")); + m_formEditor->formWindowManager()->actionFormLayout()->setIcon( + QIcon(":/images/images/editform.png")); tb->addAction(m_formEditor->formWindowManager()->actionFormLayout()); tb->addAction(m_formEditor->formWindowManager()->actionBreakLayout()); tb->addAction(m_formEditor->formWindowManager()->actionAdjustSize()); } -QWidget *DialogDesignerManager::createFormEditor(const QString &content) +QWidget* DialogDesignerManager::createFormEditor(const QString& content) { - QDesignerFormWindowInterface* wnd = m_formEditor->formWindowManager()->createFormWindow(0, Qt::Window); + QDesignerFormWindowInterface* wnd + = m_formEditor->formWindowManager()->createFormWindow(0, Qt::Window); wnd->setContents(content); m_formEditor->formWindowManager()->setActiveFormWindow(wnd); m_formEditor->objectInspector()->setFormWindow(wnd); @@ -162,79 +167,61 @@ QWidget *DialogDesignerManager::createFormEditor(const QString &content) DialogDesigner* dialogDesigner = new DialogDesigner(wnd, m_formEditor); connect(dialogDesigner, SIGNAL(dialogChanged(QString)), this, SIGNAL(dialogChanged(QString))); - connect(dialogDesigner, SIGNAL(dialogNameChanged(QString,QString)), this, SIGNAL(dialogNameChanged(QString,QString))); + connect(dialogDesigner, SIGNAL(dialogNameChanged(QString, QString)), this, + SIGNAL(dialogNameChanged(QString, QString))); connect(dialogDesigner, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*))); m_dialogDesigners.append(dialogDesigner); return dialogDesigner; - } -QByteArray DialogDesignerManager::getDialogDescription(QWidget *form) +QByteArray DialogDesignerManager::getDialogDescription(QWidget* form) { QByteArray result; DialogDesigner* dialogDesigner = dynamic_cast(form); Q_ASSERT(dialogDesigner != NULL); - //SharedTools::WidgetHost* wh = dynamic_cast(form); - if (dialogDesigner){ + // SharedTools::WidgetHost* wh = dynamic_cast(form); + if (dialogDesigner) { result = dialogDesigner->dialogContent(); - //wh->formWindow()->setDirty(false); + // wh->formWindow()->setDirty(false); } return result; } -void DialogDesignerManager::setActiveEditor(QWidget *widget) +void DialogDesignerManager::setActiveEditor(QWidget* widget) { SharedTools::WidgetHost* wh = dynamic_cast(widget); - if (wh){ + if (wh) { m_formEditor->formWindowManager()->setActiveFormWindow(wh->formWindow()); } } void DialogDesignerManager::setDirty(bool value) { - foreach(DialogDesigner* dialogDesigner, m_dialogDesigners){ + foreach (DialogDesigner* dialogDesigner, m_dialogDesigners) { dialogDesigner->setChanged(value); } } -QWidget* DialogDesignerManager::widgetBox() const -{ - return m_widgetBox; -} +QWidget* DialogDesignerManager::widgetBox() const { return m_widgetBox; } -QWidget* DialogDesignerManager::actionEditor() const -{ - return m_actionEditor; -} +QWidget* DialogDesignerManager::actionEditor() const { return m_actionEditor; } -QWidget* DialogDesignerManager::propertyEditor() const -{ - return m_propertyEditor; -} +QWidget* DialogDesignerManager::propertyEditor() const { return m_propertyEditor; } -QWidget* DialogDesignerManager::objectInspector() const -{ - return m_objectInspector; -} +QWidget* DialogDesignerManager::objectInspector() const { return m_objectInspector; } -QWidget *DialogDesignerManager::signalSlotEditor() const -{ - return m_signalSlotEditor; -} +QWidget* DialogDesignerManager::signalSlotEditor() const { return m_signalSlotEditor; } -QWidget *DialogDesignerManager::resourcesEditor() const -{ - return m_resourcesEditor; -} +QWidget* DialogDesignerManager::resourcesEditor() const { return m_resourcesEditor; } void DialogDesignerManager::slotObjectDestroyed(QObject* object) { QList::Iterator it = m_dialogDesigners.begin(); - while(it!=m_dialogDesigners.end()){ - if (*it == object){ + while (it != m_dialogDesigners.end()) { + if (*it == object) { it = m_dialogDesigners.erase(it); return; } else { @@ -242,22 +229,22 @@ void DialogDesignerManager::slotObjectDestroyed(QObject* object) } } - for ( int i = 0; iformWindowManager()->formWindowCount(); ++i){ - m_formEditor->formWindowManager()->formWindow(i)->editWidgets(); - } + for (int i = 0; i < m_formEditor->formWindowManager()->formWindowCount(); ++i) { + m_formEditor->formWindowManager()->formWindow(i)->editWidgets(); + } } -void DialogDesignerManager::slotActiveFormWindowChanged(QDesignerFormWindowInterface *formWindow) +void DialogDesignerManager::slotActiveFormWindowChanged(QDesignerFormWindowInterface* formWindow) { - if (formWindow){ + if (formWindow) { m_editWidgetsAction->setEnabled(true); m_editWidgetsAction->trigger(); m_editWidgetsAction->setChecked(true); @@ -265,7 +252,7 @@ void DialogDesignerManager::slotActiveFormWindowChanged(QDesignerFormWindowInter } } -QString DialogDesignerManager::iconPathByName(const QString &name) +QString DialogDesignerManager::iconPathByName(const QString& name) { if (name.compare("__qt_edit_signals_slots_action") == 0) return ":/images/images/signalslottool.png"; @@ -276,43 +263,33 @@ QString DialogDesignerManager::iconPathByName(const QString &name) return ""; } -DialogDesigner::DialogDesigner(QDesignerFormWindowInterface* wnd, QDesignerFormEditorInterface* formEditor, QWidget *parent, Qt::WindowFlags flags) - :QWidget(parent, flags), m_formEditor(formEditor) +DialogDesigner::DialogDesigner(QDesignerFormWindowInterface* wnd, + QDesignerFormEditorInterface* formEditor, QWidget* parent, + Qt::WindowFlags flags): + QWidget(parent, flags), + m_formEditor(formEditor) { m_dialogName = wnd->mainContainer()->objectName(); connect(wnd, SIGNAL(changed()), this, SLOT(slotDialogChanged())); - m_designerHolder = new SharedTools::WidgetHost(this,wnd); - m_designerHolder->setFrameStyle( QFrame::NoFrame | QFrame::Plain ); - m_designerHolder->setFocusProxy( wnd ); + m_designerHolder = new SharedTools::WidgetHost(this, wnd); + m_designerHolder->setFrameStyle(QFrame::NoFrame | QFrame::Plain); + m_designerHolder->setFocusProxy(wnd); QVBoxLayout* l = new QVBoxLayout(this); l->addWidget(m_designerHolder); setLayout(l); - } -DialogDesigner::~DialogDesigner(){} +DialogDesigner::~DialogDesigner() { } -QString DialogDesigner::dialogName() const -{ - return m_dialogName; -} +QString DialogDesigner::dialogName() const { return m_dialogName; } -void DialogDesigner::setDialogName(const QString &dialogName) -{ - m_dialogName = dialogName; -} +void DialogDesigner::setDialogName(const QString& dialogName) { m_dialogName = dialogName; } -bool DialogDesigner::isChanged() -{ - return m_designerHolder->formWindow()->isDirty(); -} +bool DialogDesigner::isChanged() { return m_designerHolder->formWindow()->isDirty(); } -void DialogDesigner::setChanged(bool value) -{ - m_designerHolder->formWindow()->setDirty(value); -} +void DialogDesigner::setChanged(bool value) { m_designerHolder->formWindow()->setDirty(value); } QByteArray DialogDesigner::dialogContent() { @@ -324,7 +301,7 @@ QByteArray DialogDesigner::dialogContent() void DialogDesigner::undo() { Q_ASSERT(m_formEditor != NULL); - if (m_formEditor){ + if (m_formEditor) { m_formEditor->formWindowManager()->actionUndo()->trigger(); } } @@ -332,14 +309,14 @@ void DialogDesigner::undo() void DialogDesigner::redo() { Q_ASSERT(m_formEditor != NULL); - if (m_formEditor){ + if (m_formEditor) { m_formEditor->formWindowManager()->actionRedo()->trigger(); } } void DialogDesigner::slotMainContainerNameChanged(QString newName) { - if (m_dialogName.compare(newName) != 0){ + if (m_dialogName.compare(newName) != 0) { emit dialogNameChanged(m_dialogName, newName); m_dialogName = newName; } @@ -348,9 +325,11 @@ void DialogDesigner::slotMainContainerNameChanged(QString newName) void DialogDesigner::slotDialogChanged() { Q_ASSERT(m_designerHolder != NULL); - if (m_designerHolder && m_designerHolder->formWindow()){ - if ( m_designerHolder->formWindow()->mainContainer()->objectName().compare(m_dialogName) !=0 ){ - emit dialogNameChanged(m_dialogName, m_designerHolder->formWindow()->mainContainer()->objectName()); + if (m_designerHolder && m_designerHolder->formWindow()) { + if (m_designerHolder->formWindow()->mainContainer()->objectName().compare(m_dialogName) + != 0) { + emit dialogNameChanged(m_dialogName, + m_designerHolder->formWindow()->mainContainer()->objectName()); m_dialogName = m_designerHolder->formWindow()->mainContainer()->objectName(); } emit dialogChanged(m_dialogName); @@ -358,4 +337,4 @@ void DialogDesigner::slotDialogChanged() } } -} +} // namespace LimeReport diff --git a/limereport/dialogdesigner/lrdialogdesigner.h b/limereport/dialogdesigner/lrdialogdesigner.h index a5c33bc..b3fbd86 100644 --- a/limereport/dialogdesigner/lrdialogdesigner.h +++ b/limereport/dialogdesigner/lrdialogdesigner.h @@ -1,10 +1,10 @@ #ifndef DIALOGDESIGNER_H #define DIALOGDESIGNER_H -#include -#include -#include #include +#include +#include +#include class QDesignerFormEditorInterface; class QDesignerFormWindowInterface; @@ -15,21 +15,22 @@ class QDesignerPropertyEditorInterface; class QDesignerObjectInspectorInterface; class QDesignerFormWindowManagerInterface; -namespace SharedTools{ - class WidgetHost; +namespace SharedTools { +class WidgetHost; } -namespace LimeReport{ +namespace LimeReport { -class DialogDesigner : public QWidget{ +class DialogDesigner: public QWidget { Q_OBJECT public: - DialogDesigner(QDesignerFormWindowInterface *wnd, QDesignerFormEditorInterface* formEditor, QWidget *parent = NULL, Qt::WindowFlags flags = Qt::WindowFlags()); + DialogDesigner(QDesignerFormWindowInterface* wnd, QDesignerFormEditorInterface* formEditor, + QWidget* parent = NULL, Qt::WindowFlags flags = Qt::WindowFlags()); ~DialogDesigner(); QString dialogName() const; - void setDialogName(const QString &dialogName); - bool isChanged(); - void setChanged(bool value); + void setDialogName(const QString& dialogName); + bool isChanged(); + void setChanged(bool value); QByteArray dialogContent(); public slots: void undo(); @@ -40,17 +41,17 @@ signals: private slots: void slotMainContainerNameChanged(QString newName); void slotDialogChanged(); + private: QString m_dialogName; SharedTools::WidgetHost* m_designerHolder; QDesignerFormEditorInterface* m_formEditor; }; -class DialogDesignerManager : public QObject -{ +class DialogDesignerManager: public QObject { Q_OBJECT public: - explicit DialogDesignerManager(QObject *parent = 0); + explicit DialogDesignerManager(QObject* parent = 0); ~DialogDesignerManager(); void initToolBar(QToolBar* tb); QWidget* createFormEditor(const QString& content); @@ -69,9 +70,11 @@ signals: private slots: void slotObjectDestroyed(QObject* object); void slotEditWidgets(); - void slotActiveFormWindowChanged(QDesignerFormWindowInterface *formWindow); + void slotActiveFormWindowChanged(QDesignerFormWindowInterface* formWindow); + private: QString iconPathByName(const QString& name); + private: QDesignerFormEditorInterface* m_formEditor; QDesignerIntegrationInterface* m_designerIntegration; diff --git a/limereport/exporters/lrpdfexporter.cpp b/limereport/exporters/lrpdfexporter.cpp index 08f6f60..6bf1b91 100644 --- a/limereport/exporters/lrpdfexporter.cpp +++ b/limereport/exporters/lrpdfexporter.cpp @@ -1,32 +1,36 @@ -#include - #include "lrpdfexporter.h" + #include "lrexportersfactory.h" #include "lrreportengine_p.h" -namespace{ +#include -LimeReport::ReportExporterInterface* createPDFExporter(LimeReport::ReportEnginePrivate* parent){ +namespace { + +LimeReport::ReportExporterInterface* createPDFExporter(LimeReport::ReportEnginePrivate* parent) +{ return new LimeReport::PDFExporter(parent); } -bool VARIABLE_IS_NOT_USED registred = LimeReport::ExportersFactory::instance().registerCreator("PDF", LimeReport::ExporterAttribs(QObject::tr("Export to PDF"), "PDFExporter"), createPDFExporter); +bool VARIABLE_IS_NOT_USED registred = LimeReport::ExportersFactory::instance().registerCreator( + "PDF", LimeReport::ExporterAttribs(QObject::tr("Export to PDF"), "PDFExporter"), + createPDFExporter); -} +} // namespace -namespace LimeReport{ +namespace LimeReport { -PDFExporter::PDFExporter(ReportEnginePrivate *parent) : QObject(parent), m_reportEngine(parent) -{} +PDFExporter::PDFExporter(ReportEnginePrivate* parent): QObject(parent), m_reportEngine(parent) { } -bool PDFExporter::exportPages(ReportPages pages, const QString &fileName, const QMap ¶ms) +bool PDFExporter::exportPages(ReportPages pages, const QString& fileName, + const QMap& params) { Q_UNUSED(params); - if (!fileName.isEmpty()){ + if (!fileName.isEmpty()) { QPrinter printer; printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); - if (!pages.isEmpty()){ + if (!pages.isEmpty()) { m_reportEngine->printPages(pages, &printer); } m_reportEngine->emitPrintedToPDF(fileName); @@ -35,4 +39,4 @@ bool PDFExporter::exportPages(ReportPages pages, const QString &fileName, const return false; } -} +} // namespace LimeReport diff --git a/limereport/exporters/lrpdfexporter.h b/limereport/exporters/lrpdfexporter.h index d758ff1..77ca6f9 100644 --- a/limereport/exporters/lrpdfexporter.h +++ b/limereport/exporters/lrpdfexporter.h @@ -1,35 +1,28 @@ #ifndef LRPDFEXPORTER_H #define LRPDFEXPORTER_H -#include #include "lrexporterintf.h" -namespace LimeReport{ +#include + +namespace LimeReport { class ReportEnginePrivate; -class PDFExporter : public QObject, public ReportExporterInterface -{ +class PDFExporter: public QObject, public ReportExporterInterface { Q_OBJECT public: - explicit PDFExporter(ReportEnginePrivate *parent = NULL); + explicit PDFExporter(ReportEnginePrivate* parent = NULL); // ReportExporterInterface interface - bool exportPages(ReportPages pages, const QString &fileName, const QMap ¶ms); - QString exporterName() - { - return "PDF"; - } - QString exporterFileExt() - { - return "pdf"; - } - QString hint() - { - return tr("Export to PDF"); - } + bool exportPages(ReportPages pages, const QString& fileName, + const QMap& params); + QString exporterName() { return "PDF"; } + QString exporterFileExt() { return "pdf"; } + QString hint() { return tr("Export to PDF"); } + private: ReportEnginePrivate* m_reportEngine; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRPDFEXPORTER_H diff --git a/limereport/items/charts/lrgridlineschart.cpp b/limereport/items/charts/lrgridlineschart.cpp index 5c2f3bc..45b2abb 100644 --- a/limereport/items/charts/lrgridlineschart.cpp +++ b/limereport/items/charts/lrgridlineschart.cpp @@ -1,7 +1,7 @@ #include "lrgridlineschart.h" namespace LimeReport { -void GridLinesChart::paintChart(QPainter *painter, QRectF chartRect) +void GridLinesChart::paintChart(QPainter* painter, QRectF chartRect) { updateMinAndMaxValues(); @@ -10,22 +10,18 @@ void GridLinesChart::paintChart(QPainter *painter, QRectF chartRect) const qreal valuesVMargin = this->valuesVMargin(painter); - QRectF gridRect = chartRect.adjusted( - hPadding, - vPadding + valuesVMargin * 2, - -hPadding * 3, - -vPadding * 3 - ); + QRectF gridRect + = chartRect.adjusted(hPadding, vPadding + valuesVMargin * 2, -hPadding * 3, -vPadding * 3); if (!m_chartItem->horizontalAxisOnTop()) { // If horizontal axis is on the bottom, move grid a little up - gridRect.adjust(0, -valuesVMargin, 0 , -valuesVMargin); + gridRect.adjust(0, -valuesVMargin, 0, -valuesVMargin); } // Adapt font for horizontal axis - painter->setFont(adaptFont((gridRect.width() - this->valuesHMargin(painter)) / xAxisData().segmentCount() * 0.8, - painter->font(), - xAxisData())); + painter->setFont(adaptFont((gridRect.width() - this->valuesHMargin(painter)) + / xAxisData().segmentCount() * 0.8, + painter->font(), xAxisData())); const qreal valuesHMargin = this->valuesHMargin(painter); @@ -34,23 +30,21 @@ void GridLinesChart::paintChart(QPainter *painter, QRectF chartRect) paintGrid(painter, gridRect); - paintSerialLines( - painter, - gridRect.adjusted(hPadding + valuesHMargin, 0, 0, 0) - ); + paintSerialLines(painter, gridRect.adjusted(hPadding + valuesHMargin, 0, 0, 0)); } void GridLinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) { - if (valuesCount() == 0) return; + if (valuesCount() == 0) + return; painter->save(); - painter->setRenderHint(QPainter::Antialiasing,true); + painter->setRenderHint(QPainter::Antialiasing, true); - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); const qreal delta = yAxisData.delta(); - if (m_chartItem->itemMode() == DesignMode){ + if (m_chartItem->itemMode() == DesignMode) { const qreal hStep = barsRect.width() / valuesCount(); const qreal vStep = barsRect.height() / delta; const qreal topShift = (delta - (maxValue() - minValue())) * vStep + barsRect.top(); @@ -59,7 +53,7 @@ void GridLinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) return; } - const AxisData &xAxisData = this->xAxisData(); + const AxisData& xAxisData = this->xAxisData(); const qreal hStep = barsRect.width() / (xAxisData.rangeMax() - xAxisData.rangeMin()); qreal leftMargin = 0; @@ -70,8 +64,8 @@ void GridLinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) pen.setWidth(m_chartItem->seriesLineWidth()); painter->setPen(pen); - const QList &xAxisValues = series->data()->xAxisValues(); - const QList &values = series->data()->values(); + const QList& xAxisValues = series->data()->xAxisValues(); + const QList& values = series->data()->values(); const int xAxisValuesSize = xAxisValues.size(); qreal lastXPos = 0; qreal lastYPos = 0; @@ -85,16 +79,16 @@ void GridLinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) leftMargin = barsRect.left(); lastXPos = calculatePos(xAxisData, xAxisValues.first(), barsRect.width()); } - for (int i = 0; i < values.count() - 1; ++i ) { + for (int i = 0; i < values.count() - 1; ++i) { const qreal startY = lastYPos; - const qreal endY = calculatePos(yAxisData, values.at(i+1), barsRect.height()); + const qreal endY = calculatePos(yAxisData, values.at(i + 1), barsRect.height()); // Record last used Y position to only calculate new one lastYPos = endY; qreal startX = lastXPos; qreal endX = 0; if (i + 1 < xAxisValuesSize) { - endX = calculatePos(xAxisData, xAxisValues.at(i+1), barsRect.width()); + endX = calculatePos(xAxisData, xAxisValues.at(i + 1), barsRect.width()); } else { endX = startX + hStep; } @@ -109,4 +103,4 @@ void GridLinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) painter->restore(); } -} +} // namespace LimeReport diff --git a/limereport/items/charts/lrgridlineschart.h b/limereport/items/charts/lrgridlineschart.h index a95a07b..78e74b7 100644 --- a/limereport/items/charts/lrgridlineschart.h +++ b/limereport/items/charts/lrgridlineschart.h @@ -4,14 +4,14 @@ #include "lrlineschart.h" namespace LimeReport { -class GridLinesChart : public LinesChart{ +class GridLinesChart: public LinesChart { public: - GridLinesChart(ChartItem* chartItem):LinesChart(chartItem){} - void paintChart(QPainter *painter, QRectF chartRect); + GridLinesChart(ChartItem* chartItem): LinesChart(chartItem) { } + void paintChart(QPainter* painter, QRectF chartRect); private: - void paintSerialLines(QPainter *painter, QRectF barsRect); + void paintSerialLines(QPainter* painter, QRectF barsRect); }; -} +} // namespace LimeReport #endif // GRIDLINESCHART_H diff --git a/limereport/items/charts/lrhorizontalbarchart.cpp b/limereport/items/charts/lrhorizontalbarchart.cpp index eeb04ac..a5e1bd5 100644 --- a/limereport/items/charts/lrhorizontalbarchart.cpp +++ b/limereport/items/charts/lrhorizontalbarchart.cpp @@ -1,52 +1,49 @@ #include "lrhorizontalbarchart.h" -namespace LimeReport{ +namespace LimeReport { -void HorizontalBarChart::paintChart(QPainter *painter, QRectF chartRect) +void HorizontalBarChart::paintChart(QPainter* painter, QRectF chartRect) { updateMinAndMaxValues(); const qreal valuesVMargin = this->valuesVMargin(painter); - QRectF calcRect = verticalLabelsRect(painter, chartRect.adjusted( - hPadding(chartRect), - vPadding(chartRect) * 2, - -(chartRect.width() * 0.9), - -(vPadding(chartRect) * 2 + valuesVMargin) - )); + QRectF calcRect = verticalLabelsRect( + painter, + chartRect.adjusted(hPadding(chartRect), vPadding(chartRect) * 2, -(chartRect.width() * 0.9), + -(vPadding(chartRect) * 2 + valuesVMargin))); qreal barsShift = calcRect.width(); - paintHorizontalGrid(painter, chartRect.adjusted( - hPadding(chartRect) + barsShift, - vPadding(chartRect), - -(hPadding(chartRect)), - -vPadding(chartRect))); + paintHorizontalGrid(painter, + chartRect.adjusted(hPadding(chartRect) + barsShift, vPadding(chartRect), + -(hPadding(chartRect)), -vPadding(chartRect))); - paintHorizontalBars(painter, chartRect.adjusted( - hPadding(chartRect) + barsShift, - vPadding(chartRect) * 2, - -(hPadding(chartRect)), - -(vPadding(chartRect) * 2) )); + paintHorizontalBars(painter, + chartRect.adjusted(hPadding(chartRect) + barsShift, vPadding(chartRect) * 2, + -(hPadding(chartRect)), -(vPadding(chartRect) * 2))); paintVerticalLabels(painter, calcRect); } -void HorizontalBarChart::paintHorizontalBars(QPainter *painter, QRectF barsRect) +void HorizontalBarChart::paintHorizontalBars(QPainter* painter, QRectF barsRect) { - if (seriesCount() == 0) return; + if (seriesCount() == 0) + return; painter->save(); - painter->setRenderHint(QPainter::Antialiasing,false); + painter->setRenderHint(QPainter::Antialiasing, false); - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); const qreal delta = yAxisData.delta(); const qreal verticalOffset = painter->fontMetrics().height(); qreal vStep = (barsRect.height() - verticalOffset) / valuesCount() / seriesCount(); - qreal hStep = (barsRect.width()-painter->fontMetrics().boundingRect(QString::number(maxValue())).width()) / delta; + qreal hStep = (barsRect.width() + - painter->fontMetrics().boundingRect(QString::number(maxValue())).width()) + / delta; - if (!m_chartItem->series().isEmpty() && (m_chartItem->itemMode() != DesignMode)){ + if (!m_chartItem->series().isEmpty() && (m_chartItem->itemMode() != DesignMode)) { qreal curVOffset = barsRect.top(); if (m_chartItem->horizontalAxisOnTop()) { curVOffset += verticalOffset; @@ -55,8 +52,9 @@ void HorizontalBarChart::paintHorizontalBars(QPainter *painter, QRectF barsRect) painter->setBrush(series->color()); qreal y = curVOffset; foreach (qreal value, series->data()->values()) { - painter->drawRect(QRectF((-minValue()*hStep)+barsRect.left(), y, value*hStep, vStep)); - y+=vStep*seriesCount(); + painter->drawRect( + QRectF((-minValue() * hStep) + barsRect.left(), y, value * hStep, vStep)); + y += vStep * seriesCount(); } curVOffset += vStep; } @@ -66,15 +64,17 @@ void HorizontalBarChart::paintHorizontalBars(QPainter *painter, QRectF barsRect) curVOffset += verticalOffset; } int curColor = 0; - for (int i=0; i<9; ++i){ - if (curColor==3) curColor=0; + for (int i = 0; i < 9; ++i) { + if (curColor == 3) + curColor = 0; painter->setBrush(color_map[curColor]); - painter->drawRect(QRectF(barsRect.left(), curVOffset, designValues()[i]*hStep, vStep)); - curVOffset+=vStep; + painter->drawRect( + QRectF(barsRect.left(), curVOffset, designValues()[i] * hStep, vStep)); + curVOffset += vStep; curColor++; } } painter->restore(); } -} +} // namespace LimeReport diff --git a/limereport/items/charts/lrhorizontalbarchart.h b/limereport/items/charts/lrhorizontalbarchart.h index af478dc..f72133d 100644 --- a/limereport/items/charts/lrhorizontalbarchart.h +++ b/limereport/items/charts/lrhorizontalbarchart.h @@ -3,13 +3,13 @@ #include "lrchartitem.h" -namespace LimeReport{ +namespace LimeReport { -class HorizontalBarChart: public AbstractBarChart{ +class HorizontalBarChart: public AbstractBarChart { public: - HorizontalBarChart(ChartItem* chartItem):AbstractBarChart(chartItem){} - void paintChart(QPainter *painter, QRectF chartRect); - void paintHorizontalBars(QPainter *painter, QRectF barsRect); + HorizontalBarChart(ChartItem* chartItem): AbstractBarChart(chartItem) { } + void paintChart(QPainter* painter, QRectF chartRect); + void paintHorizontalBars(QPainter* painter, QRectF barsRect); }; } // namespace LimeReport diff --git a/limereport/items/charts/lrlineschart.cpp b/limereport/items/charts/lrlineschart.cpp index 18c8692..37f00c9 100644 --- a/limereport/items/charts/lrlineschart.cpp +++ b/limereport/items/charts/lrlineschart.cpp @@ -2,7 +2,7 @@ namespace LimeReport { -void LinesChart::paintChart(QPainter *painter, QRectF chartRect) +void LinesChart::paintChart(QPainter* painter, QRectF chartRect) { updateMinAndMaxValues(); @@ -11,64 +11,47 @@ void LinesChart::paintChart(QPainter *painter, QRectF chartRect) QRectF calcRect = horizontalLabelsRect( painter, - chartRect.adjusted( - hPadding(chartRect) * 2 + valuesHMargin, - chartRect.height() - (painter->fontMetrics().height() + vPadding(chartRect)*2), - -(hPadding(chartRect) * 2), - -vPadding(chartRect) - ) - ); + chartRect.adjusted(hPadding(chartRect) * 2 + valuesHMargin, + chartRect.height() + - (painter->fontMetrics().height() + vPadding(chartRect) * 2), + -(hPadding(chartRect) * 2), -vPadding(chartRect))); qreal barsShift = calcRect.height(); - paintVerticalGrid( - painter, - chartRect.adjusted( - hPadding(chartRect), - vPadding(chartRect) + valuesVMargin, - -hPadding(chartRect), - -(vPadding(chartRect) + barsShift) - ) - ); - paintSerialLines( - painter, - chartRect.adjusted( - hPadding(chartRect) * 2 + valuesHMargin, - vPadding(chartRect) + valuesVMargin, - -(hPadding(chartRect) * 2), - -(vPadding(chartRect)+barsShift) - ) - ); + paintVerticalGrid(painter, + chartRect.adjusted(hPadding(chartRect), vPadding(chartRect) + valuesVMargin, + -hPadding(chartRect), -(vPadding(chartRect) + barsShift))); + paintSerialLines(painter, + chartRect.adjusted(hPadding(chartRect) * 2 + valuesHMargin, + vPadding(chartRect) + valuesVMargin, + -(hPadding(chartRect) * 2), + -(vPadding(chartRect) + barsShift))); paintHorizontalLabels(painter, calcRect); } -void LinesChart::drawDesignMode(QPainter* painter, qreal hStep, qreal vStep, qreal topShift, QRectF barsRect){ - for (int i = 0; i < valuesCount()-1; ++i){ - QPoint startPoint = QPoint((i+1) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i] * vStep - ); - QPoint endPoint = QPoint((i+2) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i+1] * vStep - ); +void LinesChart::drawDesignMode(QPainter* painter, qreal hStep, qreal vStep, qreal topShift, + QRectF barsRect) +{ + for (int i = 0; i < valuesCount() - 1; ++i) { + QPoint startPoint = QPoint((i + 1) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i] * vStep); + QPoint endPoint = QPoint((i + 2) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i + 1] * vStep); drawSegment(painter, startPoint, endPoint, color_map[0]); - startPoint = QPoint((i+1) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i+3] * vStep - ); - endPoint = QPoint((i+2) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i+3+1] * vStep - ); + startPoint = QPoint((i + 1) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i + 3] * vStep); + endPoint = QPoint((i + 2) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i + 3 + 1] * vStep); drawSegment(painter, startPoint, endPoint, color_map[1]); - startPoint = QPoint((i+1) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i+6] * vStep - ); - endPoint = QPoint((i+2) * hStep + barsRect.left() - hStep/2, - (maxValue() * vStep+topShift) - designValues()[i+6+1] * vStep - ); + startPoint = QPoint((i + 1) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i + 6] * vStep); + endPoint = QPoint((i + 2) * hStep + barsRect.left() - hStep / 2, + (maxValue() * vStep + topShift) - designValues()[i + 6 + 1] * vStep); drawSegment(painter, startPoint, endPoint, color_map[2]); } } -qreal LinesChart::calculatePos(const AxisData &data, qreal value, qreal rectSize) const +qreal LinesChart::calculatePos(const AxisData& data, qreal value, qreal rectSize) const { if (data.type() == AxisData::XAxis || (data.reverseDirection() && data.rangeMin() >= 0)) { // Not flipping for minimum less than 0 because lower number is at the bottom. @@ -78,10 +61,10 @@ qreal LinesChart::calculatePos(const AxisData &data, qreal value, qreal rectSize } } -void LinesChart::paintSeries(QPainter *painter, SeriesItem *series, QRectF barsRect) +void LinesChart::paintSeries(QPainter* painter, SeriesItem* series, QRectF barsRect) { - const AxisData &yAxisData = this->yAxisData(); - const AxisData &xAxisData = this->xAxisData(); + const AxisData& yAxisData = this->yAxisData(); + const AxisData& xAxisData = this->xAxisData(); const qreal xAxisDiff = std::max(1.0, xAxisData.maxValue() - xAxisData.minValue()); const qreal hStep = barsRect.width() / xAxisDiff; @@ -91,17 +74,17 @@ void LinesChart::paintSeries(QPainter *painter, SeriesItem *series, QRectF barsR pen.setWidth(4); painter->setPen(pen); - const QList &values = series->data()->values(); + const QList& values = series->data()->values(); qreal lastYValue = 0; - qreal lastXValue = barsRect.left() + hStep/2; + qreal lastXValue = barsRect.left() + hStep / 2; if (!values.isEmpty()) { // Calculate first point position on plot before loop lastYValue = calculatePos(yAxisData, values.first(), barsRect.height()); } - for (int i = 0; i < values.count()-1; ++i ){ + for (int i = 0; i < values.count() - 1; ++i) { const qreal startY = lastYValue; - const qreal endY = calculatePos(yAxisData, values.at(i+1), barsRect.height()); + const qreal endY = calculatePos(yAxisData, values.at(i + 1), barsRect.height()); // Record last used Y position to only calculate new one lastYValue = endY; @@ -118,13 +101,14 @@ void LinesChart::paintSeries(QPainter *painter, SeriesItem *series, QRectF barsR void LinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) { - if (valuesCount() == 0) return; + if (valuesCount() == 0) + return; painter->save(); - painter->setRenderHint(QPainter::Antialiasing,true); + painter->setRenderHint(QPainter::Antialiasing, true); - if (m_chartItem->itemMode() == DesignMode){ - const AxisData &yAxisData = this->yAxisData(); + if (m_chartItem->itemMode() == DesignMode) { + const AxisData& yAxisData = this->yAxisData(); const qreal delta = yAxisData.delta(); const qreal hStep = barsRect.width() / valuesCount(); const qreal vStep = barsRect.height() / delta; @@ -134,12 +118,11 @@ void LinesChart::paintSerialLines(QPainter* painter, QRectF barsRect) return; } - for (SeriesItem *series : m_chartItem->series()) { + for (SeriesItem* series : m_chartItem->series()) { paintSeries(painter, series, barsRect); } painter->restore(); } -} //namespace LimeReport - +} // namespace LimeReport diff --git a/limereport/items/charts/lrlineschart.h b/limereport/items/charts/lrlineschart.h index d9325fc..1fc5b4b 100644 --- a/limereport/items/charts/lrlineschart.h +++ b/limereport/items/charts/lrlineschart.h @@ -4,18 +4,20 @@ #include "lrchartitem.h" namespace LimeReport { -class LinesChart: public AbstractBarChart{ +class LinesChart: public AbstractBarChart { public: - LinesChart(ChartItem* chartItem):AbstractBarChart(chartItem){} - void paintChart(QPainter *painter, QRectF chartRect); + LinesChart(ChartItem* chartItem): AbstractBarChart(chartItem) { } + void paintChart(QPainter* painter, QRectF chartRect); + protected: - void drawDesignMode(QPainter *painter, qreal hStep, qreal vStep, qreal topShift, QRectF barsRect); - qreal calculatePos(const AxisData &data, qreal value, qreal rectSize) const; - void paintSeries(QPainter *painter, SeriesItem *series, QRectF barsRect); + void drawDesignMode(QPainter* painter, qreal hStep, qreal vStep, qreal topShift, + QRectF barsRect); + qreal calculatePos(const AxisData& data, qreal value, qreal rectSize) const; + void paintSeries(QPainter* painter, SeriesItem* series, QRectF barsRect); private: - void paintSerialLines(QPainter *painter, QRectF barsRect); + void paintSerialLines(QPainter* painter, QRectF barsRect); }; -} +} // namespace LimeReport #endif // LINESCHART_H diff --git a/limereport/items/charts/lrpiechart.cpp b/limereport/items/charts/lrpiechart.cpp index dbc7687..9fc45ab 100644 --- a/limereport/items/charts/lrpiechart.cpp +++ b/limereport/items/charts/lrpiechart.cpp @@ -1,36 +1,36 @@ #include "lrpiechart.h" -namespace LimeReport{ +namespace LimeReport { -void PieChart::drawPercent(QPainter *painter, QRectF chartRect, qreal startAngle, qreal angle) +void PieChart::drawPercent(QPainter* painter, QRectF chartRect, qreal startAngle, qreal angle) { painter->save(); - QPointF center(chartRect.left()+chartRect.width()/2,chartRect.top()+chartRect.height()/2); - qreal percent = angle/3.6; + QPointF center(chartRect.left() + chartRect.width() / 2, + chartRect.top() + chartRect.height() / 2); + qreal percent = angle / 3.6; #if QT_VERSION < 0x050000 - qreal radAngle = (angle/2+startAngle)*(M_PI/180); + qreal radAngle = (angle / 2 + startAngle) * (M_PI / 180); #else - qreal radAngle = qDegreesToRadians(angle/2+startAngle); + qreal radAngle = qDegreesToRadians(angle / 2 + startAngle); #endif qreal radius = painter->fontMetrics().boundingRect("99,9%").width(); - qreal border = chartRect.height()*0.02; - qreal length = (chartRect.height())/2-(radius/2+border); - qreal x,y; - x = length*qCos(radAngle); - y = length*qSin(radAngle); - QPointF endPoint(center.x()+x,center.y()-y); + qreal border = chartRect.height() * 0.02; + qreal length = (chartRect.height()) / 2 - (radius / 2 + border); + qreal x, y; + x = length * qCos(radAngle); + y = length * qSin(radAngle); + QPointF endPoint(center.x() + x, center.y() - y); painter->setPen(Qt::white); - QRectF textRect(endPoint.x()-(radius/2),endPoint.y()-(radius/2),radius,radius); + QRectF textRect(endPoint.x() - (radius / 2), endPoint.y() - (radius / 2), radius, radius); qreal arcLength = 3.14 * length * angle / 180; if (arcLength >= radius) - painter->drawText(textRect,Qt::AlignCenter,QString::number(percent,'f',1)+"%"); + painter->drawText(textRect, Qt::AlignCenter, QString::number(percent, 'f', 1) + "%"); painter->restore(); - } -void PieChart::paintChart(QPainter *painter, QRectF chartRect) +void PieChart::paintChart(QPainter* painter, QRectF chartRect) { painter->save(); QPen pen(Qt::white); @@ -42,10 +42,10 @@ void PieChart::paintChart(QPainter *painter, QRectF chartRect) painter->setBackground(QBrush(Qt::NoBrush)); QRectF tmpRect = chartRect; - if (chartRect.height()>chartRect.width()){ + if (chartRect.height() > chartRect.width()) { tmpRect.setHeight(chartRect.width()); - tmpRect.adjust(0,(chartRect.bottom()-tmpRect.bottom())/2, - 0,(chartRect.bottom()-tmpRect.bottom())/2); + tmpRect.adjust(0, (chartRect.bottom() - tmpRect.bottom()) / 2, 0, + (chartRect.bottom() - tmpRect.bottom()) / 2); } else { tmpRect.setWidth(chartRect.height()); } @@ -53,31 +53,32 @@ void PieChart::paintChart(QPainter *painter, QRectF chartRect) chartRect = tmpRect; painter->drawRect(chartRect); - if (!m_chartItem->series().isEmpty()&&!m_chartItem->series().at(0)->data()->values().isEmpty()){ + if (!m_chartItem->series().isEmpty() + && !m_chartItem->series().at(0)->data()->values().isEmpty()) { SeriesItem* si = m_chartItem->series().at(0); qreal sum = 0; - foreach(qreal value, si->data()->values()){ - sum+=value; + foreach (qreal value, si->data()->values()) { + sum += value; } qreal onePercent = sum / 100; qreal currentDegree = 0; - for(int i=0; idata()->values().count(); ++i){ + for (int i = 0; i < si->data()->values().count(); ++i) { qreal value = si->data()->values().at(i); - qreal sectorDegree = (value/onePercent)*3.6; + qreal sectorDegree = (value / onePercent) * 3.6; painter->setBrush(si->data()->colors().at(i)); - painter->drawPie(chartRect,currentDegree*16,sectorDegree*16); + painter->drawPie(chartRect, currentDegree * 16, sectorDegree * 16); drawPercent(painter, chartRect, currentDegree, sectorDegree); currentDegree += sectorDegree; } - } else if (m_chartItem->itemMode() == DesignMode){ + } else if (m_chartItem->itemMode() == DesignMode) { painter->setBrush(color_map[0]); - painter->drawPie(chartRect,0,260*16); + painter->drawPie(chartRect, 0, 260 * 16); drawPercent(painter, chartRect, 0, 260); painter->setBrush(color_map[1]); - painter->drawPie(chartRect,260*16,40*16); + painter->drawPie(chartRect, 260 * 16, 40 * 16); drawPercent(painter, chartRect, 260, 40); painter->setBrush(color_map[2]); - painter->drawPie(chartRect,300*16,60*16); + painter->drawPie(chartRect, 300 * 16, 60 * 16); drawPercent(painter, chartRect, 300, 60); } @@ -89,83 +90,77 @@ void PieChart::paintChart(QPainter *painter, QRectF chartRect) painter->restore(); } -void PieChart::paintChartLegend(QPainter *painter, QRectF legendRect) +void PieChart::paintChartLegend(QPainter* painter, QRectF legendRect) { prepareLegendToPaint(legendRect, painter); - int indicatorSize = painter->fontMetrics().height()/2; - painter->setRenderHint(QPainter::Antialiasing,false); + int indicatorSize = painter->fontMetrics().height() / 2; + painter->setRenderHint(QPainter::Antialiasing, false); if (m_chartItem->drawLegendBorder()) painter->drawRect(legendRect); - painter->setRenderHint(QPainter::Antialiasing,true); - QRectF indicatorsRect = legendRect.adjusted(painter->fontMetrics().height()/2,painter->fontMetrics().height()/2,0,0); + painter->setRenderHint(QPainter::Antialiasing, true); + QRectF indicatorsRect = legendRect.adjusted(painter->fontMetrics().height() / 2, + painter->fontMetrics().height() / 2, 0, 0); - if (!m_chartItem->series().isEmpty() && !m_chartItem->series().at(0)->data()->labels().isEmpty()){ + if (!m_chartItem->series().isEmpty() + && !m_chartItem->series().at(0)->data()->labels().isEmpty()) { qreal cw = 0; SeriesItem* si = m_chartItem->series().at(0); - for (int i=0;idata()->labels().count();++i){ + for (int i = 0; i < si->data()->labels().count(); ++i) { QString label = si->data()->labels().at(i); painter->setPen(Qt::black); - painter->drawText(indicatorsRect.adjusted(indicatorSize+indicatorSize/2,cw,0,0),label); + painter->drawText(indicatorsRect.adjusted(indicatorSize + indicatorSize / 2, cw, 0, 0), + label); painter->setPen(si->data()->colors().at(i)); painter->setBrush(si->data()->colors().at(i)); - painter->drawEllipse( - indicatorsRect.adjusted( - 0, - cw+indicatorSize/2, - -(indicatorsRect.width()-indicatorSize), - -(indicatorsRect.height()-(cw+indicatorSize+indicatorSize/2)) - ) - ); + painter->drawEllipse(indicatorsRect.adjusted( + 0, cw + indicatorSize / 2, -(indicatorsRect.width() - indicatorSize), + -(indicatorsRect.height() - (cw + indicatorSize + indicatorSize / 2)))); cw += painter->fontMetrics().height(); } - } else if (m_chartItem->itemMode() == DesignMode){ + } else if (m_chartItem->itemMode() == DesignMode) { qreal cw = 0; - for (int i=0;isetPen(Qt::black); - painter->drawText(indicatorsRect.adjusted(indicatorSize+indicatorSize/2,cw,0,0),label); + painter->drawText(indicatorsRect.adjusted(indicatorSize + indicatorSize / 2, cw, 0, 0), + label); painter->setBrush(color_map[i]); painter->setPen(color_map[i]); - painter->drawEllipse( - indicatorsRect.adjusted( - 0, - cw+indicatorSize/2, - -(indicatorsRect.width()-indicatorSize), - -(indicatorsRect.height()-(cw+indicatorSize+indicatorSize/2)) - ) - ); + painter->drawEllipse(indicatorsRect.adjusted( + 0, cw + indicatorSize / 2, -(indicatorsRect.width() - indicatorSize), + -(indicatorsRect.height() - (cw + indicatorSize + indicatorSize / 2)))); cw += painter->fontMetrics().height(); } - } } -QSizeF PieChart::calcChartLegendSize(const QFont &font, qreal) +QSizeF PieChart::calcChartLegendSize(const QFont& font, qreal) { QFontMetrics fm(font); qreal cw = 0; qreal maxWidth = 0; - if (!m_chartItem->series().isEmpty() && !m_chartItem->series().at(0)->data()->labels().isEmpty()){ + if (!m_chartItem->series().isEmpty() + && !m_chartItem->series().at(0)->data()->labels().isEmpty()) { SeriesItem* si = m_chartItem->series().at(0); - foreach(QString label, si->data()->labels()){ + foreach (QString label, si->data()->labels()) { cw += fm.height(); - if (maxWidthfontMetrics().height() + vPadding(chartRect) * 2), - -(hPadding(chartRect) * 2), - -vPadding(chartRect) - ) - ); + chartRect.adjusted(hPadding(chartRect) * 2 + valuesHMargin, + chartRect.height() + - (painter->fontMetrics().height() + vPadding(chartRect) * 2), + -(hPadding(chartRect) * 2), -vPadding(chartRect))); qreal barsShift = calcRect.height(); - paintVerticalGrid( - painter, - chartRect.adjusted( - hPadding(chartRect), - vPadding(chartRect) + valuesVMargin, - -hPadding(chartRect), - -(vPadding(chartRect) + barsShift) - ) - ); - paintVerticalBars( - painter, - chartRect.adjusted( - hPadding(chartRect) * 2 + valuesHMargin, - vPadding(chartRect) + valuesVMargin, - -hPadding(chartRect) * 2, - -(vPadding(chartRect) + barsShift) - ) - ); - paintSerialLines( - painter, - chartRect.adjusted( - hPadding(chartRect) * 2 + valuesHMargin, - vPadding(chartRect) + valuesVMargin, - -hPadding(chartRect) * 2, - -(vPadding(chartRect) + barsShift) - ) - ); + paintVerticalGrid(painter, + chartRect.adjusted(hPadding(chartRect), vPadding(chartRect) + valuesVMargin, + -hPadding(chartRect), -(vPadding(chartRect) + barsShift))); + paintVerticalBars(painter, + chartRect.adjusted(hPadding(chartRect) * 2 + valuesHMargin, + vPadding(chartRect) + valuesVMargin, + -hPadding(chartRect) * 2, + -(vPadding(chartRect) + barsShift))); + paintSerialLines(painter, + chartRect.adjusted(hPadding(chartRect) * 2 + valuesHMargin, + vPadding(chartRect) + valuesVMargin, + -hPadding(chartRect) * 2, + -(vPadding(chartRect) + barsShift))); paintHorizontalLabels(painter, calcRect); } -void VerticalBarChart::paintVerticalBars(QPainter *painter, QRectF barsRect) +void VerticalBarChart::paintVerticalBars(QPainter* painter, QRectF barsRect) { - if (valuesCount() == 0) return; + if (valuesCount() == 0) + return; - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); const qreal delta = yAxisData.delta(); int barSeriesCount = 0; - foreach(SeriesItem* series, m_chartItem->series()){ - if (series->preferredType() == SeriesItem::Bar) barSeriesCount++; + foreach (SeriesItem* series, m_chartItem->series()) { + if (series->preferredType() == SeriesItem::Bar) + barSeriesCount++; } barSeriesCount = (m_chartItem->itemMode() == DesignMode) ? seriesCount() : barSeriesCount; - if (barSeriesCount < 1) return; + if (barSeriesCount < 1) + return; painter->save(); - painter->setRenderHint(QPainter::Antialiasing,false); + painter->setRenderHint(QPainter::Antialiasing, false); qreal vStep = barsRect.height() / delta; qreal hStep = (barsRect.width() / valuesCount()) / (barSeriesCount == 0 ? 1 : barSeriesCount); qreal topShift = (delta - (maxValue() - minValue())) * vStep + barsRect.top(); - if (!m_chartItem->series().isEmpty() && (m_chartItem->itemMode() != DesignMode)){ + if (!m_chartItem->series().isEmpty() && (m_chartItem->itemMode() != DesignMode)) { int curSeries = 0; foreach (SeriesItem* series, m_chartItem->series()) { - if (series->preferredType() == SeriesItem::Bar){ + if (series->preferredType() == SeriesItem::Bar) { qreal curHOffset = curSeries * hStep + barsRect.left(); painter->setBrush(series->color()); foreach (qreal value, series->data()->values()) { - painter->drawRect(QRectF(curHOffset, maxValue() * vStep + topShift, hStep, -value * vStep)); + painter->drawRect( + QRectF(curHOffset, maxValue() * vStep + topShift, hStep, -value * vStep)); curHOffset += hStep * barSeriesCount; } curSeries++; @@ -87,10 +74,12 @@ void VerticalBarChart::paintVerticalBars(QPainter *painter, QRectF barsRect) } else { qreal curHOffset = barsRect.left(); int curColor = 0; - for (int i = 0; i < 9; ++i){ - if (curColor == 3) curColor = 0; + for (int i = 0; i < 9; ++i) { + if (curColor == 3) + curColor = 0; painter->setBrush(color_map[curColor]); - painter->drawRect(QRectF(curHOffset, maxValue() * vStep + barsRect.top(), hStep, -designValues()[i] * vStep)); + painter->drawRect(QRectF(curHOffset, maxValue() * vStep + barsRect.top(), hStep, + -designValues()[i] * vStep)); curHOffset += hStep; curColor++; } @@ -100,13 +89,14 @@ void VerticalBarChart::paintVerticalBars(QPainter *painter, QRectF barsRect) void VerticalBarChart::paintSerialLines(QPainter* painter, QRectF barsRect) { - if (valuesCount() == 0 || m_chartItem->series().isEmpty() ) return; + if (valuesCount() == 0 || m_chartItem->series().isEmpty()) + return; painter->save(); - painter->setRenderHint(QPainter::Antialiasing,true); + painter->setRenderHint(QPainter::Antialiasing, true); - for (SeriesItem *series : m_chartItem->series()) { - if (series->preferredType() == SeriesItem::Line){ + for (SeriesItem* series : m_chartItem->series()) { + if (series->preferredType() == SeriesItem::Line) { paintSeries(painter, series, barsRect); } } diff --git a/limereport/items/charts/lrverticalbarchart.h b/limereport/items/charts/lrverticalbarchart.h index 8f302c5..d26fa68 100644 --- a/limereport/items/charts/lrverticalbarchart.h +++ b/limereport/items/charts/lrverticalbarchart.h @@ -3,17 +3,17 @@ #include "lrlineschart.h" -namespace LimeReport{ +namespace LimeReport { -class VerticalBarChart: public LinesChart{ +class VerticalBarChart: public LinesChart { public: - VerticalBarChart(ChartItem* chartItem):LinesChart(chartItem){} - void paintChart(QPainter *painter, QRectF chartRect); -// void paintVerticalGrid(QPainter *painter, QRectF gridRect); - void paintVerticalBars(QPainter *painter, QRectF barsRect); - void paintSerialLines(QPainter *painter, QRectF barsRect); + VerticalBarChart(ChartItem* chartItem): LinesChart(chartItem) { } + void paintChart(QPainter* painter, QRectF chartRect); + // void paintVerticalGrid(QPainter *painter, QRectF gridRect); + void paintVerticalBars(QPainter* painter, QRectF barsRect); + void paintSerialLines(QPainter* painter, QRectF barsRect); }; -} //namespace LimeReport +} // namespace LimeReport #endif // VERTICALBARCHART_H diff --git a/limereport/items/editors/lrfonteditorwidget.cpp b/limereport/items/editors/lrfonteditorwidget.cpp index ad62f6a..193b6b6 100644 --- a/limereport/items/editors/lrfonteditorwidget.cpp +++ b/limereport/items/editors/lrfonteditorwidget.cpp @@ -29,10 +29,11 @@ ****************************************************************************/ #include "lrfonteditorwidget.h" -namespace LimeReport{ +namespace LimeReport { -FontEditorWidget::FontEditorWidget(const QString& title, QWidget* parent) - :ItemEditorWidget(title, parent), m_ignoreSlots(false) +FontEditorWidget::FontEditorWidget(const QString& title, QWidget* parent): + ItemEditorWidget(title, parent), + m_ignoreSlots(false) { initEditor(); } @@ -40,91 +41,107 @@ FontEditorWidget::FontEditorWidget(const QString& title, QWidget* parent) void FontEditorWidget::setItemEvent(BaseDesignIntf* item) { - QVariant font=item->property("font"); - if (font.isValid()){ + QVariant font = item->property("font"); + if (font.isValid()) { updateValues(font.value()); setEnabled(true); } - } void FontEditorWidget::initEditor() { - setIconSize(QSize(24,24)); + setIconSize(QSize(24, 24)); setAllowedAreas(Qt::TopToolBarArea); setFloatable(false); m_fontNameEditor = new QFontComboBox(this); m_fontNameEditor->setFontFilters(QFontComboBox::AllFonts); - connect(m_fontNameEditor,SIGNAL(currentFontChanged(QFont)),this,SLOT(slotFontChanged(QFont))); + connect(m_fontNameEditor, SIGNAL(currentFontChanged(QFont)), this, + SLOT(slotFontChanged(QFont))); addWidget(m_fontNameEditor); - m_fontSizeModel.setStringList(QStringList()<<"6"<<"7"<<"8"<<"9"<<"10"<<"11"<<"12"<<"14"<<"16"<<"18"<<"20"<<"24"<<"28"<<"30"<<"36"<<"48"<<"64"<<"72"); + m_fontSizeModel.setStringList(QStringList() << "6" + << "7" + << "8" + << "9" + << "10" + << "11" + << "12" + << "14" + << "16" + << "18" + << "20" + << "24" + << "28" + << "30" + << "36" + << "48" + << "64" + << "72"); m_fontSizeEditor = new QComboBox(this); m_fontSizeEditor->setModel(&m_fontSizeModel); m_fontSizeEditor->setEditable(true); #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 3) - connect(m_fontSizeEditor,SIGNAL(currentTextChanged(QString)),this,SLOT(slotFontSizeChanged(QString))); + connect(m_fontSizeEditor, SIGNAL(currentTextChanged(QString)), this, + SLOT(slotFontSizeChanged(QString))); #else - connect(m_fontSizeEditor,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotFontSizeChanged(QString))); + connect(m_fontSizeEditor, SIGNAL(currentIndexChanged(QString)), this, + SLOT(slotFontSizeChanged(QString))); #endif addWidget(m_fontSizeEditor); addSeparator(); setEnabled(false); - m_fontBold = new QAction(tr("Font bold"),this); + m_fontBold = new QAction(tr("Font bold"), this); m_fontBold->setIcon(QIcon(":/report/images/textBold")); m_fontBold->setCheckable(true); - connect(m_fontBold,SIGNAL(toggled(bool)),this,SLOT(slotFontAttribsChanged(bool))); + connect(m_fontBold, SIGNAL(toggled(bool)), this, SLOT(slotFontAttribsChanged(bool))); addAction(m_fontBold); - m_fontItalic = new QAction(tr("Font Italic"),this); + m_fontItalic = new QAction(tr("Font Italic"), this); m_fontItalic->setIcon(QIcon(":/report/images/textItalic")); m_fontItalic->setCheckable(true); - connect(m_fontItalic,SIGNAL(toggled(bool)),this,SLOT(slotFontAttribsChanged(bool))); + connect(m_fontItalic, SIGNAL(toggled(bool)), this, SLOT(slotFontAttribsChanged(bool))); addAction(m_fontItalic); - m_fontUnderline = new QAction(tr("Font Underline"),this); + m_fontUnderline = new QAction(tr("Font Underline"), this); m_fontUnderline->setIcon(QIcon(":/report/images/textUnderline")); m_fontUnderline->setCheckable(true); - connect(m_fontUnderline,SIGNAL(toggled(bool)),this,SLOT(slotFontAttribsChanged(bool))); + connect(m_fontUnderline, SIGNAL(toggled(bool)), this, SLOT(slotFontAttribsChanged(bool))); addAction(m_fontUnderline); - } void FontEditorWidget::updateValues(const QFont& font) { - m_ignoreSlots=true; + m_ignoreSlots = true; m_fontNameEditor->setCurrentFont(font); m_fontSizeEditor->setEditText(QString::number(font.pointSize())); m_fontBold->setChecked(font.bold()); m_fontItalic->setChecked(font.italic()); m_fontUnderline->setChecked(font.underline()); - m_ignoreSlots=false; -} - -bool FontEditorWidget::ignoreSlots() const -{ - return m_ignoreSlots; + m_ignoreSlots = false; } +bool FontEditorWidget::ignoreSlots() const { return m_ignoreSlots; } void FontEditorWidget::slotFontChanged(const QFont& /*font*/) { - //if (page()) page()->setFont(font); + // if (page()) page()->setFont(font); } -void FontEditorWidget::slotFontSizeChanged(const QString &value) +void FontEditorWidget::slotFontSizeChanged(const QString& value) { - if (m_ignoreSlots) return; + if (m_ignoreSlots) + return; m_resFont = fontNameEditor()->currentFont(); m_resFont.setPointSize(value.toInt()); } void FontEditorWidget::slotFontAttribsChanged(bool) { - if (m_ignoreSlots) return; + if (m_ignoreSlots) + return; m_resFont = m_fontNameEditor->currentFont(); m_resFont.setPointSize(m_fontSizeEditor->currentText().toInt()); m_resFont.setBold(m_fontBold->isChecked()); @@ -132,16 +149,16 @@ void FontEditorWidget::slotFontAttribsChanged(bool) m_resFont.setUnderline(m_fontUnderline->isChecked()); } -void FontEditorWidget::slotPropertyChanged(const QString &objectName, const QString &property, const QVariant& oldValue, const QVariant& newValue) +void FontEditorWidget::slotPropertyChanged(const QString& objectName, const QString& property, + const QVariant& oldValue, const QVariant& newValue) { Q_UNUSED(oldValue) Q_UNUSED(newValue) - if (item()&&(item()->objectName()==objectName)&&(property=="font")){ + if (item() && (item()->objectName() == objectName) && (property == "font")) { updateValues(item()->property("font").value()); } } - void FontEditorWidgetForPage::slotFontChanged(const QFont& font) { if (!ignoreSlots()) @@ -150,7 +167,7 @@ void FontEditorWidgetForPage::slotFontChanged(const QFont& font) void FontEditorWidgetForPage::slotFontSizeChanged(const QString& value) { - if (!ignoreSlots()){ + if (!ignoreSlots()) { FontEditorWidget::slotFontSizeChanged(value); m_page->setFont(resFont()); } @@ -158,7 +175,7 @@ void FontEditorWidgetForPage::slotFontSizeChanged(const QString& value) void FontEditorWidgetForPage::slotFontAttribsChanged(bool value) { - if (!ignoreSlots()){ + if (!ignoreSlots()) { FontEditorWidget::slotFontAttribsChanged(value); m_page->setFont(resFont()); } @@ -167,18 +184,19 @@ void FontEditorWidgetForPage::slotFontAttribsChanged(bool value) #ifdef HAVE_REPORT_DESIGNER void FontEditorWidgetForDesigner::initEditor() { - connect(m_reportEditor,SIGNAL(itemPropertyChanged(QString,QString,QVariant,QVariant)), - this,SLOT(slotPropertyChanged(QString,QString,QVariant,QVariant))); + connect(m_reportEditor, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QString, QVariant, QVariant))); } void FontEditorWidgetForDesigner::slotFontChanged(const QFont& font) { - if (!ignoreSlots()) m_reportEditor->setFont(font); + if (!ignoreSlots()) + m_reportEditor->setFont(font); } void FontEditorWidgetForDesigner::slotFontSizeChanged(const QString& value) { - if (!ignoreSlots()){ + if (!ignoreSlots()) { FontEditorWidget::slotFontSizeChanged(value); m_reportEditor->setFont(resFont()); } @@ -186,7 +204,7 @@ void FontEditorWidgetForDesigner::slotFontSizeChanged(const QString& value) void FontEditorWidgetForDesigner::slotFontAttribsChanged(bool value) { - if (!ignoreSlots()){ + if (!ignoreSlots()) { FontEditorWidget::slotFontAttribsChanged(value); m_reportEditor->setFont(resFont()); } @@ -194,5 +212,4 @@ void FontEditorWidgetForDesigner::slotFontAttribsChanged(bool value) #endif - -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/items/editors/lrfonteditorwidget.h b/limereport/items/editors/lrfonteditorwidget.h index 2845988..0036553 100644 --- a/limereport/items/editors/lrfonteditorwidget.h +++ b/limereport/items/editors/lrfonteditorwidget.h @@ -30,10 +30,10 @@ #ifndef LRFONTEDITORWIDGET_H #define LRFONTEDITORWIDGET_H -#include +#include #include #include -#include +#include #ifdef HAVE_REPORT_DESIGNER #include "lrreportdesignwidget.h" @@ -41,27 +41,30 @@ #include "lritemeditorwidget.h" -namespace LimeReport{ +namespace LimeReport { -class FontEditorWidget :public ItemEditorWidget{ +class FontEditorWidget: public ItemEditorWidget { Q_OBJECT public: - explicit FontEditorWidget(const QString &title, QWidget *parent = 0); + explicit FontEditorWidget(const QString& title, QWidget* parent = 0); bool ignoreSlots() const; + protected: - void setItemEvent(BaseDesignIntf *item); - QFontComboBox* fontNameEditor(){return m_fontNameEditor;} + void setItemEvent(BaseDesignIntf* item); + QFontComboBox* fontNameEditor() { return m_fontNameEditor; } void initEditor(); protected slots: virtual void slotFontChanged(const QFont&); virtual void slotFontSizeChanged(const QString& value); virtual void slotFontAttribsChanged(bool); - void slotPropertyChanged(const QString& objectName, const QString& property, const QVariant &oldValue, const QVariant &newValue); -protected: - QFont resFont(){return m_resFont;} -private: + void slotPropertyChanged(const QString& objectName, const QString& property, + const QVariant& oldValue, const QVariant& newValue); - void updateValues(const QFont &font); +protected: + QFont resFont() { return m_resFont; } + +private: + void updateValues(const QFont& font); QFontComboBox* m_fontNameEditor; QComboBox* m_fontSizeEditor; @@ -73,28 +76,37 @@ private: bool m_ignoreSlots; QFont m_resFont; - }; -class FontEditorWidgetForPage : public FontEditorWidget{ +class FontEditorWidgetForPage: public FontEditorWidget { Q_OBJECT public: - explicit FontEditorWidgetForPage(PageDesignIntf* page, const QString &title, QWidget *parent = 0) - : FontEditorWidget(title, parent), m_page(page){} + explicit FontEditorWidgetForPage(PageDesignIntf* page, const QString& title, + QWidget* parent = 0): + FontEditorWidget(title, parent), + m_page(page) + { + } protected slots: virtual void slotFontChanged(const QFont& font); virtual void slotFontSizeChanged(const QString& value); virtual void slotFontAttribsChanged(bool value); + private: PageDesignIntf* m_page; }; #ifdef HAVE_REPORT_DESIGNER -class FontEditorWidgetForDesigner : public FontEditorWidget{ +class FontEditorWidgetForDesigner: public FontEditorWidget { Q_OBJECT public: - explicit FontEditorWidgetForDesigner(ReportDesignWidget* reportEditor, const QString &title, QWidget *parent = 0) - : FontEditorWidget(title, parent), m_reportEditor(reportEditor){initEditor();} + explicit FontEditorWidgetForDesigner(ReportDesignWidget* reportEditor, const QString& title, + QWidget* parent = 0): + FontEditorWidget(title, parent), + m_reportEditor(reportEditor) + { + initEditor(); + } protected: void initEditor(); @@ -102,11 +114,12 @@ protected slots: virtual void slotFontChanged(const QFont& font); virtual void slotFontSizeChanged(const QString& value); virtual void slotFontAttribsChanged(bool value); + private: ReportDesignWidget* m_reportEditor; }; #endif -} //namespace LimeReport +} // namespace LimeReport #endif // LRFONTEDITORWIDGET_H diff --git a/limereport/items/editors/lritemeditorwidget.cpp b/limereport/items/editors/lritemeditorwidget.cpp index 354ff44..e6abc3e 100644 --- a/limereport/items/editors/lritemeditorwidget.cpp +++ b/limereport/items/editors/lritemeditorwidget.cpp @@ -29,22 +29,24 @@ ****************************************************************************/ #include "lritemeditorwidget.h" -namespace LimeReport{ +namespace LimeReport { void ItemEditorWidget::setItem(BaseDesignIntf* item) { - if (m_item!=item){ - if (m_item) m_item->disconnect(this); - m_item=item; - connect(m_item,SIGNAL(destroyed(QObject*)),this,SLOT(slotItemDestroyed(QObject*))); - connect(m_item,SIGNAL(propertyChanged(QString,QVariant,QVariant)), - this,SLOT(slotPropertyChanged(QString,QVariant,QVariant))); + if (m_item != item) { + if (m_item) + m_item->disconnect(this); + m_item = item; + connect(m_item, SIGNAL(destroyed(QObject*)), this, SLOT(slotItemDestroyed(QObject*))); + connect(m_item, SIGNAL(propertyChanged(QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QVariant, QVariant))); setEnabled(false); setItemEvent(item); } } -void ItemEditorWidget::properyChangedEvent(const QString& propertName, const QVariant& oldValue, const QVariant& newValue) +void ItemEditorWidget::properyChangedEvent(const QString& propertName, const QVariant& oldValue, + const QVariant& newValue) { Q_UNUSED(propertName) Q_UNUSED(oldValue) @@ -53,19 +55,16 @@ void ItemEditorWidget::properyChangedEvent(const QString& propertName, const QVa void ItemEditorWidget::slotItemDestroyed(QObject* item) { - if (item==m_item) { + if (item == m_item) { m_item = 0; setEnabled(false); } } -void ItemEditorWidget::slotPropertyChanged(const QString& propertName, const QVariant& oldValue, const QVariant& newValue) +void ItemEditorWidget::slotPropertyChanged(const QString& propertName, const QVariant& oldValue, + const QVariant& newValue) { - properyChangedEvent(propertName,oldValue,newValue); + properyChangedEvent(propertName, oldValue, newValue); } -} - - - - +} // namespace LimeReport diff --git a/limereport/items/editors/lritemeditorwidget.h b/limereport/items/editors/lritemeditorwidget.h index 3c5c320..6dd4076 100644 --- a/limereport/items/editors/lritemeditorwidget.h +++ b/limereport/items/editors/lritemeditorwidget.h @@ -39,20 +39,26 @@ namespace LimeReport { -class ItemEditorWidget : public QToolBar -{ +class ItemEditorWidget: public QToolBar { Q_OBJECT public: - explicit ItemEditorWidget(const QString &title, QWidget *parent = 0) - : QToolBar(title, parent), m_item(0){} - void setItem(BaseDesignIntf *item); + explicit ItemEditorWidget(const QString& title, QWidget* parent = 0): + QToolBar(title, parent), + m_item(0) + { + } + void setItem(BaseDesignIntf* item); + protected: - virtual void setItemEvent(BaseDesignIntf*){} - virtual void properyChangedEvent(const QString& propertName, const QVariant& oldValue, const QVariant& newValue); - BaseDesignIntf* item(){return m_item;} + virtual void setItemEvent(BaseDesignIntf*) { } + virtual void properyChangedEvent(const QString& propertName, const QVariant& oldValue, + const QVariant& newValue); + BaseDesignIntf* item() { return m_item; } private slots: void slotItemDestroyed(QObject* item); - void slotPropertyChanged(const QString& propertName, const QVariant& oldValue, const QVariant& newValue); + void slotPropertyChanged(const QString& propertName, const QVariant& oldValue, + const QVariant& newValue); + private: BaseDesignIntf* m_item; }; diff --git a/limereport/items/editors/lritemsaligneditorwidget.cpp b/limereport/items/editors/lritemsaligneditorwidget.cpp index c2b97e2..8580be8 100644 --- a/limereport/items/editors/lritemsaligneditorwidget.cpp +++ b/limereport/items/editors/lritemsaligneditorwidget.cpp @@ -29,143 +29,174 @@ ****************************************************************************/ #include "lritemsaligneditorwidget.h" -namespace LimeReport{ +namespace LimeReport { -ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(LimeReport::ReportDesignWidget* reportEditor, const QString& title, QWidget* parent) - :QToolBar(title,parent), m_reportEditor(reportEditor), m_page(0) +ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(LimeReport::ReportDesignWidget* reportEditor, + const QString& title, QWidget* parent): + QToolBar(title, parent), + m_reportEditor(reportEditor), + m_page(0) { initEditor(); } -ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, QWidget* parent) - :QToolBar(parent), m_reportEditor(reportEditor), m_page(0) +ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, + QWidget* parent): + QToolBar(parent), + m_reportEditor(reportEditor), + m_page(0) { initEditor(); } -ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(PageDesignIntf* page, const QString& title, QWidget* parent) - :QToolBar(title,parent), m_reportEditor(0), m_page(page) +ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(PageDesignIntf* page, const QString& title, + QWidget* parent): + QToolBar(title, parent), + m_reportEditor(0), + m_page(page) { initEditor(); } -ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(PageDesignIntf* page, QWidget* parent) - :QToolBar(parent), m_reportEditor(0), m_page(page) +ItemsAlignmentEditorWidget::ItemsAlignmentEditorWidget(PageDesignIntf* page, QWidget* parent): + QToolBar(parent), + m_reportEditor(0), + m_page(page) { initEditor(); } void ItemsAlignmentEditorWidget::slotBringToFront() { - if (m_reportEditor) m_reportEditor->bringToFront(); - if (m_page) m_page->bringToFront(); + if (m_reportEditor) + m_reportEditor->bringToFront(); + if (m_page) + m_page->bringToFront(); } void ItemsAlignmentEditorWidget::slotSendToBack() { - if (m_reportEditor) m_reportEditor->sendToBack(); - if (m_page) m_page->sendToBack(); + if (m_reportEditor) + m_reportEditor->sendToBack(); + if (m_page) + m_page->sendToBack(); } void ItemsAlignmentEditorWidget::slotAlignToLeft() { - if (m_reportEditor) m_reportEditor->alignToLeft(); - if (m_page) m_page->alignToLeft(); + if (m_reportEditor) + m_reportEditor->alignToLeft(); + if (m_page) + m_page->alignToLeft(); } void ItemsAlignmentEditorWidget::slotAlignToRight() { - if (m_reportEditor) m_reportEditor->alignToRight(); - if (m_page) m_page->alignToRigth(); + if (m_reportEditor) + m_reportEditor->alignToRight(); + if (m_page) + m_page->alignToRigth(); } void ItemsAlignmentEditorWidget::slotAlignToVCenter() { - if (m_reportEditor) m_reportEditor->alignToVCenter(); - if (m_page) m_page->alignToVCenter(); + if (m_reportEditor) + m_reportEditor->alignToVCenter(); + if (m_page) + m_page->alignToVCenter(); } void ItemsAlignmentEditorWidget::slotAlignToTop() { - if (m_reportEditor) m_reportEditor->alignToTop(); - if (m_page) m_page->alignToTop(); + if (m_reportEditor) + m_reportEditor->alignToTop(); + if (m_page) + m_page->alignToTop(); } void ItemsAlignmentEditorWidget::slotAlignToBottom() { - if (m_reportEditor) m_reportEditor->alignToBottom(); - if (m_page) m_page->alignToBottom(); + if (m_reportEditor) + m_reportEditor->alignToBottom(); + if (m_page) + m_page->alignToBottom(); } void ItemsAlignmentEditorWidget::slotAlignToHCenter() { - if (m_reportEditor) m_reportEditor->alignToHCenter(); - if (m_page) m_page->alignToHCenter(); + if (m_reportEditor) + m_reportEditor->alignToHCenter(); + if (m_page) + m_page->alignToHCenter(); } void ItemsAlignmentEditorWidget::slotSameHeight() { - if (m_reportEditor) m_reportEditor->sameHeight(); - if (m_page) m_page->sameHeight(); + if (m_reportEditor) + m_reportEditor->sameHeight(); + if (m_page) + m_page->sameHeight(); } void ItemsAlignmentEditorWidget::slotSameWidth() { - if (m_reportEditor) m_reportEditor->sameWidth(); - if (m_page) m_page->sameWidth(); + if (m_reportEditor) + m_reportEditor->sameWidth(); + if (m_page) + m_page->sameWidth(); } void ItemsAlignmentEditorWidget::initEditor() { - m_bringToFront = new QAction(tr("Bring to top"),this); + m_bringToFront = new QAction(tr("Bring to top"), this); m_bringToFront->setIcon(QIcon(":/report/images/bringToTop")); - connect(m_bringToFront,SIGNAL(triggered()),this,SLOT(slotBringToFront())); + connect(m_bringToFront, SIGNAL(triggered()), this, SLOT(slotBringToFront())); addAction(m_bringToFront); - m_sendToBack = new QAction(tr("Send to back"),this); + m_sendToBack = new QAction(tr("Send to back"), this); m_sendToBack->setIcon(QIcon(":/report/images/sendToBack")); - connect(m_sendToBack,SIGNAL(triggered()),this,SLOT(slotSendToBack())); + connect(m_sendToBack, SIGNAL(triggered()), this, SLOT(slotSendToBack())); addAction(m_sendToBack); - m_alignToLeft = new QAction(tr("Align to left"),this); + m_alignToLeft = new QAction(tr("Align to left"), this); m_alignToLeft->setIcon(QIcon(":/report/images/alignToLeft")); - connect(m_alignToLeft,SIGNAL(triggered()),this,SLOT(slotAlignToLeft())); + connect(m_alignToLeft, SIGNAL(triggered()), this, SLOT(slotAlignToLeft())); addAction(m_alignToLeft); - m_alignToRight = new QAction(tr("Align to right"),this); + m_alignToRight = new QAction(tr("Align to right"), this); m_alignToRight->setIcon(QIcon(":/report/images/alignToRight")); - connect(m_alignToRight,SIGNAL(triggered()),this,SLOT(slotAlignToRight())); + connect(m_alignToRight, SIGNAL(triggered()), this, SLOT(slotAlignToRight())); addAction(m_alignToRight); - m_alignToVCenter = new QAction(tr("Align to vertical center"),this); + m_alignToVCenter = new QAction(tr("Align to vertical center"), this); m_alignToVCenter->setIcon(QIcon(":/report/images/alignToVCenter")); - connect(m_alignToVCenter,SIGNAL(triggered()),this,SLOT(slotAlignToVCenter())); + connect(m_alignToVCenter, SIGNAL(triggered()), this, SLOT(slotAlignToVCenter())); addAction(m_alignToVCenter); - m_alignToTop = new QAction(tr("Align to top"),this); + m_alignToTop = new QAction(tr("Align to top"), this); m_alignToTop->setIcon(QIcon(":/report/images/alignToTop")); - connect(m_alignToTop,SIGNAL(triggered()),this,SLOT(slotAlignToTop())); + connect(m_alignToTop, SIGNAL(triggered()), this, SLOT(slotAlignToTop())); addAction(m_alignToTop); - m_alignToBottom = new QAction(tr("Align to bottom"),this); + m_alignToBottom = new QAction(tr("Align to bottom"), this); m_alignToBottom->setIcon(QIcon(":/report/images/alignToBottom")); - connect(m_alignToBottom,SIGNAL(triggered()),this,SLOT(slotAlignToBottom())); + connect(m_alignToBottom, SIGNAL(triggered()), this, SLOT(slotAlignToBottom())); addAction(m_alignToBottom); - m_alignToHCenter = new QAction(tr("Align to horizontal center"),this); + m_alignToHCenter = new QAction(tr("Align to horizontal center"), this); m_alignToHCenter->setIcon(QIcon(":/report/images/alignToHCenter")); - connect(m_alignToHCenter,SIGNAL(triggered()),this,SLOT(slotAlignToHCenter())); + connect(m_alignToHCenter, SIGNAL(triggered()), this, SLOT(slotAlignToHCenter())); addAction(m_alignToHCenter); - m_sameHeight = new QAction(tr("Set same height"),this); + m_sameHeight = new QAction(tr("Set same height"), this); m_sameHeight->setIcon(QIcon(":/report/images/sameHeight")); - connect(m_sameHeight,SIGNAL(triggered()),this,SLOT(slotSameHeight())); + connect(m_sameHeight, SIGNAL(triggered()), this, SLOT(slotSameHeight())); addAction(m_sameHeight); - m_sameWidth = new QAction(tr("Set same width"),this); + m_sameWidth = new QAction(tr("Set same width"), this); m_sameWidth->setIcon(QIcon(":/report/images/sameWidth")); - connect(m_sameWidth,SIGNAL(triggered()),this,SLOT(slotSameWidth())); + connect(m_sameWidth, SIGNAL(triggered()), this, SLOT(slotSameWidth())); addAction(m_sameWidth); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/items/editors/lritemsaligneditorwidget.h b/limereport/items/editors/lritemsaligneditorwidget.h index 3ce4213..cff4a2f 100644 --- a/limereport/items/editors/lritemsaligneditorwidget.h +++ b/limereport/items/editors/lritemsaligneditorwidget.h @@ -31,19 +31,21 @@ #define LRITEMSALIGNEDITORWIDGET_H #include "lrreportdesignwidget.h" -#include + #include +#include -namespace LimeReport{ +namespace LimeReport { -class ItemsAlignmentEditorWidget : public QToolBar -{ +class ItemsAlignmentEditorWidget: public QToolBar { Q_OBJECT public: - explicit ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, const QString &title, QWidget *parent = 0); - explicit ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, QWidget *parent = 0); - explicit ItemsAlignmentEditorWidget(PageDesignIntf* page, const QString &title, QWidget *parent = 0); - explicit ItemsAlignmentEditorWidget(PageDesignIntf* page, QWidget *parent = 0); + explicit ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, const QString& title, + QWidget* parent = 0); + explicit ItemsAlignmentEditorWidget(ReportDesignWidget* reportEditor, QWidget* parent = 0); + explicit ItemsAlignmentEditorWidget(PageDesignIntf* page, const QString& title, + QWidget* parent = 0); + explicit ItemsAlignmentEditorWidget(PageDesignIntf* page, QWidget* parent = 0); private slots: void slotBringToFront(); void slotSendToBack(); @@ -55,6 +57,7 @@ private slots: void slotAlignToHCenter(); void slotSameHeight(); void slotSameWidth(); + private: void initEditor(); ReportDesignWidget* m_reportEditor; @@ -72,6 +75,6 @@ private: QAction* m_sameWidth; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRITEMSALIGNEDITORWIDGET_H diff --git a/limereport/items/editors/lritemsborderseditorwidget.cpp b/limereport/items/editors/lritemsborderseditorwidget.cpp index a49aef2..48e16e2 100644 --- a/limereport/items/editors/lritemsborderseditorwidget.cpp +++ b/limereport/items/editors/lritemsborderseditorwidget.cpp @@ -28,57 +28,56 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lritemsborderseditorwidget.h" -#include + #include "lrbordereditor.h" -namespace LimeReport{ + +#include +namespace LimeReport { void ItemsBordersEditorWidget::setItemEvent(BaseDesignIntf* item) { - if(QString(item->metaObject()->className()) == "LimeReport::ShapeItem") - { + if (QString(item->metaObject()->className()) == "LimeReport::ShapeItem") { setDisabled(true); return; } - QVariant borders=item->property("borders"); - if (borders.isValid()){ + QVariant borders = item->property("borders"); + if (borders.isValid()) { updateValues((BaseDesignIntf::BorderLines)borders.toInt()); setEnabled(true); } m_item = item; } -void ItemsBordersEditorWidget::properyChangedEvent(const QString& property, const QVariant& oldValue, const QVariant& newValue) +void ItemsBordersEditorWidget::properyChangedEvent(const QString& property, + const QVariant& oldValue, + const QVariant& newValue) { Q_UNUSED(oldValue) - if (property == "borders"){ + if (property == "borders") { m_changing = true; updateValues((BaseDesignIntf::BorderLines)newValue.toInt()); m_changing = false; } } -void ItemsBordersEditorWidget::noBordesClicked() -{ - updateValues({}); -} +void ItemsBordersEditorWidget::noBordesClicked() { updateValues({}); } void ItemsBordersEditorWidget::allBordesClicked() { - int borders = BaseDesignIntf::LeftLine | - BaseDesignIntf::RightLine | - BaseDesignIntf::TopLine | - BaseDesignIntf::BottomLine; + int borders = BaseDesignIntf::LeftLine | BaseDesignIntf::RightLine | BaseDesignIntf::TopLine + | BaseDesignIntf::BottomLine; updateValues((BaseDesignIntf::BorderLines)borders); } -void ItemsBordersEditorWidget::buttonClicked(bool){} +void ItemsBordersEditorWidget::buttonClicked(bool) { } void ItemsBordersEditorWidget::editBorderClicked() { BorderEditor be; be.loadItem(m_item); - if ( be.exec() == QDialog::Rejected ) return; + if (be.exec() == QDialog::Rejected) + return; updateValues(be.borderSides()); m_item->setBorderLinesFlags(be.borderSides()); m_item->setBorderLineSize(be.borderWidth()); @@ -89,49 +88,48 @@ void ItemsBordersEditorWidget::editBorderClicked() void ItemsBordersEditorWidget::initEditor() { - m_topLine = new QAction(tr("Top line"),this); + m_topLine = new QAction(tr("Top line"), this); m_topLine->setIcon(QIcon(":/report/images/topLine")); m_topLine->setCheckable(true); - connect(m_topLine,SIGNAL(toggled(bool)),this,SLOT(buttonClicked(bool))); + connect(m_topLine, SIGNAL(toggled(bool)), this, SLOT(buttonClicked(bool))); addAction(m_topLine); - m_bottomLine = new QAction(tr("Bottom line"),this); + m_bottomLine = new QAction(tr("Bottom line"), this); m_bottomLine->setIcon(QIcon(":/report/images/bottomLine")); m_bottomLine->setCheckable(true); - connect(m_bottomLine,SIGNAL(toggled(bool)),this,SLOT(buttonClicked(bool))); + connect(m_bottomLine, SIGNAL(toggled(bool)), this, SLOT(buttonClicked(bool))); addAction(m_bottomLine); - m_leftLine = new QAction(tr("Left line"),this); + m_leftLine = new QAction(tr("Left line"), this); m_leftLine->setIcon(QIcon(":/report/images/leftLine")); m_leftLine->setCheckable(true); - connect(m_leftLine,SIGNAL(toggled(bool)),this,SLOT(buttonClicked(bool))); + connect(m_leftLine, SIGNAL(toggled(bool)), this, SLOT(buttonClicked(bool))); addAction(m_leftLine); - m_rightLine = new QAction(tr("Right line"),this); + m_rightLine = new QAction(tr("Right line"), this); m_rightLine->setIcon(QIcon(":/report/images/rightLine")); m_rightLine->setCheckable(true); - connect(m_rightLine,SIGNAL(toggled(bool)),this,SLOT(buttonClicked(bool))); + connect(m_rightLine, SIGNAL(toggled(bool)), this, SLOT(buttonClicked(bool))); addAction(m_rightLine); addSeparator(); - m_noLines = new QAction(tr("No borders"),this); + m_noLines = new QAction(tr("No borders"), this); m_noLines->setIcon(QIcon(":/report/images/noLines")); - connect(m_noLines,SIGNAL(triggered()),this,SLOT(noBordesClicked())); + connect(m_noLines, SIGNAL(triggered()), this, SLOT(noBordesClicked())); addAction(m_noLines); - m_allLines = new QAction(tr("All borders"),this); + m_allLines = new QAction(tr("All borders"), this); m_allLines->setIcon(QIcon(":/report/images/allLines")); - connect(m_allLines,SIGNAL(triggered()),this,SLOT(allBordesClicked())); + connect(m_allLines, SIGNAL(triggered()), this, SLOT(allBordesClicked())); addAction(m_allLines); addSeparator(); - m_BorderEditor = new QAction(tr("Edit border"),this); + m_BorderEditor = new QAction(tr("Edit border"), this); m_BorderEditor->setIcon(QIcon(":/report/images/borderEditor")); - connect(m_BorderEditor,SIGNAL(triggered()),this,SLOT(editBorderClicked())); + connect(m_BorderEditor, SIGNAL(triggered()), this, SLOT(editBorderClicked())); addAction(m_BorderEditor); setEnabled(false); - } void ItemsBordersEditorWidget::updateValues(BaseDesignIntf::BorderLines borders) @@ -147,17 +145,14 @@ void ItemsBordersEditorWidget::updateValues(BaseDesignIntf::BorderLines borders) BaseDesignIntf::BorderLines ItemsBordersEditorWidget::createBorders() { int borders = 0; - borders += (m_topLine->isChecked()) ? BaseDesignIntf::TopLine:0; - borders += (m_bottomLine->isChecked()) ? BaseDesignIntf::BottomLine:0; - borders += (m_leftLine->isChecked()) ? BaseDesignIntf::LeftLine:0; - borders += (m_rightLine->isChecked()) ? BaseDesignIntf::RightLine:0; + borders += (m_topLine->isChecked()) ? BaseDesignIntf::TopLine : 0; + borders += (m_bottomLine->isChecked()) ? BaseDesignIntf::BottomLine : 0; + borders += (m_leftLine->isChecked()) ? BaseDesignIntf::LeftLine : 0; + borders += (m_rightLine->isChecked()) ? BaseDesignIntf::RightLine : 0; return (BaseDesignIntf::BorderLines)borders; } -bool ItemsBordersEditorWidget::changing() const -{ - return m_changing; -} +bool ItemsBordersEditorWidget::changing() const { return m_changing; } #ifdef HAVE_REPORT_DESIGNER void ItemsBordersEditorWidgetForDesigner::buttonClicked(bool) @@ -182,16 +177,14 @@ void ItemsBordersEditorWidgetForDesigner::editBorderClicked() { BorderEditor be; be.loadItem(m_item); - if ( be.exec() == QDialog::Rejected ) return; + if (be.exec() == QDialog::Rejected) + return; - m_reportEditor->setBordersExt( - be.borderSides(), - be.borderWidth(), - (LimeReport::BaseDesignIntf::BorderStyle)be.borderStyle(), - be.borderColor() - ); + m_reportEditor->setBordersExt(be.borderSides(), be.borderWidth(), + (LimeReport::BaseDesignIntf::BorderStyle)be.borderStyle(), + be.borderColor()); } #endif -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/items/editors/lritemsborderseditorwidget.h b/limereport/items/editors/lritemsborderseditorwidget.h index ef83dbc..3742cc0 100644 --- a/limereport/items/editors/lritemsborderseditorwidget.h +++ b/limereport/items/editors/lritemsborderseditorwidget.h @@ -30,18 +30,21 @@ #ifndef LRITEMSBORDERSEDITORWIDGET_H #define LRITEMSBORDERSEDITORWIDGET_H -#include -#include "lrreportdesignwidget.h" #include "lritemeditorwidget.h" +#include "lrreportdesignwidget.h" -namespace LimeReport{ +#include -class ItemsBordersEditorWidget : public ItemEditorWidget -{ +namespace LimeReport { + +class ItemsBordersEditorWidget: public ItemEditorWidget { Q_OBJECT public: - explicit ItemsBordersEditorWidget(const QString &title, QWidget *parent = 0) - : ItemEditorWidget(title, parent), m_changing(false), m_borders(0){ + explicit ItemsBordersEditorWidget(const QString& title, QWidget* parent = 0): + ItemEditorWidget(title, parent), + m_changing(false), + m_borders(0) + { initEditor(); } bool changing() const; @@ -50,11 +53,14 @@ protected slots: virtual void allBordesClicked(); virtual void buttonClicked(bool); virtual void editBorderClicked(); + protected: - void setItemEvent(BaseDesignIntf *item); - void properyChangedEvent(const QString &property, const QVariant &oldValue, const QVariant &newValue); + void setItemEvent(BaseDesignIntf* item); + void properyChangedEvent(const QString& property, const QVariant& oldValue, + const QVariant& newValue); BaseDesignIntf::BorderLines createBorders(); - BaseDesignIntf *m_item; + BaseDesignIntf* m_item; + private: void initEditor(); void updateValues(BaseDesignIntf::BorderLines borders); @@ -67,26 +73,29 @@ private: QAction* m_BorderEditor; bool m_changing; int m_borders; - }; #ifdef HAVE_REPORT_DESIGNER -class ItemsBordersEditorWidgetForDesigner : public ItemsBordersEditorWidget{ +class ItemsBordersEditorWidgetForDesigner: public ItemsBordersEditorWidget { Q_OBJECT public: - explicit ItemsBordersEditorWidgetForDesigner(ReportDesignWidget* reportEditor, const QString &title="", QWidget *parent = 0) - : ItemsBordersEditorWidget(title,parent), m_reportEditor(reportEditor){} + explicit ItemsBordersEditorWidgetForDesigner(ReportDesignWidget* reportEditor, + const QString& title = "", QWidget* parent = 0): + ItemsBordersEditorWidget(title, parent), + m_reportEditor(reportEditor) + { + } protected slots: void buttonClicked(bool); void noBordesClicked(); void allBordesClicked(); void editBorderClicked(); + private: ReportDesignWidget* m_reportEditor; - }; #endif -}//namespace LimeReport +} // namespace LimeReport #endif // LRITEMSBORDERSEDITORWIDGET_H diff --git a/limereport/items/editors/lrtextalignmenteditorwidget.cpp b/limereport/items/editors/lrtextalignmenteditorwidget.cpp index 2569555..73f09b8 100644 --- a/limereport/items/editors/lrtextalignmenteditorwidget.cpp +++ b/limereport/items/editors/lrtextalignmenteditorwidget.cpp @@ -29,17 +29,19 @@ ****************************************************************************/ #include "lrtextalignmenteditorwidget.h" -namespace LimeReport{ -TextAlignmentEditorWidget::TextAlignmentEditorWidget(const QString& title, QWidget* parent) - :ItemEditorWidget(title, parent), m_textAttibutesIsChanging(false), m_flag(0) +namespace LimeReport { +TextAlignmentEditorWidget::TextAlignmentEditorWidget(const QString& title, QWidget* parent): + ItemEditorWidget(title, parent), + m_textAttibutesIsChanging(false), + m_flag(0) { initEditor(); } -void TextAlignmentEditorWidget::setItemEvent(BaseDesignIntf *item) +void TextAlignmentEditorWidget::setItemEvent(BaseDesignIntf* item) { - QVariant align=item->property("alignment"); - if (align.isValid()){ + QVariant align = item->property("alignment"); + if (align.isValid()) { updateValues(Qt::Alignment(align.value())); setEnabled(true); } @@ -47,178 +49,197 @@ void TextAlignmentEditorWidget::setItemEvent(BaseDesignIntf *item) void TextAlignmentEditorWidget::initEditor() { - m_textAliginLeft = new QAction(tr("Text align left"),this); + m_textAliginLeft = new QAction(tr("Text align left"), this); m_textAliginLeft->setIcon(QIcon(":/report/images/textAlignHLeft")); m_textAliginLeft->setCheckable(true); - connect(m_textAliginLeft,SIGNAL(toggled(bool)),this,SLOT(slotTextHAttribsChanged(bool))); + connect(m_textAliginLeft, SIGNAL(toggled(bool)), this, SLOT(slotTextHAttribsChanged(bool))); addAction(m_textAliginLeft); - m_textAliginHCenter = new QAction(tr("Text align center"),this); + m_textAliginHCenter = new QAction(tr("Text align center"), this); m_textAliginHCenter->setIcon(QIcon(":/report/images/textAlignHCenter")); m_textAliginHCenter->setCheckable(true); - connect(m_textAliginHCenter,SIGNAL(toggled(bool)),this,SLOT(slotTextHAttribsChanged(bool))); + connect(m_textAliginHCenter, SIGNAL(toggled(bool)), this, SLOT(slotTextHAttribsChanged(bool))); addAction(m_textAliginHCenter); - m_textAliginRight = new QAction(tr("Text align right"),this); + m_textAliginRight = new QAction(tr("Text align right"), this); m_textAliginRight->setIcon(QIcon(":/report/images/textAlignHRight")); m_textAliginRight->setCheckable(true); - connect(m_textAliginRight,SIGNAL(toggled(bool)),this,SLOT(slotTextHAttribsChanged(bool))); + connect(m_textAliginRight, SIGNAL(toggled(bool)), this, SLOT(slotTextHAttribsChanged(bool))); addAction(m_textAliginRight); - m_textAliginJustify = new QAction(tr("Text align justify"),this); + m_textAliginJustify = new QAction(tr("Text align justify"), this); m_textAliginJustify->setIcon(QIcon(":/report/images/textAlignHJustify")); m_textAliginJustify->setCheckable(true); - connect(m_textAliginJustify,SIGNAL(toggled(bool)),this,SLOT(slotTextHAttribsChanged(bool))); + connect(m_textAliginJustify, SIGNAL(toggled(bool)), this, SLOT(slotTextHAttribsChanged(bool))); addAction(m_textAliginJustify); addSeparator(); - m_textAliginTop = new QAction(tr("Text align top"),this); + m_textAliginTop = new QAction(tr("Text align top"), this); m_textAliginTop->setIcon(QIcon(":/report/images/textAlignVTop")); m_textAliginTop->setCheckable(true); - connect(m_textAliginTop,SIGNAL(toggled(bool)),this,SLOT(slotTextVAttribsChanged(bool))); + connect(m_textAliginTop, SIGNAL(toggled(bool)), this, SLOT(slotTextVAttribsChanged(bool))); addAction(m_textAliginTop); - m_textAliginVCenter = new QAction(tr("Text align center"),this); + m_textAliginVCenter = new QAction(tr("Text align center"), this); m_textAliginVCenter->setIcon(QIcon(":/report/images/textAlignVCenter")); m_textAliginVCenter->setCheckable(true); - connect(m_textAliginVCenter,SIGNAL(toggled(bool)),this,SLOT(slotTextVAttribsChanged(bool))); + connect(m_textAliginVCenter, SIGNAL(toggled(bool)), this, SLOT(slotTextVAttribsChanged(bool))); addAction(m_textAliginVCenter); - m_textAliginBottom = new QAction(tr("Text align bottom"),this); + m_textAliginBottom = new QAction(tr("Text align bottom"), this); m_textAliginBottom->setIcon(QIcon(":/report/images/textAlignVBottom")); m_textAliginBottom->setCheckable(true); - connect(m_textAliginBottom,SIGNAL(toggled(bool)),this,SLOT(slotTextVAttribsChanged(bool))); + connect(m_textAliginBottom, SIGNAL(toggled(bool)), this, SLOT(slotTextVAttribsChanged(bool))); addAction(m_textAliginBottom); setEnabled(false); } -void TextAlignmentEditorWidget::updateValues(const Qt::Alignment &align) +void TextAlignmentEditorWidget::updateValues(const Qt::Alignment& align) { - m_textAttibutesIsChanging=true; - m_textAliginLeft->setChecked((align & Qt::AlignLeft)==Qt::AlignLeft); - m_textAliginRight->setChecked((align & Qt::AlignRight)==Qt::AlignRight); - m_textAliginHCenter->setChecked((align & Qt::AlignHCenter)==Qt::AlignHCenter); - m_textAliginJustify->setChecked((align & Qt::AlignJustify)==Qt::AlignJustify); - m_textAliginTop->setChecked((align & Qt::AlignTop)==Qt::AlignTop); - m_textAliginVCenter->setChecked((align & Qt::AlignVCenter)==Qt::AlignVCenter); - m_textAliginBottom->setChecked((align & Qt::AlignBottom)==Qt::AlignBottom); - m_textAttibutesIsChanging=false; + m_textAttibutesIsChanging = true; + m_textAliginLeft->setChecked((align & Qt::AlignLeft) == Qt::AlignLeft); + m_textAliginRight->setChecked((align & Qt::AlignRight) == Qt::AlignRight); + m_textAliginHCenter->setChecked((align & Qt::AlignHCenter) == Qt::AlignHCenter); + m_textAliginJustify->setChecked((align & Qt::AlignJustify) == Qt::AlignJustify); + m_textAliginTop->setChecked((align & Qt::AlignTop) == Qt::AlignTop); + m_textAliginVCenter->setChecked((align & Qt::AlignVCenter) == Qt::AlignVCenter); + m_textAliginBottom->setChecked((align & Qt::AlignBottom) == Qt::AlignBottom); + m_textAttibutesIsChanging = false; } Qt::Alignment TextAlignmentEditorWidget::createAlignment() { Qt::Alignment align = Qt::Alignment(); - if (m_textAliginLeft->isChecked()) align |= Qt::AlignLeft; - if (m_textAliginHCenter->isChecked()) align |= Qt::AlignHCenter; - if (m_textAliginRight->isChecked()) align |= Qt::AlignRight; - if (m_textAliginJustify->isChecked()) align |= Qt::AlignJustify; - if (m_textAliginTop->isChecked()) align |= Qt::AlignTop; - if (m_textAliginVCenter->isChecked()) align |= Qt::AlignVCenter; - if (m_textAliginBottom->isChecked()) align |= Qt::AlignBottom; + if (m_textAliginLeft->isChecked()) + align |= Qt::AlignLeft; + if (m_textAliginHCenter->isChecked()) + align |= Qt::AlignHCenter; + if (m_textAliginRight->isChecked()) + align |= Qt::AlignRight; + if (m_textAliginJustify->isChecked()) + align |= Qt::AlignJustify; + if (m_textAliginTop->isChecked()) + align |= Qt::AlignTop; + if (m_textAliginVCenter->isChecked()) + align |= Qt::AlignVCenter; + if (m_textAliginBottom->isChecked()) + align |= Qt::AlignBottom; return align; } void TextAlignmentEditorWidget::slotTextHAttribsChanged(bool) { - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_textAliginLeft->setChecked(sender()==m_textAliginLeft); - m_textAliginHCenter->setChecked(sender()==m_textAliginHCenter); - m_textAliginRight->setChecked(sender()==m_textAliginRight); - m_textAliginJustify->setChecked(sender()==m_textAliginJustify); + m_textAliginLeft->setChecked(sender() == m_textAliginLeft); + m_textAliginHCenter->setChecked(sender() == m_textAliginHCenter); + m_textAliginRight->setChecked(sender() == m_textAliginRight); + m_textAliginJustify->setChecked(sender() == m_textAliginJustify); m_flag = 0; - if (sender()==m_textAliginLeft) m_flag |= Qt::AlignLeft; - if (sender()==m_textAliginHCenter) m_flag |= Qt::AlignHCenter; - if (sender()==m_textAliginRight) m_flag |= Qt::AlignRight; - if (sender()==m_textAliginJustify) m_flag |= Qt::AlignJustify; + if (sender() == m_textAliginLeft) + m_flag |= Qt::AlignLeft; + if (sender() == m_textAliginHCenter) + m_flag |= Qt::AlignHCenter; + if (sender() == m_textAliginRight) + m_flag |= Qt::AlignRight; + if (sender() == m_textAliginJustify) + m_flag |= Qt::AlignJustify; m_textAttibutesIsChanging = false; } void TextAlignmentEditorWidget::slotTextVAttribsChanged(bool) { - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_textAliginTop->setChecked(sender()==m_textAliginTop); - m_textAliginVCenter->setChecked(sender()==m_textAliginVCenter); - m_textAliginBottom->setChecked(sender()==m_textAliginBottom); + m_textAliginTop->setChecked(sender() == m_textAliginTop); + m_textAliginVCenter->setChecked(sender() == m_textAliginVCenter); + m_textAliginBottom->setChecked(sender() == m_textAliginBottom); m_flag = 0; - if (sender()==m_textAliginTop) m_flag |= Qt::AlignTop; - if (sender()==m_textAliginVCenter) m_flag |= Qt::AlignVCenter; - if (sender()==m_textAliginBottom) m_flag |= Qt::AlignBottom; + if (sender() == m_textAliginTop) + m_flag |= Qt::AlignTop; + if (sender() == m_textAliginVCenter) + m_flag |= Qt::AlignVCenter; + if (sender() == m_textAliginBottom) + m_flag |= Qt::AlignBottom; m_textAttibutesIsChanging = false; } -void TextAlignmentEditorWidget::slotPropertyChanged(const QString &objectName, const QString &property, const QVariant &oldValue, const QVariant &newValue) +void TextAlignmentEditorWidget::slotPropertyChanged(const QString& objectName, + const QString& property, + const QVariant& oldValue, + const QVariant& newValue) { Q_UNUSED(oldValue) Q_UNUSED(newValue) - if (item()&&(item()->objectName()==objectName)&&(property=="alignment")){ + if (item() && (item()->objectName() == objectName) && (property == "alignment")) { updateValues(Qt::Alignment(item()->property("alignment").value())); } } -int TextAlignmentEditorWidget::flag() const -{ - return m_flag; -} +int TextAlignmentEditorWidget::flag() const { return m_flag; } void TextAlignmentEditorWidgetForPage::initEditor() { TextAlignmentEditorWidget::initEditor(); - connect(m_page,SIGNAL(itemPropertyChanged(QString,QString,QVariant,QVariant)), - this,SLOT(slotPropertyChanged(QString,QString,QVariant,QVariant))); + connect(m_page, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QString, QVariant, QVariant))); } void TextAlignmentEditorWidgetForPage::slotTextHAttribsChanged(bool value) { TextAlignmentEditorWidget::slotTextHAttribsChanged(value); - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_page->changeSelectedGrpoupTextAlignPropperty(true,Qt::AlignmentFlag(flag())); + m_page->changeSelectedGrpoupTextAlignPropperty(true, Qt::AlignmentFlag(flag())); m_textAttibutesIsChanging = false; } void TextAlignmentEditorWidgetForPage::slotTextVAttribsChanged(bool value) { TextAlignmentEditorWidget::slotTextVAttribsChanged(value); - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_page->changeSelectedGrpoupTextAlignPropperty(false,Qt::AlignmentFlag(flag()) ); + m_page->changeSelectedGrpoupTextAlignPropperty(false, Qt::AlignmentFlag(flag())); m_textAttibutesIsChanging = false; } #ifdef HAVE_REPORT_DESIGNER void TextAlignmentEditorWidgetForDesigner::initEditor() { - connect(m_reportEditor,SIGNAL(itemPropertyChanged(QString,QString,QVariant,QVariant)), - this,SLOT(slotPropertyChanged(QString,QString,QVariant,QVariant))); - + connect(m_reportEditor, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QString, QVariant, QVariant))); } void TextAlignmentEditorWidgetForDesigner::slotTextHAttribsChanged(bool value) { TextAlignmentEditorWidget::slotTextHAttribsChanged(value); - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_reportEditor->setTextAlign(true,Qt::AlignmentFlag(flag())); + m_reportEditor->setTextAlign(true, Qt::AlignmentFlag(flag())); m_textAttibutesIsChanging = false; } void TextAlignmentEditorWidgetForDesigner::slotTextVAttribsChanged(bool value) { TextAlignmentEditorWidget::slotTextVAttribsChanged(value); - if (m_textAttibutesIsChanging) return; + if (m_textAttibutesIsChanging) + return; m_textAttibutesIsChanging = true; - m_reportEditor->setTextAlign(false,Qt::AlignmentFlag(flag())); + m_reportEditor->setTextAlign(false, Qt::AlignmentFlag(flag())); m_textAttibutesIsChanging = false; } #endif -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/items/editors/lrtextalignmenteditorwidget.h b/limereport/items/editors/lrtextalignmenteditorwidget.h index 958f25a..ca5d5b0 100644 --- a/limereport/items/editors/lrtextalignmenteditorwidget.h +++ b/limereport/items/editors/lrtextalignmenteditorwidget.h @@ -30,30 +30,34 @@ #ifndef LRTEXTALIGNMENTEDITORWIDGET_H #define LRTEXTALIGNMENTEDITORWIDGET_H -#include "lrreportdesignwidget.h" #include "lritemeditorwidget.h" -#include +#include "lrreportdesignwidget.h" + #include +#include -namespace LimeReport{ +namespace LimeReport { -class TextAlignmentEditorWidget:public ItemEditorWidget -{ +class TextAlignmentEditorWidget: public ItemEditorWidget { Q_OBJECT public: - explicit TextAlignmentEditorWidget(const QString &title, QWidget *parent = 0); + explicit TextAlignmentEditorWidget(const QString& title, QWidget* parent = 0); int flag() const; + protected: - void setItemEvent(BaseDesignIntf *item); + void setItemEvent(BaseDesignIntf* item); void initEditor(); bool m_textAttibutesIsChanging; + private: void updateValues(const Qt::Alignment& align); Qt::Alignment createAlignment(); protected slots: virtual void slotTextHAttribsChanged(bool); virtual void slotTextVAttribsChanged(bool); - virtual void slotPropertyChanged(const QString& objectName, const QString& property, const QVariant &oldValue, const QVariant &newValue); + virtual void slotPropertyChanged(const QString& objectName, const QString& property, + const QVariant& oldValue, const QVariant& newValue); + private: QAction* m_textAliginLeft; QAction* m_textAliginRight; @@ -65,36 +69,49 @@ private: int m_flag; }; -class TextAlignmentEditorWidgetForPage: public TextAlignmentEditorWidget{ +class TextAlignmentEditorWidgetForPage: public TextAlignmentEditorWidget { Q_OBJECT public: - TextAlignmentEditorWidgetForPage(PageDesignIntf* page, const QString &title, QWidget *parent = 0) - :TextAlignmentEditorWidget(title, parent), m_page(page){} + TextAlignmentEditorWidgetForPage(PageDesignIntf* page, const QString& title, + QWidget* parent = 0): + TextAlignmentEditorWidget(title, parent), + m_page(page) + { + } + protected: void initEditor(); protected slots: void slotTextHAttribsChanged(bool value); void slotTextVAttribsChanged(bool value); + private: PageDesignIntf* m_page; }; #ifdef HAVE_REPORT_DESIGNER -class TextAlignmentEditorWidgetForDesigner: public TextAlignmentEditorWidget{ +class TextAlignmentEditorWidgetForDesigner: public TextAlignmentEditorWidget { Q_OBJECT public: - TextAlignmentEditorWidgetForDesigner(ReportDesignWidget* reportEditor, const QString &title, QWidget *parent = 0) - :TextAlignmentEditorWidget(title, parent), m_reportEditor(reportEditor){initEditor();} + TextAlignmentEditorWidgetForDesigner(ReportDesignWidget* reportEditor, const QString& title, + QWidget* parent = 0): + TextAlignmentEditorWidget(title, parent), + m_reportEditor(reportEditor) + { + initEditor(); + } + protected: void initEditor(); protected slots: void slotTextHAttribsChanged(bool value); void slotTextVAttribsChanged(bool value); + private: ReportDesignWidget* m_reportEditor; }; #endif -} //namespace LimeReport +} // namespace LimeReport #endif // LRTEXTALIGNMENTEDITORWIDGET_H diff --git a/limereport/items/lrabstractlayout.cpp b/limereport/items/lrabstractlayout.cpp index b1b9e0c..726a7ab 100644 --- a/limereport/items/lrabstractlayout.cpp +++ b/limereport/items/lrabstractlayout.cpp @@ -2,9 +2,12 @@ namespace LimeReport { -AbstractLayout::AbstractLayout(QString xmlTag, QObject* owner, QGraphicsItem* parent) - : LayoutDesignIntf(xmlTag, owner, parent), m_isRelocating(false), m_layoutType(Layout), - m_hideEmptyItems(false), m_layoutSpacing(0) +AbstractLayout::AbstractLayout(QString xmlTag, QObject* owner, QGraphicsItem* parent): + LayoutDesignIntf(xmlTag, owner, parent), + m_isRelocating(false), + m_layoutType(Layout), + m_hideEmptyItems(false), + m_layoutSpacing(0) { setPossibleResizeDirectionFlags(AllDirections); m_layoutMarker = new LayoutMarker(this); @@ -17,38 +20,25 @@ AbstractLayout::AbstractLayout(QString xmlTag, QObject* owner, QGraphicsItem* pa AbstractLayout::~AbstractLayout() { if (m_layoutMarker) { - delete m_layoutMarker; m_layoutMarker=0; + delete m_layoutMarker; + m_layoutMarker = 0; } } -QList& AbstractLayout::layoutsChildren() -{ - return m_children; -} +QList& AbstractLayout::layoutsChildren() { return m_children; } -bool AbstractLayout::isRelocating() const -{ - return m_isRelocating; -} +bool AbstractLayout::isRelocating() const { return m_isRelocating; } -void AbstractLayout::setIsRelocating(bool isRelocating) -{ - m_isRelocating = isRelocating; -} +void AbstractLayout::setIsRelocating(bool isRelocating) { m_isRelocating = isRelocating; } -AbstractLayout::LayoutType AbstractLayout::layoutType() const -{ - return m_layoutType; -} +AbstractLayout::LayoutType AbstractLayout::layoutType() const { return m_layoutType; } -void AbstractLayout::setLayoutType(const LayoutType& layoutType) -{ - m_layoutType = layoutType; -} +void AbstractLayout::setLayoutType(const LayoutType& layoutType) { m_layoutType = layoutType; } void AbstractLayout::addChild(BaseDesignIntf* item, bool updateSize) { - if (updateSize) placeItemInLayout(item); + if (updateSize) + placeItemInLayout(item); m_children.append(item); item->setParentItem(this); @@ -58,13 +48,13 @@ void AbstractLayout::addChild(BaseDesignIntf* item, bool updateSize) connectToLayout(item); - if (updateSize){ + if (updateSize) { relocateChildren(); updateLayoutSize(); } } -void AbstractLayout::removeChild(BaseDesignIntf *item) +void AbstractLayout::removeChild(BaseDesignIntf* item) { if (!item) { return; @@ -75,8 +65,9 @@ void AbstractLayout::removeChild(BaseDesignIntf *item) void AbstractLayout::restoreChild(BaseDesignIntf* item) { - if (m_children.contains(item)) return; - m_isRelocating=true; + if (m_children.contains(item)) + return; + m_isRelocating = true; insertItemInLayout(item); @@ -88,7 +79,7 @@ void AbstractLayout::restoreChild(BaseDesignIntf* item) item->setParentItem(this); updateLayoutSize(); - m_isRelocating=false; + m_isRelocating = false; } bool AbstractLayout::isEmpty() const @@ -97,54 +88,49 @@ bool AbstractLayout::isEmpty() const bool allItemsIsText = true; foreach (QGraphicsItem* qgItem, childItems()) { ContentItemDesignIntf* item = dynamic_cast(qgItem); - if (item && !item->content().isEmpty()) isEmpty = false; + if (item && !item->content().isEmpty()) + isEmpty = false; if (!item && dynamic_cast(qgItem)) allItemsIsText = false; } return (isEmpty && allItemsIsText); } -void AbstractLayout::paintChild(BaseDesignIntf *child, QPointF parentPos, QPainter *painter) +void AbstractLayout::paintChild(BaseDesignIntf* child, QPointF parentPos, QPainter* painter) { - if (!child->childBaseItems().isEmpty()){ + if (!child->childBaseItems().isEmpty()) { foreach (BaseDesignIntf* item, child->childBaseItems()) { - paintChild(item, child->pos(),painter); + paintChild(item, child->pos(), painter); } } - painter->drawRect( - QRectF(parentPos.x()+child->pos().x(), parentPos.y()+child->pos().y(), - child->rect().bottomRight().rx(), - child->rect().bottomRight().ry() - ) - ); + painter->drawRect(QRectF(parentPos.x() + child->pos().x(), parentPos.y() + child->pos().y(), + child->rect().bottomRight().rx(), child->rect().bottomRight().ry())); } -void AbstractLayout::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void AbstractLayout::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { - if (isSelected()){ + if (isSelected()) { painter->save(); painter->setPen(Qt::red); - foreach( BaseDesignIntf* item, m_children){ - paintChild(item, QPointF(0,0), painter); + foreach (BaseDesignIntf* item, m_children) { + paintChild(item, QPointF(0, 0), painter); } painter->restore(); } LayoutDesignIntf::paint(painter, option, widget); } -int AbstractLayout::childrenCount() -{ - return m_children.size(); -} +int AbstractLayout::childrenCount() { return m_children.size(); } void AbstractLayout::beforeDelete() { #ifdef HAVE_QT5 - foreach (QObject *item, children()) { + foreach (QObject* item, children()) { #else - foreach (QObject *item, QObject::children()) { + foreach (QObject* item, QObject::children()) { #endif - BaseDesignIntf *bi = dynamic_cast(item); + BaseDesignIntf* bi = dynamic_cast(item); if (bi) { bi->disconnect(this); bi->setParentItem(parentItem()); @@ -158,16 +144,13 @@ void AbstractLayout::beforeDelete() m_children.clear(); } -void AbstractLayout::childAddedEvent(BaseDesignIntf* child) -{ - addChild(child,false); -} +void AbstractLayout::childAddedEvent(BaseDesignIntf* child) { addChild(child, false); } void AbstractLayout::geometryChangedEvent(QRectF newRect, QRectF) { layoutMarker()->setHeight(newRect.height()); relocateChildren(); - if (!isRelocating()){ + if (!isRelocating()) { divideSpace(); } } @@ -175,7 +158,7 @@ void AbstractLayout::geometryChangedEvent(QRectF newRect, QRectF) void AbstractLayout::initMode(BaseDesignIntf::ItemMode mode) { BaseDesignIntf::initMode(mode); - if ((mode==PreviewMode)||(mode==PrintMode)){ + if ((mode == PreviewMode) || (mode == PrintMode)) { layoutMarker()->setVisible(false); } else { layoutMarker()->setVisible(true); @@ -185,22 +168,22 @@ void AbstractLayout::initMode(BaseDesignIntf::ItemMode mode) void AbstractLayout::setBorderLinesFlags(BaseDesignIntf::BorderLines flags) { BaseDesignIntf::setBorderLinesFlags(flags); - if (flags!=0) + if (flags != 0) relocateChildren(); } void AbstractLayout::collectionLoadFinished(const QString& collectionName) { ItemDesignIntf::collectionLoadFinished(collectionName); - if (collectionName.compare("children",Qt::CaseInsensitive)==0){ + if (collectionName.compare("children", Qt::CaseInsensitive) == 0) { #ifdef HAVE_QT5 - foreach(QObject* obj, children()){ + foreach (QObject* obj, children()) { #else - foreach(QObject* obj,QObject::children()){ + foreach (QObject* obj, QObject::children()) { #endif BaseDesignIntf* item = dynamic_cast(obj); if (item) { - addChild(item,false); + addChild(item, false); } } } @@ -220,9 +203,9 @@ bool AbstractLayout::isNeedUpdateSize(RenderPass pass) const QVariant AbstractLayout::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant& value) { - if (change == QGraphicsItem::ItemSelectedHasChanged){ + if (change == QGraphicsItem::ItemSelectedHasChanged) { setIsRelocating(true); - foreach(BaseDesignIntf* item, layoutsChildren()){ + foreach (BaseDesignIntf* item, layoutsChildren()) { item->setVisible(!value.toBool()); } setIsRelocating(false); @@ -234,7 +217,7 @@ void AbstractLayout::updateItemSize(DataSourceManager* dataManager, RenderPass p { setIsRelocating(true); ItemDesignIntf::updateItemSize(dataManager, pass, maxHeight); - foreach(QGraphicsItem *child, childItems()){ + foreach (QGraphicsItem* child, childItems()) { BaseDesignIntf* item = dynamic_cast(child); if (item && item->isNeedUpdateSize(pass)) item->updateItemSize(dataManager, pass, maxHeight); @@ -245,8 +228,9 @@ void AbstractLayout::updateItemSize(DataSourceManager* dataManager, RenderPass p BaseDesignIntf::updateItemSize(dataManager, pass, maxHeight); } -void AbstractLayout::rebuildChildrenIfNeeded(){ - if (layoutsChildren().count() < childItems().size()-1){ +void AbstractLayout::rebuildChildrenIfNeeded() +{ + if (layoutsChildren().count() < childItems().size() - 1) { layoutsChildren().clear(); foreach (BaseDesignIntf* childItem, childBaseItems()) { layoutsChildren().append(childItem); @@ -255,89 +239,75 @@ void AbstractLayout::rebuildChildrenIfNeeded(){ } } -void AbstractLayout::connectToLayout(BaseDesignIntf *item) +void AbstractLayout::connectToLayout(BaseDesignIntf* item) { - connect( - item, SIGNAL(destroyed(QObject*)), - this, SLOT(slotOnChildDestroy(QObject*)) - ); - connect( - item,SIGNAL(geometryChanged(QObject*,QRectF,QRectF)), - this,SLOT(slotOnChildGeometryChanged(QObject*,QRectF,QRectF)) - ); - connect( - item, SIGNAL(itemVisibleHasChanged(BaseDesignIntf*)), - this, SLOT(slotOnChildVisibleHasChanged(BaseDesignIntf*)) - ); - connect( - item, SIGNAL(itemSelectedHasBeenChanged(BaseDesignIntf*,bool)), - this, SLOT(slotOnChildSelectionHasChanged(BaseDesignIntf*,bool)) - ); - connect( - item, SIGNAL(itemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&)), - this, SLOT(slotOnChildItemAlignChanged(BaseDesignIntf*,const ItemAlign&,const ItemAlign&)) - ); + connect(item, SIGNAL(destroyed(QObject*)), this, SLOT(slotOnChildDestroy(QObject*))); + connect(item, SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), this, + SLOT(slotOnChildGeometryChanged(QObject*, QRectF, QRectF))); + connect(item, SIGNAL(itemVisibleHasChanged(BaseDesignIntf*)), this, + SLOT(slotOnChildVisibleHasChanged(BaseDesignIntf*))); + connect(item, SIGNAL(itemSelectedHasBeenChanged(BaseDesignIntf*, bool)), this, + SLOT(slotOnChildSelectionHasChanged(BaseDesignIntf*, bool))); + connect(item, SIGNAL(itemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&)), + this, + SLOT(slotOnChildItemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&))); } -void AbstractLayout::disconnectFromLayout(BaseDesignIntf *item) +void AbstractLayout::disconnectFromLayout(BaseDesignIntf* item) { + disconnect(item, SIGNAL(destroyed(QObject*)), this, SLOT(slotOnChildDestroy(QObject*))); + disconnect(item, SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), this, + SLOT(slotOnChildGeometryChanged(QObject*, QRectF, QRectF))); + disconnect(item, SIGNAL(itemVisibleHasChanged(BaseDesignIntf*)), this, + SLOT(slotOnChildVisibleHasChanged(BaseDesignIntf*))); + disconnect(item, SIGNAL(itemSelectedHasBeenChanged(BaseDesignIntf*, bool)), this, + SLOT(slotOnChildSelectionHasChanged(BaseDesignIntf*, bool))); disconnect( - item, SIGNAL(destroyed(QObject*)), - this, SLOT(slotOnChildDestroy(QObject*)) - ); - disconnect( - item,SIGNAL(geometryChanged(QObject*,QRectF,QRectF)), - this,SLOT(slotOnChildGeometryChanged(QObject*,QRectF,QRectF)) - ); - disconnect( - item, SIGNAL(itemVisibleHasChanged(BaseDesignIntf*)), - this, SLOT(slotOnChildVisibleHasChanged(BaseDesignIntf*)) - ); - disconnect( - item, SIGNAL(itemSelectedHasBeenChanged(BaseDesignIntf*,bool)), - this, SLOT(slotOnChildSelectionHasChanged(BaseDesignIntf*,bool)) - ); - disconnect( - item, SIGNAL(itemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&)), - this, SLOT(slotOnChildItemAlignChanged(BaseDesignIntf*,const ItemAlign&,const ItemAlign&)) - ); + item, SIGNAL(itemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&)), this, + SLOT(slotOnChildItemAlignChanged(BaseDesignIntf*, const ItemAlign&, const ItemAlign&))); } -BaseDesignIntf *AbstractLayout::findNext(BaseDesignIntf *item) +BaseDesignIntf* AbstractLayout::findNext(BaseDesignIntf* item) { rebuildChildrenIfNeeded(); - for (int i=0; ii+1){ return layoutsChildren()[i+1];} + for (int i = 0; i < layoutsChildren().count(); ++i) { + if (layoutsChildren()[i] == item && layoutsChildren().size() > i + 1) { + return layoutsChildren()[i + 1]; + } } return 0; } -BaseDesignIntf *AbstractLayout::findPrior(BaseDesignIntf *item) +BaseDesignIntf* AbstractLayout::findPrior(BaseDesignIntf* item) { rebuildChildrenIfNeeded(); - for (int i=0; ipos() == item->pos()){ + if (child->pos() == item->pos()) { layoutsChildren().insert(i, item); inserted = true; break; } } - if (!inserted) layoutsChildren().append(item); + if (!inserted) + layoutsChildren().append(item); } void AbstractLayout::slotOnChildDestroy(QObject* child) { m_children.removeAll(static_cast(child)); - if (m_children.count() < 2 && !static_cast(child)){ + if (m_children.count() < 2 && !static_cast(child)) { beforeDelete(); } else { relocateChildren(); @@ -345,19 +315,20 @@ void AbstractLayout::slotOnChildDestroy(QObject* child) } } -void AbstractLayout::slotOnChildGeometryChanged(QObject* item, QRectF newGeometry, QRectF oldGeometry) +void AbstractLayout::slotOnChildGeometryChanged(QObject* item, QRectF newGeometry, + QRectF oldGeometry) { - if (!m_isRelocating && !isLoading()){ - if (m_layoutType == Layout){ + if (!m_isRelocating && !isLoading()) { + if (m_layoutType == Layout) { relocateChildren(); updateLayoutSize(); } else { m_isRelocating = true; - qreal delta = newGeometry.width()-oldGeometry.width(); + qreal delta = newGeometry.width() - oldGeometry.width(); BaseDesignIntf* resizingItem = findNext(dynamic_cast(item)); if (resizingItem) { - resizingItem->setWidth(resizingItem->width()-delta); - resizingItem->setPos(resizingItem->pos().x()+delta,resizingItem->pos().y()); + resizingItem->setWidth(resizingItem->width() - delta); + resizingItem->setPos(resizingItem->pos().x() + delta, resizingItem->pos().y()); } updateLayoutSize(); m_isRelocating = false; @@ -365,7 +336,8 @@ void AbstractLayout::slotOnChildGeometryChanged(QObject* item, QRectF newGeometr } } -void AbstractLayout::slotOnChildItemAlignChanged(BaseDesignIntf* item, const ItemAlign&, const ItemAlign&) +void AbstractLayout::slotOnChildItemAlignChanged(BaseDesignIntf* item, const ItemAlign&, + const ItemAlign&) { item->setPossibleResizeDirectionFlags(ResizeBottom | ResizeRight); } @@ -373,28 +345,25 @@ void AbstractLayout::slotOnChildItemAlignChanged(BaseDesignIntf* item, const Ite void AbstractLayout::slotOnChildVisibleHasChanged(BaseDesignIntf*) { relocateChildren(); - if (m_layoutType == Table && !m_isRelocating){ + if (m_layoutType == Table && !m_isRelocating) { divideSpace(); } } void AbstractLayout::slotOnChildSelectionHasChanged(BaseDesignIntf* item, bool value) { - item->setZValue(value ? item->zValue()+1 : item->zValue()-1); + item->setZValue(value ? item->zValue() + 1 : item->zValue() - 1); } -int AbstractLayout::layoutSpacing() const -{ - return m_layoutSpacing; -} +int AbstractLayout::layoutSpacing() const { return m_layoutSpacing; } void AbstractLayout::setLayoutSpacing(int layoutSpacing) { - if (m_layoutSpacing != layoutSpacing){ + if (m_layoutSpacing != layoutSpacing) { int oldValue = m_layoutSpacing; m_layoutSpacing = layoutSpacing; - if (!isLoading()){ - int delta = (m_layoutSpacing - oldValue) * (m_children.count()-1); + if (!isLoading()) { + int delta = (m_layoutSpacing - oldValue) * (m_children.count() - 1); notify("layoutSpacing", oldValue, m_layoutSpacing); setWidth(width() + delta); } @@ -402,16 +371,13 @@ void AbstractLayout::setLayoutSpacing(int layoutSpacing) } } -bool AbstractLayout::hideEmptyItems() const -{ - return m_hideEmptyItems; -} +bool AbstractLayout::hideEmptyItems() const { return m_hideEmptyItems; } void AbstractLayout::setHideEmptyItems(bool hideEmptyItems) { m_hideEmptyItems = hideEmptyItems; - if (m_hideEmptyItems != hideEmptyItems){ + if (m_hideEmptyItems != hideEmptyItems) { m_hideEmptyItems = hideEmptyItems; notify("hideEmptyItems", !m_hideEmptyItems, m_hideEmptyItems); } @@ -420,13 +386,11 @@ void AbstractLayout::setHideEmptyItems(bool hideEmptyItems) QObject* AbstractLayout::at(int index) { rebuildChildrenIfNeeded(); - if (layoutsChildren().size() > index) return layoutsChildren()[index]; + if (layoutsChildren().size() > index) + return layoutsChildren()[index]; return 0; } -LayoutMarker* AbstractLayout::layoutMarker() const -{ - return m_layoutMarker; -} +LayoutMarker* AbstractLayout::layoutMarker() const { return m_layoutMarker; } } // namespace LimeReport diff --git a/limereport/items/lrabstractlayout.h b/limereport/items/lrabstractlayout.h index 6d32391..aecc079 100644 --- a/limereport/items/lrabstractlayout.h +++ b/limereport/items/lrabstractlayout.h @@ -3,22 +3,25 @@ #include "lritemdesignintf.h" #include "lrlayoutmarker.h" + #include -namespace LimeReport{ -class AbstractLayout: public LayoutDesignIntf -{ +namespace LimeReport { +class AbstractLayout: public LayoutDesignIntf { Q_OBJECT Q_PROPERTY(bool hideEmptyItems READ hideEmptyItems WRITE setHideEmptyItems) Q_PROPERTY(int layoutSpacing READ layoutSpacing WRITE setLayoutSpacing) public: - enum LayoutType{Layout,Table}; + enum LayoutType { + Layout, + Table + }; #if QT_VERSION >= 0x050500 Q_ENUM(LayoutType) #else Q_ENUMS(LayoutType) #endif - AbstractLayout(QString xmlTag, QObject *owner = 0, QGraphicsItem *parent = 0); + AbstractLayout(QString xmlTag, QObject* owner = 0, QGraphicsItem* parent = 0); ~AbstractLayout(); QList& layoutsChildren(); LayoutMarker* layoutMarker() const; @@ -27,9 +30,9 @@ public: LayoutType layoutType() const; void setLayoutType(const LayoutType& layoutType); - void addChild(BaseDesignIntf *item,bool updateSize=true); - void removeChild(BaseDesignIntf *item); - void restoreChild(BaseDesignIntf *item); + void addChild(BaseDesignIntf* item, bool updateSize = true); + void removeChild(BaseDesignIntf* item); + void restoreChild(BaseDesignIntf* item); bool isEmpty() const; void paintChild(BaseDesignIntf* child, QPointF parentPos, QPainter* painter); void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); @@ -37,42 +40,45 @@ public: bool hideEmptyItems() const; void setHideEmptyItems(bool hideEmptyItems); Q_INVOKABLE QObject* at(int index); - int childrenCount(); + int childrenCount(); int layoutSpacing() const; void setLayoutSpacing(int layoutSpacing); - qreal layoutSpacingMM(){ return m_layoutSpacing * Const::mmFACTOR;} + qreal layoutSpacingMM() { return m_layoutSpacing * Const::mmFACTOR; } + protected: void beforeDelete(); - void childAddedEvent(BaseDesignIntf *child); + void childAddedEvent(BaseDesignIntf* child); void geometryChangedEvent(QRectF newRect, QRectF); void initMode(ItemMode mode); void setBorderLinesFlags(BorderLines flags); - void collectionLoadFinished(const QString &collectionName); + void collectionLoadFinished(const QString& collectionName); void objectLoadFinished(); bool isNeedUpdateSize(RenderPass pass) const; - QVariant itemChange(GraphicsItemChange change, const QVariant &value); + QVariant itemChange(GraphicsItemChange change, const QVariant& value); void updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight); void rebuildChildrenIfNeeded(); void connectToLayout(BaseDesignIntf* item); void disconnectFromLayout(BaseDesignIntf* item); virtual void insertItemInLayout(BaseDesignIntf* item); + private: virtual void sortChildren() = 0; virtual void divideSpace() = 0; virtual void updateLayoutSize() = 0; virtual void relocateChildren() = 0; - virtual BaseDesignIntf* findNext(BaseDesignIntf *item); - virtual BaseDesignIntf* findPrior(BaseDesignIntf *item); + virtual BaseDesignIntf* findNext(BaseDesignIntf* item); + virtual BaseDesignIntf* findPrior(BaseDesignIntf* item); virtual void placeItemInLayout(BaseDesignIntf* item) = 0; private slots: - void slotOnChildDestroy(QObject *child); - void slotOnChildGeometryChanged(QObject*item, QRectF newGeometry, QRectF oldGeometry); + void slotOnChildDestroy(QObject* child); + void slotOnChildGeometryChanged(QObject* item, QRectF newGeometry, QRectF oldGeometry); void slotOnChildItemAlignChanged(BaseDesignIntf* item, const ItemAlign&, const ItemAlign&); void slotOnChildVisibleHasChanged(BaseDesignIntf*); void slotOnChildSelectionHasChanged(BaseDesignIntf* item, bool value); + private: - QList m_children; + QList m_children; bool m_isRelocating; LayoutMarker* m_layoutMarker; LayoutType m_layoutType; diff --git a/limereport/items/lralignpropitem.cpp b/limereport/items/lralignpropitem.cpp index 5edb725..e2718f7 100644 --- a/limereport/items/lralignpropitem.cpp +++ b/limereport/items/lralignpropitem.cpp @@ -28,54 +28,63 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lralignpropitem.h" -#include "objectinspector/propertyItems/lrenumpropitem.h" -#include "objectinspector/editors/lrcomboboxeditor.h" + #include "lrtextitem.h" +#include "objectinspector/editors/lrcomboboxeditor.h" +#include "objectinspector/propertyItems/lrenumpropitem.h" -namespace{ - LimeReport::ObjectPropItem * createAlignItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly - ){ - return new LimeReport::AlignmentPropItem(object, objects, name, displayName, data, parent, readonly); - } - - bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("alignment","LimeReport::TextItem"), - QObject::tr("alignment"), - createAlignItem - ); +namespace { +LimeReport::ObjectPropItem* createAlignItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::AlignmentPropItem(object, objects, name, displayName, data, parent, + readonly); } -namespace LimeReport{ +bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("alignment", "LimeReport::TextItem"), QObject::tr("alignment"), + createAlignItem); +} // namespace + +namespace LimeReport { QString AlignmentPropItem::associateValue(int value, const AlignMap* map) const { QString result; - QMap::const_iterator it = map->constBegin(); - for(;it!= map->constEnd();++it){ + QMap::const_iterator it = map->constBegin(); + for (; it != map->constEnd(); ++it) { if ((value & it.value())) { - if (result.isEmpty()) result+=it.key(); - else result=result+" | "+it.key(); + if (result.isEmpty()) + result += it.key(); + else + result = result + " | " + it.key(); } } return result; } -AlignmentPropItem::AlignmentPropItem(QObject *object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem *parent, bool readonly) - :ObjectPropItem(object, objects, name,displayName,value,parent,readonly) +AlignmentPropItem::AlignmentPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) { - m_horizMap.insert(tr("Left"),Qt::AlignLeft); - m_horizMap.insert(tr("Right"),Qt::AlignRight); - m_horizMap.insert(tr("Center"),Qt::AlignHCenter); - m_horizMap.insert(tr("Justify"),Qt::AlignJustify); + m_horizMap.insert(tr("Left"), Qt::AlignLeft); + m_horizMap.insert(tr("Right"), Qt::AlignRight); + m_horizMap.insert(tr("Center"), Qt::AlignHCenter); + m_horizMap.insert(tr("Justify"), Qt::AlignJustify); - m_vertMap.insert(tr("Top"),Qt::AlignTop); - m_vertMap.insert(tr("Center"),Qt::AlignVCenter); - m_vertMap.insert(tr("Botom"),Qt::AlignBottom); + m_vertMap.insert(tr("Top"), Qt::AlignTop); + m_vertMap.insert(tr("Center"), Qt::AlignVCenter); + m_vertMap.insert(tr("Botom"), Qt::AlignBottom); - m_horizEditor = new AlignmentItemEditor(object, objects, name,tr("horizontal"),value.toInt(),this,false,m_horizMap); - m_vertEditor = new AlignmentItemEditor(object, objects, name,tr("vertical"), value.toInt(),this,false,m_vertMap); + m_horizEditor = new AlignmentItemEditor(object, objects, name, tr("horizontal"), value.toInt(), + this, false, m_horizMap); + m_vertEditor = new AlignmentItemEditor(object, objects, name, tr("vertical"), value.toInt(), + this, false, m_vertMap); this->appendItem(m_horizEditor); this->appendItem(m_vertEditor); @@ -83,8 +92,8 @@ AlignmentPropItem::AlignmentPropItem(QObject *object, ObjectsList* objects, cons QString AlignmentPropItem::displayValue() const { - return associateValue(propertyValue().toInt(),&m_horizMap)+" | "+ - associateValue(propertyValue().toInt(),&m_vertMap); + return associateValue(propertyValue().toInt(), &m_horizMap) + " | " + + associateValue(propertyValue().toInt(), &m_vertMap); } void AlignmentPropItem::setPropertyValue(QVariant value) @@ -94,62 +103,67 @@ void AlignmentPropItem::setPropertyValue(QVariant value) ObjectPropItem::setPropertyValue(value); } -AlignmentItemEditor::AlignmentItemEditor(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, - bool readonly, AlignMap acceptableValues) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly),m_acceptableValues(acceptableValues) +AlignmentItemEditor::AlignmentItemEditor(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly, + AlignMap acceptableValues): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly), + m_acceptableValues(acceptableValues) { - if (! extractAcceptableValue(value.toInt()).isEmpty()) + if (!extractAcceptableValue(value.toInt()).isEmpty()) setPropertyValue(extractAcceptableValue(value.toInt())[0]); - else setPropertyValue(0); + else + setPropertyValue(0); } -void AlignmentItemEditor::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void AlignmentItemEditor::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { int flags = object()->property(propertyName().toLatin1()).toInt(); int align = m_acceptableValues.value(qobject_cast(propertyEditor)->text()); - flags=clearAcceptableValues(flags) | align; - object()->setProperty(propertyName().toLatin1(),flags); + flags = clearAcceptableValues(flags) | align; + object()->setProperty(propertyName().toLatin1(), flags); if (objects()) - foreach(QObject* item,*objects()){item->setProperty(propertyName().toLatin1(),flags);} + foreach (QObject* item, *objects()) { + item->setProperty(propertyName().toLatin1(), flags); + } parent()->setPropertyValue(flags); - model->setData(index,align); + model->setData(index, align); } QVector AlignmentItemEditor::extractAcceptableValue(int flags) { QVector result; AlignMap::const_iterator it = m_acceptableValues.constBegin(); - for (;it != m_acceptableValues.constEnd();++it) - { - if (flags & it.value()) result<addItems(enumValues); return editor; } -void AlignmentItemEditor::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void AlignmentItemEditor::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - ComboBoxEditor *editor=qobject_cast(propertyEditor); + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(m_acceptableValues.key(Qt::Alignment(propertyValue().toInt()))); } @@ -160,10 +174,11 @@ QString AlignmentItemEditor::displayValue() const void AlignmentItemEditor::setPropertyValue(QVariant value) { - QVector _accpepttableValueList= extractAcceptableValue(value.toInt()); - if(_accpepttableValueList.isEmpty()) return; + QVector _accpepttableValueList = extractAcceptableValue(value.toInt()); + if (_accpepttableValueList.isEmpty()) + return; ObjectPropItem::setPropertyValue(_accpepttableValueList[0]); } -} +} // namespace LimeReport diff --git a/limereport/items/lralignpropitem.h b/limereport/items/lralignpropitem.h index 0dae738..8bf7a8b 100644 --- a/limereport/items/lralignpropitem.h +++ b/limereport/items/lralignpropitem.h @@ -33,48 +33,51 @@ #include "lrobjectpropitem.h" #include "objectinspector/propertyItems/lrenumpropitem.h" -namespace LimeReport{ +namespace LimeReport { -typedef QMap AlignMap; +typedef QMap AlignMap; class AlignmentItemEditor; -class AlignmentPropItem : public ObjectPropItem -{ +class AlignmentPropItem: public ObjectPropItem { Q_OBJECT public: - AlignmentPropItem():ObjectPropItem(),m_horizEditor(NULL),m_vertEditor(NULL){} - AlignmentPropItem(QObject *object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly=true); + AlignmentPropItem(): ObjectPropItem(), m_horizEditor(NULL), m_vertEditor(NULL) { } + AlignmentPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true); QString displayValue() const; void setPropertyValue(QVariant value); + private: AlignMap m_vertMap; AlignMap m_horizMap; AlignmentItemEditor* m_horizEditor; AlignmentItemEditor* m_vertEditor; - QString associateValue(int value, const AlignMap *map) const; + QString associateValue(int value, const AlignMap* map) const; }; -class AlignmentItemEditor : public ObjectPropItem -{ +class AlignmentItemEditor: public ObjectPropItem { Q_OBJECT public: - AlignmentItemEditor():ObjectPropItem(){} - AlignmentItemEditor(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly, - AlignMap acceptableValues); - void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); - void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - QWidget* createProperyEditor(QWidget *parent) const; - QString displayValue() const; + AlignmentItemEditor(): ObjectPropItem() { } + AlignmentItemEditor(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly, AlignMap acceptableValues); + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + QWidget* createProperyEditor(QWidget* parent) const; + QString displayValue() const; void setPropertyValue(QVariant value); + protected: - QVector extractAcceptableValue(int flags); - int clearAcceptableValues(int flags); - AlignMap acceptableValues() const {return m_acceptableValues;} + QVector extractAcceptableValue(int flags); + int clearAcceptableValues(int flags); + AlignMap acceptableValues() const { return m_acceptableValues; } + private: AlignMap m_acceptableValues; }; - -} +} // namespace LimeReport #endif // LRALIGNPROPITEM_H diff --git a/limereport/items/lrbarcodeitem.cpp b/limereport/items/lrbarcodeitem.cpp index 78a242c..0f6f225 100644 --- a/limereport/items/lrbarcodeitem.cpp +++ b/limereport/items/lrbarcodeitem.cpp @@ -28,44 +28,59 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrbarcodeitem.h" -#include "lrdesignelementsfactory.h" -#include "qzint.h" -#include "lrglobal.h" -namespace{ +#include "lrdesignelementsfactory.h" +#include "lrglobal.h" +#include "qzint.h" + +namespace { const QString xmlTag = "BarcodeItem"; -LimeReport::BaseDesignIntf * createBarcodeItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::BarcodeItem(owner,parent); -} -bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator(xmlTag, LimeReport::ItemAttribs(QObject::tr("Barcode Item"),"Item"), createBarcodeItem); - -} - -namespace LimeReport{ - -BarcodeItem::BarcodeItem(QObject* owner,QGraphicsItem* parent) - : ContentItemDesignIntf(xmlTag,owner,parent),m_designTestValue("1"), m_barcodeType(CODE128), - m_foregroundColor(Qt::black), m_backgroundColor(Qt::white), m_whitespace(10), m_angle(Angle0), - m_barcodeWidth(0), m_securityLevel(0), m_pdf417CodeWords(928), m_inputMode(UNICODE_INPUT_MODE), - m_hideText(false), m_option3(0), m_hideIfEmpty(false) -{} - -BarcodeItem::~BarcodeItem() -{} - -BaseDesignIntf *BarcodeItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +LimeReport::BaseDesignIntf* createBarcodeItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::BarcodeItem(owner, parent); +} +bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTag, LimeReport::ItemAttribs(QObject::tr("Barcode Item"), "Item"), createBarcodeItem); + +} // namespace + +namespace LimeReport { + +BarcodeItem::BarcodeItem(QObject* owner, QGraphicsItem* parent): + ContentItemDesignIntf(xmlTag, owner, parent), + m_designTestValue("1"), + m_barcodeType(CODE128), + m_foregroundColor(Qt::black), + m_backgroundColor(Qt::white), + m_whitespace(10), + m_angle(Angle0), + m_barcodeWidth(0), + m_securityLevel(0), + m_pdf417CodeWords(928), + m_inputMode(UNICODE_INPUT_MODE), + m_hideText(false), + m_option3(0), + m_hideIfEmpty(false) { - return new BarcodeItem(owner,parent); } -void BarcodeItem::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *option, QWidget *widget) +BarcodeItem::~BarcodeItem() { } + +BaseDesignIntf* BarcodeItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) +{ + return new BarcodeItem(owner, parent); +} + +void BarcodeItem::paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, QWidget* widget) { ppainter->save(); Zint::QZint bc; - if (itemMode() & DesignMode) bc.setText(m_designTestValue); - else bc.setText(m_content); + if (itemMode() & DesignMode) + bc.setText(m_designTestValue); + else + bc.setText(m_content); bc.setInputMode(m_inputMode); bc.setSymbol(m_barcodeType); bc.setWhitespace(m_whitespace); @@ -77,7 +92,8 @@ void BarcodeItem::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *opti bc.setHideText(m_hideText); bc.setOption3(m_option3); - if (isSelected()) ppainter->setOpacity(Const::SELECTION_OPACITY); + if (isSelected()) + ppainter->setOpacity(Const::SELECTION_OPACITY); QRectF bcRect; @@ -86,45 +102,42 @@ void BarcodeItem::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *opti bcRect = rect(); break; case Angle90: - ppainter->translate(width(),0); + ppainter->translate(width(), 0); ppainter->rotate(90); - bcRect = QRectF(0,0,height(),width()); + bcRect = QRectF(0, 0, height(), width()); break; case Angle180: bcRect = rect(); - ppainter->translate(width(),height()); + ppainter->translate(width(), height()); ppainter->rotate(180); break; case Angle270: - ppainter->translate(0,height()); + ppainter->translate(0, height()); ppainter->rotate(270); - bcRect = QRectF(0,0,height(),width()); + bcRect = QRectF(0, 0, height(), width()); break; } - bc.render(*ppainter,bcRect); + bc.render(*ppainter, bcRect); ppainter->restore(); - ItemDesignIntf::paint(ppainter,option,widget); + ItemDesignIntf::paint(ppainter, option, widget); } -void BarcodeItem::setContent(const QString &content) +void BarcodeItem::setContent(const QString& content) { - if (m_content!=content){ + if (m_content != content) { QString oldValue = m_content; - m_content=content; + m_content = content; update(); - notify("content",oldValue,m_content); + notify("content", oldValue, m_content); } } -QString BarcodeItem::datasource() const -{ - return m_datasource; -} +QString BarcodeItem::datasource() const { return m_datasource; } -void BarcodeItem::setDatasource(const QString &datasource) +void BarcodeItem::setDatasource(const QString& datasource) { - if (m_datasource != datasource){ + if (m_datasource != datasource) { QString oldValue = m_datasource; m_datasource = datasource; update(); @@ -132,14 +145,11 @@ void BarcodeItem::setDatasource(const QString &datasource) } } -QString BarcodeItem::field() const -{ - return m_field; -} +QString BarcodeItem::field() const { return m_field; } -void BarcodeItem::setField(const QString &field) +void BarcodeItem::setField(const QString& field) { - if (m_field != field){ + if (m_field != field) { QString oldValue = m_field; m_field = field; update(); @@ -149,189 +159,162 @@ void BarcodeItem::setField(const QString &field) void BarcodeItem::setBarcodeType(BarcodeItem::BarcodeType value) { - if (m_barcodeType!=value){ + if (m_barcodeType != value) { BarcodeType oldValue = m_barcodeType; m_barcodeType = value; update(); - notify("barcodeType",oldValue,value); + notify("barcodeType", oldValue, value); } } void BarcodeItem::setDesignTestValue(QString value) { - if (m_designTestValue!=value){ + if (m_designTestValue != value) { QString oldValue = m_designTestValue; - m_designTestValue=value; + m_designTestValue = value; update(); - notify("testValue",oldValue,value); + notify("testValue", oldValue, value); } } void BarcodeItem::setForegroundColor(QColor value) { - if (m_foregroundColor != value){ + if (m_foregroundColor != value) { QColor oldValue = m_foregroundColor; - m_foregroundColor=value; + m_foregroundColor = value; update(); - notify("foregroundColor",oldValue,value); + notify("foregroundColor", oldValue, value); } } void BarcodeItem::setBackgroundColor(QColor value) { - if (m_backgroundColor != value){ + if (m_backgroundColor != value) { QColor oldValue = m_backgroundColor; - m_backgroundColor=value; + m_backgroundColor = value; update(); - notify("backgroundColor",oldValue,value); + notify("backgroundColor", oldValue, value); } } void BarcodeItem::setWhitespace(int value) { - if (m_whitespace != value){ + if (m_whitespace != value) { int oldValue = m_whitespace; m_whitespace = value; update(); - notify("whitespace",oldValue,value); + notify("whitespace", oldValue, value); } } -BarcodeItem::AngleType BarcodeItem::angle() const -{ - return m_angle; -} +BarcodeItem::AngleType BarcodeItem::angle() const { return m_angle; } -void BarcodeItem::setAngle(const AngleType &angle) +void BarcodeItem::setAngle(const AngleType& angle) { - if (m_angle!=angle){ + if (m_angle != angle) { AngleType oldValue = m_angle; m_angle = angle; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("angle",oldValue,angle); + notify("angle", oldValue, angle); } } } -int BarcodeItem::barcodeWidth() const -{ - return m_barcodeWidth; -} +int BarcodeItem::barcodeWidth() const { return m_barcodeWidth; } void BarcodeItem::setBarcodeWidth(int barcodeWidth) { - if (m_barcodeWidth != barcodeWidth){ + if (m_barcodeWidth != barcodeWidth) { int oldValue = m_barcodeWidth; m_barcodeWidth = barcodeWidth; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("barcodeWidth",oldValue,m_barcodeWidth); + notify("barcodeWidth", oldValue, m_barcodeWidth); } } } -int BarcodeItem::securityLevel() const -{ - return m_securityLevel; -} +int BarcodeItem::securityLevel() const { return m_securityLevel; } void BarcodeItem::setSecurityLevel(int securityLevel) { - if (m_securityLevel != securityLevel){ + if (m_securityLevel != securityLevel) { int oldValue = m_securityLevel; m_securityLevel = securityLevel; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("securityLevel",oldValue,m_securityLevel); + notify("securityLevel", oldValue, m_securityLevel); } } } -int BarcodeItem::pdf417CodeWords() const -{ - return m_pdf417CodeWords; -} +int BarcodeItem::pdf417CodeWords() const { return m_pdf417CodeWords; } void BarcodeItem::setPdf417CodeWords(int pdf417CodeWords) { - if (m_pdf417CodeWords != pdf417CodeWords){ + if (m_pdf417CodeWords != pdf417CodeWords) { int oldValue = m_pdf417CodeWords; m_pdf417CodeWords = pdf417CodeWords; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("pdf417CodeWords",oldValue,m_pdf417CodeWords); + notify("pdf417CodeWords", oldValue, m_pdf417CodeWords); } } } -BarcodeItem::InputMode BarcodeItem::inputMode() const -{ - return m_inputMode; -} +BarcodeItem::InputMode BarcodeItem::inputMode() const { return m_inputMode; } -void BarcodeItem::setInputMode(const InputMode &inputMode) +void BarcodeItem::setInputMode(const InputMode& inputMode) { - if (m_inputMode != inputMode){ + if (m_inputMode != inputMode) { InputMode oldValue = m_inputMode; m_inputMode = inputMode; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("inputMode",oldValue,inputMode); + notify("inputMode", oldValue, inputMode); } } } -bool BarcodeItem::hideText() const -{ - return m_hideText; -} +bool BarcodeItem::hideText() const { return m_hideText; } void BarcodeItem::setHideText(bool hideText) { - if (m_hideText != hideText){ + if (m_hideText != hideText) { m_hideText = hideText; - if (!isLoading()){ + if (!isLoading()) { update(); notify("hideText", !m_hideText, m_hideText); } } } -int BarcodeItem::option3() const -{ - return m_option3; -} +int BarcodeItem::option3() const { return m_option3; } void BarcodeItem::setOption3(int option3) { - if (m_option3 != option3){ + if (m_option3 != option3) { int oldValue = m_option3; m_option3 = option3; - if(!isLoading()){ + if (!isLoading()) { update(); notify("option3", oldValue, m_option3); } } } -bool BarcodeItem::hideIfEmpty() const -{ - return m_hideIfEmpty; -} +bool BarcodeItem::hideIfEmpty() const { return m_hideIfEmpty; } void BarcodeItem::setHideIfEmpty(bool hideIfEmpty) { - if (m_hideIfEmpty != hideIfEmpty){ + if (m_hideIfEmpty != hideIfEmpty) { m_hideIfEmpty = hideIfEmpty; - notify("hideIfEmpty",!m_hideIfEmpty, m_hideIfEmpty); + notify("hideIfEmpty", !m_hideIfEmpty, m_hideIfEmpty); } } -bool BarcodeItem::isEmpty() const -{ - return m_content.isEmpty(); -} +bool BarcodeItem::isEmpty() const { return m_content.isEmpty(); } void BarcodeItem::expandContent(QString data, DataSourceManager* dataManager, RenderPass pass) { @@ -342,28 +325,23 @@ void BarcodeItem::expandContent(QString data, DataSourceManager* dataManager, Re void BarcodeItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { - if (content().isEmpty()) - { - if (!m_datasource.isEmpty() && !m_field.isEmpty()) - { - IDataSource* ds = dataManager->dataSource(m_datasource); - if (ds) - { - QVariant data = ds->data(m_field); - if (data.isValid()) - { - switch(pass) - { - case FirstPass: - expandContent(data.toString(), dataManager, pass); - break; - default:; - } - } - } + if (content().isEmpty()) { + if (!m_datasource.isEmpty() && !m_field.isEmpty()) { + IDataSource* ds = dataManager->dataSource(m_datasource); + if (ds) { + QVariant data = ds->data(m_field); + if (data.isValid()) { + switch (pass) { + case FirstPass: + expandContent(data.toString(), dataManager, pass); + break; + default:; + } + } + } } } else { - switch(pass){ + switch (pass) { case FirstPass: expandContent(content(), dataManager, pass); break; @@ -371,10 +349,13 @@ void BarcodeItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass } } BaseDesignIntf::updateItemSize(dataManager, pass, maxHeight); - if (isEmpty() && hideIfEmpty()) setVisible(false); + if (isEmpty() && hideIfEmpty()) + setVisible(false); } bool BarcodeItem::isNeedUpdateSize(RenderPass pass) const -{return (pass==FirstPass)?true:false;} - +{ + return (pass == FirstPass) ? true : false; } + +} // namespace LimeReport diff --git a/limereport/items/lrbarcodeitem.h b/limereport/items/lrbarcodeitem.h index b156c14..95f8901 100644 --- a/limereport/items/lrbarcodeitem.h +++ b/limereport/items/lrbarcodeitem.h @@ -30,11 +30,12 @@ #ifndef LRBARCODEITEM_H #define LRBARCODEITEM_H #include "lritemdesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -class BarcodeItem : public LimeReport::ContentItemDesignIntf { +class BarcodeItem: public LimeReport::ContentItemDesignIntf { Q_OBJECT Q_PROPERTY(QString content READ content WRITE setContent) Q_PROPERTY(BarcodeType barcodeType READ barcodeType WRITE setBarcodeType) @@ -54,103 +55,107 @@ class BarcodeItem : public LimeReport::ContentItemDesignIntf { Q_PROPERTY(bool hideIfEmpty READ hideIfEmpty WRITE setHideIfEmpty) public: enum BarcodeType { - CODE11 =1, - C25MATRIX =2, - C25INTER =3, - C25IATA =4, - C25LOGIC =6, - C25IND =7, - CODE39 =8, - EXCODE39 =9, - EANX =13, - EANX_CHK =14, - EAN128 =16, - CODABAR =18, - CODE128 =20, - DPLEIT =21, - DPIDENT =22, - CODE16K =23, - CODE93 =25, - FLAT =28, - RSS14 =29, - RSS_LTD =30, - RSS_EXP =31, - TELEPEN =32, - UPCA =34, - UPCE =37, - POSTNET =40, - MSI_PLESSEY =47, - FIM =49, - LOGMARS =50, - PHARMA =51, - PZN =52, - PHARMA_TWO =53, - PDF417 =55, - PDF417TRUNC =56, - MAXICODE =57, - QRCODE =58, - CODE128B =60, - AUSPOST =63, - AUSREPLY =66, - AUSROUTE =67, - AUSREDIRECT =68, - ISBNX =69, - RM4SCC =70, - DATAMATRIX =71, - ITF14 =72, - CODABLOCKF =74, - NVE18 =75, - KOREAPOST =77, - RSS14STACK =79, - RSS14STACK_OMNI =80, - RSS_EXPSTACK =81, - PLANET =82, - MICROPDF417 =84, - ONECODE =85, - PLESSEY =86, - KIX =90, - AZTEC =92, - DAFT =93, - ITALYPOST =94, - DPD =96, - MICROQR =97, - HIBC_128 =98, - HIBC_39 =99, - HIBC_DM =102, - HIBC_QR =104, - HIBC_PDF =106, - HIBC_MICPDF =108, - HIBC_BLOCKF =110, - HIBC_AZTEC =112, - DOTCODE =115, - HANXIN =116, - TELEPEN_NUM =128, - CODE32 =129, -// EANX_CC =130, -// EAN128_CC =131, -// RSS14_CC =132, -// RSS_LTD_CC =133, -// RSS_EXP_CC =134, -// UPCA_CC =135, -// UPCE_CC =136, -// RSS14STACK_CC =137, -// RSS14_OMNI_CC =138, -// RSS_EXPSTACK_CC =139, - CHANNEL =140, - CODEONE =141, - GRIDMATRIX =142, - UPNQR =143 - + CODE11 = 1, + C25MATRIX = 2, + C25INTER = 3, + C25IATA = 4, + C25LOGIC = 6, + C25IND = 7, + CODE39 = 8, + EXCODE39 = 9, + EANX = 13, + EANX_CHK = 14, + EAN128 = 16, + CODABAR = 18, + CODE128 = 20, + DPLEIT = 21, + DPIDENT = 22, + CODE16K = 23, + CODE93 = 25, + FLAT = 28, + RSS14 = 29, + RSS_LTD = 30, + RSS_EXP = 31, + TELEPEN = 32, + UPCA = 34, + UPCE = 37, + POSTNET = 40, + MSI_PLESSEY = 47, + FIM = 49, + LOGMARS = 50, + PHARMA = 51, + PZN = 52, + PHARMA_TWO = 53, + PDF417 = 55, + PDF417TRUNC = 56, + MAXICODE = 57, + QRCODE = 58, + CODE128B = 60, + AUSPOST = 63, + AUSREPLY = 66, + AUSROUTE = 67, + AUSREDIRECT = 68, + ISBNX = 69, + RM4SCC = 70, + DATAMATRIX = 71, + ITF14 = 72, + CODABLOCKF = 74, + NVE18 = 75, + KOREAPOST = 77, + RSS14STACK = 79, + RSS14STACK_OMNI = 80, + RSS_EXPSTACK = 81, + PLANET = 82, + MICROPDF417 = 84, + ONECODE = 85, + PLESSEY = 86, + KIX = 90, + AZTEC = 92, + DAFT = 93, + ITALYPOST = 94, + DPD = 96, + MICROQR = 97, + HIBC_128 = 98, + HIBC_39 = 99, + HIBC_DM = 102, + HIBC_QR = 104, + HIBC_PDF = 106, + HIBC_MICPDF = 108, + HIBC_BLOCKF = 110, + HIBC_AZTEC = 112, + DOTCODE = 115, + HANXIN = 116, + TELEPEN_NUM = 128, + CODE32 = 129, + // EANX_CC =130, + // EAN128_CC =131, + // RSS14_CC =132, + // RSS_LTD_CC =133, + // RSS_EXP_CC =134, + // UPCA_CC =135, + // UPCE_CC =136, + // RSS14STACK_CC =137, + // RSS14_OMNI_CC =138, + // RSS_EXPSTACK_CC =139, + CHANNEL = 140, + CODEONE = 141, + GRIDMATRIX = 142, + UPNQR = 143 }; - enum AngleType{Angle0,Angle90,Angle180,Angle270}; + enum AngleType { + Angle0, + Angle90, + Angle180, + Angle270 + }; - enum InputMode{ - DATA_INPUT_MODE = 0, - UNICODE_INPUT_MODE = 1, - GS1_INPUT_MODE = 2, - KANJI_INPUT_MODE = 3, - SJIS_INPUT_MODE = 4 + enum InputMode { + DATA_INPUT_MODE = 0, + UNICODE_INPUT_MODE = 1, + GS1_INPUT_MODE = 2, + KANJI_INPUT_MODE = 3, + SJIS_INPUT_MODE = 4 }; #if QT_VERSION >= 0x050500 Q_ENUM(BarcodeType) @@ -161,30 +166,30 @@ public: Q_ENUMS(AngleType) Q_ENUMS(InputMode) #endif - BarcodeItem(QObject *owner, QGraphicsItem *parent); + BarcodeItem(QObject* owner, QGraphicsItem* parent); ~BarcodeItem(); - virtual BaseDesignIntf* createSameTypeItem(QObject *owner, QGraphicsItem *parent); - virtual void paint(QPainter *ppainter, const QStyleOptionGraphicsItem *option, QWidget *widget); - virtual void updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + virtual void paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, QWidget* widget); + virtual void updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight); virtual bool isNeedUpdateSize(RenderPass pass) const; void setContent(const QString& content); - QString content() const {return m_content;} + QString content() const { return m_content; } void setBarcodeType(BarcodeType value); - BarcodeType barcodeType(){return m_barcodeType;} + BarcodeType barcodeType() { return m_barcodeType; } QString datasource() const; - void setDatasource(const QString &datasource); + void setDatasource(const QString& datasource); QString field() const; - void setField(const QString &field); + void setField(const QString& field); void setDesignTestValue(QString value); - QString designTestValue(){return m_designTestValue;} - QColor foregroundColor(){return m_foregroundColor;} + QString designTestValue() { return m_designTestValue; } + QColor foregroundColor() { return m_foregroundColor; } void setForegroundColor(QColor value); - QColor backgroundColor(){return m_backgroundColor;} + QColor backgroundColor() { return m_backgroundColor; } void setBackgroundColor(QColor value); - int whitespace(){return m_whitespace;} + int whitespace() { return m_whitespace; } void setWhitespace(int value); AngleType angle() const; - void setAngle(const AngleType &angle); + void setAngle(const AngleType& angle); int barcodeWidth() const; void setBarcodeWidth(int barcodeWidth); int securityLevel() const; @@ -192,7 +197,7 @@ public: int pdf417CodeWords() const; void setPdf417CodeWords(int pdf417CodeWords); InputMode inputMode() const; - void setInputMode(const InputMode &inputMode); + void setInputMode(const InputMode& inputMode); bool hideText() const; void setHideText(bool hideText); int option3() const; @@ -202,7 +207,7 @@ public: bool isEmpty() const; private: - void expandContent(QString data, DataSourceManager *dataManager, RenderPass pass); + void expandContent(QString data, DataSourceManager* dataManager, RenderPass pass); private: QString m_content; @@ -223,5 +228,5 @@ private: bool m_hideIfEmpty; }; -} +} // namespace LimeReport #endif // LRBARCODEITEM_H diff --git a/limereport/items/lrbordereditor.cpp b/limereport/items/lrbordereditor.cpp index 63d8b88..fc15078 100644 --- a/limereport/items/lrbordereditor.cpp +++ b/limereport/items/lrbordereditor.cpp @@ -1,34 +1,39 @@ #include "lrbordereditor.h" #include "ui_lrbordereditor.h" -#include + #include "lrbasedesignintf.h" -namespace LimeReport{ +#include -BorderEditor::BorderEditor(QWidget *parent) : +namespace LimeReport { + +BorderEditor::BorderEditor(QWidget* parent): QDialog(parent), ui(new Ui::BorderEditor), m_borderStyle(1), m_borderWidth(1) { ui->setupUi(this); - connect( - ui->borderFrame, SIGNAL(borderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool)), - this, SLOT(checkToolButtons(LimeReport::BaseDesignIntf::BorderSide, bool)) - ); + connect(ui->borderFrame, + SIGNAL(borderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool)), this, + SLOT(checkToolButtons(LimeReport::BaseDesignIntf::BorderSide, bool))); } -void BorderEditor::loadItem(LimeReport::BaseDesignIntf *item) +void BorderEditor::loadItem(LimeReport::BaseDesignIntf* item) { m_item = item; emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::TopLine, - item->borderLines() & LimeReport::BaseDesignIntf::TopLine); + item->borderLines() + & LimeReport::BaseDesignIntf::TopLine); emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::LeftLine, - item->borderLines() & LimeReport::BaseDesignIntf::LeftLine); + item->borderLines() + & LimeReport::BaseDesignIntf::LeftLine); emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::RightLine, - item->borderLines() & LimeReport::BaseDesignIntf::RightLine); + item->borderLines() + & LimeReport::BaseDesignIntf::RightLine); emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::BottomLine, - item->borderLines() & LimeReport::BaseDesignIntf::BottomLine); + item->borderLines() + & LimeReport::BaseDesignIntf::BottomLine); QPen pen; pen.setWidthF(item->borderLineSize()); @@ -39,7 +44,7 @@ void BorderEditor::loadItem(LimeReport::BaseDesignIntf *item) ui->listWidget->setCurrentRow((Qt::PenStyle)item->borderStyle()); ui->comboBox->setCurrentText(QString::number(item->borderLineSize())); m_borderWidth = ui->comboBox->currentText().toDouble(); - m_borderStyle =ui->listWidget->currentRow(); + m_borderStyle = ui->listWidget->currentRow(); ui->colorIndicator->setStyleSheet(QString("background-color:%1;").arg(m_borderColor)); } @@ -50,28 +55,19 @@ LimeReport::BaseDesignIntf::BorderLines BorderEditor::borderSides() borders += (ui->bottomLine->isChecked()) ? LimeReport::BaseDesignIntf::BottomLine : 0; borders += (ui->leftLine->isChecked()) ? LimeReport::BaseDesignIntf::LeftLine : 0; borders += (ui->rightLine->isChecked()) ? LimeReport::BaseDesignIntf::RightLine : 0; - return (LimeReport::BaseDesignIntf::BorderLines) borders; + return (LimeReport::BaseDesignIntf::BorderLines)borders; } LimeReport::BaseDesignIntf::BorderStyle BorderEditor::borderStyle() { - return (LimeReport::BaseDesignIntf::BorderStyle) m_borderStyle; + return (LimeReport::BaseDesignIntf::BorderStyle)m_borderStyle; } -QString BorderEditor::borderColor() -{ - return m_borderColor; -} +QString BorderEditor::borderColor() { return m_borderColor; } -double BorderEditor::borderWidth() -{ - return m_borderWidth; -} +double BorderEditor::borderWidth() { return m_borderWidth; } -BorderEditor::~BorderEditor() -{ - delete ui; -} +BorderEditor::~BorderEditor() { delete ui; } void BorderEditor::on_listWidget_currentRowChanged(int currentRow) { @@ -81,7 +77,7 @@ void BorderEditor::on_listWidget_currentRowChanged(int currentRow) ui->borderFrame->setPen(pen); } -void BorderEditor::on_comboBox_currentTextChanged(const QString &arg1) +void BorderEditor::on_comboBox_currentTextChanged(const QString& arg1) { QPen pen = ui->borderFrame->pen(); pen.setWidthF(arg1.toDouble()); @@ -91,61 +87,69 @@ void BorderEditor::on_comboBox_currentTextChanged(const QString &arg1) void BorderEditor::checkToolButtons(LimeReport::BaseDesignIntf::BorderSide side, bool check) { - switch(side) - { - case BaseDesignIntf::BorderSide::TopLine: - ui->topLine->setChecked(check); - break; - case BaseDesignIntf::BorderSide::BottomLine: - ui->bottomLine->setChecked(check); - break; - case BaseDesignIntf::BorderSide::LeftLine: - ui->leftLine->setChecked(check); - break; - case BaseDesignIntf::BorderSide::RightLine: - ui->rightLine->setChecked(check); - break; + switch (side) { + case BaseDesignIntf::BorderSide::TopLine: + ui->topLine->setChecked(check); + break; + case BaseDesignIntf::BorderSide::BottomLine: + ui->bottomLine->setChecked(check); + break; + case BaseDesignIntf::BorderSide::LeftLine: + ui->leftLine->setChecked(check); + break; + case BaseDesignIntf::BorderSide::RightLine: + ui->rightLine->setChecked(check); + break; } } -void BorderEditor::on_topLine_clicked(bool checked){ - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::TopLine, checked); +void BorderEditor::on_topLine_clicked(bool checked) +{ + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::TopLine, + checked); } -void BorderEditor::on_bottomLine_clicked(bool checked){ +void BorderEditor::on_bottomLine_clicked(bool checked) +{ emit ui->borderFrame->borderSideClicked(BaseDesignIntf::BorderSide::BottomLine, checked); } -void BorderEditor::on_leftLine_clicked(bool checked){ +void BorderEditor::on_leftLine_clicked(bool checked) +{ emit ui->borderFrame->borderSideClicked(BaseDesignIntf::BorderSide::LeftLine, checked); } -void BorderEditor::on_rightLine_clicked(bool checked){ +void BorderEditor::on_rightLine_clicked(bool checked) +{ emit ui->borderFrame->borderSideClicked(BaseDesignIntf::BorderSide::RightLine, checked); } - void BorderEditor::on_allLines_clicked() { emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::TopLine, true); - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::BottomLine, true); + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::BottomLine, + true); emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::LeftLine, true); - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::RightLine, true); + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::RightLine, + true); } void BorderEditor::on_noLines_clicked() { emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::TopLine, false); - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::BottomLine, false); - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::LeftLine, false); - emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::RightLine, false); + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::BottomLine, + false); + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::LeftLine, + false); + emit ui->borderFrame->borderSideClicked(LimeReport::BaseDesignIntf::BorderSide::RightLine, + false); } - void BorderEditor::on_selectColor_clicked() { QColorDialog cd(this); - if(cd.exec() == QDialog::Rejected) return; + if (cd.exec() == QDialog::Rejected) + return; QPen pen = ui->borderFrame->pen(); pen.setColor(cd.selectedColor().name()); m_borderColor = pen.color().name(); diff --git a/limereport/items/lrbordereditor.h b/limereport/items/lrbordereditor.h index 2baf2f3..1455c34 100644 --- a/limereport/items/lrbordereditor.h +++ b/limereport/items/lrbordereditor.h @@ -1,23 +1,22 @@ #ifndef LRBORDEREDITOR_H #define LRBORDEREDITOR_H -#include #include "lrbasedesignintf.h" -namespace LimeReport{ +#include + +namespace LimeReport { namespace Ui { class BorderEditor; } - -class LIMEREPORT_EXPORT BorderEditor : public QDialog -{ +class LIMEREPORT_EXPORT BorderEditor: public QDialog { Q_OBJECT public: - explicit BorderEditor(QWidget *parent = nullptr); - void loadItem(LimeReport::BaseDesignIntf *item); + explicit BorderEditor(QWidget* parent = nullptr); + void loadItem(LimeReport::BaseDesignIntf* item); LimeReport::BaseDesignIntf::BorderLines borderSides(); LimeReport::BaseDesignIntf::BorderStyle borderStyle(); QString borderColor(); @@ -26,7 +25,7 @@ public: private slots: void on_listWidget_currentRowChanged(int currentRow); - void on_comboBox_currentTextChanged(const QString &arg1); + void on_comboBox_currentTextChanged(const QString& arg1); void on_noLines_clicked(); void on_topLine_clicked(bool checked); void on_bottomLine_clicked(bool checked); @@ -37,8 +36,8 @@ private slots: void on_selectColor_clicked(); private: - Ui::BorderEditor *ui; - LimeReport::BaseDesignIntf *m_item; + Ui::BorderEditor* ui; + LimeReport::BaseDesignIntf* m_item; QString m_borderColor; int m_borderStyle; double m_borderWidth; diff --git a/limereport/items/lrborderframeeditor.cpp b/limereport/items/lrborderframeeditor.cpp index 46fd9b9..d3f99e0 100644 --- a/limereport/items/lrborderframeeditor.cpp +++ b/limereport/items/lrborderframeeditor.cpp @@ -1,57 +1,56 @@ #include "lrborderframeeditor.h" #include "ui_lrborderframeeditor.h" -#include -#include -#include -#include + #include "lrbasedesignintf.h" #include "lrbordereditor.h" -namespace LimeReport{ +#include +#include +#include +#include -BorderFrameEditor::BorderFrameEditor(QWidget *parent) - : QWidget(parent) - , ui(new Ui::BorderFrameEditor) +namespace LimeReport { + +BorderFrameEditor::BorderFrameEditor(QWidget* parent): + QWidget(parent), + ui(new Ui::BorderFrameEditor) { ui->setupUi(this); scene = new QGraphicsScene(ui->graphicsView); QRect vRect = rect(); - //Draw corder lines - //topLeft + // Draw corder lines + // topLeft scene->addLine(10, 5, 10, 10, QPen(Qt::gray)); scene->addLine(5, 10, 10, 10, QPen(Qt::gray)); - //bottomLeft - scene->addLine(10,vRect.bottom() -5, 10, vRect.bottom()-10, QPen(Qt::gray)); - scene->addLine(5,vRect.bottom()-10, 10, vRect.bottom()-10, QPen(Qt::gray)); - //bottomRight - scene->addLine(vRect.right() - 10, vRect.bottom() - 5, vRect.right()- 10, vRect.bottom() - 10, QPen(Qt::gray)); - scene->addLine(vRect.right() - 5, vRect.bottom() - 10, vRect.right() - 10, vRect.bottom() - 10, QPen(Qt::gray)); - //topRight + // bottomLeft + scene->addLine(10, vRect.bottom() - 5, 10, vRect.bottom() - 10, QPen(Qt::gray)); + scene->addLine(5, vRect.bottom() - 10, 10, vRect.bottom() - 10, QPen(Qt::gray)); + // bottomRight + scene->addLine(vRect.right() - 10, vRect.bottom() - 5, vRect.right() - 10, vRect.bottom() - 10, + QPen(Qt::gray)); + scene->addLine(vRect.right() - 5, vRect.bottom() - 10, vRect.right() - 10, vRect.bottom() - 10, + QPen(Qt::gray)); + // topRight scene->addLine(vRect.width() - 10, 5, vRect.width() - 10, 10, QPen(Qt::gray)); scene->addLine(vRect.width() - 5, 10, vRect.width() - 10, 10, QPen(Qt::gray)); scene->setSceneRect(vRect); ui->graphicsView->setScene(scene); - QGraphicsSimpleTextItem * io = new QGraphicsSimpleTextItem(); + QGraphicsSimpleTextItem* io = new QGraphicsSimpleTextItem(); io->setAcceptedMouseButtons(Qt::LeftButton); io->setPos(scene->sceneRect().center()); io->setText(tr("Text")); scene->addItem(io); QRectF bR = io->sceneBoundingRect(); - io->setPos( scene->sceneRect().center().x() - bR.width()/2, scene->sceneRect().center().y() - bR.height()/2 ); - connect( - this, SIGNAL(borderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool)), - this, SLOT(slotBorderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool)) - ); - + io->setPos(scene->sceneRect().center().x() - bR.width() / 2, + scene->sceneRect().center().y() - bR.height() / 2); + connect(this, SIGNAL(borderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool)), this, + SLOT(slotBorderSideClicked(LimeReport::BaseDesignIntf::BorderSide, bool))); } -BorderFrameEditor::~BorderFrameEditor() -{ - delete ui; -} +BorderFrameEditor::~BorderFrameEditor() { delete ui; } void BorderFrameEditor::setPen(QPen pen) { @@ -59,10 +58,7 @@ void BorderFrameEditor::setPen(QPen pen) updateBorders(); } -QPen BorderFrameEditor::pen() -{ - return m_pen; -} +QPen BorderFrameEditor::pen() { return m_pen; } void BorderFrameEditor::setAllLines() { @@ -78,34 +74,33 @@ void BorderFrameEditor::setAllLines() void BorderFrameEditor::unSetAllLines() { - if (topLine){ + if (topLine) { scene->removeItem(topLine); topLine = NULL; } - if (leftLine){ + if (leftLine) { scene->removeItem(leftLine); leftLine = NULL; } - if (bottomLine){ + if (bottomLine) { scene->removeItem(bottomLine); bottomLine = NULL; } - if (rightLine){ + if (rightLine) { scene->removeItem(rightLine); rightLine = NULL; } - } -void BorderFrameEditor::mousePressEvent(QMouseEvent *event) +void BorderFrameEditor::mousePressEvent(QMouseEvent* event) { - if (event->x() >= 10 && event->y() <30) + if (event->x() >= 10 && event->y() < 30) emit borderSideClicked(BaseDesignIntf::BorderSide::TopLine, !topLine); if ((event->x() >= 10 && event->x() < 30) && (event->y() > 10)) emit borderSideClicked(BaseDesignIntf::BorderSide::LeftLine, !leftLine); - if (event->x() >= 10 && (event->y() >80 && event->y() < rect().bottom())) + if (event->x() >= 10 && (event->y() > 80 && event->y() < rect().bottom())) emit borderSideClicked(BaseDesignIntf::BorderSide::BottomLine, !bottomLine); if ((event->x() >= 130 && event->x() < rect().width()) && event->y() > 10) @@ -115,67 +110,80 @@ void BorderFrameEditor::mousePressEvent(QMouseEvent *event) void BorderFrameEditor::slotBorderSideClicked(BaseDesignIntf::BorderSide side, bool show) { - switch(side){ + switch (side) { case BaseDesignIntf::BorderSide::TopLine: - if (show){ - if (!topLine) topLine = createSideLine(side); + if (show) { + if (!topLine) + topLine = createSideLine(side); } else { - if (topLine) scene->removeItem(topLine); + if (topLine) + scene->removeItem(topLine); topLine = NULL; } break; case BaseDesignIntf::LeftLine: - if (show){ - if (!leftLine) leftLine = createSideLine(side); + if (show) { + if (!leftLine) + leftLine = createSideLine(side); } else { - if (leftLine) scene->removeItem(leftLine); + if (leftLine) + scene->removeItem(leftLine); leftLine = NULL; } break; case BaseDesignIntf::BottomLine: - if (show){ - if (!bottomLine) bottomLine = createSideLine(side); + if (show) { + if (!bottomLine) + bottomLine = createSideLine(side); } else { - if (bottomLine) scene->removeItem(bottomLine); + if (bottomLine) + scene->removeItem(bottomLine); bottomLine = NULL; } break; case BaseDesignIntf::RightLine: - if (show){ - if (!rightLine) rightLine = createSideLine(side); + if (show) { + if (!rightLine) + rightLine = createSideLine(side); } else { - if(rightLine) scene->removeItem(rightLine); + if (rightLine) + scene->removeItem(rightLine); rightLine = NULL; } - } updateBorders(); } -QGraphicsLineItem *BorderFrameEditor::createSideLine(LimeReport::BaseDesignIntf::BorderSide side) +QGraphicsLineItem* BorderFrameEditor::createSideLine(LimeReport::BaseDesignIntf::BorderSide side) { - switch(side){ + switch (side) { case BaseDesignIntf::BorderSide::TopLine: return scene->addLine(QLineF(10, 10, rect().width() - 10, 10), m_pen); case BaseDesignIntf::BorderSide::LeftLine: return scene->addLine(QLineF(10, 10, 10, rect().height() - 10), m_pen); case BaseDesignIntf::BorderSide::RightLine: - return scene->addLine(QLineF(rect().width() - 10, 10 ,rect().width() - 10, rect().height() - 10), m_pen); + return scene->addLine( + QLineF(rect().width() - 10, 10, rect().width() - 10, rect().height() - 10), m_pen); case BaseDesignIntf::BorderSide::BottomLine: - return scene->addLine(QLineF(10, rect().bottom() - 10, rect().width() - 10, rect().bottom() - 10), m_pen); + return scene->addLine( + QLineF(10, rect().bottom() - 10, rect().width() - 10, rect().bottom() - 10), m_pen); } } void BorderFrameEditor::updateBorders() { - if (topLine) topLine->setPen(m_pen); - if (leftLine) leftLine->setPen(m_pen); - if (bottomLine) bottomLine->setPen(m_pen); - if (rightLine) rightLine->setPen(m_pen); + if (topLine) + topLine->setPen(m_pen); + if (leftLine) + leftLine->setPen(m_pen); + if (bottomLine) + bottomLine->setPen(m_pen); + if (rightLine) + rightLine->setPen(m_pen); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/items/lrborderframeeditor.h b/limereport/items/lrborderframeeditor.h index 9333677..93d3a23 100644 --- a/limereport/items/lrborderframeeditor.h +++ b/limereport/items/lrborderframeeditor.h @@ -1,46 +1,44 @@ #ifndef WIDGET #define WIDGET -#include -#include -#include #include "lrbasedesignintf.h" -namespace LimeReport{ -namespace Ui { class BorderFrameEditor; } +#include +#include +#include +namespace LimeReport { -class BorderFrameEditor : public QWidget -{ +namespace Ui { + class BorderFrameEditor; +} + +class BorderFrameEditor: public QWidget { Q_OBJECT public: - BorderFrameEditor(QWidget *parent = nullptr); + BorderFrameEditor(QWidget* parent = nullptr); ~BorderFrameEditor(); void setPen(QPen pen); QPen pen(); void setAllLines(); void unSetAllLines(); + protected: - void mousePressEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent* event); signals: void borderSideClicked(LimeReport::BaseDesignIntf::BorderSide side, bool show); private slots: void slotBorderSideClicked(LimeReport::BaseDesignIntf::BorderSide side, bool show); private: - QGraphicsLineItem *createSideLine(LimeReport::BaseDesignIntf::BorderSide side); + QGraphicsLineItem* createSideLine(LimeReport::BaseDesignIntf::BorderSide side); void updateBorders(); + private: - Ui::BorderFrameEditor *ui; - QGraphicsScene *scene; - QGraphicsLineItem *topLine = NULL - ,*bottomLine = NULL - ,*leftLine = NULL - ,*rightLine = NULL; + Ui::BorderFrameEditor* ui; + QGraphicsScene* scene; + QGraphicsLineItem *topLine = NULL, *bottomLine = NULL, *leftLine = NULL, *rightLine = NULL; QPen m_pen; - - - }; } // namespace LimeReport #endif // WIDGET diff --git a/limereport/items/lrchartaxiseditor.cpp b/limereport/items/lrchartaxiseditor.cpp index 548a0f5..4960c51 100644 --- a/limereport/items/lrchartaxiseditor.cpp +++ b/limereport/items/lrchartaxiseditor.cpp @@ -1,13 +1,17 @@ #include "lrchartaxiseditor.h" - #include "ui_lrchartaxiseditor.h" -#include "lraxisdata.h" +#include "lraxisdata.h" #include "lrbasedesignintf.h" -ChartAxisEditor::ChartAxisEditor(LimeReport::ChartItem *item, LimeReport::PageDesignIntf *page, bool isXAxis, QSettings *settings, QWidget *parent): - QWidget(parent), ui(new Ui::ChartAxisEditor), m_chartItem(item), m_page(page), - m_settings(settings), m_isXAxis(isXAxis) +ChartAxisEditor::ChartAxisEditor(LimeReport::ChartItem* item, LimeReport::PageDesignIntf* page, + bool isXAxis, QSettings* settings, QWidget* parent): + QWidget(parent), + ui(new Ui::ChartAxisEditor), + m_chartItem(item), + m_page(page), + m_settings(settings), + m_isXAxis(isXAxis) { ui->setupUi(this); readSetting(); @@ -24,16 +28,17 @@ ChartAxisEditor::~ChartAxisEditor() QSettings* ChartAxisEditor::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } - m_settings = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_settings = new QSettings("LimeReport", QCoreApplication::applicationName()); return m_settings; } void ChartAxisEditor::readSetting() { - if (settings() == 0) return; + if (settings() == 0) + return; settings()->beginGroup("ChartAxisEditor"); QVariant v = settings()->value("Geometry"); @@ -50,7 +55,7 @@ void ChartAxisEditor::writeSetting() return; } settings()->beginGroup("ChartAxisEditor"); - settings()->setValue("Geometry",saveGeometry()); + settings()->setValue("Geometry", saveGeometry()); settings()->endGroup(); } @@ -59,7 +64,8 @@ void ChartAxisEditor::init() ui->gbAxis->setTitle(m_isXAxis ? QObject::tr("X Axis") : QObject::tr("Y Axis")); ui->direction_checkbox->setVisible(!m_isXAxis); - LimeReport::AxisData *axisData = m_isXAxis ? m_chartItem->xAxisData() : m_chartItem->yAxisData(); + LimeReport::AxisData* axisData + = m_isXAxis ? m_chartItem->xAxisData() : m_chartItem->yAxisData(); ui->minimumSpinBox->setValue(axisData->manualMinimum()); ui->maximumSpinBox->setValue(axisData->manualMaximum()); @@ -96,7 +102,8 @@ void ChartAxisEditor::on_stepCheckBox_stateChanged(int arg1) void ChartAxisEditor::on_pushButtonOk_clicked() { - LimeReport::AxisData *axisData = m_isXAxis ? m_chartItem->xAxisData() : m_chartItem->yAxisData(); + LimeReport::AxisData* axisData + = m_isXAxis ? m_chartItem->xAxisData() : m_chartItem->yAxisData(); if (!m_isXAxis) { axisData->setReverseDirection(ui->direction_checkbox->isChecked()); } @@ -135,8 +142,4 @@ void ChartAxisEditor::on_enableScaleCalculation_checkbox_stateChanged(int arg1) ui->stepCheckBox->setEnabled(isEnabled); } -void ChartAxisEditor::on_cancelButton_clicked() -{ - close(); -} - +void ChartAxisEditor::on_cancelButton_clicked() { close(); } diff --git a/limereport/items/lrchartaxiseditor.h b/limereport/items/lrchartaxiseditor.h index 5eeb58b..d42cd26 100644 --- a/limereport/items/lrchartaxiseditor.h +++ b/limereport/items/lrchartaxiseditor.h @@ -1,22 +1,22 @@ #ifndef CHARTAXISEDITOR_H #define CHARTAXISEDITOR_H -#include #include "lrchartitem.h" +#include + namespace Ui { class ChartAxisEditor; } -class ChartAxisEditor : public QWidget -{ +class ChartAxisEditor: public QWidget { Q_OBJECT - public: +public: ChartAxisEditor(LimeReport::ChartItem* item, LimeReport::PageDesignIntf* page, bool isXAxis, - QSettings* settings=0, QWidget *parent = 0); + QSettings* settings = 0, QWidget* parent = 0); ~ChartAxisEditor(); - QSettings *settings(); + QSettings* settings(); private slots: void on_minimumCheckBox_stateChanged(int arg1); void on_maximumCheckBox_stateChanged(int arg1); @@ -31,7 +31,7 @@ private: void writeSetting(); void init(); - Ui::ChartAxisEditor *ui; + Ui::ChartAxisEditor* ui; LimeReport::ChartItem* m_chartItem; LimeReport::PageDesignIntf* m_page; QSettings* m_settings; diff --git a/limereport/items/lrchartitem.cpp b/limereport/items/lrchartitem.cpp index a438d5f..d6af54c 100644 --- a/limereport/items/lrchartitem.cpp +++ b/limereport/items/lrchartitem.cpp @@ -1,157 +1,132 @@ #include "lrchartitem.h" -#include -#include -#include "lrdesignelementsfactory.h" -#include "lrchartitemeditor.h" -#include "lrdatasourcemanager.h" -#include "lrpagedesignintf.h" -#include "lrreportengine_p.h" -#include "lrdatadesignintf.h" -#include "lrchartaxiseditor.h" - -#include "charts/lrpiechart.h" -#include "charts/lrverticalbarchart.h" +#include "charts/lrgridlineschart.h" #include "charts/lrhorizontalbarchart.h" #include "charts/lrlineschart.h" -#include "charts/lrgridlineschart.h" +#include "charts/lrpiechart.h" +#include "charts/lrverticalbarchart.h" +#include "lrchartaxiseditor.h" +#include "lrchartitemeditor.h" +#include "lrdatadesignintf.h" +#include "lrdatasourcemanager.h" +#include "lrdesignelementsfactory.h" +#include "lrpagedesignintf.h" +#include "lrreportengine_p.h" -namespace{ +#include +#include + +namespace { const QString xmlTag = "ChartItem"; -LimeReport::BaseDesignIntf * createChartItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::ChartItem(owner,parent); +LimeReport::BaseDesignIntf* createChartItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::ChartItem(owner, parent); } bool registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, LimeReport::ItemAttribs(QObject::tr("Chart Item"),"Item"), createChartItem - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Chart Item"), "Item"), createChartItem); +} // namespace -namespace LimeReport{ +namespace LimeReport { QColor generateColor() { - int red = (rand()%(256 - 1)) + 1; - int green = (rand()%(256 - 1)) + 1; - int blue = (rand()%(256 - 1)) + 1;; - return QColor(red,green,blue); + int red = (rand() % (256 - 1)) + 1; + int green = (rand() % (256 - 1)) + 1; + int blue = (rand() % (256 - 1)) + 1; + ; + return QColor(red, green, blue); } -QColor color_map[39] = { - QColor(51,102,204), QColor(220,57,18), QColor(225, 153, 0), QColor(16, 150, 24), - QColor(153,0,153), QColor(0,153,198), QColor(221, 68, 119), QColor(255,0,0), - QColor(0,0,139), QColor(0,205,0), QColor(233,30,99), QColor(255,255,0), - QColor(244,67,54), QColor(156,39,176), QColor(103,58,183), QColor(63,81,181), - QColor(33,153,243), QColor(0,150,136), QColor(78,175,80), QColor(139,195,74), - QColor(205,228,57), QColor(0,139,0), QColor(0,0,255), QColor(255,235,59), - QColor(255,193,7), QColor(255,152,0), QColor(255,87,34), QColor(121,85,72), - QColor(158,158,158), QColor(96,125,139), QColor(241,153,185), QColor(64,64,64), - QColor(188,229,218), QColor(139,0,0), QColor(139,139,0), QColor(171, 130, 255), - QColor(139, 123, 139), QColor(255, 0, 255), QColor(139, 69, 19) -}; +QColor color_map[39] + = { QColor(51, 102, 204), QColor(220, 57, 18), QColor(225, 153, 0), QColor(16, 150, 24), + QColor(153, 0, 153), QColor(0, 153, 198), QColor(221, 68, 119), QColor(255, 0, 0), + QColor(0, 0, 139), QColor(0, 205, 0), QColor(233, 30, 99), QColor(255, 255, 0), + QColor(244, 67, 54), QColor(156, 39, 176), QColor(103, 58, 183), QColor(63, 81, 181), + QColor(33, 153, 243), QColor(0, 150, 136), QColor(78, 175, 80), QColor(139, 195, 74), + QColor(205, 228, 57), QColor(0, 139, 0), QColor(0, 0, 255), QColor(255, 235, 59), + QColor(255, 193, 7), QColor(255, 152, 0), QColor(255, 87, 34), QColor(121, 85, 72), + QColor(158, 158, 158), QColor(96, 125, 139), QColor(241, 153, 185), QColor(64, 64, 64), + QColor(188, 229, 218), QColor(139, 0, 0), QColor(139, 139, 0), QColor(171, 130, 255), + QColor(139, 123, 139), QColor(255, 0, 255), QColor(139, 69, 19) }; -QString SeriesItem::name() const -{ - return m_name; -} +QString SeriesItem::name() const { return m_name; } -void SeriesItem::setName(const QString &name) -{ - m_name = name; -} +void SeriesItem::setName(const QString& name) { m_name = name; } -QString SeriesItem::valuesColumn() const -{ - return m_valuesColumn; -} +QString SeriesItem::valuesColumn() const { return m_valuesColumn; } -void SeriesItem::setValuesColumn(const QString &valuesColumn) -{ - m_valuesColumn = valuesColumn; -} +void SeriesItem::setValuesColumn(const QString& valuesColumn) { m_valuesColumn = valuesColumn; } -QString SeriesItem::labelsColumn() const -{ - return m_labelsColumn; -} +QString SeriesItem::labelsColumn() const { return m_labelsColumn; } -void SeriesItem::setLabelsColumn(const QString &labelsColumn) -{ - m_labelsColumn = labelsColumn; -} +void SeriesItem::setLabelsColumn(const QString& labelsColumn) { m_labelsColumn = labelsColumn; } -QString SeriesItem::xAxisColumn() const -{ - return m_xAxisColumn; -} +QString SeriesItem::xAxisColumn() const { return m_xAxisColumn; } -void SeriesItem::setXAxisColumn(const QString &xAxisColumn) -{ - m_xAxisColumn = xAxisColumn; -} +void SeriesItem::setXAxisColumn(const QString& xAxisColumn) { m_xAxisColumn = xAxisColumn; } -SeriesItem *SeriesItem::clone() +SeriesItem* SeriesItem::clone() { SeriesItem* result = new SeriesItem(); - for (int i = 0; i < this->metaObject()->propertyCount(); ++i){ - result->setProperty(this->metaObject()->property(i).name(),property(this->metaObject()->property(i).name())); + for (int i = 0; i < this->metaObject()->propertyCount(); ++i) { + result->setProperty(this->metaObject()->property(i).name(), + property(this->metaObject()->property(i).name())); } return result; } -void SeriesItem::fillSeriesData(IDataSource *dataSource) +void SeriesItem::fillSeriesData(IDataSource* dataSource) { m_data.clear(); - if (dataSource){ + if (dataSource) { dataSource->first(); int currentColorIndex = 0; - while(!dataSource->eof()){ + while (!dataSource->eof()) { if (!m_labelsColumn.isEmpty()) m_data.labels().append(dataSource->data(m_labelsColumn).toString()); if (!m_xAxisColumn.isEmpty()) m_data.xAxisValues().append(dataSource->data(m_xAxisColumn).toDouble()); m_data.values().append(dataSource->data(m_valuesColumn).toDouble()); - m_data.colors().append((currentColorIndex<32)?color_map[currentColorIndex]:generateColor()); + m_data.colors().append((currentColorIndex < 32) ? color_map[currentColorIndex] + : generateColor()); dataSource->next(); currentColorIndex++; } } } -QColor SeriesItem::color() const -{ - return m_color; -} +QColor SeriesItem::color() const { return m_color; } -void SeriesItem::setColor(const QColor &color) -{ - m_color = color; -} +void SeriesItem::setColor(const QColor& color) { m_color = color; } -SeriesItem::SeriesItemPreferredType SeriesItem::preferredType() const -{ - return m_preferredType; -} +SeriesItem::SeriesItemPreferredType SeriesItem::preferredType() const { return m_preferredType; } -void SeriesItem::setPreferredType(const SeriesItemPreferredType& type) -{ - m_preferredType = type; -} +void SeriesItem::setPreferredType(const SeriesItemPreferredType& type) { m_preferredType = type; } -ChartItem::ChartItem(QObject *owner, QGraphicsItem *parent) - : ItemDesignIntf(xmlTag, owner, parent), m_legendBorder(true), - m_legendAlign(LegendAlignRightCenter), m_titleAlign(TitleAlignCenter), - m_chartType(Pie), m_labelsField(""), m_isEmpty(true), - m_showLegend(true), m_drawPoints(true), m_seriesLineWidth(4), - m_horizontalAxisOnTop(false), m_gridChartLines(AllLines), - m_legendStyle(LegendPoints) +ChartItem::ChartItem(QObject* owner, QGraphicsItem* parent): + ItemDesignIntf(xmlTag, owner, parent), + m_legendBorder(true), + m_legendAlign(LegendAlignRightCenter), + m_titleAlign(TitleAlignCenter), + m_chartType(Pie), + m_labelsField(""), + m_isEmpty(true), + m_showLegend(true), + m_drawPoints(true), + m_seriesLineWidth(4), + m_horizontalAxisOnTop(false), + m_gridChartLines(AllLines), + m_legendStyle(LegendPoints) { m_xAxisData = new AxisData(AxisData::XAxis, this); m_xAxisData->setReverseDirection(true); m_yAxisData = new AxisData(AxisData::YAxis, this); - m_labels<<"First"<<"Second"<<"Thrid"; + m_labels << "First" + << "Second" + << "Thrid"; m_chart = new PieChart(this); m_chart->setTitleFont(font()); } @@ -165,47 +140,48 @@ ChartItem::~ChartItem() delete m_chart; } -ChartItem::TitleAlign ChartItem::titleAlign() const -{ - return m_titleAlign; -} +ChartItem::TitleAlign ChartItem::titleAlign() const { return m_titleAlign; } -void ChartItem::setTitleAlign(const TitleAlign &titleAlign) +void ChartItem::setTitleAlign(const TitleAlign& titleAlign) { - if (m_titleAlign != titleAlign){ + if (m_titleAlign != titleAlign) { TitleAlign oldValue = m_titleAlign; m_titleAlign = titleAlign; - notify("titleAlign",oldValue,m_titleAlign); + notify("titleAlign", oldValue, m_titleAlign); update(); } } -void ChartItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void ChartItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); setupPainter(painter); painter->setFont(transformToSceneFont(painter->font())); - painter->setRenderHint(QPainter::Antialiasing,true); - painter->setRenderHint(QPainter::TextAntialiasing,true); - qreal borderMargin = (rect().height()*0.01>10)?(10):(rect().height()*0.01); - qreal maxTitleHeight = rect().height()*0.5; + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setRenderHint(QPainter::TextAntialiasing, true); + qreal borderMargin = (rect().height() * 0.01 > 10) ? (10) : (rect().height() * 0.01); + qreal maxTitleHeight = rect().height() * 0.5; QFont tmpFont = painter->font(); qreal titleOffset = 0; if (!m_title.isEmpty()) { QFontMetrics fm(titleFont()); - const qreal titleHeight = fm.boundingRect(rect().toRect(), Qt::TextWordWrap,chartTitle()).height() + borderMargin * 2; + const qreal titleHeight + = fm.boundingRect(rect().toRect(), Qt::TextWordWrap, chartTitle()).height() + + borderMargin * 2; titleOffset = std::min(titleHeight, maxTitleHeight); } - const QRectF titleRect = QRectF(borderMargin,borderMargin,rect().width()-borderMargin*2,titleOffset); + const QRectF titleRect + = QRectF(borderMargin, borderMargin, rect().width() - borderMargin * 2, titleOffset); QRectF legendRect = QRectF(0, 0, 0, 0); QRectF diagramRect = rect().adjusted(borderMargin, titleOffset + borderMargin, -(borderMargin * 2), -borderMargin); if (m_showLegend) { - legendRect = m_chart->calcChartLegendRect(painter->font(), rect(), false, borderMargin, titleOffset); - switch(legendAlign()) { + legendRect = m_chart->calcChartLegendRect(painter->font(), rect(), false, borderMargin, + titleOffset); + switch (legendAlign()) { case LegendAlignRightTop: case LegendAlignRightBottom: case LegendAlignRightCenter: @@ -221,67 +197,55 @@ void ChartItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, paintChartTitle(painter, titleRect); if (m_showLegend) - m_chart->paintChartLegend(painter,legendRect); - m_chart->paintChart(painter,diagramRect); + m_chart->paintChartLegend(painter, legendRect); + m_chart->paintChart(painter, diagramRect); painter->restore(); - ItemDesignIntf::paint(painter,option,widget); + ItemDesignIntf::paint(painter, option, widget); } -QObject *ChartItem::xAxisSettings() -{ - return m_xAxisData; -} +QObject* ChartItem::xAxisSettings() { return m_xAxisData; } -void ChartItem::setYAxisSettings(QObject *axis) +void ChartItem::setYAxisSettings(QObject* axis) { - AxisData *data = dynamic_cast(axis); + AxisData* data = dynamic_cast(axis); if (data) { m_yAxisData->copy(data); } } -QObject *ChartItem::yAxisSettings() -{ - return m_yAxisData; -} +QObject* ChartItem::yAxisSettings() { return m_yAxisData; } -void ChartItem::setXAxisSettings(QObject *axis) +void ChartItem::setXAxisSettings(QObject* axis) { - AxisData *data = static_cast(axis); + AxisData* data = static_cast(axis); if (data) { m_xAxisData->copy(data); } } -AxisData *ChartItem::xAxisData() -{ - return m_xAxisData; -} +AxisData* ChartItem::xAxisData() { return m_xAxisData; } -AxisData *ChartItem::yAxisData() -{ - return m_yAxisData; -} +AxisData* ChartItem::yAxisData() { return m_yAxisData; } void ChartItem::showAxisEditorDialog(bool isXAxis) { showDialog(new ChartAxisEditor(this, page(), isXAxis, settings())); } -BaseDesignIntf *ChartItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* ChartItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - ChartItem* result = new ChartItem(owner,parent); + ChartItem* result = new ChartItem(owner, parent); foreach (SeriesItem* series, m_series) { result->m_series.append(series->clone()); } return result; } -QObject *ChartItem::createElement(const QString &collectionName, const QString &elementType) +QObject* ChartItem::createElement(const QString& collectionName, const QString& elementType) { Q_UNUSED(elementType); - if (collectionName.compare("series")==0){ + if (collectionName.compare("series") == 0) { SeriesItem* seriesItem = new SeriesItem(); m_series.append(seriesItem); return seriesItem; @@ -289,28 +253,28 @@ QObject *ChartItem::createElement(const QString &collectionName, const QString & return 0; } -int ChartItem::elementsCount(const QString &collectionName) +int ChartItem::elementsCount(const QString& collectionName) { - if (collectionName.compare("series")==0) + if (collectionName.compare("series") == 0) return m_series.count(); return 0; } -QObject *ChartItem::elementAt(const QString &collectionName, int index) +QObject* ChartItem::elementAt(const QString& collectionName, int index) { - if (collectionName.compare("series")==0) + if (collectionName.compare("series") == 0) return m_series.at(index); return 0; } -void ChartItem::updateItemSize(DataSourceManager *dataManager, RenderPass , int ) +void ChartItem::updateItemSize(DataSourceManager* dataManager, RenderPass, int) { m_isEmpty = false; - if (dataManager && dataManager->dataSource(m_datasource)){ - IDataSource* ds = dataManager->dataSource(m_datasource); + if (dataManager && dataManager->dataSource(m_datasource)) { + IDataSource* ds = dataManager->dataSource(m_datasource); foreach (SeriesItem* series, m_series) { - if (series->isEmpty()){ + if (series->isEmpty()) { series->setLabelsColumn(m_labelsField); series->setXAxisColumn(m_xAxisField); series->fillSeriesData(ds); @@ -320,33 +284,30 @@ void ChartItem::updateItemSize(DataSourceManager *dataManager, RenderPass , int } } -void ChartItem::fillLabels(IDataSource *dataSource) +void ChartItem::fillLabels(IDataSource* dataSource) { m_labels.clear(); - if (dataSource && !m_labelsField.isEmpty()){ + if (dataSource && !m_labelsField.isEmpty()) { dataSource->first(); - while(!dataSource->eof()){ + while (!dataSource->eof()) { m_labels.append(dataSource->data(m_labelsField).toString()); dataSource->next(); } } } -QWidget *ChartItem::defaultEditor() +QWidget* ChartItem::defaultEditor() { QWidget* editor = new ChartItemEditor(this, page(), settings()); editor->setAttribute(Qt::WA_DeleteOnClose); return editor; } -bool ChartItem::isNeedUpdateSize(RenderPass pass) const -{ - return pass == FirstPass && m_isEmpty; -} +bool ChartItem::isNeedUpdateSize(RenderPass pass) const { return pass == FirstPass && m_isEmpty; } -QSettings *ChartItem::settings() +QSettings* ChartItem::settings() { - PageDesignIntf *page = this->page(); + PageDesignIntf* page = this->page(); if (page->settings()) { return page->settings(); } @@ -356,14 +317,11 @@ QSettings *ChartItem::settings() return 0; } -bool ChartItem::showLegend() const -{ - return m_showLegend; -} +bool ChartItem::showLegend() const { return m_showLegend; } void ChartItem::setShowLegend(bool showLegend) { - if (m_showLegend != showLegend){ + if (m_showLegend != showLegend) { m_showLegend = showLegend; notify("showLegend", !m_showLegend, m_showLegend); update(); @@ -371,34 +329,19 @@ void ChartItem::setShowLegend(bool showLegend) m_showLegend = showLegend; } -QList ChartItem::labels() const -{ - return m_labels; -} +QList ChartItem::labels() const { return m_labels; } -void ChartItem::setLabels(const QList &labels) -{ - m_labels = labels; -} +void ChartItem::setLabels(const QList& labels) { m_labels = labels; } -QString ChartItem::labelsField() const -{ - return m_labelsField; -} +QString ChartItem::labelsField() const { return m_labelsField; } -void ChartItem::setLabelsField(const QString &labelsField) -{ - m_labelsField = labelsField; -} +void ChartItem::setLabelsField(const QString& labelsField) { m_labelsField = labelsField; } -ChartItem::ChartType ChartItem::chartType() const -{ - return m_chartType; -} +ChartItem::ChartType ChartItem::chartType() const { return m_chartType; } -void ChartItem::setChartType(const ChartType &chartType) +void ChartItem::setChartType(const ChartType& chartType) { - if (m_chartType != chartType){ + if (m_chartType != chartType) { ChartType oldValue = m_chartType; m_chartType = chartType; QFont oldTitleFont = m_chart->titleFont(); @@ -421,32 +364,28 @@ void ChartItem::setChartType(const ChartType &chartType) break; } m_chart->setTitleFont(oldTitleFont); - notify("chartType",oldValue,m_chartType); + notify("chartType", oldValue, m_chartType); update(); } } -QString ChartItem::datasource() const -{ - return m_datasource; -} +QString ChartItem::datasource() const { return m_datasource; } -void ChartItem::setDatasource(const QString &datasource) -{ - m_datasource = datasource; -} +void ChartItem::setDatasource(const QString& datasource) { m_datasource = datasource; } -void ChartItem::paintChartTitle(QPainter *painter, QRectF titleRect) +void ChartItem::paintChartTitle(QPainter* painter, QRectF titleRect) { painter->save(); QFont tmpFont = transformToSceneFont(titleFont()); - QRect titleBoundingRect = QFontMetrics(tmpFont).boundingRect(rect().toRect(), Qt::TextWordWrap, chartTitle()); + QRect titleBoundingRect + = QFontMetrics(tmpFont).boundingRect(rect().toRect(), Qt::TextWordWrap, chartTitle()); - while ((titleBoundingRect.height() > titleRect.height() || titleBoundingRect.width() > titleRect.width()) - && tmpFont.pixelSize() > 1) - { - tmpFont.setPixelSize(tmpFont.pixelSize()-1); - titleBoundingRect = QFontMetrics(tmpFont).boundingRect(rect().toRect(), Qt::TextWordWrap, chartTitle()); + while ((titleBoundingRect.height() > titleRect.height() + || titleBoundingRect.width() > titleRect.width()) + && tmpFont.pixelSize() > 1) { + tmpFont.setPixelSize(tmpFont.pixelSize() - 1); + titleBoundingRect + = QFontMetrics(tmpFont).boundingRect(rect().toRect(), Qt::TextWordWrap, chartTitle()); } painter->setFont(tmpFont); @@ -466,28 +405,21 @@ void ChartItem::paintChartTitle(QPainter *painter, QRectF titleRect) painter->restore(); } +ChartItem::LegendAlign ChartItem::legendAlign() const { return m_legendAlign; } -ChartItem::LegendAlign ChartItem::legendAlign() const +void ChartItem::setLegendAlign(const LegendAlign& legendAlign) { - return m_legendAlign; -} - -void ChartItem::setLegendAlign(const LegendAlign &legendAlign) -{ - if (m_legendAlign != legendAlign){ + if (m_legendAlign != legendAlign) { LegendAlign oldValue = m_legendAlign; m_legendAlign = legendAlign; - notify("legendAlign",oldValue,m_legendAlign); + notify("legendAlign", oldValue, m_legendAlign); update(); } } -ChartItem::LegendStyle ChartItem::legendStyle() const -{ - return m_legendStyle; -} +ChartItem::LegendStyle ChartItem::legendStyle() const { return m_legendStyle; } -void ChartItem::setLegendStyle(const LegendStyle &legendStyle) +void ChartItem::setLegendStyle(const LegendStyle& legendStyle) { if (m_legendStyle == legendStyle) { return; @@ -498,66 +430,49 @@ void ChartItem::setLegendStyle(const LegendStyle &legendStyle) update(); } -bool ChartItem::drawLegendBorder() const -{ - return m_legendBorder; -} +bool ChartItem::drawLegendBorder() const { return m_legendBorder; } void ChartItem::setDrawLegendBorder(bool legendBorder) { - if (m_legendBorder!=legendBorder){ + if (m_legendBorder != legendBorder) { m_legendBorder = legendBorder; - notify("legendBorder",!m_legendBorder,m_legendBorder); + notify("legendBorder", !m_legendBorder, m_legendBorder); update(); } } -QString ChartItem::chartTitle() const -{ - return m_title; -} +QString ChartItem::chartTitle() const { return m_title; } -void ChartItem::setChartTitle(const QString &title) +void ChartItem::setChartTitle(const QString& title) { - if (m_title != title){ + if (m_title != title) { QString oldValue = m_title; m_title = title; update(); - notify("chartTitle",oldValue,title); + notify("chartTitle", oldValue, title); } } -QList &ChartItem::series() -{ - return m_series; -} +QList& ChartItem::series() { return m_series; } -void ChartItem::setSeries(const QList &series) -{ - m_series = series; -} +void ChartItem::setSeries(const QList& series) { m_series = series; } -bool ChartItem::isSeriesExists(const QString &name) +bool ChartItem::isSeriesExists(const QString& name) { foreach (SeriesItem* series, m_series) { - if (series->name().compare(name)==0) return true; + if (series->name().compare(name) == 0) + return true; } return false; } -int ChartItem::seriesLineWidth() const -{ - return m_seriesLineWidth; -} +int ChartItem::seriesLineWidth() const { return m_seriesLineWidth; } -bool ChartItem::drawPoints() const -{ - return m_drawPoints; -} +bool ChartItem::drawPoints() const { return m_drawPoints; } void ChartItem::setDrawPoints(bool drawPoints) { - if (m_drawPoints != drawPoints){ + if (m_drawPoints != drawPoints) { m_drawPoints = drawPoints; notify("drawPoints", !m_drawPoints, m_drawPoints); update(); @@ -567,7 +482,7 @@ void ChartItem::setDrawPoints(bool drawPoints) void ChartItem::setSeriesLineWidth(int newSeriesLineWidth) { - if (m_seriesLineWidth != newSeriesLineWidth){ + if (m_seriesLineWidth != newSeriesLineWidth) { int oldValue = m_seriesLineWidth; m_seriesLineWidth = newSeriesLineWidth; notify("seriesLineWidth", oldValue, m_seriesLineWidth); @@ -576,24 +491,15 @@ void ChartItem::setSeriesLineWidth(int newSeriesLineWidth) m_seriesLineWidth = newSeriesLineWidth; } -QString ChartItem::xAxisField() const -{ - return m_xAxisField; -} +QString ChartItem::xAxisField() const { return m_xAxisField; } -void ChartItem::setXAxisField(const QString &xAxisField) -{ - m_xAxisField = xAxisField; -} +void ChartItem::setXAxisField(const QString& xAxisField) { m_xAxisField = xAxisField; } -bool ChartItem::horizontalAxisOnTop() const -{ - return m_horizontalAxisOnTop; -} +bool ChartItem::horizontalAxisOnTop() const { return m_horizontalAxisOnTop; } void ChartItem::setHorizontalAxisOnTop(bool horizontalAxisOnTop) { - if (m_horizontalAxisOnTop != horizontalAxisOnTop){ + if (m_horizontalAxisOnTop != horizontalAxisOnTop) { m_horizontalAxisOnTop = horizontalAxisOnTop; notify("horizontalAxisOnTop", !m_horizontalAxisOnTop, m_horizontalAxisOnTop); update(); @@ -601,10 +507,7 @@ void ChartItem::setHorizontalAxisOnTop(bool horizontalAxisOnTop) m_horizontalAxisOnTop = horizontalAxisOnTop; } -ChartItem::GridChartLines ChartItem::gridChartLines() const -{ - return m_gridChartLines; -} +ChartItem::GridChartLines ChartItem::gridChartLines() const { return m_gridChartLines; } void ChartItem::setGridChartLines(GridChartLines flags) { @@ -617,7 +520,7 @@ void ChartItem::setGridChartLines(GridChartLines flags) return; } update(rect()); - notify("gridChartLines",QVariant(oldValue),QVariant(flags)); + notify("gridChartLines", QVariant(oldValue), QVariant(flags)); } void ChartItem::setCharItemFont(QFont value) @@ -627,33 +530,32 @@ void ChartItem::setCharItemFont(QFont value) } QFont oldValue = font(); setFont(value); - if (!isLoading()) update(); - notify("font",oldValue,value); + if (!isLoading()) + update(); + notify("font", oldValue, value); } -QFont ChartItem::titleFont() const -{ - return m_chart->titleFont(); -} +QFont ChartItem::titleFont() const { return m_chart->titleFont(); } void ChartItem::setTitleFont(QFont value) { - if (m_chart->titleFont() == value){ + if (m_chart->titleFont() == value) { return; } QFont oldValue = value; m_chart->setTitleFont(value); - if (!isLoading()) update(); + if (!isLoading()) + update(); notify("titleFont", oldValue, value); } -AbstractChart::AbstractChart(ChartItem *chartItem) - :m_chartItem(chartItem) +AbstractChart::AbstractChart(ChartItem* chartItem): m_chartItem(chartItem) { - m_designLabels< parentRect.width() / 2 - borderMargin) ? - (parentRect.width() / 2) : - (parentRect.width() - legendSize.width())) : 0; + qreal rightOffset = !takeAllRect + ? ((legendSize.width() > parentRect.width() / 2 - borderMargin) + ? (parentRect.width() / 2) + : (parentRect.width() - legendSize.width())) + : 0; return parentRect.adjusted( rightOffset, - (legendSize.height()>(parentRect.height()-titleOffset))?(titleOffset):(legendTopMargin), + (legendSize.height() > (parentRect.height() - titleOffset)) ? (titleOffset) + : (legendTopMargin), -borderMargin, - (legendSize.height()>(parentRect.height()-titleOffset))?(0):(-legendBottomMargin) - ); + (legendSize.height() > (parentRect.height() - titleOffset)) ? (0) + : (-legendBottomMargin)); } else { const qreal verticalOffset = borderMargin * 2; return parentRect.adjusted( - legendLeftMargin, - (parentRect.height()) - (legendSize.height() + verticalOffset), - -(parentRect.width() - (legendSize.width() + legendLeftMargin)), - -verticalOffset - ); + legendLeftMargin, (parentRect.height()) - (legendSize.height() + verticalOffset), + -(parentRect.width() - (legendSize.width() + legendLeftMargin)), -verticalOffset); } } +QFont AbstractChart::titleFont() { return m_titleFont; } -QFont AbstractChart::titleFont() -{ - return m_titleFont; -} +void AbstractChart::setTitleFont(const QFont& value) { m_titleFont = value; } -void AbstractChart::setTitleFont(const QFont &value) -{ - m_titleFont = value; -} - -void AbstractChart::prepareLegendToPaint(QRectF &legendRect, QPainter *painter) +void AbstractChart::prepareLegendToPaint(QRectF& legendRect, QPainter* painter) { QFont tmpFont = painter->font(); - switch(m_chartItem->legendAlign()) { + switch (m_chartItem->legendAlign()) { case ChartItem::LegendAlignBottomLeft: case ChartItem::LegendAlignBottomCenter: case ChartItem::LegendAlignBottomRight: { const qreal maxWidth = legendRect.width() * 0.95; - qreal legendWidth = std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0); + qreal legendWidth + = std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0); if (legendWidth < maxWidth) { return; } - while ( (legendWidth > maxWidth) && tmpFont.pixelSize() > 1) { + while ((legendWidth > maxWidth) && tmpFont.pixelSize() > 1) { tmpFont.setPixelSize(tmpFont.pixelSize() - 1); calcChartLegendSize(tmpFont, legendRect.width()); - legendWidth = std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0); + legendWidth + = std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0); } painter->setFont(tmpFont); break; @@ -747,12 +646,13 @@ void AbstractChart::prepareLegendToPaint(QRectF &legendRect, QPainter *painter) case ChartItem::LegendAlignRightCenter: case ChartItem::LegendAlignRightBottom: QSizeF legendSize = calcChartLegendSize(tmpFont, legendRect.width()); - if ((legendSize.height() <= legendRect.height() && legendSize.width() <= legendRect.width())) { + if ((legendSize.height() <= legendRect.height() + && legendSize.width() <= legendRect.width())) { return; } - while ((legendSize.height() > legendRect.height() || legendSize.width() > legendRect.width()) - && tmpFont.pixelSize() > 1) - { + while ( + (legendSize.height() > legendRect.height() || legendSize.width() > legendRect.width()) + && tmpFont.pixelSize() > 1) { tmpFont.setPixelSize(tmpFont.pixelSize() - 1); legendSize = calcChartLegendSize(tmpFont, legendRect.width()); } @@ -762,8 +662,7 @@ void AbstractChart::prepareLegendToPaint(QRectF &legendRect, QPainter *painter) } } -AbstractSeriesChart::AbstractSeriesChart(ChartItem *chartItem) - :AbstractChart(chartItem) +AbstractSeriesChart::AbstractSeriesChart(ChartItem* chartItem): AbstractChart(chartItem) { m_designValues[0] = 10; m_designValues[1] = 35; @@ -776,25 +675,13 @@ AbstractSeriesChart::AbstractSeriesChart(ChartItem *chartItem) m_designValues[8] = 5; } -qreal AbstractSeriesChart::maxValue() -{ - return m_chartItem->yAxisData()->maxValue(); -} +qreal AbstractSeriesChart::maxValue() { return m_chartItem->yAxisData()->maxValue(); } -qreal AbstractSeriesChart::minValue() -{ - return m_chartItem->yAxisData()->minValue(); -} +qreal AbstractSeriesChart::minValue() { return m_chartItem->yAxisData()->minValue(); } -AxisData &AbstractSeriesChart::xAxisData() const -{ - return *m_chartItem->xAxisData(); -} +AxisData& AbstractSeriesChart::xAxisData() const { return *m_chartItem->xAxisData(); } -AxisData &AbstractSeriesChart::yAxisData() const -{ - return *m_chartItem->yAxisData(); -} +AxisData& AbstractSeriesChart::yAxisData() const { return *m_chartItem->yAxisData(); } void AbstractSeriesChart::updateMinAndMaxValues() { @@ -809,8 +696,8 @@ void AbstractSeriesChart::updateMinAndMaxValues() qreal maxXValue = 0; qreal minXValue = std::numeric_limits::max(); - for (SeriesItem* series : m_chartItem->series()){ - for (qreal value : series->data()->values()){ + for (SeriesItem* series : m_chartItem->series()) { + for (qreal value : series->data()->values()) { minYValue = std::min(minYValue, value); maxYValue = std::max(maxYValue, value); } @@ -821,7 +708,7 @@ void AbstractSeriesChart::updateMinAndMaxValues() minXValue = std::min(0.0, minXValue); maxXValue = std::max(valuesCount, maxXValue); } else { - for (qreal value : series->data()->xAxisValues()){ + for (qreal value : series->data()->xAxisValues()) { minXValue = std::min(value, minXValue); maxXValue = std::max(value, maxXValue); } @@ -832,37 +719,36 @@ void AbstractSeriesChart::updateMinAndMaxValues() m_chartItem->yAxisData()->update(minYValue, maxYValue); } -qreal AbstractSeriesChart::hPadding(QRectF chartRect) -{ - return (chartRect.width() * 0.02); -} +qreal AbstractSeriesChart::hPadding(QRectF chartRect) { return (chartRect.width() * 0.02); } -qreal AbstractSeriesChart::vPadding(QRectF chartRect) -{ - return (chartRect.height() * 0.02); -} +qreal AbstractSeriesChart::vPadding(QRectF chartRect) { return (chartRect.height() * 0.02); } int AbstractSeriesChart::valuesCount() { - if (m_chartItem->itemMode() == DesignMode) return 3; - return (m_chartItem->series().isEmpty()) ? 0 : m_chartItem->series().at(0)->data()->values().count(); + if (m_chartItem->itemMode() == DesignMode) + return 3; + return (m_chartItem->series().isEmpty()) + ? 0 + : m_chartItem->series().at(0)->data()->values().count(); } int AbstractSeriesChart::seriesCount() { - if (m_chartItem->itemMode() == DesignMode) return 3; + if (m_chartItem->itemMode() == DesignMode) + return 3; return m_chartItem->series().count(); } -QSizeF AbstractSeriesChart::calcChartLegendSize(const QFont &font, const qreal maxWidth) +QSizeF AbstractSeriesChart::calcChartLegendSize(const QFont& font, const qreal maxWidth) { QFontMetrics fm(font); - switch(m_chartItem->legendAlign()) { + switch (m_chartItem->legendAlign()) { case ChartItem::LegendAlignBottomLeft: case ChartItem::LegendAlignBottomCenter: case ChartItem::LegendAlignBottomRight: { - const qreal seriesCount = m_chartItem->series().isEmpty() ? m_designLabels.size() : m_chartItem->series().size(); + const qreal seriesCount = m_chartItem->series().isEmpty() ? m_designLabels.size() + : m_chartItem->series().size(); const qreal indicatorWidth = fm.height() * 1.5; m_legendColumnWidths.clear(); while (!calculateLegendColumnWidths(indicatorWidth, maxWidth, fm)) { @@ -873,8 +759,10 @@ QSizeF AbstractSeriesChart::calcChartLegendSize(const QFont &font, const qreal m } const qreal columnCount = m_legendColumnWidths.size(); const qreal rowCount = std::ceil(seriesCount / columnCount); - QSizeF legendSize(std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0) + fm.height() / 2, - (rowCount + 1) * fm.height()); + QSizeF legendSize( + std::accumulate(m_legendColumnWidths.cbegin(), m_legendColumnWidths.cend(), 0.0) + + fm.height() / 2, + (rowCount + 1) * fm.height()); if (legendSize.width() > maxWidth) { legendSize.setWidth(maxWidth); } @@ -885,20 +773,20 @@ QSizeF AbstractSeriesChart::calcChartLegendSize(const QFont &font, const qreal m qreal maxWidth = 0; if (m_chartItem->series().isEmpty()) { - foreach(QString label, m_designLabels){ + foreach (QString label, m_designLabels) { cw += fm.height(); - if (maxWidthseries()){ + foreach (SeriesItem* series, m_chartItem->series()) { cw += fm.height(); - if (maxWidthname()).width()) - maxWidth = fm.boundingRect(series->name()).width()+10; + if (maxWidth < fm.boundingRect(series->name()).width()) + maxWidth = fm.boundingRect(series->name()).width() + 10; } } cw += fm.height(); - return QSizeF(maxWidth+fm.height()*2,cw); + return QSizeF(maxWidth + fm.height() * 2, cw); } } return QSizeF(); @@ -906,39 +794,41 @@ QSizeF AbstractSeriesChart::calcChartLegendSize(const QFont &font, const qreal m bool AbstractSeriesChart::verticalLabels(QPainter* painter, QRectF labelsRect) { - if (valuesCount() == 0) return false; + if (valuesCount() == 0) + return false; qreal hStep = (labelsRect.width() / valuesCount()); QFontMetrics fm = painter->fontMetrics(); - foreach(QString label, m_chartItem->labels()){ - if (fm.boundingRect(label).width() > hStep){ - return true; + foreach (QString label, m_chartItem->labels()) { + if (fm.boundingRect(label).width() > hStep) { + return true; } } return false; } -void AbstractSeriesChart::paintHorizontalLabels(QPainter *painter, QRectF labelsRect) +void AbstractSeriesChart::paintHorizontalLabels(QPainter* painter, QRectF labelsRect) { - if (valuesCount() == 0) return; + if (valuesCount() == 0) + return; painter->save(); qreal hStep = (labelsRect.width() / valuesCount()); - if (!m_chartItem->labels().isEmpty()){ - if (verticalLabels(painter, labelsRect)){ + if (!m_chartItem->labels().isEmpty()) { + if (verticalLabels(painter, labelsRect)) { painter->rotate(270); - painter->translate( -(labelsRect.top()+labelsRect.height()), labelsRect.left() ); + painter->translate(-(labelsRect.top() + labelsRect.height()), labelsRect.left()); foreach (QString label, m_chartItem->labels()) { - painter->drawText(QRectF(QPoint(0,0), - QSize(labelsRect.height()-4, hStep)), Qt::AlignVCenter | Qt::AlignRight, label); - painter->translate(0,hStep); + painter->drawText(QRectF(QPoint(0, 0), QSize(labelsRect.height() - 4, hStep)), + Qt::AlignVCenter | Qt::AlignRight, label); + painter->translate(0, hStep); } painter->rotate(-270); } else { - painter->translate( labelsRect.left(), labelsRect.top() ); + painter->translate(labelsRect.left(), labelsRect.top()); foreach (QString label, m_chartItem->labels()) { - painter->drawText(QRectF(QPoint(0, 4), - QSize(hStep, labelsRect.height()-4)), Qt::AlignHCenter | Qt::AlignTop, label); + painter->drawText(QRectF(QPoint(0, 4), QSize(hStep, labelsRect.height() - 4)), + Qt::AlignHCenter | Qt::AlignTop, label); painter->translate(hStep, 0); } } @@ -946,9 +836,10 @@ void AbstractSeriesChart::paintHorizontalLabels(QPainter *painter, QRectF labels painter->restore(); } -void AbstractSeriesChart::paintVerticalLabels(QPainter *painter, QRectF labelsRect) +void AbstractSeriesChart::paintVerticalLabels(QPainter* painter, QRectF labelsRect) { - if (valuesCount() == 0) return; + if (valuesCount() == 0) + return; painter->save(); painter->setFont(adaptLabelsFont(labelsRect.adjusted(0, 0, -hPadding(m_chartItem->rect()), 0), @@ -957,11 +848,12 @@ void AbstractSeriesChart::paintVerticalLabels(QPainter *painter, QRectF labelsRe int curLabel = 0; painter->translate(labelsRect.topLeft()); - if (!m_chartItem->labels().isEmpty()){ + if (!m_chartItem->labels().isEmpty()) { foreach (QString label, m_chartItem->labels()) { - painter->drawText(QRectF(QPoint(0,vStep*curLabel), - QSize(labelsRect.width()-hPadding(m_chartItem->rect()),vStep)), - Qt::AlignVCenter | Qt::AlignRight | Qt::TextWordWrap,label); + painter->drawText( + QRectF(QPoint(0, vStep * curLabel), + QSize(labelsRect.width() - hPadding(m_chartItem->rect()), vStep)), + Qt::AlignVCenter | Qt::AlignRight | Qt::TextWordWrap, label); curLabel++; } @@ -969,19 +861,21 @@ void AbstractSeriesChart::paintVerticalLabels(QPainter *painter, QRectF labelsRe painter->restore(); } -void AbstractSeriesChart::paintHorizontalGrid(QPainter *painter, QRectF gridRect) +void AbstractSeriesChart::paintHorizontalGrid(QPainter* painter, QRectF gridRect) { painter->save(); - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); const int segmentCount = yAxisData.segmentCount(); const int lineCount = segmentCount + 1; - painter->setRenderHint(QPainter::Antialiasing,false); - qreal hStep = (gridRect.width() - painter->fontMetrics().boundingRect(QString::number(maxValue())).width()) / segmentCount; + painter->setRenderHint(QPainter::Antialiasing, false); + qreal hStep = (gridRect.width() + - painter->fontMetrics().boundingRect(QString::number(maxValue())).width()) + / segmentCount; - painter->setFont(adaptFont(hStep-4, painter->font(), yAxisData)); + painter->setFont(adaptFont(hStep - 4, painter->font(), yAxisData)); QPointF textPos; if (m_chartItem->horizontalAxisOnTop()) { @@ -989,7 +883,7 @@ void AbstractSeriesChart::paintHorizontalGrid(QPainter *painter, QRectF gridRect } else { textPos.setY(gridRect.bottom() - painter->fontMetrics().height()); } - for (int i = 0 ; i < lineCount ; i++ ) { + for (int i = 0; i < lineCount; i++) { const qreal x = gridRect.left() + hStep * i; textPos.setX(x + 4); painter->drawText(QRectF(textPos, QSizeF(hStep, painter->fontMetrics().height())), @@ -999,11 +893,11 @@ void AbstractSeriesChart::paintHorizontalGrid(QPainter *painter, QRectF gridRect painter->restore(); } -void AbstractSeriesChart::paintVerticalGrid(QPainter *painter, QRectF gridRect) +void AbstractSeriesChart::paintVerticalGrid(QPainter* painter, QRectF gridRect) { - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); - painter->setRenderHint(QPainter::Antialiasing,false); + painter->setRenderHint(QPainter::Antialiasing, false); const int segmentCount = yAxisData.segmentCount(); const int lineCount = segmentCount + 1; @@ -1015,27 +909,27 @@ void AbstractSeriesChart::paintVerticalGrid(QPainter *painter, QRectF gridRect) const qreal textPositionOffset = valuesHMargin * 0.2; const QTextOption verticalTextOption(Qt::AlignRight); - for (int i = 0 ; i < lineCount ; i++ ) { + for (int i = 0; i < lineCount; i++) { const qreal y = vStep * i; - painter->drawText(QRectF(gridRect.bottomLeft()-QPointF(textPositionOffset,y+halfFontHeight), - QSizeF(valuesHMargin,fontHeight)), - axisLabel(i, yAxisData), - verticalTextOption); - painter->drawLine(gridRect.bottomLeft()-QPointF(-valuesHMargin,y), - gridRect.bottomRight()-QPointF(0,y)); + painter->drawText( + QRectF(gridRect.bottomLeft() - QPointF(textPositionOffset, y + halfFontHeight), + QSizeF(valuesHMargin, fontHeight)), + axisLabel(i, yAxisData), verticalTextOption); + painter->drawLine(gridRect.bottomLeft() - QPointF(-valuesHMargin, y), + gridRect.bottomRight() - QPointF(0, y)); } - painter->setRenderHint(QPainter::Antialiasing,true); + painter->setRenderHint(QPainter::Antialiasing, true); } -void AbstractSeriesChart::paintGrid(QPainter *painter, QRectF gridRect) +void AbstractSeriesChart::paintGrid(QPainter* painter, QRectF gridRect) { painter->save(); - const AxisData &yAxisData = this->yAxisData(); - AxisData &xAxisData = this->xAxisData(); + const AxisData& yAxisData = this->yAxisData(); + AxisData& xAxisData = this->xAxisData(); - painter->setRenderHint(QPainter::Antialiasing,false); + painter->setRenderHint(QPainter::Antialiasing, false); const int xAxisSegmentCount = xAxisData.segmentCount(); const int xAxisLineCount = xAxisSegmentCount + 1; @@ -1052,14 +946,14 @@ void AbstractSeriesChart::paintGrid(QPainter *painter, QRectF gridRect) // Vertical axis lines const QTextOption verticalTextOption(Qt::AlignRight); - for (int i = 0 ; i < yAxisLineCount ; i++ ) { + for (int i = 0; i < yAxisLineCount; i++) { const qreal y = vStep * i; const bool drawFullLine = m_chartItem->gridChartLines() & ChartItem::HorizontalLine - || i == 0 || i == xAxisSegmentCount; - painter->drawText(QRectF(gridRect.bottomLeft()-QPointF(textPositionHOffset, y + halfFontHeight), - QSizeF(valuesHMargin,fontHeight)), - axisLabel(i, yAxisData), - verticalTextOption); + || i == 0 || i == xAxisSegmentCount; + painter->drawText( + QRectF(gridRect.bottomLeft() - QPointF(textPositionHOffset, y + halfFontHeight), + QSizeF(valuesHMargin, fontHeight)), + axisLabel(i, yAxisData), verticalTextOption); QPointF lineEndPos = gridRect.bottomRight() - QPointF(0, y); if (!drawFullLine) { @@ -1069,22 +963,22 @@ void AbstractSeriesChart::paintGrid(QPainter *painter, QRectF gridRect) } // Horizontal axis lines - for (int i = 0 ; i < xAxisLineCount ; i++) { + for (int i = 0; i < xAxisLineCount; i++) { const qreal x = gridRect.left() + hStep * i + valuesHMargin + gridOffset.width(); - const bool drawFullLine = m_chartItem->gridChartLines() & ChartItem::VerticalLine - || i == 0 || i == xAxisSegmentCount; + const bool drawFullLine = m_chartItem->gridChartLines() & ChartItem::VerticalLine || i == 0 + || i == xAxisSegmentCount; const QString text = axisLabel(i, xAxisData); if (m_chartItem->horizontalAxisOnTop()) { - painter->drawLine(x, gridRect.top() - gridOffset.height(), - x, (drawFullLine ? gridRect.bottom() : gridRect.top())); + painter->drawLine(x, gridRect.top() - gridOffset.height(), x, + (drawFullLine ? gridRect.bottom() : gridRect.top())); painter->drawText(QRectF(x - painter->fontMetrics().boundingRect(text).width() / 2, - gridRect.top() - (fontHeight + gridOffset.height()), - hStep, fontHeight), + gridRect.top() - (fontHeight + gridOffset.height()), hStep, + fontHeight), text); } else { - painter->drawLine(x, gridRect.bottom() + gridOffset.height(), - x, (drawFullLine ? gridRect.top() : gridRect.bottom())); + painter->drawLine(x, gridRect.bottom() + gridOffset.height(), x, + (drawFullLine ? gridRect.top() : gridRect.bottom())); painter->drawText(QRectF(x - painter->fontMetrics().boundingRect(text).width() / 2, gridRect.bottom() + halfFontHeight * 0 + gridOffset.height(), hStep, fontHeight), @@ -1094,7 +988,8 @@ void AbstractSeriesChart::paintGrid(QPainter *painter, QRectF gridRect) painter->restore(); } -void AbstractSeriesChart::drawSegment(QPainter *painter, QPoint startPoint, QPoint endPoint, QColor color) +void AbstractSeriesChart::drawSegment(QPainter* painter, QPoint startPoint, QPoint endPoint, + QColor color) { int radius = m_chartItem->seriesLineWidth(); QPen pen(color); @@ -1104,28 +999,28 @@ void AbstractSeriesChart::drawSegment(QPainter *painter, QPoint startPoint, QPoi if (!m_chartItem->drawPoints()) { return; } - QRect startPointRect(startPoint,startPoint); - QRect endPointRect(endPoint,endPoint); + QRect startPointRect(startPoint, startPoint); + QRect endPointRect(endPoint, endPoint); painter->setBrush(color); - painter->drawEllipse(startPointRect.adjusted(radius,radius,-radius,-radius)); - painter->drawEllipse(endPointRect.adjusted(radius,radius,-radius,-radius)); + painter->drawEllipse(startPointRect.adjusted(radius, radius, -radius, -radius)); + painter->drawEllipse(endPointRect.adjusted(radius, radius, -radius, -radius)); } -qreal AbstractSeriesChart::valuesHMargin(QPainter *painter) +qreal AbstractSeriesChart::valuesHMargin(QPainter* painter) { qreal max = 0; - const AxisData &yAxisData = this->yAxisData(); + const AxisData& yAxisData = this->yAxisData(); const int offset = 4; const int yAxisLineCount = yAxisData.segmentCount() + 1; - for (int i = 0 ; i < yAxisLineCount ; i++) { + for (int i = 0; i < yAxisLineCount; i++) { const QString label = axisLabel(i, yAxisData); - max = std::max(max, (qreal)painter->fontMetrics().boundingRect(label).width()+offset); + max = std::max(max, (qreal)painter->fontMetrics().boundingRect(label).width() + offset); } return max; } -qreal AbstractSeriesChart::valuesVMargin(QPainter *painter) +qreal AbstractSeriesChart::valuesVMargin(QPainter* painter) { return painter->fontMetrics().height(); } @@ -1135,19 +1030,20 @@ QFont AbstractSeriesChart::adaptLabelsFont(QRectF rect, QFont font) QString maxWord; QFontMetrics fm(font); - foreach(QString label, m_chartItem->labels()){ + foreach (QString label, m_chartItem->labels()) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - foreach (QString currentWord, label.split(QRegExp("\\W+"))){ + foreach (QString currentWord, label.split(QRegExp("\\W+"))) { #else - foreach (QString currentWord, label.split(QRegularExpression("\\W+"))){ + foreach (QString currentWord, label.split(QRegularExpression("\\W+"))) { #endif - if (fm.boundingRect(maxWord).width() < fm.boundingRect(currentWord).width()) maxWord = currentWord; + if (fm.boundingRect(maxWord).width() < fm.boundingRect(currentWord).width()) + maxWord = currentWord; } } qreal curWidth = fm.boundingRect(maxWord).width(); QFont tmpFont = font; - while (curWidth>rect.width() && tmpFont.pixelSize() > 1){ + while (curWidth > rect.width() && tmpFont.pixelSize() > 1) { tmpFont.setPixelSize(tmpFont.pixelSize() - 1); QFontMetricsF tmpFM(tmpFont); curWidth = tmpFM.boundingRect(maxWord).width(); @@ -1155,15 +1051,15 @@ QFont AbstractSeriesChart::adaptLabelsFont(QRectF rect, QFont font) return tmpFont; } -QFont AbstractSeriesChart::adaptFont(qreal width, QFont font, const AxisData &axisData) +QFont AbstractSeriesChart::adaptFont(qreal width, QFont font, const AxisData& axisData) { QFont tmpFont = font; const int axisLineCount = axisData.segmentCount() + 1; QScopedPointer fm(new QFontMetricsF(tmpFont)); - for (int i = 0 ; i < axisLineCount ; i++) { + for (int i = 0; i < axisLineCount; i++) { QString strValue = axisLabel(i, axisData); qreal curWidth = fm->boundingRect(strValue).width(); - while (curWidth > width && tmpFont.pixelSize() > 1){ + while (curWidth > width && tmpFont.pixelSize() > 1) { tmpFont.setPixelSize(tmpFont.pixelSize() - 1); fm.reset(new QFontMetricsF(tmpFont)); curWidth = fm->boundingRect(strValue).width(); @@ -1172,7 +1068,7 @@ QFont AbstractSeriesChart::adaptFont(qreal width, QFont font, const AxisData &ax return tmpFont; } -QString AbstractSeriesChart::axisLabel(int i, const AxisData &axisData) +QString AbstractSeriesChart::axisLabel(int i, const AxisData& axisData) { const qreal min = axisData.rangeMin(); const qreal step = axisData.step(); @@ -1189,12 +1085,13 @@ QString AbstractSeriesChart::axisLabel(int i, const AxisData &axisData) return QString::number(round(value * 100.0) / 100.0); } -bool AbstractSeriesChart::calculateLegendColumnWidths(qreal indicatorWidth, qreal maxWidth, const QFontMetrics &fm) +bool AbstractSeriesChart::calculateLegendColumnWidths(qreal indicatorWidth, qreal maxWidth, + const QFontMetrics& fm) { // This method is called in the loop, because to handle case when we get // 3 small series names in first row and then in second row small name and long name. - // In this case we need to set maximum column count to 2 and iterate from the start to recalculate - // all the sizes + // In this case we need to set maximum column count to 2 and iterate from the start to + // recalculate all the sizes qreal currentRowWidth = 0; int currentColumn = 0; // During first iteration it is updated when moving to second row @@ -1202,17 +1099,21 @@ bool AbstractSeriesChart::calculateLegendColumnWidths(qreal indicatorWidth, qrea // because all rows need to have same column count (except last one) int maxColumnCount = m_legendColumnWidths.size(); if (m_chartItem->series().isEmpty()) { - for (int i=0 ; i < m_designLabels.size() ; ++i) { - const qreal itemWidth = (qreal)(fm.boundingRect(m_designLabels[i]).width()) + indicatorWidth; - if (!calculateLegendSingleColumnWidth(currentRowWidth, currentColumn, maxColumnCount, itemWidth, maxWidth)) { + for (int i = 0; i < m_designLabels.size(); ++i) { + const qreal itemWidth + = (qreal)(fm.boundingRect(m_designLabels[i]).width()) + indicatorWidth; + if (!calculateLegendSingleColumnWidth(currentRowWidth, currentColumn, maxColumnCount, + itemWidth, maxWidth)) { return false; } } } else { - for (int i = 0 ; i < m_chartItem->series().size() ; ++i) { + for (int i = 0; i < m_chartItem->series().size(); ++i) { SeriesItem* series = m_chartItem->series().at(i); - const qreal itemWidth = (qreal)(fm.boundingRect(series->name()).width()) + indicatorWidth; - if (!calculateLegendSingleColumnWidth(currentRowWidth, currentColumn, maxColumnCount, itemWidth, maxWidth)) { + const qreal itemWidth + = (qreal)(fm.boundingRect(series->name()).width()) + indicatorWidth; + if (!calculateLegendSingleColumnWidth(currentRowWidth, currentColumn, maxColumnCount, + itemWidth, maxWidth)) { return false; } } @@ -1220,8 +1121,10 @@ bool AbstractSeriesChart::calculateLegendColumnWidths(qreal indicatorWidth, qrea return true; } -bool AbstractSeriesChart::calculateLegendSingleColumnWidth(qreal ¤tRowWidth, int ¤tColumn, int &maxColumnCount, - const qreal itemWidth, const qreal maxRowWidth) +bool AbstractSeriesChart::calculateLegendSingleColumnWidth(qreal& currentRowWidth, + int& currentColumn, int& maxColumnCount, + const qreal itemWidth, + const qreal maxRowWidth) { const bool maxColumnCountDefined = maxColumnCount > 0; // Check if there is enough space for current item in the row @@ -1248,9 +1151,10 @@ bool AbstractSeriesChart::calculateLegendSingleColumnWidth(qreal ¤tRowWidt } else if (m_legendColumnWidths.at(currentColumn) < itemWidth) { // Update size if item in column is bigger than items in same column in previous rows m_legendColumnWidths[currentColumn] = itemWidth; - // After any updating column size we must recheck if all columns fit in the max row width + // After any updating column size we must recheck if all columns fit in the max row + // width qreal rowWidth = itemWidth; - for (int c = 1 ; c < m_legendColumnWidths.size() ; c++) { + for (int c = 1; c < m_legendColumnWidths.size(); c++) { rowWidth += m_legendColumnWidths.at(c); // When column widths exceed max row width remove columns at the end if (rowWidth > maxRowWidth) { @@ -1265,26 +1169,23 @@ bool AbstractSeriesChart::calculateLegendSingleColumnWidth(qreal ¤tRowWidt return true; } -QVector AbstractChart::legendColumnWidths() const -{ - return m_legendColumnWidths; -} +QVector AbstractChart::legendColumnWidths() const { return m_legendColumnWidths; } -void AbstractBarChart::paintChartLegend(QPainter *painter, QRectF legendRect) +void AbstractBarChart::paintChartLegend(QPainter* painter, QRectF legendRect) { prepareLegendToPaint(legendRect, painter); painter->setPen(Qt::black); - painter->setRenderHint(QPainter::Antialiasing,false); + painter->setRenderHint(QPainter::Antialiasing, false); if (m_chartItem->drawLegendBorder()) painter->drawRect(legendRect); - painter->setRenderHint(QPainter::Antialiasing,true); + painter->setRenderHint(QPainter::Antialiasing, true); const qreal halfFontSize = painter->fontMetrics().height() / 2; int indicatorSize = halfFontSize; const QRectF indicatorsRect = legendRect.adjusted(halfFontSize, halfFontSize, 0, 0); bool isHorizontal = false; - switch(m_chartItem->legendAlign()) { + switch (m_chartItem->legendAlign()) { case ChartItem::LegendAlignBottomLeft: case ChartItem::LegendAlignBottomCenter: case ChartItem::LegendAlignBottomRight: @@ -1295,73 +1196,74 @@ void AbstractBarChart::paintChartLegend(QPainter *painter, QRectF legendRect) break; } - if (!m_chartItem->series().isEmpty()){ - for (int i = 0 ; i < m_chartItem->series().size() ; ++i) { + if (!m_chartItem->series().isEmpty()) { + for (int i = 0; i < m_chartItem->series().size(); ++i) { SeriesItem* series = m_chartItem->series().at(i); if (isHorizontal) { - drawHorizontalLegendItem(painter, i, series->name(), indicatorSize, indicatorsRect, series->color()); + drawHorizontalLegendItem(painter, i, series->name(), indicatorSize, indicatorsRect, + series->color()); } else { - drawVerticalLegendItem(painter, i, series->name(), indicatorSize, indicatorsRect, series->color()); + drawVerticalLegendItem(painter, i, series->name(), indicatorSize, indicatorsRect, + series->color()); } } } else if (m_chartItem->itemMode() == DesignMode) { - for (int i = 0 ; i < m_designLabels.size() ; ++i){ + for (int i = 0; i < m_designLabels.size(); ++i) { if (isHorizontal) { - drawHorizontalLegendItem(painter, i, m_designLabels.at(i), indicatorSize, indicatorsRect, color_map[i]); + drawHorizontalLegendItem(painter, i, m_designLabels.at(i), indicatorSize, + indicatorsRect, color_map[i]); } else { - drawVerticalLegendItem(painter, i, m_designLabels.at(i), indicatorSize, indicatorsRect, color_map[i]); + drawVerticalLegendItem(painter, i, m_designLabels.at(i), indicatorSize, + indicatorsRect, color_map[i]); } } - } } -QRectF AbstractBarChart::verticalLabelsRect(QPainter *painter, QRectF labelsRect) +QRectF AbstractBarChart::verticalLabelsRect(QPainter* painter, QRectF labelsRect) { qreal maxWidth = 0; foreach (QString label, m_chartItem->labels()) { - if (painter->fontMetrics().boundingRect(label).width()>maxWidth) + if (painter->fontMetrics().boundingRect(label).width() > maxWidth) maxWidth = painter->fontMetrics().boundingRect(label).width(); } if (maxWidth + hPadding(m_chartItem->rect()) * 2 < labelsRect.width()) return labelsRect; else - return labelsRect.adjusted(0, 0, -(labelsRect.width() - (maxWidth + hPadding(m_chartItem->rect()) * 2)), 0); + return labelsRect.adjusted( + 0, 0, -(labelsRect.width() - (maxWidth + hPadding(m_chartItem->rect()) * 2)), 0); } -QRectF AbstractBarChart::horizontalLabelsRect(QPainter *painter, QRectF labelsRect) +QRectF AbstractBarChart::horizontalLabelsRect(QPainter* painter, QRectF labelsRect) { qreal maxWidth = 0; foreach (QString label, m_chartItem->labels()) { - if (painter->fontMetrics().boundingRect(label).width()>maxWidth) + if (painter->fontMetrics().boundingRect(label).width() > maxWidth) maxWidth = painter->fontMetrics().boundingRect(label).width(); } - if ((maxWidth + vPadding(m_chartItem->rect()) < labelsRect.height()) || !verticalLabels(painter, labelsRect)) + if ((maxWidth + vPadding(m_chartItem->rect()) < labelsRect.height()) + || !verticalLabels(painter, labelsRect)) return labelsRect; else return labelsRect.adjusted(0, (labelsRect.height() - maxWidth), 0, 0); } -void AbstractBarChart::drawVerticalLegendItem(QPainter *painter, int i, const QString &text, int indicatorSize, - const QRectF &indicatorsRect, const QColor &indicatorColor) +void AbstractBarChart::drawVerticalLegendItem(QPainter* painter, int i, const QString& text, + int indicatorSize, const QRectF& indicatorsRect, + const QColor& indicatorColor) { const qreal y = i * painter->fontMetrics().height(); - painter->drawText(indicatorsRect.adjusted(indicatorSize+indicatorSize * 1.5, y, 0, 0),text); - switch(m_chartItem->legendStyle()) { + painter->drawText(indicatorsRect.adjusted(indicatorSize + indicatorSize * 1.5, y, 0, 0), text); + switch (m_chartItem->legendStyle()) { case ChartItem::LegendPoints: { painter->setBrush(indicatorColor); - painter->drawEllipse( - indicatorsRect.adjusted( - 0, - y+indicatorSize/2, - -(indicatorsRect.width()-indicatorSize), - -(indicatorsRect.height()-(y+indicatorSize+indicatorSize/2)) - ) - ); + painter->drawEllipse(indicatorsRect.adjusted( + 0, y + indicatorSize / 2, -(indicatorsRect.width() - indicatorSize), + -(indicatorsRect.height() - (y + indicatorSize + indicatorSize / 2)))); break; } case ChartItem::LegendLines: { @@ -1369,7 +1271,8 @@ void AbstractBarChart::drawVerticalLegendItem(QPainter *painter, int i, const QS QPen indicatorPen(indicatorColor); indicatorPen.setWidth(4); painter->setPen(indicatorPen); - const QPointF linePos = QPointF(indicatorsRect.left(), indicatorsRect.top() + y + painter->fontMetrics().height()/2); + const QPointF linePos = QPointF( + indicatorsRect.left(), indicatorsRect.top() + y + painter->fontMetrics().height() / 2); painter->drawLine(linePos, linePos + QPointF(indicatorSize, 0)); painter->setPen(tmpPen); break; @@ -1377,20 +1280,22 @@ void AbstractBarChart::drawVerticalLegendItem(QPainter *painter, int i, const QS } } -void AbstractBarChart::drawHorizontalLegendItem(QPainter *painter, int i, const QString &text, - int indicatorSize, const QRectF &indicatorsRect, const QColor &indicatorColor) +void AbstractBarChart::drawHorizontalLegendItem(QPainter* painter, int i, const QString& text, + int indicatorSize, const QRectF& indicatorsRect, + const QColor& indicatorColor) { - const QVector &columnWidths = legendColumnWidths(); + const QVector& columnWidths = legendColumnWidths(); if (columnWidths.isEmpty()) return; const int column = i % columnWidths.size(); const int row = std::floor(i / columnWidths.size()); const qreal halfTextSize = painter->fontMetrics().height() / 2; - const qreal x = indicatorsRect.x() + std::accumulate(columnWidths.cbegin(), columnWidths.cbegin() + column, 0.0); + const qreal x = indicatorsRect.x() + + std::accumulate(columnWidths.cbegin(), columnWidths.cbegin() + column, 0.0); const qreal y = indicatorsRect.y() + (row + 1) * painter->fontMetrics().height(); painter->drawText(QPointF(x + indicatorSize * 1.5, y), text); - switch(m_chartItem->legendStyle()) { + switch (m_chartItem->legendStyle()) { case ChartItem::LegendPoints: { painter->setBrush(indicatorColor); painter->drawEllipse(x, y - halfTextSize, indicatorSize, indicatorSize); diff --git a/limereport/items/lrchartitem.h b/limereport/items/lrchartitem.h index 8194f64..be1b4a9 100644 --- a/limereport/items/lrchartitem.h +++ b/limereport/items/lrchartitem.h @@ -1,32 +1,39 @@ #ifndef LRCHARTITEM_H #define LRCHARTITEM_H -#include "lritemdesignintf.h" -#include "lrglobal.h" #include "lraxisdata.h" +#include "lrglobal.h" +#include "lritemdesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { QColor generateColor(); extern QColor color_map[39]; class IDataSource; -class SeriesItemData : public QObject{ +class SeriesItemData: public QObject { Q_OBJECT public: - QList& values(){ return m_values;} - QList& xAxisValues(){ return m_xAxisValues;} - QList& labels(){ return m_labels;} - QList& colors() { return m_colors;} - void clear(){ m_values.clear(); m_labels.clear(); m_colors.clear(); } + QList& values() { return m_values; } + QList& xAxisValues() { return m_xAxisValues; } + QList& labels() { return m_labels; } + QList& colors() { return m_colors; } + void clear() + { + m_values.clear(); + m_labels.clear(); + m_colors.clear(); + } + private: QList m_values, m_xAxisValues; QList m_labels; QList m_colors; }; -class SeriesItem : public QObject{ +class SeriesItem: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString valuesColumn READ valuesColumn WRITE setValuesColumn) @@ -35,29 +42,33 @@ class SeriesItem : public QObject{ Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(SeriesItemPreferredType preferredType READ preferredType WRITE setPreferredType) public: - enum SeriesItemPreferredType {Bar, Line}; + enum SeriesItemPreferredType { + Bar, + Line + }; #if QT_VERSION >= 0x050500 Q_ENUM(SeriesItemPreferredType) #else Q_ENUMS(SeriesItemPreferredType) #endif - SeriesItem(QObject* parent = 0) : QObject(parent), m_preferredType(Bar){} + SeriesItem(QObject* parent = 0): QObject(parent), m_preferredType(Bar) { } QString name() const; - void setName(const QString &name); + void setName(const QString& name); QString valuesColumn() const; - void setValuesColumn(const QString &valuesColumn); + void setValuesColumn(const QString& valuesColumn); QString labelsColumn() const; - void setLabelsColumn(const QString &labelsColumn); + void setLabelsColumn(const QString& labelsColumn); QString xAxisColumn() const; - void setXAxisColumn(const QString &xAxisColumn); + void setXAxisColumn(const QString& xAxisColumn); SeriesItem* clone(); void fillSeriesData(IDataSource* dataSource); - SeriesItemData* data(){ return &m_data;} + SeriesItemData* data() { return &m_data; } QColor color() const; - void setColor(const QColor &color); + void setColor(const QColor& color); SeriesItemPreferredType preferredType() const; void setPreferredType(const SeriesItemPreferredType& preferredType); - bool isEmpty(){ return m_data.values().isEmpty();} + bool isEmpty() { return m_data.values().isEmpty(); } + private: QString m_name; QString m_valuesColumn; @@ -73,17 +84,20 @@ class ChartItem; class AbstractChart { public: AbstractChart(ChartItem* chartItem); - virtual ~AbstractChart(){} - virtual void paintChart(QPainter *painter, QRectF rect) = 0; - virtual void paintChartLegend(QPainter *painter, QRectF legendRect) =0; - virtual QSizeF calcChartLegendSize(const QFont &font, qreal maxWidth = 0) = 0; - virtual QRectF calcChartLegendRect(const QFont& font, const QRectF& parentRect, bool takeAllRect, qreal borderMargin, qreal titleOffset); + virtual ~AbstractChart() { } + virtual void paintChart(QPainter* painter, QRectF rect) = 0; + virtual void paintChartLegend(QPainter* painter, QRectF legendRect) = 0; + virtual QSizeF calcChartLegendSize(const QFont& font, qreal maxWidth = 0) = 0; + virtual QRectF calcChartLegendRect(const QFont& font, const QRectF& parentRect, + bool takeAllRect, qreal borderMargin, qreal titleOffset); QFont titleFont(); - void setTitleFont(const QFont &value); + void setTitleFont(const QFont& value); + protected: QVector legendColumnWidths() const; - virtual void prepareLegendToPaint(QRectF& legendRect, QPainter *painter); + virtual void prepareLegendToPaint(QRectF& legendRect, QPainter* painter); + protected: // Title font must be placed here instead of CharItem, becuase // it would cause crash when creating CharItem object on embedded @@ -93,57 +107,60 @@ protected: QVector m_legendColumnWidths; }; -class AbstractSeriesChart: public AbstractChart{ +class AbstractSeriesChart: public AbstractChart { public: AbstractSeriesChart(ChartItem* chartItem); + protected: - AxisData &xAxisData() const; - AxisData &yAxisData() const; + AxisData& xAxisData() const; + AxisData& yAxisData() const; qreal maxValue(); qreal minValue(); void updateMinAndMaxValues(); int valuesCount(); int seriesCount(); bool verticalLabels(QPainter* painter, QRectF labelsRect); - QSizeF calcChartLegendSize(const QFont &font, qreal maxWidth); - qreal* designValues(){ return m_designValues;} + QSizeF calcChartLegendSize(const QFont& font, qreal maxWidth); + qreal* designValues() { return m_designValues; } virtual qreal hPadding(QRectF chartRect); virtual qreal vPadding(QRectF chartRect); - virtual void paintHorizontalLabels(QPainter *painter, QRectF labelsRect); - virtual void paintVerticalLabels(QPainter *painter, QRectF labelsRect); - virtual void paintHorizontalGrid(QPainter *painter, QRectF gridRect); - virtual void paintGrid(QPainter *painter, QRectF gridRect); - virtual void paintVerticalGrid(QPainter *painter, QRectF gridRect); - virtual void drawSegment(QPainter *painter, QPoint startPoint, QPoint endPoint, QColor color); - virtual qreal valuesHMargin(QPainter *painter); - virtual qreal valuesVMargin(QPainter *painter); + virtual void paintHorizontalLabels(QPainter* painter, QRectF labelsRect); + virtual void paintVerticalLabels(QPainter* painter, QRectF labelsRect); + virtual void paintHorizontalGrid(QPainter* painter, QRectF gridRect); + virtual void paintGrid(QPainter* painter, QRectF gridRect); + virtual void paintVerticalGrid(QPainter* painter, QRectF gridRect); + virtual void drawSegment(QPainter* painter, QPoint startPoint, QPoint endPoint, QColor color); + virtual qreal valuesHMargin(QPainter* painter); + virtual qreal valuesVMargin(QPainter* painter); virtual QFont adaptLabelsFont(QRectF rect, QFont font); - virtual QFont adaptFont(qreal width, QFont font, const AxisData &axisData); - virtual QString axisLabel(int i, const AxisData &axisData); + virtual QFont adaptFont(qreal width, QFont font, const AxisData& axisData); + virtual QString axisLabel(int i, const AxisData& axisData); private: - bool calculateLegendColumnWidths(qreal indicatorWidth, qreal maxWidth, const QFontMetrics &fm); - bool calculateLegendSingleColumnWidth(qreal ¤tRowWidth, int ¤tColumn, int &maxColumnCount, - const qreal itemWidth, const qreal maxRowWidth); - qreal m_designValues [9]; + bool calculateLegendColumnWidths(qreal indicatorWidth, qreal maxWidth, const QFontMetrics& fm); + bool calculateLegendSingleColumnWidth(qreal& currentRowWidth, int& currentColumn, + int& maxColumnCount, const qreal itemWidth, + const qreal maxRowWidth); + qreal m_designValues[9]; }; -class AbstractBarChart: public AbstractSeriesChart{ +class AbstractBarChart: public AbstractSeriesChart { public: - AbstractBarChart(ChartItem* chartItem):AbstractSeriesChart(chartItem){} - void paintChartLegend(QPainter *painter, QRectF legendRect); + AbstractBarChart(ChartItem* chartItem): AbstractSeriesChart(chartItem) { } + void paintChartLegend(QPainter* painter, QRectF legendRect); + protected: QRectF verticalLabelsRect(QPainter* painter, QRectF horizontalLabelsRect); virtual QRectF horizontalLabelsRect(QPainter* painter, QRectF horizontalLabelsRect); + private: - void drawVerticalLegendItem(QPainter *painter, int i, const QString &text, - int indicatorSize, const QRectF &indicatorsRect, const QColor &indicatorColor); - void drawHorizontalLegendItem(QPainter *painter, int i, const QString &text, - int indicatorSize, const QRectF &indicatorsRect, const QColor &indicatorColor); + void drawVerticalLegendItem(QPainter* painter, int i, const QString& text, int indicatorSize, + const QRectF& indicatorsRect, const QColor& indicatorColor); + void drawHorizontalLegendItem(QPainter* painter, int i, const QString& text, int indicatorSize, + const QRectF& indicatorsRect, const QColor& indicatorColor); }; -class ChartItem : public LimeReport::ItemDesignIntf -{ +class ChartItem: public LimeReport::ItemDesignIntf { Q_OBJECT Q_PROPERTY(QObject* xAxisSettings READ xAxisSettings WRITE setXAxisSettings) Q_PROPERTY(QObject* yAxisSettings READ yAxisSettings WRITE setYAxisSettings) @@ -160,23 +177,42 @@ class ChartItem : public LimeReport::ItemDesignIntf Q_PROPERTY(QFont titleFont READ titleFont WRITE setTitleFont) Q_PROPERTY(QFont font READ font WRITE setCharItemFont) - //linesChart + // linesChart Q_PROPERTY(bool drawPoints READ drawPoints WRITE setDrawPoints) Q_PROPERTY(int seriesLineWidth READ seriesLineWidth WRITE setSeriesLineWidth) Q_PROPERTY(bool horizontalAxisOnTop READ horizontalAxisOnTop WRITE setHorizontalAxisOnTop) - //gridChart + // gridChart Q_FLAGS(GridChartLines) Q_PROPERTY(QString xAxisField READ xAxisField WRITE setXAxisField) Q_PROPERTY(GridChartLines gridChartLines READ gridChartLines WRITE setGridChartLines) friend class AbstractChart; -public: - enum LegendAlign{LegendAlignRightTop,LegendAlignRightCenter,LegendAlignRightBottom, - LegendAlignBottomLeft,LegendAlignBottomCenter,LegendAlignBottomRight}; - enum LegendStyle{LegendPoints, LegendLines}; - enum TitleAlign{TitleAlignLeft, TitleAlignCenter, TitleAlignRight}; - enum ChartType{Pie, VerticalBar, HorizontalBar, Lines, GridLines}; +public: + enum LegendAlign { + LegendAlignRightTop, + LegendAlignRightCenter, + LegendAlignRightBottom, + LegendAlignBottomLeft, + LegendAlignBottomCenter, + LegendAlignBottomRight + }; + enum LegendStyle { + LegendPoints, + LegendLines + }; + enum TitleAlign { + TitleAlignLeft, + TitleAlignCenter, + TitleAlignRight + }; + enum ChartType { + Pie, + VerticalBar, + HorizontalBar, + Lines, + GridLines + }; enum LineType { NoLine = 0, HorizontalLine = 1, @@ -200,48 +236,48 @@ public: ChartItem(QObject* owner, QGraphicsItem* parent); ~ChartItem(); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QObject* xAxisSettings(); - void setYAxisSettings(QObject *axis); + void setYAxisSettings(QObject* axis); QObject* yAxisSettings(); - void setXAxisSettings(QObject *axis); + void setXAxisSettings(QObject* axis); - AxisData *xAxisData(); - AxisData *yAxisData(); + AxisData* xAxisData(); + AxisData* yAxisData(); void showAxisEditorDialog(bool isXAxis); - QList &series(); - void setSeries(const QList &series); + QList& series(); + void setSeries(const QList& series); bool isSeriesExists(const QString& name); QString datasource() const; - void setDatasource(const QString &datasource); + void setDatasource(const QString& datasource); QString chartTitle() const; - void setChartTitle(const QString &chartTitle); + void setChartTitle(const QString& chartTitle); bool drawLegendBorder() const; void setDrawLegendBorder(bool drawLegendBorder); LegendAlign legendAlign() const; - void setLegendAlign(const LegendAlign &legendAlign); + void setLegendAlign(const LegendAlign& legendAlign); LegendStyle legendStyle() const; - void setLegendStyle(const LegendStyle &legendStyle); + void setLegendStyle(const LegendStyle& legendStyle); TitleAlign titleAlign() const; - void setTitleAlign(const TitleAlign &titleAlign); + void setTitleAlign(const TitleAlign& titleAlign); ChartType chartType() const; - void setChartType(const ChartType &chartType); + void setChartType(const ChartType& chartType); QString labelsField() const; - void setLabelsField(const QString &labelsField); + void setLabelsField(const QString& labelsField); QList labels() const; - void setLabels(const QList &labels); + void setLabels(const QList& labels); QWidget* defaultEditor(); bool showLegend() const; @@ -254,7 +290,7 @@ public: void setSeriesLineWidth(int newSeriesLineWidth); QString xAxisField() const; - void setXAxisField(const QString &xAxisField); + void setXAxisField(const QString& xAxisField); bool horizontalAxisOnTop() const; void setHorizontalAxisOnTop(bool horizontalAxisOnTop); @@ -266,20 +302,21 @@ public: void setTitleFont(QFont value); void setCharItemFont(QFont value); - QSettings *settings(); + QSettings* settings(); protected: void paintChartTitle(QPainter* painter, QRectF titleRect); - virtual BaseDesignIntf* createSameTypeItem(QObject *owner, QGraphicsItem *parent); - //ICollectionContainer + virtual BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + // ICollectionContainer QObject* createElement(const QString& collectionName, const QString& elementType); int elementsCount(const QString& collectionName); - QObject* elementAt(const QString& collectionName,int index); - void collectionLoadFinished(const QString& collectionName){Q_UNUSED(collectionName)} - void updateItemSize(DataSourceManager *dataManager, RenderPass, int); - void fillLabels(IDataSource* dataSource); + QObject* elementAt(const QString& collectionName, int index); + void collectionLoadFinished(const QString& collectionName) { Q_UNUSED(collectionName) } + void updateItemSize(DataSourceManager* dataManager, RenderPass, int); + void fillLabels(IDataSource* dataSource); bool isNeedUpdateSize(RenderPass pass) const; - void setSeries(ACollectionProperty series){Q_UNUSED(series)} + void setSeries(ACollectionProperty series) { Q_UNUSED(series) } + private: QList m_series; QString m_datasource; @@ -288,9 +325,9 @@ private: AbstractChart* m_chart; bool m_legendBorder; LegendAlign m_legendAlign; - TitleAlign m_titleAlign; - ChartType m_chartType; - QString m_labelsField; + TitleAlign m_titleAlign; + ChartType m_chartType; + QString m_labelsField; QList m_labels; bool m_isEmpty; bool m_showLegend; @@ -302,5 +339,5 @@ private: LegendStyle m_legendStyle; AxisData *m_xAxisData, *m_yAxisData; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRCHARTITEM_H diff --git a/limereport/items/lrchartitemeditor.cpp b/limereport/items/lrchartitemeditor.cpp index b2f35cb..6d61405 100644 --- a/limereport/items/lrchartitemeditor.cpp +++ b/limereport/items/lrchartitemeditor.cpp @@ -1,21 +1,29 @@ #include "lrchartitemeditor.h" #include "ui_lrchartitemeditor.h" + #include "lrchartitem.h" #include "lrpagedesignintf.h" + #include -ChartItemEditor::ChartItemEditor(LimeReport::ChartItem *item, LimeReport::PageDesignIntf *page, QSettings *settings, QWidget *parent): - QWidget(parent), ui(new Ui::ChartItemEditor), m_charItem(item), m_page(page), - m_settings(settings), m_ownedSettings(false), m_isReadingSetting(false) +ChartItemEditor::ChartItemEditor(LimeReport::ChartItem* item, LimeReport::PageDesignIntf* page, + QSettings* settings, QWidget* parent): + QWidget(parent), + ui(new Ui::ChartItemEditor), + m_charItem(item), + m_page(page), + m_settings(settings), + m_ownedSettings(false), + m_isReadingSetting(false) { ui->setupUi(this); QHBoxLayout* colorLayout = new QHBoxLayout(); colorLayout->setContentsMargins(0, 0, 0, 0); m_colorButton = new QToolButton(); m_colorButton->setText("..."); - m_colorButton->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); + m_colorButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); m_colorIndicator = new ColorIndicator(); - m_colorIndicator->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); + m_colorIndicator->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); ui->colorWidget->setLayout(colorLayout); colorLayout->addWidget(m_colorIndicator); colorLayout->addWidget(m_colorButton); @@ -38,10 +46,10 @@ ChartItemEditor::~ChartItemEditor() QSettings* ChartItemEditor::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_settings = new QSettings("LimeReport", QCoreApplication::applicationName()); m_ownedSettings = true; return m_settings; } @@ -49,17 +57,18 @@ QSettings* ChartItemEditor::settings() void ChartItemEditor::readSetting() { - if (settings()==0) return; + if (settings() == 0) + return; m_isReadingSetting = true; settings()->beginGroup("ChartItemEditor"); QVariant v = settings()->value("Geometry"); - if (v.isValid()){ + if (v.isValid()) { restoreGeometry(v.toByteArray()); } v = settings()->value("State"); - if (v.isValid()){ + if (v.isValid()) { ui->splitter->restoreState(v.toByteArray()); } @@ -70,10 +79,10 @@ void ChartItemEditor::readSetting() void ChartItemEditor::writeSetting() { - if (settings()!=0){ + if (settings() != 0) { settings()->beginGroup("ChartItemEditor"); - settings()->setValue("Geometry",saveGeometry()); - settings()->setValue("State",ui->splitter->saveState()); + settings()->setValue("Geometry", saveGeometry()); + settings()->setValue("State", ui->splitter->saveState()); settings()->endGroup(); } } @@ -82,9 +91,9 @@ void ChartItemEditor::rebuildTable() { ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(m_charItem->series().count()); - for( int i=0;iseries().count();++i){ + for (int i = 0; i < m_charItem->series().count(); ++i) { QTableWidgetItem* newRow = new QTableWidgetItem(m_charItem->series().at(i)->name()); - ui->tableWidget->setItem(i,0,newRow); + ui->tableWidget->setItem(i, 0, newRow); } } @@ -95,38 +104,41 @@ void ChartItemEditor::init() ui->tableWidget->setColumnCount(1); ui->tableWidget->setRowCount(m_charItem->series().count()); ui->tableWidget->horizontalHeader()->setStretchLastSection(true); - ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem(tr("Series name"))); + ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("Series name"))); rebuildTable(); - if (!m_charItem->datasource().isEmpty()){ - if (m_page && m_page->datasourceManager()){ - LimeReport::IDataSource* ds = m_page->datasourceManager()->dataSource(m_charItem->datasource()); - if (ds){ - for (int i=0;icolumnCount();++i){ - ui->valuesFieldComboBox->addItem(ds->columnNameByIndex(i)); - ui->labelsFieldComboBox->addItem(ds->columnNameByIndex(i)); - ui->xAxisFieldComboBox->addItem(ds->columnNameByIndex(i)); + if (!m_charItem->datasource().isEmpty()) { + if (m_page && m_page->datasourceManager()) { + LimeReport::IDataSource* ds + = m_page->datasourceManager()->dataSource(m_charItem->datasource()); + if (ds) { + for (int i = 0; i < ds->columnCount(); ++i) { + ui->valuesFieldComboBox->addItem(ds->columnNameByIndex(i)); + ui->labelsFieldComboBox->addItem(ds->columnNameByIndex(i)); + ui->xAxisFieldComboBox->addItem(ds->columnNameByIndex(i)); } } } - } - static int enumIndex = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); + static int enumIndex + = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); QMetaEnum enumerator = LimeReport::SeriesItem::staticMetaObject.enumerator(enumIndex); - for (int i = 0; iseriesTypeComboBox->addItem(enumerator.key(i)); } #if QT_VERSION < 0x050000 - ui->labelsFieldComboBox->setCurrentIndex(ui->labelsFieldComboBox->findText( m_charItem->labelsField())); - ui->xAxisFieldComboBox->setCurrentIndex(ui->xAxisFieldComboBox->findText( m_charItem->xAxisField())); + ui->labelsFieldComboBox->setCurrentIndex( + ui->labelsFieldComboBox->findText(m_charItem->labelsField())); + ui->xAxisFieldComboBox->setCurrentIndex( + ui->xAxisFieldComboBox->findText(m_charItem->xAxisField())); #else ui->labelsFieldComboBox->setCurrentText(m_charItem->labelsField()); ui->xAxisFieldComboBox->setCurrentText(m_charItem->xAxisField()); #endif - if (!m_charItem->series().isEmpty()){ + if (!m_charItem->series().isEmpty()) { enableSeriesEditor(); ui->tableWidget->selectRow(0); } else { @@ -160,30 +172,30 @@ void ChartItemEditor::disableSeriesEditor() ui->seriesTypeComboBox->setDisabled(true); } -LimeReport::SeriesItem *ChartItemEditor::currentSeries() +LimeReport::SeriesItem* ChartItemEditor::currentSeries() { int curRow = ui->tableWidget->currentRow(); - if ((curRow>-1) && !m_charItem->series().isEmpty() && m_charItem->series().count()>curRow){ + if ((curRow > -1) && !m_charItem->series().isEmpty() && m_charItem->series().count() > curRow) { return m_charItem->series().at(curRow); } return 0; } -void ChartItemEditor::resizeEvent(QResizeEvent *) +void ChartItemEditor::resizeEvent(QResizeEvent*) { #ifdef Q_OS_UNIX writeSetting(); #endif } -void ChartItemEditor::moveEvent(QMoveEvent *) +void ChartItemEditor::moveEvent(QMoveEvent*) { #ifdef Q_OS_UNIX writeSetting(); #endif } -void ChartItemEditor::on_splitter_splitterMoved(int , int ) +void ChartItemEditor::on_splitter_splitterMoved(int, int) { #ifdef Q_OS_UNIX writeSetting(); @@ -200,15 +212,19 @@ void ChartItemEditor::slotAddSeries() { LimeReport::SeriesItem* series = new LimeReport::SeriesItem(); int curSeriesNumber = m_charItem->series().count(); - while (m_charItem->isSeriesExists("Series"+QString::number(curSeriesNumber))) curSeriesNumber++; - series->setName("Series"+QString::number(curSeriesNumber)); + while (m_charItem->isSeriesExists("Series" + QString::number(curSeriesNumber))) + curSeriesNumber++; + series->setName("Series" + QString::number(curSeriesNumber)); series->setValuesColumn(""); series->setLabelsColumn(""); - series->setColor((m_charItem->series().count()<32)?LimeReport::color_map[m_charItem->series().count()]:LimeReport::generateColor()); + series->setColor((m_charItem->series().count() < 32) + ? LimeReport::color_map[m_charItem->series().count()] + : LimeReport::generateColor()); m_charItem->series().append(series); ui->tableWidget->setRowCount(m_charItem->series().count()); - ui->tableWidget->setItem(m_charItem->series().count()-1, 0, new QTableWidgetItem(series->name())); - ui->tableWidget->selectRow(m_charItem->series().count()-1); + ui->tableWidget->setItem(m_charItem->series().count() - 1, 0, + new QTableWidgetItem(series->name())); + ui->tableWidget->selectRow(m_charItem->series().count() - 1); #if QT_VERSION < 0x050000 ui->valuesFieldComboBox->setEditText(""); #else @@ -219,10 +235,10 @@ void ChartItemEditor::slotAddSeries() void ChartItemEditor::slotDeleteSeries() { QList itemsToRemove; - foreach(QModelIndex index,ui->tableWidget->selectionModel()->selectedRows()){ - itemsToRemove.append(m_charItem->series().at(index.row())); + foreach (QModelIndex index, ui->tableWidget->selectionModel()->selectedRows()) { + itemsToRemove.append(m_charItem->series().at(index.row())); }; - foreach (LimeReport::SeriesItem* series, itemsToRemove){ + foreach (LimeReport::SeriesItem* series, itemsToRemove) { m_charItem->series().removeOne(series); delete series; } @@ -232,19 +248,23 @@ void ChartItemEditor::slotDeleteSeries() void ChartItemEditor::on_tableWidget_itemSelectionChanged() { - if (ui->tableWidget->selectionModel()->hasSelection()){ - LimeReport::SeriesItem* series = m_charItem->series().at(ui->tableWidget->selectionModel()->currentIndex().row()); + if (ui->tableWidget->selectionModel()->hasSelection()) { + LimeReport::SeriesItem* series + = m_charItem->series().at(ui->tableWidget->selectionModel()->currentIndex().row()); ui->seriesNameLineEdit->setText(series->name()); #if QT_VERSION < 0x050000 - ui->valuesFieldComboBox->setCurrentIndex(ui->valuesFieldComboBox->findText(series->valuesColumn())); + ui->valuesFieldComboBox->setCurrentIndex( + ui->valuesFieldComboBox->findText(series->valuesColumn())); #else ui->valuesFieldComboBox->setCurrentText(series->valuesColumn()); #endif m_colorIndicator->setColor(series->color()); - static int enumIndex = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); + static int enumIndex + = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); QMetaEnum enumerator = LimeReport::SeriesItem::staticMetaObject.enumerator(enumIndex); #if QT_VERSION < 0x050000 - ui->seriesTypeComboBox->setCurrentIndex(ui->seriesTypeComboBox->findText(enumerator.valueToKey(series->preferredType()))); + ui->seriesTypeComboBox->setCurrentIndex( + ui->seriesTypeComboBox->findText(enumerator.valueToKey(series->preferredType()))); #else ui->seriesTypeComboBox->setCurrentText(enumerator.valueToKey(series->preferredType())); #endif @@ -252,22 +272,22 @@ void ChartItemEditor::on_tableWidget_itemSelectionChanged() } } -void ChartItemEditor::on_seriesNameLineEdit_textChanged(const QString &arg1) +void ChartItemEditor::on_seriesNameLineEdit_textChanged(const QString& arg1) { - if (currentSeries()){ + if (currentSeries()) { currentSeries()->setName(arg1); ui->tableWidget->currentItem()->setText(arg1); } } -void ChartItemEditor::on_valuesFieldComboBox_currentTextChanged(const QString &arg1) +void ChartItemEditor::on_valuesFieldComboBox_currentTextChanged(const QString& arg1) { - if (currentSeries()){ + if (currentSeries()) { currentSeries()->setValuesColumn(arg1); } } -void ChartItemEditor::on_labelsFieldComboBox_currentTextChanged(const QString &arg1) +void ChartItemEditor::on_labelsFieldComboBox_currentTextChanged(const QString& arg1) { if (!m_initing) m_charItem->setLabelsField(arg1); @@ -276,27 +296,30 @@ void ChartItemEditor::on_labelsFieldComboBox_currentTextChanged(const QString &a void ChartItemEditor::slotChangeSeriesColor() { QColorDialog colorDialog; - if (colorDialog.exec()){ + if (colorDialog.exec()) { currentSeries()->setColor(colorDialog.selectedColor()); m_colorIndicator->setColor(colorDialog.selectedColor()); } } -void ChartItemEditor::on_seriesTypeComboBox_currentIndexChanged(const QString &arg1) +void ChartItemEditor::on_seriesTypeComboBox_currentIndexChanged(const QString& arg1) { - static int enumIndex = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); + static int enumIndex + = LimeReport::SeriesItem::staticMetaObject.indexOfEnumerator("SeriesItemPreferredType"); QMetaEnum enumerator = LimeReport::SeriesItem::staticMetaObject.enumerator(enumIndex); - if (currentSeries()){ - currentSeries()->setPreferredType(static_cast(enumerator.keysToValue(arg1.toLatin1()))); + if (currentSeries()) { + currentSeries()->setPreferredType( + static_cast( + enumerator.keysToValue(arg1.toLatin1()))); } } -void ChartItemEditor::on_xAxisFieldComboBox_currentTextChanged(const QString &arg1) +void ChartItemEditor::on_xAxisFieldComboBox_currentTextChanged(const QString& arg1) { if (!m_initing) m_charItem->setXAxisField(arg1); } -void ChartItemEditor::on_tableWidget_itemChanged(QTableWidgetItem *item) +void ChartItemEditor::on_tableWidget_itemChanged(QTableWidgetItem* item) { if (ui->seriesNameLineEdit->hasFocus()) return; diff --git a/limereport/items/lrchartitemeditor.h b/limereport/items/lrchartitemeditor.h index 7c72556..1245566 100644 --- a/limereport/items/lrchartitemeditor.h +++ b/limereport/items/lrchartitemeditor.h @@ -1,30 +1,31 @@ #ifndef CHARITEMEDITOR_H #define CHARITEMEDITOR_H -#include #include "lrchartitem.h" #include "lrcolorindicator.h" + #include #include +#include namespace Ui { class ChartItemEditor; } -class ChartItemEditor : public QWidget -{ +class ChartItemEditor: public QWidget { Q_OBJECT public: ChartItemEditor(LimeReport::ChartItem* item, LimeReport::PageDesignIntf* page, - QSettings* settings=0, QWidget *parent = 0); + QSettings* settings = 0, QWidget* parent = 0); ~ChartItemEditor(); + public: - QSettings *settings(); + QSettings* settings(); void rebuildTable(); - + protected: - void resizeEvent(QResizeEvent *); - void moveEvent(QMoveEvent *); + void resizeEvent(QResizeEvent*); + void moveEvent(QMoveEvent*); signals: void editingFinished(); @@ -35,13 +36,13 @@ private slots: void slotAddSeries(); void slotDeleteSeries(); void on_tableWidget_itemSelectionChanged(); - void on_seriesNameLineEdit_textChanged(const QString &arg1); - void on_valuesFieldComboBox_currentTextChanged(const QString &arg1); - void on_labelsFieldComboBox_currentTextChanged(const QString &arg1); + void on_seriesNameLineEdit_textChanged(const QString& arg1); + void on_valuesFieldComboBox_currentTextChanged(const QString& arg1); + void on_labelsFieldComboBox_currentTextChanged(const QString& arg1); void slotChangeSeriesColor(); - void on_seriesTypeComboBox_currentIndexChanged(const QString &arg1); - void on_xAxisFieldComboBox_currentTextChanged(const QString &arg1); - void on_tableWidget_itemChanged(QTableWidgetItem *item); + void on_seriesTypeComboBox_currentIndexChanged(const QString& arg1); + void on_xAxisFieldComboBox_currentTextChanged(const QString& arg1); + void on_tableWidget_itemChanged(QTableWidgetItem* item); private: void readSetting(); @@ -50,8 +51,9 @@ private: void enableSeriesEditor(); void disableSeriesEditor(); LimeReport::SeriesItem* currentSeries(); + private: - Ui::ChartItemEditor *ui; + Ui::ChartItemEditor* ui; LimeReport::ChartItem* m_charItem; LimeReport::PageDesignIntf* m_page; QSettings* m_settings; diff --git a/limereport/items/lreditableimageitemintf.h b/limereport/items/lreditableimageitemintf.h index d470b64..2e52804 100644 --- a/limereport/items/lreditableimageitemintf.h +++ b/limereport/items/lreditableimageitemintf.h @@ -5,16 +5,15 @@ namespace LimeReport { -class IEditableImageItem{ +class IEditableImageItem { public: virtual QByteArray imageAsByteArray() const = 0; virtual void setImageAsByteArray(QByteArray image) = 0; - virtual QString resourcePath() const = 0; - virtual void setResourcePath(const QString &value) = 0; + virtual QString resourcePath() const = 0; + virtual void setResourcePath(const QString& value) = 0; virtual QString fileFilter() const = 0; }; -} - +} // namespace LimeReport #endif // LREDITABLEIMAGEITEMINTF_H diff --git a/limereport/items/lrhorizontallayout.cpp b/limereport/items/lrhorizontallayout.cpp index 82a301b..10010ad 100644 --- a/limereport/items/lrhorizontallayout.cpp +++ b/limereport/items/lrhorizontallayout.cpp @@ -28,101 +28,105 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrhorizontallayout.h" + +#include "lrbasedesignintf.h" #include "lrdesignelementsfactory.h" #include -#include #include #include - -#include "lrbasedesignintf.h" +#include const QString xmlTag = "HLayout"; namespace { -LimeReport::BaseDesignIntf *createHLayout(QObject *owner, LimeReport::BaseDesignIntf *parent) +LimeReport::BaseDesignIntf* createHLayout(QObject* owner, LimeReport::BaseDesignIntf* parent) { return new LimeReport::HorizontalLayout(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("HLayout"), LimeReport::Const::bandTAG), - createHLayout - ); -} - + xmlTag, LimeReport::ItemAttribs(QObject::tr("HLayout"), LimeReport::Const::bandTAG), + createHLayout); +} // namespace namespace LimeReport { -bool horizontalLessThen(BaseDesignIntf *c1, BaseDesignIntf* c2){ - return c1->pos().x()pos().x(); +bool horizontalLessThen(BaseDesignIntf* c1, BaseDesignIntf* c2) +{ + return c1->pos().x() < c2->pos().x(); } -HorizontalLayout::HorizontalLayout(QObject *owner, QGraphicsItem *parent) - : AbstractLayout(xmlTag, owner, parent) -{} +HorizontalLayout::HorizontalLayout(QObject* owner, QGraphicsItem* parent): + AbstractLayout(xmlTag, owner, parent) +{ +} -HorizontalLayout::~HorizontalLayout() -{} +HorizontalLayout::~HorizontalLayout() { } -BaseDesignIntf *HorizontalLayout::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* HorizontalLayout::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { return new LimeReport::HorizontalLayout(owner, parent); } bool HorizontalLayout::canBeSplitted(int height) const { - foreach(QGraphicsItem* qgItem,childItems()){ - BaseDesignIntf* item=dynamic_cast(qgItem); + foreach (QGraphicsItem* qgItem, childItems()) { + BaseDesignIntf* item = dynamic_cast(qgItem); if (item) - if (!item->canBeSplitted(height - item->pos().y())) return false; + if (!item->canBeSplitted(height - item->pos().y())) + return false; } return true; } -BaseDesignIntf *HorizontalLayout::cloneUpperPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* HorizontalLayout::cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent) { - HorizontalLayout* upperPart = dynamic_cast(createSameTypeItem(owner,parent)); + HorizontalLayout* upperPart + = dynamic_cast(createSameTypeItem(owner, parent)); upperPart->initFromItem(this); qreal maxHeight = 0; - foreach(BaseDesignIntf* item,childBaseItems()){ + foreach (BaseDesignIntf* item, childBaseItems()) { - if ((item->geometry().top()geometry().bottom()>height)){ - int sliceHeight = height-item->geometry().top(); - if (item->canBeSplitted(sliceHeight)){ - BaseDesignIntf* slicedPart = item->cloneUpperPart(sliceHeight,upperPart,upperPart); - if (maxHeightheight()) maxHeight = slicedPart->height(); + if ((item->geometry().top() < height) && (item->geometry().bottom() > height)) { + int sliceHeight = height - item->geometry().top(); + if (item->canBeSplitted(sliceHeight)) { + BaseDesignIntf* slicedPart + = item->cloneUpperPart(sliceHeight, upperPart, upperPart); + if (maxHeight < slicedPart->height()) + maxHeight = slicedPart->height(); } else { - item->cloneEmpty(sliceHeight,upperPart,upperPart); - item->setPos(item->pos().x(),item->pos().y()+((height+1)-item->geometry().top())); + item->cloneEmpty(sliceHeight, upperPart, upperPart); + item->setPos(item->pos().x(), + item->pos().y() + ((height + 1) - item->geometry().top())); } } } - foreach(BaseDesignIntf* item, upperPart->childBaseItems()){ - item->setHeight((maxHeightchildBaseItems()) { + item->setHeight((maxHeight < height) ? maxHeight : height); } upperPart->setHeight(height); return upperPart; } -BaseDesignIntf *HorizontalLayout::cloneBottomPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* HorizontalLayout::cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent) { qreal maxHeight = 0; - HorizontalLayout* bottomPart = dynamic_cast(createSameTypeItem(owner,parent)); + HorizontalLayout* bottomPart + = dynamic_cast(createSameTypeItem(owner, parent)); bottomPart->initFromItem(this); - foreach(BaseDesignIntf* item,childBaseItems()){ - if ((item->geometry().top()geometry().bottom()>height)){ - BaseDesignIntf* tmpItem=item->cloneBottomPart(height,bottomPart,bottomPart); - tmpItem->setPos(tmpItem->pos().x(),0); - if (maxHeightheight()) + foreach (BaseDesignIntf* item, childBaseItems()) { + if ((item->geometry().top() < height) && (item->geometry().bottom() > height)) { + BaseDesignIntf* tmpItem = item->cloneBottomPart(height, bottomPart, bottomPart); + tmpItem->setPos(tmpItem->pos().x(), 0); + if (maxHeight < tmpItem->height()) maxHeight = tmpItem->height(); } } - if (!bottomPart->isEmpty()){ + if (!bottomPart->isEmpty()) { foreach (BaseDesignIntf* item, bottomPart->childBaseItems()) { item->setHeight(maxHeight); } @@ -131,7 +135,7 @@ BaseDesignIntf *HorizontalLayout::cloneBottomPart(int height, QObject *owner, QG return bottomPart; } -void HorizontalLayout::setItemAlign(const BaseDesignIntf::ItemAlign &itemAlign) +void HorizontalLayout::setItemAlign(const BaseDesignIntf::ItemAlign& itemAlign) { if (itemAlign == ParentWidthItemAlign) setLayoutType(Table); @@ -140,29 +144,32 @@ void HorizontalLayout::setItemAlign(const BaseDesignIntf::ItemAlign &itemAlign) void HorizontalLayout::sortChildren() { - std::sort(layoutsChildren().begin(),layoutsChildren().end(),horizontalLessThen); + std::sort(layoutsChildren().begin(), layoutsChildren().end(), horizontalLessThen); } void HorizontalLayout::updateLayoutSize() { int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; - qreal w = spaceBorder*2; + qreal w = spaceBorder * 2; qreal h = 0; int visibleItemCount = 0; - foreach(BaseDesignIntf* item, layoutsChildren()){ - if (item->isEmpty() && hideEmptyItems()) item->setVisible(false); - if (item->isVisible()){ - if (hheight()) h=item->height(); - w+=item->width(); + foreach (BaseDesignIntf* item, layoutsChildren()) { + if (item->isEmpty() && hideEmptyItems()) + item->setVisible(false); + if (item->isVisible()) { + if (h < item->height()) + h = item->height(); + w += item->width(); visibleItemCount++; } } - if (h>0) setHeight(h+spaceBorder*2); + if (h > 0) + setHeight(h + spaceBorder * 2); if (layoutType() == Layout) - setWidth(w + layoutSpacingMM() * (visibleItemCount-1)); - else{ + setWidth(w + layoutSpacingMM() * (visibleItemCount - 1)); + else { relocateChildren(); - if (!isRelocating()){ + if (!isRelocating()) { divideSpace(); } } @@ -172,7 +179,7 @@ void HorizontalLayout::relocateChildren() { int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; QList newChildren; - if (layoutsChildren().count() < childItems().size()-1){ + if (layoutsChildren().count() < childItems().size() - 1) { auto oldChildren = layoutsChildren(); layoutsChildren().clear(); foreach (BaseDesignIntf* item, childBaseItems()) { @@ -182,14 +189,14 @@ void HorizontalLayout::relocateChildren() layoutsChildren().append(item); } } - std::sort(layoutsChildren().begin(),layoutsChildren().end(),horizontalLessThen); + std::sort(layoutsChildren().begin(), layoutsChildren().end(), horizontalLessThen); qreal curX = spaceBorder; setIsRelocating(true); foreach (BaseDesignIntf* item, layoutsChildren()) { - if (item->isVisible() || itemMode() == DesignMode){ - item->setPos(curX,spaceBorder); + if (item->isVisible() || itemMode() == DesignMode) { + item->setPos(curX, spaceBorder); curX += item->width() + layoutSpacingMM(); - item->setHeight(height()-(spaceBorder * 2)); + item->setHeight(height() - (spaceBorder * 2)); } } setIsRelocating(false); @@ -199,32 +206,36 @@ void HorizontalLayout::relocateChildren() } } -void HorizontalLayout::divideSpace(){ +void HorizontalLayout::divideSpace() +{ setIsRelocating(true); qreal itemsSumSize = 0; int visibleItemsCount = 0; int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; - foreach(BaseDesignIntf* item, layoutsChildren()){ - if (item->isVisible() || itemMode() == DesignMode ){ + foreach (BaseDesignIntf* item, layoutsChildren()) { + if (item->isVisible() || itemMode() == DesignMode) { itemsSumSize += item->width(); visibleItemsCount++; } } - itemsSumSize += layoutSpacingMM() * (visibleItemsCount-1); + itemsSumSize += layoutSpacingMM() * (visibleItemsCount - 1); - if (itemMode() == DesignMode && !layoutsChildren().isEmpty()){ - qreal delta = (width() - (itemsSumSize+spaceBorder*2)); - layoutsChildren().last()->setWidth(layoutsChildren().last()->width()+delta); + if (itemMode() == DesignMode && !layoutsChildren().isEmpty()) { + qreal delta = (width() - (itemsSumSize + spaceBorder * 2)); + layoutsChildren().last()->setWidth(layoutsChildren().last()->width() + delta); } else { - qreal delta = (width() - (itemsSumSize+spaceBorder*2)) / (visibleItemsCount!=0 ? visibleItemsCount : 1); - for (int i=0; iisVisible() || itemMode() == DesignMode) - layoutsChildren()[i]->setWidth(layoutsChildren()[i]->width()+delta); - if ((i+1)isVisible() || itemMode() == DesignMode) - layoutsChildren()[i+1]->setPos(layoutsChildren()[i+1]->pos().x()+delta*(i+1),layoutsChildren()[i+1]->pos().y()); + layoutsChildren()[i]->setWidth(layoutsChildren()[i]->width() + delta); + if ((i + 1) < layoutsChildren().size()) + if (layoutsChildren()[i + 1]->isVisible() || itemMode() == DesignMode) + layoutsChildren()[i + 1]->setPos(layoutsChildren()[i + 1]->pos().x() + + delta * (i + 1), + layoutsChildren()[i + 1]->pos().y()); } } setIsRelocating(false); diff --git a/limereport/items/lrhorizontallayout.h b/limereport/items/lrhorizontallayout.h index 17cfaba..669a378 100644 --- a/limereport/items/lrhorizontallayout.h +++ b/limereport/items/lrhorizontallayout.h @@ -29,34 +29,32 @@ ****************************************************************************/ #ifndef LRHORIZONTALLAYOUT_H #define LRHORIZONTALLAYOUT_H +#include "lrabstractlayout.h" #include "lritemdesignintf.h" #include "lrlayoutmarker.h" -#include "lrabstractlayout.h" -namespace LimeReport -{ +namespace LimeReport { -class HorizontalLayout : public AbstractLayout -{ +class HorizontalLayout: public AbstractLayout { Q_OBJECT Q_PROPERTY(LayoutType layoutType READ layoutType WRITE setLayoutType) public: friend class LayoutMarker; friend class BaseDesignIntf; - HorizontalLayout(QObject *owner = 0, QGraphicsItem *parent = 0); + HorizontalLayout(QObject* owner = 0, QGraphicsItem* parent = 0); ~HorizontalLayout(); - BaseDesignIntf *createSameTypeItem(QObject *owner = 0, QGraphicsItem *parent = 0); - bool isSplittable() const { return true;} - bool canContainChildren() const { return true;} + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + bool isSplittable() const { return true; } + bool canContainChildren() const { return true; } protected: void updateLayoutSize(); void relocateChildren(); bool canBeSplitted(int height) const; - BaseDesignIntf* cloneUpperPart(int height, QObject* owner=0, QGraphicsItem* parent=0); - BaseDesignIntf* cloneBottomPart(int height, QObject *owner=0, QGraphicsItem *parent=0); - void setItemAlign(const ItemAlign &itemAlign); + BaseDesignIntf* cloneUpperPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); + BaseDesignIntf* cloneBottomPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); + void setItemAlign(const ItemAlign& itemAlign); private: void sortChildren(); @@ -64,5 +62,5 @@ private: void placeItemInLayout(BaseDesignIntf* item); }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRHORIZONTALLAYOUT_H diff --git a/limereport/items/lrimageitem.cpp b/limereport/items/lrimageitem.cpp index 4958807..54fbf80 100644 --- a/limereport/items/lrimageitem.cpp +++ b/limereport/items/lrimageitem.cpp @@ -28,47 +28,56 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrimageitem.h" + +#include "lrdatasourcemanager.h" #include "lrdesignelementsfactory.h" #include "lrglobal.h" -#include "lrdatasourcemanager.h" -#include "lrpagedesignintf.h" #include "lrimageitemeditor.h" +#include "lrpagedesignintf.h" -namespace{ +namespace { const QString xmlTag = "ImageItem"; -LimeReport::BaseDesignIntf * createImageItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::ImageItem(owner,parent); +LimeReport::BaseDesignIntf* createImageItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::ImageItem(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, LimeReport::ItemAttribs(QObject::tr("Image Item"),"Item"), createImageItem - ); + xmlTag, LimeReport::ItemAttribs(QObject::tr("Image Item"), "Item"), createImageItem); +} // namespace + +namespace LimeReport { + +ImageItem::ImageItem(QObject* owner, QGraphicsItem* parent): + ItemDesignIntf(xmlTag, owner, parent), + m_useExternalPainter(false), + m_externalPainter(0), + m_autoSize(false), + m_scale(true), + m_keepAspectRatio(true), + m_center(true), + m_format(Binary) +{ } -namespace LimeReport{ - -ImageItem::ImageItem(QObject* owner,QGraphicsItem* parent) - :ItemDesignIntf(xmlTag,owner,parent), m_useExternalPainter(false), m_externalPainter(0), - m_autoSize(false), m_scale(true), - m_keepAspectRatio(true), m_center(true), m_format(Binary){} - -BaseDesignIntf *ImageItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* ImageItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - ImageItem* result = new ImageItem(owner,parent); + ImageItem* result = new ImageItem(owner, parent); result->setExternalPainter(m_externalPainter); return result; } -void ImageItem::loadPictureFromVariant(QVariant& data){ - //TODO: Migrate to QMetaType - if (data.isValid()){ +void ImageItem::loadPictureFromVariant(QVariant& data) +{ + // TODO: Migrate to QMetaType + if (data.isValid()) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (data.typeId() == QMetaType::QImage){ + if (data.typeId() == QMetaType::QImage) { #else - if (data.type() == QVariant::Image){ + if (data.type() == QVariant::Image) { #endif - m_picture = data.value(); + m_picture = data.value(); } else { switch (m_format) { default: @@ -83,35 +92,34 @@ void ImageItem::loadPictureFromVariant(QVariant& data){ break; } } - } } -void ImageItem::preparePopUpMenu(QMenu &menu) +void ImageItem::preparePopUpMenu(QMenu& menu) { - QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"),tr("Edit")); - menu.insertAction(menu.actions().at(0),editAction); + QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"), tr("Edit")); + menu.insertAction(menu.actions().at(0), editAction); menu.insertSeparator(menu.actions().at(1)); menu.addSeparator(); QAction* action = menu.addAction(tr("Watermark")); action->setCheckable(true); action->setChecked(isWatermark()); - } -void ImageItem::processPopUpAction(QAction *action) +void ImageItem::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Watermark")) == 0){ - page()->setPropertyToSelectedItems("watermark",action->isChecked()); + if (action->text().compare(tr("Watermark")) == 0) { + page()->setPropertyToSelectedItems("watermark", action->isChecked()); } - if (action->text().compare(tr("Edit")) == 0){ + if (action->text().compare(tr("Edit")) == 0) { this->showEditorDialog(); } ItemDesignIntf::processPopUpAction(action); } -QImage getFileByResourcePath(QString resourcePath) { +QImage getFileByResourcePath(QString resourcePath) +{ QFileInfo resourceFile(resourcePath); if (resourceFile.exists()) return QImage(resourcePath); @@ -125,21 +133,18 @@ QImage ImageItem::drawImage() const return image(); } -bool ImageItem::useExternalPainter() const -{ - return m_useExternalPainter; -} +bool ImageItem::useExternalPainter() const { return m_useExternalPainter; } void ImageItem::setUseExternalPainter(bool value) { - if (m_useExternalPainter != value){ + if (m_useExternalPainter != value) { m_useExternalPainter = value; - notify("useExternalPainter",!value, value); + notify("useExternalPainter", !value, value); update(); } } -QWidget *ImageItem::defaultEditor() +QWidget* ImageItem::defaultEditor() { ImageItemEditor* editor = new ImageItemEditor(this); editor->setAttribute(Qt::WA_DeleteOnClose); @@ -151,7 +156,7 @@ QByteArray ImageItem::imageAsByteArray() const QByteArray result; QBuffer buffer(&result); buffer.open(QIODevice::WriteOnly); - m_picture.save(&buffer,"PNG"); + m_picture.save(&buffer, "PNG"); return result; } @@ -165,63 +170,59 @@ void ImageItem::setImageAsByteArray(QByteArray image) QString ImageItem::fileFilter() const { - return tr("Images (*.gif *.icns *.ico *.jpeg *.tga *.tiff *.wbmp *.webp *.png *.jpg *.bmp);;All(*.*)"); + return tr("Images (*.gif *.icns *.ico *.jpeg *.tga *.tiff *.wbmp *.webp *.png *.jpg " + "*.bmp);;All(*.*)"); } void ImageItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { - if (m_picture.isNull()){ - if (!m_datasource.isEmpty() && !m_field.isEmpty()){ + if (m_picture.isNull()) { + if (!m_datasource.isEmpty() && !m_field.isEmpty()) { IDataSource* ds = dataManager->dataSource(m_datasource); - if (ds) { - QVariant data = ds->data(m_field); - loadPictureFromVariant(data); - } - } else if (!m_resourcePath.isEmpty()){ - m_resourcePath = expandUserVariables(m_resourcePath, pass, NoEscapeSymbols, dataManager); - m_resourcePath = expandDataFields(m_resourcePath, NoEscapeSymbols, dataManager); - m_picture = QImage(m_resourcePath); - } else if (!m_variable.isEmpty()){ - //TODO: Migrate to QMetaType - QVariant data = dataManager->variable(m_variable); + if (ds) { + QVariant data = ds->data(m_field); + loadPictureFromVariant(data); + } + } else if (!m_resourcePath.isEmpty()) { + m_resourcePath + = expandUserVariables(m_resourcePath, pass, NoEscapeSymbols, dataManager); + m_resourcePath = expandDataFields(m_resourcePath, NoEscapeSymbols, dataManager); + m_picture = QImage(m_resourcePath); + } else if (!m_variable.isEmpty()) { + // TODO: Migrate to QMetaType + QVariant data = dataManager->variable(m_variable); #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (data.typeId() == QMetaType::QString){ + if (data.typeId() == QMetaType::QString) { #else - if (data.type() == QVariant::String){ + if (data.type() == QVariant::String) { #endif m_picture = QImage(data.toString()); - } else { + } else { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (data.typeId() == QMetaType::QImage){ + if (data.typeId() == QMetaType::QImage) { #else - if (data.type() == QVariant::Image){ + if (data.type() == QVariant::Image) { #endif loadPictureFromVariant(data); - } - } - } - } - if (m_autoSize){ - setWidth(m_picture.width()); - setHeight(m_picture.height()); - } - BaseDesignIntf::updateItemSize(dataManager, pass, maxHeight); + } + } + } + } + if (m_autoSize) { + setWidth(m_picture.width()); + setHeight(m_picture.height()); + } + BaseDesignIntf::updateItemSize(dataManager, pass, maxHeight); } -bool ImageItem::isNeedUpdateSize(RenderPass) const +bool ImageItem::isNeedUpdateSize(RenderPass) const { return m_picture.isNull() || m_autoSize; } + +QString ImageItem::resourcePath() const { return m_resourcePath; } + +qreal ImageItem::minHeight() const { - return m_picture.isNull() || m_autoSize; -} - -QString ImageItem::resourcePath() const -{ - return m_resourcePath; -} - -qreal ImageItem::minHeight() const{ - if (!m_picture.isNull() && autoSize()) - { + if (!m_picture.isNull() && autoSize()) { return m_picture.height(); } else { return 0; @@ -230,65 +231,53 @@ qreal ImageItem::minHeight() const{ void ImageItem::setVariable(const QString& content) { - if (m_variable!=content){ + if (m_variable != content) { QString oldValue = m_variable; - m_variable=content; + m_variable = content; update(); notify("variable", oldValue, m_variable); } } -bool ImageItem::center() const -{ - return m_center; -} +bool ImageItem::center() const { return m_center; } void ImageItem::setCenter(bool center) { - if (m_center != center){ + if (m_center != center) { m_center = center; update(); - notify("center",!center,center); + notify("center", !center, center); } } -bool ImageItem::keepAspectRatio() const -{ - return m_keepAspectRatio; -} +bool ImageItem::keepAspectRatio() const { return m_keepAspectRatio; } void ImageItem::setKeepAspectRatio(bool keepAspectRatio) { - if (m_keepAspectRatio != keepAspectRatio){ + if (m_keepAspectRatio != keepAspectRatio) { m_keepAspectRatio = keepAspectRatio; update(); - notify("keepAspectRatio",!keepAspectRatio,keepAspectRatio); + notify("keepAspectRatio", !keepAspectRatio, keepAspectRatio); } } -bool ImageItem::scale() const -{ - return m_scale; -} +bool ImageItem::scale() const { return m_scale; } void ImageItem::setScale(bool scale) { - if (m_scale != scale){ + if (m_scale != scale) { m_scale = scale; update(); - notify("scale",!scale,scale); + notify("scale", !scale, scale); } } -bool ImageItem::autoSize() const -{ - return m_autoSize; -} +bool ImageItem::autoSize() const { return m_autoSize; } void ImageItem::setAutoSize(bool autoSize) { - if (m_autoSize != autoSize){ + if (m_autoSize != autoSize) { m_autoSize = autoSize; - if (m_autoSize && !m_picture.isNull()){ + if (m_autoSize && !m_picture.isNull()) { setWidth(drawImage().width()); setHeight(drawImage().height()); setPossibleResizeDirectionFlags(Fixed); @@ -296,52 +285,49 @@ void ImageItem::setAutoSize(bool autoSize) setPossibleResizeDirectionFlags(AllDirections); } update(); - notify("autoSize",!autoSize,autoSize); + notify("autoSize", !autoSize, autoSize); } } -QString ImageItem::field() const -{ - return m_field; -} +QString ImageItem::field() const { return m_field; } -void ImageItem::setField(const QString &field) +void ImageItem::setField(const QString& field) { - if (m_field != field){ + if (m_field != field) { QString oldValue = m_field; m_field = field; update(); - notify("field",oldValue,field); + notify("field", oldValue, field); } } -QString ImageItem::datasource() const -{ - return m_datasource; -} +QString ImageItem::datasource() const { return m_datasource; } -void ImageItem::setDatasource(const QString &datasource) +void ImageItem::setDatasource(const QString& datasource) { - if (m_datasource != datasource){ + if (m_datasource != datasource) { QString oldValue = m_datasource; m_datasource = datasource; update(); - notify("datasource",oldValue,datasource); + notify("datasource", oldValue, datasource); } } - -void ImageItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void ImageItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); - if (isSelected()) painter->setOpacity(Const::SELECTION_OPACITY); - else painter->setOpacity(qreal(opacity())/100); + if (isSelected()) + painter->setOpacity(Const::SELECTION_OPACITY); + else + painter->setOpacity(qreal(opacity()) / 100); QPointF point = rect().topLeft(); QImage img; - if (m_scale && !drawImage().isNull()){ - img = drawImage().scaled(rect().width(), rect().height(), keepAspectRatio() ? Qt::KeepAspectRatio : Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + if (m_scale && !drawImage().isNull()) { + img = drawImage().scaled(rect().width(), rect().height(), + keepAspectRatio() ? Qt::KeepAspectRatio : Qt::IgnoreAspectRatio, + Qt::SmoothTransformation); } else { img = drawImage(); } @@ -349,73 +335,75 @@ void ImageItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, qreal shiftHeight = rect().height() - img.height(); qreal shiftWidth = rect().width() - img.width(); - if (m_center){ - if (shiftHeight<0 || shiftWidth<0){ + if (m_center) { + if (shiftHeight < 0 || shiftWidth < 0) { qreal cutX = 0; qreal cutY = 0; qreal cutWidth = img.width(); qreal cutHeigth = img.height(); - if (shiftWidth > 0){ - point.setX(point.x()+shiftWidth/2); + if (shiftWidth > 0) { + point.setX(point.x() + shiftWidth / 2); } else { - cutX = fabs(shiftWidth/2); + cutX = fabs(shiftWidth / 2); cutWidth += shiftWidth; } - if (shiftHeight > 0){ - point.setY(point.y()+shiftHeight/2); + if (shiftHeight > 0) { + point.setY(point.y() + shiftHeight / 2); } else { - cutY = fabs(shiftHeight/2); + cutY = fabs(shiftHeight / 2); cutHeigth += shiftHeight; } - img = img.copy(cutX,cutY,cutWidth,cutHeigth); + img = img.copy(cutX, cutY, cutWidth, cutHeigth); } else { - point.setX(point.x()+shiftWidth/2); - point.setY(point.y()+shiftHeight/2); + point.setX(point.x() + shiftWidth / 2); + point.setY(point.y() + shiftHeight / 2); } } - if (img.isNull() && itemMode() == DesignMode){ + if (img.isNull() && itemMode() == DesignMode) { QString text; - painter->setFont(transformToSceneFont(QFont("Arial",10))); + painter->setFont(transformToSceneFont(QFont("Arial", 10))); painter->setPen(Qt::black); if (!datasource().isEmpty() && !field().isEmpty()) - text = datasource()+"."+field(); - else if (m_useExternalPainter) text = tr("Ext."); else text = tr("Image"); - painter->drawText(rect().adjusted(4,4,-4,-4), Qt::AlignCenter, text ); + text = datasource() + "." + field(); + else if (m_useExternalPainter) + text = tr("Ext."); + else + text = tr("Image"); + painter->drawText(rect().adjusted(4, 4, -4, -4), Qt::AlignCenter, text); } else { if (m_externalPainter && m_useExternalPainter) m_externalPainter->paintByExternalPainter(this->patternName(), painter, option); else - painter->drawImage(point,img); + painter->drawImage(point, img); } - ItemDesignIntf::paint(painter,option,widget); + ItemDesignIntf::paint(painter, option, widget); painter->restore(); } void ImageItem::setImage(QImage value) { - if (m_picture != value){ + if (m_picture != value) { QImage oldValue = m_picture; m_picture = value; - if (m_autoSize){ + if (m_autoSize) { setWidth(m_picture.width()); setHeight(m_picture.height()); } update(); - notify("image",oldValue,value); + notify("image", oldValue, value); } } -QImage ImageItem::image() const{ - return m_picture; -} +QImage ImageItem::image() const { return m_picture; } -void ImageItem::setResourcePath(const QString &value){ - if (m_resourcePath != value){ +void ImageItem::setResourcePath(const QString& value) +{ + if (m_resourcePath != value) { QString oldValue = m_resourcePath; m_resourcePath = value; update(); @@ -423,24 +411,18 @@ void ImageItem::setResourcePath(const QString &value){ } } -ImageItem::Format ImageItem::format() const -{ - return m_format; -} +ImageItem::Format ImageItem::format() const { return m_format; } void ImageItem::setFormat(Format format) { - if (m_format!=format){ + if (m_format != format) { Format oldValue = m_format; - m_format=format; + m_format = format; update(); - notify("format",oldValue,format); + notify("format", oldValue, format); } } -} +} // namespace LimeReport -bool LimeReport::ImageItem::isEmpty() const -{ - return drawImage().isNull(); -} +bool LimeReport::ImageItem::isEmpty() const { return drawImage().isNull(); } diff --git a/limereport/items/lrimageitem.h b/limereport/items/lrimageitem.h index 7d6127d..136dd3f 100644 --- a/limereport/items/lrimageitem.h +++ b/limereport/items/lrimageitem.h @@ -29,14 +29,14 @@ ****************************************************************************/ #ifndef LRIMAGEITEM_H #define LRIMAGEITEM_H -#include "lritemdesignintf.h" #include "lreditableimageitemintf.h" +#include "lritemdesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -class ImageItem : public ItemDesignIntf, public IPainterProxy, public IEditableImageItem -{ +class ImageItem: public ItemDesignIntf, public IPainterProxy, public IEditableImageItem { Q_OBJECT Q_PROPERTY(QImage image READ image WRITE setImage) Q_PROPERTY(int opacity READ opacity WRITE setOpacity) @@ -54,9 +54,9 @@ class ImageItem : public ItemDesignIntf, public IPainterProxy, public IEditableI public: enum Format { - Binary = 0, - Hex = 1, - Base64 = 2 + Binary = 0, + Hex = 1, + Base64 = 2 }; #if QT_VERSION >= 0x050500 Q_ENUM(Format) @@ -64,16 +64,16 @@ public: Q_ENUMS(Format) #endif - ImageItem(QObject *owner, QGraphicsItem *parent); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + ImageItem(QObject* owner, QGraphicsItem* parent); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void setImage(QImage value); QImage image() const; - void setResourcePath(const QString &value); + void setResourcePath(const QString& value); QString resourcePath() const; QString datasource() const; - void setDatasource(const QString &datasource); + void setDatasource(const QString& datasource); QString field() const; - void setField(const QString &field); + void setField(const QString& field); bool autoSize() const; void setAutoSize(bool autoSize); @@ -87,10 +87,13 @@ public: void setFormat(Format format); qreal minHeight() const; - QString variable(){ return m_variable;} + QString variable() { return m_variable; } void setVariable(const QString& variable); - void setExternalPainter(IExternalPainter* externalPainter){ m_externalPainter = externalPainter;} + void setExternalPainter(IExternalPainter* externalPainter) + { + m_externalPainter = externalPainter; + } bool useExternalPainter() const; void setUseExternalPainter(bool value); @@ -100,34 +103,35 @@ public: QByteArray imageAsByteArray() const; void setImageAsByteArray(QByteArray image); QString fileFilter() const; + protected: - BaseDesignIntf* createSameTypeItem(QObject *owner, QGraphicsItem *parent); - void updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight); + BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + void updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight); bool isNeedUpdateSize(RenderPass) const; - bool drawDesignBorders() const {return m_picture.isNull();} + bool drawDesignBorders() const { return m_picture.isNull(); } void loadPictureFromVariant(QVariant& data); - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); QImage drawImage() const; + private: - QImage m_picture; + QImage m_picture; bool m_useExternalPainter; IExternalPainter* m_externalPainter; QString m_resourcePath; QString m_datasource; QString m_field; - bool m_autoSize; - bool m_scale; - bool m_keepAspectRatio; - bool m_center; - Format m_format; + bool m_autoSize; + bool m_scale; + bool m_keepAspectRatio; + bool m_center; + Format m_format; QString m_variable; - // BaseDesignIntf interface - public: +public: bool isEmpty() const override; }; -} +} // namespace LimeReport #endif // LRIMAGEITEM_H diff --git a/limereport/items/lrimageitemeditor.cpp b/limereport/items/lrimageitemeditor.cpp index 8cba803..03b64c3 100644 --- a/limereport/items/lrimageitemeditor.cpp +++ b/limereport/items/lrimageitemeditor.cpp @@ -1,13 +1,15 @@ #include "lrimageitemeditor.h" #include "ui_lrimageitemeditor.h" + #include "lrimageitem.h" -#include #include +#include -ImageItemEditor::ImageItemEditor(LimeReport::IEditableImageItem *item, QWidget *parent) : +ImageItemEditor::ImageItemEditor(LimeReport::IEditableImageItem* item, QWidget* parent): QWidget(parent), - ui(new Ui::ImageItemEditor), m_item(item) + ui(new Ui::ImageItemEditor), + m_item(item) { ui->setupUi(this); m_image = item->imageAsByteArray(); @@ -15,15 +17,12 @@ ImageItemEditor::ImageItemEditor(LimeReport::IEditableImageItem *item, QWidget * updateImage(); } -ImageItemEditor::~ImageItemEditor() -{ - delete ui; -} +ImageItemEditor::~ImageItemEditor() { delete ui; } void ImageItemEditor::updateImage() { QPixmap image; - if (m_image.isEmpty() && !ui->resourcePath->text().isEmpty()){ + if (m_image.isEmpty() && !ui->resourcePath->text().isEmpty()) { image.load(ui->resourcePath->text()); } else { image.loadFromData(m_image); @@ -33,9 +32,10 @@ void ImageItemEditor::updateImage() void ImageItemEditor::on_tbLoadImage_clicked() { - QString fileName = QFileDialog::getOpenFileName(this, tr("Select image file"), "", m_item->fileFilter()); + QString fileName + = QFileDialog::getOpenFileName(this, tr("Select image file"), "", m_item->fileFilter()); QFile file(fileName); - if (file.open(QIODevice::ReadOnly)){ + if (file.open(QIODevice::ReadOnly)) { m_image = file.readAll(); } updateImage(); @@ -55,10 +55,7 @@ void ImageItemEditor::on_buttonBox_accepted() this->close(); } -void ImageItemEditor::on_buttonBox_rejected() -{ - this->close(); -} +void ImageItemEditor::on_buttonBox_rejected() { this->close(); } void ImageItemEditor::on_toolButton_clicked() { diff --git a/limereport/items/lrimageitemeditor.h b/limereport/items/lrimageitemeditor.h index 80bc9c3..6481e79 100644 --- a/limereport/items/lrimageitemeditor.h +++ b/limereport/items/lrimageitemeditor.h @@ -1,9 +1,10 @@ #ifndef LRIMAGEITEMEDITOR_H #define LRIMAGEITEMEDITOR_H -#include #include "lreditableimageitemintf.h" +#include + namespace Ui { class ImageItemEditor; } @@ -12,17 +13,18 @@ namespace LimeReport { class ImageItem; } -class ImageItemEditor : public QWidget -{ +class ImageItemEditor: public QWidget { Q_OBJECT public: - explicit ImageItemEditor(LimeReport::IEditableImageItem* item, QWidget *parent = NULL); + explicit ImageItemEditor(LimeReport::IEditableImageItem* item, QWidget* parent = NULL); ~ImageItemEditor(); + private: void updateImage(); + private: - Ui::ImageItemEditor *ui; + Ui::ImageItemEditor* ui; LimeReport::IEditableImageItem* m_item; QByteArray m_image; diff --git a/limereport/items/lrlayoutmarker.cpp b/limereport/items/lrlayoutmarker.cpp index 48b534c..5ac2bb7 100644 --- a/limereport/items/lrlayoutmarker.cpp +++ b/limereport/items/lrlayoutmarker.cpp @@ -1,38 +1,44 @@ #include "lrlayoutmarker.h" -#include + #include +#include -namespace LimeReport{ +namespace LimeReport { -LayoutMarker::LayoutMarker(BaseDesignIntf* layout, QGraphicsItem *parent) - :QGraphicsItem(parent), m_rect(0,0,30,30), m_color(Qt::red), m_layout(layout){ +LayoutMarker::LayoutMarker(BaseDesignIntf* layout, QGraphicsItem* parent): + QGraphicsItem(parent), + m_rect(0, 0, 30, 30), + m_color(Qt::red), + m_layout(layout) +{ setFlag(QGraphicsItem::ItemIsMovable); } -void LayoutMarker::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +void LayoutMarker::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) { painter->save(); painter->setOpacity(Const::LAYOUT_MARKER_OPACITY); - painter->fillRect(boundingRect(),m_color); + painter->fillRect(boundingRect(), m_color); painter->setRenderHint(QPainter::Antialiasing); - qreal size = (boundingRect().width()isSelected()){ + if (m_layout->isSelected()) { painter->setOpacity(1); - QRectF r = QRectF(0,0,size,size); + QRectF r = QRectF(0, 0, size, size); painter->setBrush(Qt::white); painter->setPen(Qt::white); - painter->drawEllipse(r.adjusted(5,5,-5,-5)); + painter->drawEllipse(r.adjusted(5, 5, -5, -5)); painter->setBrush(m_color); - painter->drawEllipse(r.adjusted(7,7,-7,-7)); + painter->drawEllipse(r.adjusted(7, 7, -7, -7)); } painter->restore(); } void LayoutMarker::setHeight(qreal height) { - if (m_rect.height()!=height){ + if (m_rect.height() != height) { prepareGeometryChange(); m_rect.setHeight(height); } @@ -40,7 +46,7 @@ void LayoutMarker::setHeight(qreal height) void LayoutMarker::setWidth(qreal width) { - if (m_rect.width()!=width){ + if (m_rect.width() != width) { prepareGeometryChange(); m_rect.setWidth(width); } @@ -48,22 +54,21 @@ void LayoutMarker::setWidth(qreal width) void LayoutMarker::setColor(QColor color) { - if (m_color!=color){ + if (m_color != color) { m_color = color; update(boundingRect()); } } -void LayoutMarker::mousePressEvent(QGraphicsSceneMouseEvent *event) +void LayoutMarker::mousePressEvent(QGraphicsSceneMouseEvent* event) { - if (event->button()==Qt::LeftButton) { + if (event->button() == Qt::LeftButton) { if (!(event->modifiers() & Qt::ControlModifier)) m_layout->scene()->clearSelection(); m_layout->setSelected(true); - //m_layout->setChildVisibility(false); - update(0,0,boundingRect().width(),boundingRect().width()); + // m_layout->setChildVisibility(false); + update(0, 0, boundingRect().width(), boundingRect().width()); } } - } // namespace LimeReport diff --git a/limereport/items/lrlayoutmarker.h b/limereport/items/lrlayoutmarker.h index 3eb65b0..2476ce9 100644 --- a/limereport/items/lrlayoutmarker.h +++ b/limereport/items/lrlayoutmarker.h @@ -1,23 +1,26 @@ #ifndef LRLAYOUTMARKER_H #define LRLAYOUTMARKER_H -#include #include "lrbanddesignintf.h" -namespace LimeReport{ +#include -class LayoutMarker : public QGraphicsItem{ +namespace LimeReport { + +class LayoutMarker: public QGraphicsItem { public: - explicit LayoutMarker(BaseDesignIntf* layout, QGraphicsItem *parent=0); - virtual QRectF boundingRect() const{return m_rect;} - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); + explicit LayoutMarker(BaseDesignIntf* layout, QGraphicsItem* parent = 0); + virtual QRectF boundingRect() const { return m_rect; } + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); void setHeight(qreal height); void setWidth(qreal width); void setColor(QColor color); - qreal width(){return m_rect.width();} - qreal height(){return m_rect.height();} + qreal width() { return m_rect.width(); } + qreal height() { return m_rect.height(); } + protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent* event); + private: QRectF m_rect; QColor m_color; diff --git a/limereport/items/lrpageeditor.cpp b/limereport/items/lrpageeditor.cpp index 3748e7a..26496a8 100644 --- a/limereport/items/lrpageeditor.cpp +++ b/limereport/items/lrpageeditor.cpp @@ -1,53 +1,58 @@ #include "lrpageeditor.h" #include "ui_lrpageeditor.h" + #include "lrpagedesignintf.h" #include "lrpageitemdesignintf.h" -#include + #include +#include -namespace LimeReport{ +namespace LimeReport { -PageEditor::PageEditor(QWidget *parent, LimeReport::PageItemDesignIntf *page) : +PageEditor::PageEditor(QWidget* parent, LimeReport::PageItemDesignIntf* page): QDialog(parent), ui(new Ui::PageEditor) { ui->setupUi(this); m_page = page; - //Paper - QMetaEnum pageSizes = page->metaObject()->property(page->metaObject()->indexOfProperty("pageSize")).enumerator(); + // Paper + QMetaEnum pageSizes = page->metaObject() + ->property(page->metaObject()->indexOfProperty("pageSize")) + .enumerator(); - for (int i=0;iformat->addItem(pageSizes.key(i)); } ui->format->setCurrentIndex(m_page->pageSize()); ui->width->setValue(m_page->width() / m_page->unitFactor()); ui->height->setValue(m_page->height() / m_page->unitFactor()); ui->portrait->setChecked(m_page->pageOrientation() == LimeReport::PageItemDesignIntf::Portrait); - ui->landscape->setChecked(m_page->pageOrientation() == LimeReport::PageItemDesignIntf::Landscape); - //Margins + ui->landscape->setChecked(m_page->pageOrientation() + == LimeReport::PageItemDesignIntf::Landscape); + // Margins ui->marginTop->setValue(m_page->topMargin()); ui->marginRight->setValue(m_page->rightMargin()); ui->marginLeft->setValue(m_page->leftMargin()); ui->marginBottom->setValue(m_page->bottomMargin()); ui->dropPrinterMargins->setChecked(m_page->dropPrinterMargins()); - //Other + // Other ui->endlessHeight->setChecked(m_page->endlessHeight()); ui->extendedHeight->setValue(m_page->extendedHeight()); ui->fullPage->setChecked(m_page->fullPage()); } -PageEditor::~PageEditor() -{ - delete ui; -} +PageEditor::~PageEditor() { delete ui; } void PageEditor::applyChanges() { - m_page->setPageSize(static_cast(ui->format->currentIndex())); + m_page->setPageSize( + static_cast(ui->format->currentIndex())); m_page->setWidth(ui->width->value() * LimeReport::Const::mmFACTOR); - m_page->setHeight(ui->height->value() * LimeReport::Const::mmFACTOR); - m_page->setPageOrientation(ui->portrait->isChecked()? LimeReport::PageItemDesignIntf::Portrait : LimeReport::PageItemDesignIntf::Landscape); + m_page->setHeight(ui->height->value() * LimeReport::Const::mmFACTOR); + m_page->setPageOrientation(ui->portrait->isChecked() + ? LimeReport::PageItemDesignIntf::Portrait + : LimeReport::PageItemDesignIntf::Landscape); m_page->setTopMargin(ui->marginTop->value()); m_page->setBottomMargin(ui->marginBottom->value()); m_page->setRightMargin(ui->marginRight->value()); @@ -65,7 +70,8 @@ QSizeF PageEditor::getRectByPageSize(const LimeReport::PageItemDesignIntf::PageS QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - printer.setOrientation(ui->portrait->isChecked() ? QPrinter::Portrait : QPrinter::Landscape); + printer.setOrientation(ui->portrait->isChecked() ? QPrinter::Portrait + : QPrinter::Landscape); printer.setPaperSize((QPrinter::PageSize)size); return QSizeF(printer.paperSize(QPrinter::Millimeter).width() * m_page->unitFactor(), printer.paperSize(QPrinter::Millimeter).height() * m_page->unitFactor()); @@ -73,8 +79,10 @@ QSizeF PageEditor::getRectByPageSize(const LimeReport::PageItemDesignIntf::PageS #else printer.setPageOrientation((QPageLayout::Orientation)m_page->pageOrientation()); printer.setPageSize(QPageSize((QPageSize::PageSizeId)size)); - return QSizeF(printer.pageLayout().pageSize().size(QPageSize::Millimeter).width() * m_page->unitFactor(), - printer.pageLayout().pageSize().size(QPageSize::Millimeter).height() * m_page->unitFactor()); + return QSizeF(printer.pageLayout().pageSize().size(QPageSize::Millimeter).width() + * m_page->unitFactor(), + printer.pageLayout().pageSize().size(QPageSize::Millimeter).height() + * m_page->unitFactor()); #endif } else { return QSizeF(m_page->getItemWidth(), m_page->getItemHeight()); @@ -84,27 +92,24 @@ QSizeF PageEditor::getRectByPageSize(const LimeReport::PageItemDesignIntf::PageS void PageEditor::on_format_currentIndexChanged(int index) { QPageSize ps = *new QPageSize(); - if(ui->format->currentText() != "Custom") - { - QSizeF pageSize = getRectByPageSize(static_cast(index)); + if (ui->format->currentText() != "Custom") { + QSizeF pageSize + = getRectByPageSize(static_cast(index)); ui->width->setValue(pageSize.width() / m_page->unitFactor()); ui->height->setValue(pageSize.height() / m_page->unitFactor()); } - } - -void PageEditor::on_buttonBox_clicked(QAbstractButton *button) +void PageEditor::on_buttonBox_clicked(QAbstractButton* button) { - switch(ui->buttonBox->buttonRole(button)){ - case QDialogButtonBox::ApplyRole: - applyChanges(); - break; - case QDialogButtonBox::AcceptRole: - applyChanges(); - accept(); + switch (ui->buttonBox->buttonRole(button)) { + case QDialogButtonBox::ApplyRole: + applyChanges(); + break; + case QDialogButtonBox::AcceptRole: + applyChanges(); + accept(); } - } -} // namespace +} // namespace LimeReport diff --git a/limereport/items/lrpageeditor.h b/limereport/items/lrpageeditor.h index f2c07c2..f6e93ee 100644 --- a/limereport/items/lrpageeditor.h +++ b/limereport/items/lrpageeditor.h @@ -1,30 +1,30 @@ #ifndef LRPAGEEDITOR_H #define LRPAGEEDITOR_H -#include #include "lrpageitemdesignintf.h" + +#include #include -namespace LimeReport{ +namespace LimeReport { namespace Ui { class PageEditor; } -class LIMEREPORT_EXPORT PageEditor : public QDialog -{ +class LIMEREPORT_EXPORT PageEditor: public QDialog { Q_OBJECT public: - explicit PageEditor(QWidget *parent = nullptr,LimeReport::PageItemDesignIntf *page = nullptr); + explicit PageEditor(QWidget* parent = nullptr, LimeReport::PageItemDesignIntf* page = nullptr); ~PageEditor(); private slots: -// void on_buttonBox_accepted(); + // void on_buttonBox_accepted(); void on_format_currentIndexChanged(int index); - void on_buttonBox_clicked(QAbstractButton *button); + void on_buttonBox_clicked(QAbstractButton* button); private: - Ui::PageEditor *ui; + Ui::PageEditor* ui; LimeReport::PageItemDesignIntf* m_page; void applyChanges(); diff --git a/limereport/items/lrshapeitem.cpp b/limereport/items/lrshapeitem.cpp index 6c6b46e..b699209 100644 --- a/limereport/items/lrshapeitem.cpp +++ b/limereport/items/lrshapeitem.cpp @@ -28,53 +28,51 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrshapeitem.h" -#include "lrdesignelementsfactory.h" -#include -#include -namespace{ +#include "lrdesignelementsfactory.h" + +#include +#include + +namespace { const QString xmlTag = "ShapeItem"; -LimeReport::BaseDesignIntf * createShapeItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::ShapeItem(owner,parent); +LimeReport::BaseDesignIntf* createShapeItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::ShapeItem(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, LimeReport::ItemAttribs(QObject::tr("Shape Item"),"Item"), createShapeItem - ); -} + xmlTag, LimeReport::ItemAttribs(QObject::tr("Shape Item"), "Item"), createShapeItem); +} // namespace +namespace LimeReport { -namespace LimeReport{ - -ShapeItem::ShapeItem(QObject *owner, QGraphicsItem *parent) - :ItemDesignIntf(xmlTag,owner,parent), - m_shape(HorizontalLine), - m_shapeColor(Qt::black), - m_shapeBrushColor(Qt::black), - m_shapeBrushType(Qt::NoBrush), - m_lineWidth(1), - m_penStyle(Qt::SolidLine), - m_cornerRadius(0) +ShapeItem::ShapeItem(QObject* owner, QGraphicsItem* parent): + ItemDesignIntf(xmlTag, owner, parent), + m_shape(HorizontalLine), + m_shapeColor(Qt::black), + m_shapeBrushColor(Qt::black), + m_shapeBrushType(Qt::NoBrush), + m_lineWidth(1), + m_penStyle(Qt::SolidLine), + m_cornerRadius(0) { } -Qt::PenStyle ShapeItem::penStyle() const -{ - return m_penStyle; -} +Qt::PenStyle ShapeItem::penStyle() const { return m_penStyle; } -void ShapeItem::setPenStyle(const Qt::PenStyle &value) +void ShapeItem::setPenStyle(const Qt::PenStyle& value) { - if ((value!=m_penStyle)){ + if ((value != m_penStyle)) { Qt::PenStyle oldValue = m_penStyle; - m_penStyle=value; + m_penStyle = value; update(); - notify("penStyle",(int)oldValue,(int)value); + notify("penStyle", (int)oldValue, (int)value); } } -void ShapeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void ShapeItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); @@ -84,32 +82,30 @@ void ShapeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, pen.setStyle(m_penStyle); pen.setJoinStyle(Qt::MiterJoin); painter->setPen(pen); - QBrush brush(m_shapeBrushColor,m_shapeBrushType); + QBrush brush(m_shapeBrushColor, m_shapeBrushType); brush.setTransform(painter->worldTransform().inverted()); painter->setBrush(brush); painter->setBackground(QBrush(Qt::NoBrush)); - painter->setOpacity(qreal(opacity())/100); + painter->setOpacity(qreal(opacity()) / 100); - QRectF rectangleRect = rect().adjusted((lineWidth() / 2), - (lineWidth() / 2), - -(lineWidth() / 2), + QRectF rectangleRect = rect().adjusted((lineWidth() / 2), (lineWidth() / 2), -(lineWidth() / 2), -(lineWidth() / 2)); - switch (m_shape){ + switch (m_shape) { case HorizontalLine: - painter->drawLine(0,rect().height()/2,rect().right(),rect().height()/2); + painter->drawLine(0, rect().height() / 2, rect().right(), rect().height() / 2); break; case VerticalLine: - painter->drawLine(rect().width()/2,0,rect().width()/2,rect().height()); + painter->drawLine(rect().width() / 2, 0, rect().width() / 2, rect().height()); break; case Ellipse: painter->setRenderHint(QPainter::Antialiasing); painter->drawEllipse(rect()); break; case Rectangle: - if (m_cornerRadius != 0){ + if (m_cornerRadius != 0) { painter->setRenderHint(QPainter::Antialiasing); - painter->drawRoundedRect(rectangleRect,m_cornerRadius,m_cornerRadius); + painter->drawRoundedRect(rectangleRect, m_cornerRadius, m_cornerRadius); } else { painter->drawRect(rectangleRect); } @@ -117,79 +113,74 @@ void ShapeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, } painter->restore(); - ItemDesignIntf::paint(painter,option,widget); - + ItemDesignIntf::paint(painter, option, widget); } void ShapeItem::setShapeColor(QColor value) { - if ((value!=m_shapeColor)){ + if ((value != m_shapeColor)) { QColor oldValue = m_shapeColor; - m_shapeColor=value; + m_shapeColor = value; update(); - notify("shapeColor",oldValue,value); + notify("shapeColor", oldValue, value); } } void ShapeItem::setShapeBrushColor(QColor value) { - if (value!=m_shapeBrushColor){ + if (value != m_shapeBrushColor) { QColor oldValue = m_shapeBrushColor; - m_shapeBrushColor=value; + m_shapeBrushColor = value; update(); - notify("shapeBrushColor",oldValue,value); + notify("shapeBrushColor", oldValue, value); } } void ShapeItem::setShapeBrushType(Qt::BrushStyle value) { - if (m_shapeBrushType!=value){ + if (m_shapeBrushType != value) { Qt::BrushStyle oldValue = m_shapeBrushType; - m_shapeBrushType=value; + m_shapeBrushType = value; update(rect()); - notify("shapeBrush",QBrush(oldValue),QBrush(value)); + notify("shapeBrush", QBrush(oldValue), QBrush(value)); } } void ShapeItem::setShapeType(ShapeItem::ShapeType value) { - if (m_shape!=value){ + if (m_shape != value) { ShapeType oldValue = m_shape; - m_shape=value; + m_shape = value; update(); - notify("shape",oldValue,value); + notify("shape", oldValue, value); } } void ShapeItem::setLineWidth(qreal value) { - if (m_lineWidth!=value){ + if (m_lineWidth != value) { qreal oldValue = m_lineWidth; - m_lineWidth=value; + m_lineWidth = value; update(); - notify("lineWidth",oldValue,value); - + notify("lineWidth", oldValue, value); } } -BaseDesignIntf *ShapeItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* ShapeItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new ShapeItem(owner,parent); + return new ShapeItem(owner, parent); } -int ShapeItem::cornerRadius() const -{ - return m_cornerRadius; -} +int ShapeItem::cornerRadius() const { return m_cornerRadius; } void ShapeItem::setCornerRadius(int borderRadius) { - if (m_cornerRadius != borderRadius){ + if (m_cornerRadius != borderRadius) { int oldValue = m_cornerRadius; m_cornerRadius = borderRadius; update(); - notify("cornerRadius",oldValue,m_cornerRadius); + notify("cornerRadius", oldValue, m_cornerRadius); } } -} +} // namespace LimeReport diff --git a/limereport/items/lrshapeitem.h b/limereport/items/lrshapeitem.h index b9ba727..b899919 100644 --- a/limereport/items/lrshapeitem.h +++ b/limereport/items/lrshapeitem.h @@ -30,12 +30,12 @@ #ifndef LRSHAPEITEM_H #define LRSHAPEITEM_H #include "lritemdesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -class ShapeItem: public LimeReport::ItemDesignIntf -{ +class ShapeItem: public LimeReport::ItemDesignIntf { Q_OBJECT Q_PROPERTY(ShapeType shape READ shapeType WRITE setShapeType) Q_PROPERTY(QColor shapeColor READ shapeColor WRITE setShapeColor) @@ -46,32 +46,38 @@ class ShapeItem: public LimeReport::ItemDesignIntf Q_PROPERTY(int opacity READ opacity WRITE setOpacity) Q_PROPERTY(int cornerRadius READ cornerRadius WRITE setCornerRadius) public: - enum ShapeType{HorizontalLine,VerticalLine,Ellipse,Rectangle}; + enum ShapeType { + HorizontalLine, + VerticalLine, + Ellipse, + Rectangle + }; #if QT_VERSION >= 0x050500 Q_ENUM(ShapeType) #else Q_ENUMS(ShapeType) #endif - ShapeItem(QObject *owner, QGraphicsItem *parent); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void setShapeColor(QColor value); - QColor shapeColor() const {return m_shapeColor;} - void setShapeBrushColor(QColor value); - QColor shapeBrushColor() const {return m_shapeBrushColor;} - void setShapeBrushType(Qt::BrushStyle value); - Qt::BrushStyle shapeBrushType() const {return m_shapeBrushType;} - void setShapeType(ShapeType value); - ShapeType shapeType() const {return m_shape;} - void setLineWidth(qreal value); - qreal lineWidth() const {return m_lineWidth;} + ShapeItem(QObject* owner, QGraphicsItem* parent); + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); + void setShapeColor(QColor value); + QColor shapeColor() const { return m_shapeColor; } + void setShapeBrushColor(QColor value); + QColor shapeBrushColor() const { return m_shapeBrushColor; } + void setShapeBrushType(Qt::BrushStyle value); + Qt::BrushStyle shapeBrushType() const { return m_shapeBrushType; } + void setShapeType(ShapeType value); + ShapeType shapeType() const { return m_shape; } + void setLineWidth(qreal value); + qreal lineWidth() const { return m_lineWidth; } Qt::PenStyle penStyle() const; - void setPenStyle(const Qt::PenStyle &value); + void setPenStyle(const Qt::PenStyle& value); int cornerRadius() const; void setCornerRadius(int cornerRadius); protected: - BaseDesignIntf* createSameTypeItem(QObject *owner, QGraphicsItem *parent); - bool drawDesignBorders() const {return false;} + BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + bool drawDesignBorders() const { return false; } + private: ShapeType m_shape; QColor m_shapeColor; @@ -79,9 +85,9 @@ private: Qt::BrushStyle m_shapeBrushType; qreal m_lineWidth; Qt::PenStyle m_penStyle; -// int m_opacity; + // int m_opacity; int m_cornerRadius; }; -} +} // namespace LimeReport #endif // LRSHAPEITEM_H diff --git a/limereport/items/lrsimpletagparser.cpp b/limereport/items/lrsimpletagparser.cpp index 54f3532..d0b8a42 100644 --- a/limereport/items/lrsimpletagparser.cpp +++ b/limereport/items/lrsimpletagparser.cpp @@ -28,6 +28,7 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrsimpletagparser.h" + #include #include #if QT_VERSION < 0x060000 @@ -35,28 +36,28 @@ #else #include #endif -namespace LimeReport{ +namespace LimeReport { void HtmlContext::fillTagVector(QString html) { #if QT_VERSION < 0x060000 QRegExp rx("<[^<]*>"); - QString buff=html; - int curPos=0; - while(buff.contains(rx)){ - int pos=rx.indexIn(buff); - curPos+=pos; - buff=buff.right(buff.length()-pos); - if (rx.cap().at(1)!='/'){ - int initPos=curPos; - parseTag(m_tags,buff,initPos); + QString buff = html; + int curPos = 0; + while (buff.contains(rx)) { + int pos = rx.indexIn(buff); + curPos += pos; + buff = buff.right(buff.length() - pos); + if (rx.cap().at(1) != '/') { + int initPos = curPos; + parseTag(m_tags, buff, initPos); } - buff=buff.right(buff.length()-rx.matchedLength()); + buff = buff.right(buff.length() - rx.matchedLength()); } #else QRegularExpression rx("<[^<]*>"); - QString buff=html; - while(buff.contains(rx)){ + QString buff = html; + while (buff.contains(rx)) { QRegularExpressionMatch match = rx.match(buff); // TODO: Qt6 port } @@ -64,32 +65,32 @@ void HtmlContext::fillTagVector(QString html) #endif } -QString HtmlContext::parseTag(QVector &storage, QString text, int &curPos, bool createTag) +QString HtmlContext::parseTag(QVector& storage, QString text, int& curPos, bool createTag) { #if QT_VERSION < 0x060000 QRegExp rx("<[^<]*>"); - int pos=rx.indexIn(text); - int begPos=pos+curPos; - QString buff=text.right(text.length()-(pos+rx.matchedLength())); + int pos = rx.indexIn(text); + int begPos = pos + curPos; + QString buff = text.right(text.length() - (pos + rx.matchedLength())); - QString tagName=rx.cap(0); + QString tagName = rx.cap(0); tagName.remove('<'); tagName.remove('>'); - while (buff.contains(rx)){ - pos=rx.indexIn(buff); - buff=buff.right(buff.length()-pos); - curPos+=pos; - if (extractWord(rx.cap(0),1).compare(extractWord(tagName,1),Qt::CaseInsensitive)==0){ - if (rx.cap(0).at(1)=='/'){ - if (createTag) storage.append(new Tag(tagName,begPos,curPos)); - return buff.right(buff.length()-rx.matchedLength()); + while (buff.contains(rx)) { + pos = rx.indexIn(buff); + buff = buff.right(buff.length() - pos); + curPos += pos; + if (extractWord(rx.cap(0), 1).compare(extractWord(tagName, 1), Qt::CaseInsensitive) == 0) { + if (rx.cap(0).at(1) == '/') { + if (createTag) + storage.append(new Tag(tagName, begPos, curPos)); + return buff.right(buff.length() - rx.matchedLength()); } else { - buff=parseTag(storage,buff,curPos,false); - + buff = parseTag(storage, buff, curPos, false); } } else { - buff=buff.right(buff.length()-rx.matchedLength()); + buff = buff.right(buff.length() - rx.matchedLength()); } } #else @@ -103,29 +104,29 @@ void HtmlContext::parseSymbs(QString text) { #if QT_VERSION < 0x060000 QRegExp rx("<[^<]*[^/]>"); - while (text.contains(rx)){ - int pos=rx.indexIn(text); - if (rx.cap().compare("
",Qt::CaseInsensitive)==0) - m_symbs.append(new Symb(rx.cap(),pos)); - text.remove(pos,rx.matchedLength()); + while (text.contains(rx)) { + int pos = rx.indexIn(text); + if (rx.cap().compare("
", Qt::CaseInsensitive) == 0) + m_symbs.append(new Symb(rx.cap(), pos)); + text.remove(pos, rx.matchedLength()); } - foreach(QString pattern, m_symbPatterns){ + foreach (QString pattern, m_symbPatterns) { rx.setPattern(pattern); - while (text.contains(rx)){ - int pos=rx.indexIn(text); - m_symbs.append(new Symb(rx.cap(0),pos)); - text.replace(rx.cap(0)," "); + while (text.contains(rx)) { + int pos = rx.indexIn(text); + m_symbs.append(new Symb(rx.cap(0), pos)); + text.replace(rx.cap(0), " "); } } #else QRegularExpression rx("<[^<]*>"); - while (text.contains(rx)){ - int pos=text.indexOf(rx); //rx.indexIn(text); - if (rx.cap().compare("
",Qt::CaseInsensitive)==0) - m_symbs.append(new Symb(rx.cap(),pos)); - text.remove(pos,rx.matchedLength()); + while (text.contains(rx)) { + int pos = text.indexOf(rx); // rx.indexIn(text); + if (rx.cap().compare("
", Qt::CaseInsensitive) == 0) + m_symbs.append(new Symb(rx.cap(), pos)); + text.remove(pos, rx.matchedLength()); } // TODO: Qt6 port #endif @@ -133,7 +134,8 @@ void HtmlContext::parseSymbs(QString text) void HtmlContext::initSymbPatterns() { - m_symbPatterns<<"&[^&]*;"<<"<[^<]*/>"; + m_symbPatterns << "&[^&]*;" + << "<[^<]*/>"; } HtmlContext::HtmlContext(QString html) @@ -154,51 +156,59 @@ QString HtmlContext::extractWord(QString text, int index) text.remove('<'); text.remove('>'); text.remove('/'); - int counter=1; + int counter = 1; QString retWord(""); - for (int i=0;i HtmlContext::tagVectDiff(QVector source, QVector dest) +QVector HtmlContext::tagVectDiff(QVector source, QVector dest) { QVector resVect; - for(int i=0;i source, QVector dest) +bool HtmlContext::isVectorEqual(QVector source, QVector dest) { - if (source.count()!=dest.count()) return false; - foreach(Tag* tag,source){ - if (!dest.contains(tag)) return false; + if (source.count() != dest.count()) + return false; + foreach (Tag* tag, source) { + if (!dest.contains(tag)) + return false; } return true; } -//QString HtmlContext::extendTextByTags(QString text, int pos) +// QString HtmlContext::extendTextByTags(QString text, int pos) //{ // QString curText=""; // QVector curTags=tagsAt(pos); @@ -236,33 +246,37 @@ bool HtmlContext::isVectorEqual(QVector source, QVector dest) // return curText; //} -QVector HtmlContext::tagsAt(int pos) +QVector HtmlContext::tagsAt(int pos) { QVector result; - foreach(Tag* tag,m_tags){ - if ((pos>=tag->begin())&&(pos<=tag->end())) result.append(tag); + foreach (Tag* tag, m_tags) { + if ((pos >= tag->begin()) && (pos <= tag->end())) + result.append(tag); } return result; } Symb HtmlContext::symbAt(int pos) { - foreach(Symb* symb,m_symbs){ - if (pos==symb->pos()) return *symb; + foreach (Symb* symb, m_symbs) { + if (pos == symb->pos()) + return *symb; } return Symb(); } void HtmlContext::clearTags() { - foreach(Tag* tag,m_tags) delete tag; + foreach (Tag* tag, m_tags) + delete tag; m_tags.clear(); } void HtmlContext::clearSymbs() { - foreach(Symb* symb,m_symbs) delete symb; + foreach (Symb* symb, m_symbs) + delete symb; m_tags.clear(); } -} +} // namespace LimeReport diff --git a/limereport/items/lrsimpletagparser.h b/limereport/items/lrsimpletagparser.h index 5079fb1..a24fb55 100644 --- a/limereport/items/lrsimpletagparser.h +++ b/limereport/items/lrsimpletagparser.h @@ -30,71 +30,79 @@ #ifndef LRSIMPLETAGPARSER_H #define LRSIMPLETAGPARSER_H -#include #include #include +#include -namespace LimeReport{ +namespace LimeReport { -class Tag{ +class Tag { public: - Tag(QString text,int beginPos,int endPos) - :m_tagText(text),m_beginPos(beginPos),m_endPos(endPos){} - Tag():m_tagText(""),m_beginPos(-1),m_endPos(-1){} - bool isValid(){return (!m_tagText.isEmpty())&&(m_beginPos>0)&&(m_endPos>0);} - QString tagText() const {return m_tagText;} - int begin() const {return m_beginPos;} - int end() const {return m_endPos;} + Tag(QString text, int beginPos, int endPos): + m_tagText(text), + m_beginPos(beginPos), + m_endPos(endPos) + { + } + Tag(): m_tagText(""), m_beginPos(-1), m_endPos(-1) { } + bool isValid() { return (!m_tagText.isEmpty()) && (m_beginPos > 0) && (m_endPos > 0); } + QString tagText() const { return m_tagText; } + int begin() const { return m_beginPos; } + int end() const { return m_endPos; } + private: QString m_tagText; int m_beginPos; int m_endPos; }; -class Symb{ +class Symb { public: - Symb(QString text, int pos):m_text(text),m_pos(pos){} - Symb():m_text(""),m_pos(-1){} - bool isValid(){return (!m_text.isEmpty())&&(m_pos>0);} - bool isTag(){return isValid()&&m_text.at(0)=='<';} - QString text(){return m_text;} - int pos(){return m_pos;} + Symb(QString text, int pos): m_text(text), m_pos(pos) { } + Symb(): m_text(""), m_pos(-1) { } + bool isValid() { return (!m_text.isEmpty()) && (m_pos > 0); } + bool isTag() { return isValid() && m_text.at(0) == '<'; } + QString text() { return m_text; } + int pos() { return m_pos; } + private: QString m_text; int m_pos; }; -struct TagDiff{ +struct TagDiff { enum Direction { - Inner=0, - Outer=1 + Inner = 0, + Outer = 1 }; Tag* tag; Direction direction; }; -class HtmlContext -{ +class HtmlContext { public: HtmlContext(QString html); ~HtmlContext(); - static QString extractWord(QString text,int index); + static QString extractWord(QString text, int index); static QVector tagVectDiff(QVector source, QVector dest); static bool isVectorEqual(QVector source, QVector dest); void fillTagVector(QString html); - //QString extendTextByTags(QString text, int pos); - QVector tagsAt(int pos); + // QString extendTextByTags(QString text, int pos); + QVector tagsAt(int pos); Symb symbAt(int pos); void clearTags(); void clearSymbs(); + private: - static QString parseTag(QVector& storage,QString text,int& curPos, bool createTag=true); + static QString parseTag(QVector& storage, QString text, int& curPos, + bool createTag = true); void parseSymbs(QString text); void initSymbPatterns(); + private: QVector m_tags; QVector m_symbs; QStringList m_symbPatterns; }; -} +} // namespace LimeReport #endif // LRSIMPLETAGPARSER_H diff --git a/limereport/items/lrsubitemparentpropitem.cpp b/limereport/items/lrsubitemparentpropitem.cpp index cfb8504..76ebc87 100644 --- a/limereport/items/lrsubitemparentpropitem.cpp +++ b/limereport/items/lrsubitemparentpropitem.cpp @@ -28,38 +28,46 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrsubitemparentpropitem.h" + #include "../objectinspector/editors/lrcomboboxeditor.h" #include "lrbasedesignintf.h" #include "lritemdesignintf.h" -#include "lrpagedesignintf.h" #include "lrobjectpropitem.h" +#include "lrpagedesignintf.h" +namespace { +LimeReport::ObjectPropItem* +createLocationPropItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::ItemLocationPropItem(object, objects, name, displayName, data, parent, + readonly); +} +bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("itemLocation", "LimeReport::ItemDesignIntf"), + QObject::tr("itemLocation"), createLocationPropItem); +} // namespace -namespace{ - LimeReport::ObjectPropItem * createLocationPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::ItemLocationPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("itemLocation","LimeReport::ItemDesignIntf"),QObject::tr("itemLocation"),createLocationPropItem - ); +LimeReport::ItemLocationPropItem::ItemLocationPropItem(QObject* object, ObjectsList* objects, + const QString& name, + const QString& displayName, + const QVariant& value, + ObjectPropItem* parent, bool readonly): + LimeReport::ObjectPropItem(object, objects, name, displayName, value, parent, readonly) +{ + m_locationMap.insert(tr("Band"), LimeReport::ItemDesignIntf::Band); + m_locationMap.insert(tr("Page"), LimeReport::ItemDesignIntf::Page); } -LimeReport::ItemLocationPropItem::ItemLocationPropItem(QObject* object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem* parent, bool readonly) - :LimeReport::ObjectPropItem(object, objects, name, displayName, value, parent, readonly){ - m_locationMap.insert(tr("Band"),LimeReport::ItemDesignIntf::Band); - m_locationMap.insert(tr("Page"),LimeReport::ItemDesignIntf::Page); -} - - -QWidget * LimeReport::ItemLocationPropItem::createProperyEditor(QWidget *parent) const{ - ComboBoxEditor *editor = new ComboBoxEditor(parent); - connect(editor,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotLocationChanged(QString))); - LimeReport::BaseDesignIntf *item=dynamic_cast(object()); - if (item){ +QWidget* LimeReport::ItemLocationPropItem::createProperyEditor(QWidget* parent) const +{ + ComboBoxEditor* editor = new ComboBoxEditor(parent); + connect(editor, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotLocationChanged(QString))); + LimeReport::BaseDesignIntf* item = dynamic_cast(object()); + if (item) { QStringList locationTypes; - foreach(QString location,m_locationMap.keys()){ + foreach (QString location, m_locationMap.keys()) { locationTypes.append(location); } editor->addItems(locationTypes); @@ -67,31 +75,43 @@ QWidget * LimeReport::ItemLocationPropItem::createProperyEditor(QWidget *parent) return editor; } -QString LimeReport::ItemLocationPropItem::displayValue() const{ - return locationToString(static_cast(propertyValue().toInt())); +QString LimeReport::ItemLocationPropItem::displayValue() const +{ + return locationToString( + static_cast(propertyValue().toInt())); } -void LimeReport::ItemLocationPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const{ - ComboBoxEditor *editor=qobject_cast(propertyEditor); +void LimeReport::ItemLocationPropItem::setPropertyEditorData(QWidget* propertyEditor, + const QModelIndex&) const +{ + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(locationToString(propertyValue().toInt())); } -void LimeReport::ItemLocationPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index){ +void LimeReport::ItemLocationPropItem::setModelData(QWidget* propertyEditor, + QAbstractItemModel* model, + const QModelIndex& index) +{ Q_UNUSED(propertyEditor) - model->setData(index,object()->property(propertyName().toLatin1())); + model->setData(index, object()->property(propertyName().toLatin1())); setValueToObject(propertyName(), propertyValue()); } -QString LimeReport::ItemLocationPropItem::locationToString(LimeReport::ItemDesignIntf::LocationType location) const{ +QString LimeReport::ItemLocationPropItem::locationToString( + LimeReport::ItemDesignIntf::LocationType location) const +{ return m_locationMap.key(location); } -LimeReport::ItemDesignIntf::LocationType LimeReport::ItemLocationPropItem::stringToLocation(const QString &locationName){ +LimeReport::ItemDesignIntf::LocationType +LimeReport::ItemLocationPropItem::stringToLocation(const QString& locationName) +{ return m_locationMap.value(locationName); } -void LimeReport::ItemLocationPropItem::slotLocationChanged(const QString &text){ - if ( locationToString(object()->property(propertyName().toLatin1()).toInt())!=text){ - object()->setProperty(propertyName().toLatin1(),stringToLocation(text)); +void LimeReport::ItemLocationPropItem::slotLocationChanged(const QString& text) +{ + if (locationToString(object()->property(propertyName().toLatin1()).toInt()) != text) { + object()->setProperty(propertyName().toLatin1(), stringToLocation(text)); } } diff --git a/limereport/items/lrsubitemparentpropitem.h b/limereport/items/lrsubitemparentpropitem.h index 3733c75..39f3a63 100644 --- a/limereport/items/lrsubitemparentpropitem.h +++ b/limereport/items/lrsubitemparentpropitem.h @@ -30,29 +30,36 @@ #ifndef LRSUBITEMPARENTPROPITEM_H #define LRSUBITEMPARENTPROPITEM_H +#include "lritemdesignintf.h" +#include "lrobjectpropitem.h" + #include -#include "lrobjectpropitem.h" -#include "lritemdesignintf.h" - -namespace LimeReport{ -class ItemLocationPropItem : public LimeReport::ObjectPropItem{ +namespace LimeReport { +class ItemLocationPropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - ItemLocationPropItem():ObjectPropItem(){} - ItemLocationPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly); - QWidget* createProperyEditor(QWidget *parent) const; + ItemLocationPropItem(): ObjectPropItem() { } + ItemLocationPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly); + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; - void setPropertyEditorData(QWidget *, const QModelIndex &) const; - void setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &); + void setPropertyEditorData(QWidget*, const QModelIndex&) const; + void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&); private slots: void slotLocationChanged(const QString& text); + private: QString locationToString(LimeReport::ItemDesignIntf::LocationType location) const; - QString locationToString(int location) const {return locationToString(static_cast(location));} + QString locationToString(int location) const + { + return locationToString(static_cast(location)); + } LimeReport::ItemDesignIntf::LocationType stringToLocation(const QString& locationName); + private: - QMap m_locationMap; + QMap m_locationMap; }; -} +} // namespace LimeReport #endif // LRSUBITEMPARENTPROPITEM_H diff --git a/limereport/items/lrsvgitem.cpp b/limereport/items/lrsvgitem.cpp index 9bf1ea6..31b123f 100644 --- a/limereport/items/lrsvgitem.cpp +++ b/limereport/items/lrsvgitem.cpp @@ -1,67 +1,59 @@ #include "lrsvgitem.h" + #include "lrdesignelementsfactory.h" #include "lrimageitemeditor.h" #include "lrpagedesignintf.h" + #include -namespace{ - const QString xmlTag = "SVGItem"; - LimeReport::BaseDesignIntf * createSVGItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SVGItem(owner,parent); - } - bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, LimeReport::ItemAttribs(QObject::tr("SVG Item"),"Item"), createSVGItem - ); -} - -namespace LimeReport{ -SVGItem::SVGItem(QObject *owner, QGraphicsItem *parent) - :ItemDesignIntf(xmlTag,owner,parent) +namespace { +const QString xmlTag = "SVGItem"; +LimeReport::BaseDesignIntf* createSVGItem(QObject* owner, LimeReport::BaseDesignIntf* parent) { + return new LimeReport::SVGItem(owner, parent); } +bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTag, LimeReport::ItemAttribs(QObject::tr("SVG Item"), "Item"), createSVGItem); +} // namespace -void SVGItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +namespace LimeReport { +SVGItem::SVGItem(QObject* owner, QGraphicsItem* parent): ItemDesignIntf(xmlTag, owner, parent) { } + +void SVGItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); - if (isSelected()) painter->setOpacity(Const::SELECTION_OPACITY); - else painter->setOpacity(qreal(opacity())/100); - if (m_image.isNull() && itemMode() == DesignMode){ + if (isSelected()) + painter->setOpacity(Const::SELECTION_OPACITY); + else + painter->setOpacity(qreal(opacity()) / 100); + if (m_image.isNull() && itemMode() == DesignMode) { QString text; - painter->setFont(transformToSceneFont(QFont("Arial",10))); + painter->setFont(transformToSceneFont(QFont("Arial", 10))); painter->setPen(Qt::black); if (!datasource().isEmpty() && !field().isEmpty()) - text = datasource()+"."+field(); - else text = tr("SVG Image"); - painter->drawText(rect().adjusted(4,4,-4,-4), Qt::AlignCenter, text ); - } - else if (!m_image.isEmpty()){ + text = datasource() + "." + field(); + else + text = tr("SVG Image"); + painter->drawText(rect().adjusted(4, 4, -4, -4), Qt::AlignCenter, text); + } else if (!m_image.isEmpty()) { QSvgRenderer render; render.load(m_image); render.render(painter, option->rect); } - ItemDesignIntf::paint(painter,option,widget); + ItemDesignIntf::paint(painter, option, widget); painter->restore(); } -QByteArray SVGItem::imageAsByteArray() const -{ - return m_image; -} +QByteArray SVGItem::imageAsByteArray() const { return m_image; } -void SVGItem::setImageAsByteArray(QByteArray image) -{ - setImage(image); -} +void SVGItem::setImageAsByteArray(QByteArray image) { setImage(image); } -QString SVGItem::fileFilter() const -{ - return tr("SVG (*.svg)"); -} +QString SVGItem::fileFilter() const { return tr("SVG (*.svg)"); } -void SVGItem::preparePopUpMenu(QMenu &menu) +void SVGItem::preparePopUpMenu(QMenu& menu) { - QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"),tr("Edit")); - menu.insertAction(menu.actions().at(0),editAction); + QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"), tr("Edit")); + menu.insertAction(menu.actions().at(0), editAction); menu.insertSeparator(menu.actions().at(1)); menu.addSeparator(); @@ -70,49 +62,51 @@ void SVGItem::preparePopUpMenu(QMenu &menu) action->setChecked(isWatermark()); } -void SVGItem::processPopUpAction(QAction *action) +void SVGItem::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Watermark")) == 0){ - page()->setPropertyToSelectedItems("watermark",action->isChecked()); + if (action->text().compare(tr("Watermark")) == 0) { + page()->setPropertyToSelectedItems("watermark", action->isChecked()); } - if (action->text().compare(tr("Edit")) == 0){ + if (action->text().compare(tr("Edit")) == 0) { this->showEditorDialog(); } ItemDesignIntf::processPopUpAction(action); } -QWidget *SVGItem::defaultEditor() +QWidget* SVGItem::defaultEditor() { ImageItemEditor* editor = new ImageItemEditor(this); editor->setAttribute(Qt::WA_DeleteOnClose); return editor; }; -BaseDesignIntf* SVGItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent){ +BaseDesignIntf* SVGItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) +{ return new SVGItem(owner, parent); } -void SVGItem::updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight) +void SVGItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { Q_UNUSED(maxHeight) - if (m_image.isEmpty()){ - if (!m_datasource.isEmpty() && !m_field.isEmpty()){ + if (m_image.isEmpty()) { + if (!m_datasource.isEmpty() && !m_field.isEmpty()) { IDataSource* ds = dataManager->dataSource(m_datasource); if (ds) { QVariant data = ds->data(m_field); m_image = data.value(); } - } else if (!m_resourcePath.isEmpty()){ - m_resourcePath = expandUserVariables(m_resourcePath, pass, NoEscapeSymbols, dataManager); + } else if (!m_resourcePath.isEmpty()) { + m_resourcePath + = expandUserVariables(m_resourcePath, pass, NoEscapeSymbols, dataManager); m_resourcePath = expandDataFields(m_resourcePath, NoEscapeSymbols, dataManager); m_image = imageFromResource(m_resourcePath); - } else if (!m_variable.isEmpty()){ - //TODO: Migrate to QMetaType + } else if (!m_variable.isEmpty()) { + // TODO: Migrate to QMetaType QVariant data = dataManager->variable(m_variable); #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (data.typeId() == QMetaType::QString){ + if (data.typeId() == QMetaType::QString) { #else - if (data.type() == QVariant::String){ + if (data.type() == QVariant::String) { #endif m_image = imageFromResource(data.toString()); } else { @@ -121,7 +115,7 @@ void SVGItem::updateItemSize(DataSourceManager *dataManager, RenderPass pass, in #else if (data.type() == QVariant::ByteArray) { #endif - m_image = data.value() ; + m_image = data.value(); } } } @@ -131,20 +125,17 @@ void SVGItem::updateItemSize(DataSourceManager *dataManager, RenderPass pass, in QByteArray SVGItem::imageFromResource(QString resourcePath) { QFile file(resourcePath); - if (file.open(QIODevice::ReadOnly)){ + if (file.open(QIODevice::ReadOnly)) { return file.readAll(); } - return QByteArray(); + return QByteArray(); } -QString SVGItem::variable() const -{ - return m_variable; -} +QString SVGItem::variable() const { return m_variable; } -void SVGItem::setVariable(const QString &variable) +void SVGItem::setVariable(const QString& variable) { - if (m_variable != variable){ + if (m_variable != variable) { QString oldValue = m_variable; m_variable = variable; update(); @@ -153,20 +144,17 @@ void SVGItem::setVariable(const QString &variable) m_variable = variable; } -bool SVGItem::isNeedUpdateSize(RenderPass) const { return m_image.isNull() ; } +bool SVGItem::isNeedUpdateSize(RenderPass) const { return m_image.isNull(); } -QString SVGItem::resourcePath() const -{ - return m_resourcePath; -} +QString SVGItem::resourcePath() const { return m_resourcePath; } -void SVGItem::setResourcePath(const QString &resourcePath) +void SVGItem::setResourcePath(const QString& resourcePath) { - if (m_resourcePath != resourcePath){ + if (m_resourcePath != resourcePath) { QString oldValue = m_resourcePath; m_resourcePath = resourcePath; QFile file(resourcePath); - if (file.open(QIODevice::ReadOnly)){ + if (file.open(QIODevice::ReadOnly)) { m_image = file.readAll(); } update(); @@ -174,14 +162,11 @@ void SVGItem::setResourcePath(const QString &resourcePath) } } -QByteArray SVGItem::image() const -{ - return m_image; -} +QByteArray SVGItem::image() const { return m_image; } -void SVGItem::setImage(const QByteArray &image) +void SVGItem::setImage(const QByteArray& image) { - if (m_image != image){ + if (m_image != image) { QByteArray oldValue = m_image; m_image = image; update(); @@ -189,23 +174,11 @@ void SVGItem::setImage(const QByteArray &image) } } -QString SVGItem::datasource() const -{ - return m_datasource; -} +QString SVGItem::datasource() const { return m_datasource; } -void SVGItem::setDatasource(const QString &datasource) -{ - m_datasource = datasource; -} +void SVGItem::setDatasource(const QString& datasource) { m_datasource = datasource; } -QString SVGItem::field() const -{ - return m_field; -} +QString SVGItem::field() const { return m_field; } -void SVGItem::setField(const QString &field) -{ - m_field = field; -}; +void SVGItem::setField(const QString& field) { m_field = field; }; } // namespace LimeReport diff --git a/limereport/items/lrsvgitem.h b/limereport/items/lrsvgitem.h index 95b359b..e6a15a9 100644 --- a/limereport/items/lrsvgitem.h +++ b/limereport/items/lrsvgitem.h @@ -1,12 +1,11 @@ #ifndef SVGITEM_H #define SVGITEM_H -#include "lritemdesignintf.h" #include "lreditableimageitemintf.h" +#include "lritemdesignintf.h" -namespace LimeReport{ -class SVGItem: public ItemDesignIntf, public IEditableImageItem -{ +namespace LimeReport { +class SVGItem: public ItemDesignIntf, public IEditableImageItem { Q_OBJECT Q_PROPERTY(QString resourcePath READ resourcePath WRITE setResourcePath) Q_PROPERTY(QByteArray image READ image WRITE setImage) @@ -16,40 +15,42 @@ class SVGItem: public ItemDesignIntf, public IEditableImageItem Q_PROPERTY(QString variable READ variable WRITE setVariable) Q_PROPERTY(bool watermark READ isWatermark WRITE setWatermark) public: - SVGItem(QObject *owner, QGraphicsItem *parent); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + SVGItem(QObject* owner, QGraphicsItem* parent); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QByteArray imageAsByteArray() const; void setImageAsByteArray(QByteArray image); QString fileFilter() const; - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); QWidget* defaultEditor(); QString resourcePath() const; - void setResourcePath(const QString &resourcePath); + void setResourcePath(const QString& resourcePath); QByteArray image() const; - void setImage(const QByteArray &image); + void setImage(const QByteArray& image); QString datasource() const; - void setDatasource(const QString &datasource); + void setDatasource(const QString& datasource); QString field() const; - void setField(const QString &field); + void setField(const QString& field); QString variable() const; - void setVariable(const QString &variable); + void setVariable(const QString& variable); bool isNeedUpdateSize(RenderPass) const; + protected: - BaseDesignIntf *createSameTypeItem(QObject *owner, QGraphicsItem *parent); - void updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight); + BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + void updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight); QByteArray imageFromResource(QString resourcePath); + private: QString m_resourcePath; QByteArray m_image; QString m_datasource; QString m_field; QString m_variable; -public: +public: }; } // namespace LimeReport #endif // SVGITEM_H diff --git a/limereport/items/lrtextitem.cpp b/limereport/items/lrtextitem.cpp index b293495..1134d32 100644 --- a/limereport/items/lrtextitem.cpp +++ b/limereport/items/lrtextitem.cpp @@ -27,60 +27,73 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include -#include -#include -#include - -#include "lrpagedesignintf.h" #include "lrtextitem.h" + +#include "lrdatasourcemanager.h" #include "lrdesignelementsfactory.h" #include "lrglobal.h" -#include "lrdatasourcemanager.h" +#include "lrpagedesignintf.h" +#include "lrreportengine_p.h" #include "lrsimpletagparser.h" #include "lrtextitemeditor.h" -#include "lrreportengine_p.h" -#include -namespace{ +#include +#include +#include +#include +#include + +#include + +namespace { const QString xmlTag = "TextItem"; -LimeReport::BaseDesignIntf * createTextItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::TextItem(owner,parent); +LimeReport::BaseDesignIntf* createTextItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::TextItem(owner, parent); } -bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator(xmlTag, LimeReport::ItemAttribs(QObject::tr("Text Item"),"TextItem"), createTextItem); +bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( + xmlTag, LimeReport::ItemAttribs(QObject::tr("Text Item"), "TextItem"), createTextItem); -} +} // namespace -namespace LimeReport{ +namespace LimeReport { -TextItem::TextItem(QObject *owner, QGraphicsItem *parent) - : ContentItemDesignIntf(xmlTag,owner,parent), m_angle(Angle0), m_trimValue(true), m_allowHTML(false), - m_allowHTMLInFields(false), m_replaceCarriageReturns(false), m_followTo(""), m_follower(0), m_textIndent(0), - m_textLayoutDirection(Qt::LayoutDirectionAuto), m_hideIfEmpty(false), m_fontLetterSpacing(0) +TextItem::TextItem(QObject* owner, QGraphicsItem* parent): + ContentItemDesignIntf(xmlTag, owner, parent), + m_angle(Angle0), + m_trimValue(true), + m_allowHTML(false), + m_allowHTMLInFields(false), + m_replaceCarriageReturns(false), + m_followTo(""), + m_follower(0), + m_textIndent(0), + m_textLayoutDirection(Qt::LayoutDirectionAuto), + m_hideIfEmpty(false), + m_fontLetterSpacing(0) { PageItemDesignIntf* pageItem = dynamic_cast(parent); BaseDesignIntf* parentItem = dynamic_cast(parent); - while (!pageItem && parentItem){ + while (!pageItem && parentItem) { parentItem = dynamic_cast(parentItem->parentItem()); pageItem = dynamic_cast(parentItem); } - if (pageItem){ + if (pageItem) { QFont defaultFont = pageItem->font(); setFont(defaultFont); } Init(); } -TextItem::~TextItem(){} +TextItem::~TextItem() { } -void TextItem::preparePopUpMenu(QMenu &menu) +void TextItem::preparePopUpMenu(QMenu& menu) { - QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"),tr("Edit")); - menu.insertAction(menu.actions().at(0),editAction); + QAction* editAction = menu.addAction(QIcon(":/report/images/edit_pecil2.png"), tr("Edit")); + menu.insertAction(menu.actions().at(0), editAction); menu.insertSeparator(menu.actions().at(1)); menu.addSeparator(); @@ -112,159 +125,161 @@ void TextItem::preparePopUpMenu(QMenu &menu) action = menu.addAction(tr("Hide if empty")); action->setCheckable(true); action->setChecked(hideIfEmpty()); - } -void TextItem::processPopUpAction(QAction *action) +void TextItem::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Edit")) == 0){ + if (action->text().compare(tr("Edit")) == 0) { this->showEditorDialog(); } - if (page()){ - if (action->text().compare(tr("Auto height")) == 0){ - page()->setPropertyToSelectedItems("autoHeight",action->isChecked()); + if (page()) { + if (action->text().compare(tr("Auto height")) == 0) { + page()->setPropertyToSelectedItems("autoHeight", action->isChecked()); } - if (action->text().compare(tr("Allow HTML")) == 0){ - page()->setPropertyToSelectedItems("allowHTML",action->isChecked()); + if (action->text().compare(tr("Allow HTML")) == 0) { + page()->setPropertyToSelectedItems("allowHTML", action->isChecked()); } - if (action->text().compare(tr("Allow HTML in fields")) == 0){ - page()->setPropertyToSelectedItems("allowHTMLInFields",action->isChecked()); + if (action->text().compare(tr("Allow HTML in fields")) == 0) { + page()->setPropertyToSelectedItems("allowHTMLInFields", action->isChecked()); } - if (action->text().compare(tr("Stretch to max height")) == 0){ - page()->setPropertyToSelectedItems("stretchToMaxHeight",action->isChecked()); + if (action->text().compare(tr("Stretch to max height")) == 0) { + page()->setPropertyToSelectedItems("stretchToMaxHeight", action->isChecked()); } } - if (action->text().compare(tr("Transparent")) == 0){ - if (action->isChecked()){ - setProperty("backgroundMode",TransparentMode); + if (action->text().compare(tr("Transparent")) == 0) { + if (action->isChecked()) { + setProperty("backgroundMode", TransparentMode); } else { - setProperty("backgroundMode",OpaqueMode); + setProperty("backgroundMode", OpaqueMode); } } - if (action->text().compare(tr("Watermark")) == 0){ - page()->setPropertyToSelectedItems("watermark",action->isChecked()); + if (action->text().compare(tr("Watermark")) == 0) { + page()->setPropertyToSelectedItems("watermark", action->isChecked()); } - if (action->text().compare(tr("Hide if empty")) == 0){ - page()->setPropertyToSelectedItems("hideIfEmpty",action->isChecked()); + if (action->text().compare(tr("Hide if empty")) == 0) { + page()->setPropertyToSelectedItems("hideIfEmpty", action->isChecked()); } ContentItemDesignIntf::processPopUpAction(action); } -void TextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* style, QWidget* widget) { +void TextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* style, QWidget* widget) +{ Q_UNUSED(widget); Q_UNUSED(style); - TextPtr text = textDocument(); painter->save(); setupPainter(painter); - prepareRect(painter,style,widget); + prepareRect(painter, style, widget); - QSizeF tmpSize = rect().size()-text->size(); + QSizeF tmpSize = rect().size() - text->size(); - if (!painter->clipRegion().isEmpty()){ - QRegion clipReg=painter->clipRegion().xored(painter->clipRegion().subtracted(rect().toRect())); + if (!painter->clipRegion().isEmpty()) { + QRegion clipReg + = painter->clipRegion().xored(painter->clipRegion().subtracted(rect().toRect())); painter->setClipRegion(clipReg); } else { painter->setClipRect(rect()); } qreal hOffset = 0, vOffset = 0; - switch (m_angle){ - case Angle0: - hOffset = marginSize(); - if ((tmpSize.height() > 0) && (m_alignment & Qt::AlignVCenter)){ - vOffset = tmpSize.height() / 2; - } - if ((tmpSize.height() > 0) && (m_alignment & Qt::AlignBottom)) // allow html - vOffset = tmpSize.height(); - painter->translate(hOffset,vOffset); + switch (m_angle) { + case Angle0: + hOffset = marginSize(); + if ((tmpSize.height() > 0) && (m_alignment & Qt::AlignVCenter)) { + vOffset = tmpSize.height() / 2; + } + if ((tmpSize.height() > 0) && (m_alignment & Qt::AlignBottom)) // allow html + vOffset = tmpSize.height(); + painter->translate(hOffset, vOffset); break; - case Angle90: - hOffset = width() - marginSize(); - vOffset = marginSize(); - if (m_alignment & Qt::AlignVCenter){ - hOffset = (width() - text->size().height()) / 2 + text->size().height(); - } + case Angle90: + hOffset = width() - marginSize(); + vOffset = marginSize(); + if (m_alignment & Qt::AlignVCenter) { + hOffset = (width() - text->size().height()) / 2 + text->size().height(); + } - if (m_alignment & Qt::AlignBottom){ - hOffset = (text->size().height()); - } - painter->translate(hOffset,vOffset); - painter->rotate(90); + if (m_alignment & Qt::AlignBottom) { + hOffset = (text->size().height()); + } + painter->translate(hOffset, vOffset); + painter->rotate(90); break; - case Angle180: - hOffset = width() - marginSize(); - vOffset = height() - marginSize(); - if ((tmpSize.width()>0) && (m_alignment & Qt::AlignVCenter)){ - vOffset = tmpSize.height() / 2+ text->size().height(); - } - if ((tmpSize.height()>0) && (m_alignment & Qt::AlignBottom)){ - vOffset = (text->size().height()); - } - painter->translate(hOffset,vOffset); - painter->rotate(180); + case Angle180: + hOffset = width() - marginSize(); + vOffset = height() - marginSize(); + if ((tmpSize.width() > 0) && (m_alignment & Qt::AlignVCenter)) { + vOffset = tmpSize.height() / 2 + text->size().height(); + } + if ((tmpSize.height() > 0) && (m_alignment & Qt::AlignBottom)) { + vOffset = (text->size().height()); + } + painter->translate(hOffset, vOffset); + painter->rotate(180); break; - case Angle270: - hOffset = marginSize(); - vOffset = height()-marginSize(); - if (m_alignment & Qt::AlignVCenter){ - hOffset = (width() - text->size().height())/2; - } + case Angle270: + hOffset = marginSize(); + vOffset = height() - marginSize(); + if (m_alignment & Qt::AlignVCenter) { + hOffset = (width() - text->size().height()) / 2; + } - if (m_alignment & Qt::AlignBottom){ - hOffset = (width() - text->size().height()); - } - painter->translate(hOffset,vOffset); - painter->rotate(270); + if (m_alignment & Qt::AlignBottom) { + hOffset = (width() - text->size().height()); + } + painter->translate(hOffset, vOffset); + painter->rotate(270); break; - case Angle45: - painter->translate(width()/2,0); - painter->rotate(45); - text->setTextWidth(sqrt(2*(pow(width()/2,2)))); + case Angle45: + painter->translate(width() / 2, 0); + painter->rotate(45); + text->setTextWidth(sqrt(2 * (pow(width() / 2, 2)))); break; - case Angle315: - painter->translate(0,height()/2); - painter->rotate(315); - text->setTextWidth(sqrt(2*(pow(height()/2,2)))); + case Angle315: + painter->translate(0, height() / 2); + painter->rotate(315); + text->setTextWidth(sqrt(2 * (pow(height() / 2, 2)))); break; } int lineHeight = painter->fontMetrics().height(); qreal curpos = 0; - if (m_underlines){ + if (m_underlines) { QPen pen = painter->pen(); pen.setWidth(m_underlineLineSize); painter->setPen(pen); } - painter->setOpacity(qreal(foregroundOpacity())/100); + painter->setOpacity(qreal(foregroundOpacity()) / 100); QAbstractTextDocumentLayout::PaintContext ctx; ctx.palette.setColor(QPalette::Text, fontColor()); - for(QTextBlock it = text->begin(); it != text->end(); it=it.next()){ - it.blockFormat().setLineHeight(m_lineSpacing,QTextBlockFormat::LineDistanceHeight); - for (int i=0;ilineCount();i++){ + for (QTextBlock it = text->begin(); it != text->end(); it = it.next()) { + it.blockFormat().setLineHeight(m_lineSpacing, QTextBlockFormat::LineDistanceHeight); + for (int i = 0; i < it.layout()->lineCount(); i++) { QTextLine line = it.layout()->lineAt(i); - if (m_underlines){ - painter->drawLine(QPointF(0,line.rect().bottomLeft().y()),QPoint(rect().width(),line.rect().bottomRight().y())); - lineHeight = line.height()+m_lineSpacing; + if (m_underlines) { + painter->drawLine(QPointF(0, line.rect().bottomLeft().y()), + QPoint(rect().width(), line.rect().bottomRight().y())); + lineHeight = line.height() + m_lineSpacing; curpos = line.rect().bottom(); } } } - text->documentLayout()->draw(painter,ctx); + text->documentLayout()->draw(painter, ctx); - if (m_underlines){ - if (lineHeight<0) lineHeight = painter->fontMetrics().height(); - for (curpos+=lineHeight; curposdrawLine(QPointF(0,curpos),QPoint(rect().width(),curpos)); + if (m_underlines) { + if (lineHeight < 0) + lineHeight = painter->fontMetrics().height(); + for (curpos += lineHeight; curpos < rect().height(); curpos += lineHeight) { + painter->drawLine(QPointF(0, curpos), QPoint(rect().width(), curpos)); } } @@ -275,7 +290,7 @@ void TextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* style, Q void TextItem::Init() { m_autoWidth = NoneAutoWidth; - m_alignment = Qt::AlignLeft|Qt::AlignTop; + m_alignment = Qt::AlignLeft | Qt::AlignTop; m_autoHeight = false; m_textSize = QSizeF(); m_firstLineSize = 0; @@ -287,25 +302,23 @@ void TextItem::Init() m_valueType = Default; } -void TextItem::setContent(const QString &value) +void TextItem::setContent(const QString& value) { - if (m_strText.compare(value)!=0){ + if (m_strText.compare(value) != 0) { QString oldValue = m_strText; m_strText = value; - if (!isLoading()){ + if (!isLoading()) { if (autoHeight() || autoWidth() || hasFollower()) initTextSizes(); update(rect()); - notify("content",oldValue,value); + notify("content", oldValue, value); } } } -QString TextItem::content() const{ - return m_strText; -} +QString TextItem::content() const { return m_strText; } void TextItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { @@ -313,43 +326,45 @@ void TextItem::updateItemSize(DataSourceManager* dataManager, RenderPass pass, i if (isNeedExpandContent()) expandContent(dataManager, pass); - if (!isLoading() && (autoHeight() || autoWidth() || hasFollower()) ) + if (!isLoading() && (autoHeight() || autoWidth() || hasFollower())) initTextSizes(); - if (m_textSize.width()>width() && ((m_autoWidth==MaxWordLength)||(m_autoWidth==MaxStringLength))){ - setWidth(m_textSize.width() + marginSize()*2); + if (m_textSize.width() > width() + && ((m_autoWidth == MaxWordLength) || (m_autoWidth == MaxStringLength))) { + setWidth(m_textSize.width() + marginSize() * 2); } - if (m_textSize.height()>height()) { + if (m_textSize.height() > height()) { if (m_autoHeight) - setHeight(m_textSize.height()+borderLineSize()*2); - else if (hasFollower() && !content().isEmpty()){ - follower()->setContent(getTextPart(0,height())); - setContent(getTextPart(height(),0)); + setHeight(m_textSize.height() + borderLineSize() * 2); + else if (hasFollower() && !content().isEmpty()) { + follower()->setContent(getTextPart(0, height())); + setContent(getTextPart(height(), 0)); } } BaseDesignIntf::updateItemSize(dataManager, pass, maxHeight); - if (isEmpty() && hideIfEmpty()) setVisible(false); + if (isEmpty() && hideIfEmpty()) + setVisible(false); } void TextItem::updateLayout() { -// m_layout.setFont(transformToSceneFont(font())); -// m_layout.setText(content()); -// qreal linePos = 0; -// m_layout.beginLayout(); -// while(true){ -// QTextLine line = m_layout.createLine(); -// if (!line.isValid()) break; -// line.setLineWidth(width()-marginSize()*2); -// line.setPosition(QPoint(marginSize(),linePos)); -// linePos+=line.height(); -// } -// m_layout.endLayout(); + // m_layout.setFont(transformToSceneFont(font())); + // m_layout.setText(content()); + // qreal linePos = 0; + // m_layout.beginLayout(); + // while(true){ + // QTextLine line = m_layout.createLine(); + // if (!line.isValid()) break; + // line.setLineWidth(width()-marginSize()*2); + // line.setPosition(QPoint(marginSize(),linePos)); + // linePos+=line.height(); + // } + // m_layout.endLayout(); } bool TextItem::isNeedExpandContent() const -{ +{ #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx("$*\\{[^{]*\\}"); #else @@ -361,79 +376,72 @@ bool TextItem::isNeedExpandContent() const return content().contains(rx) || isContentBackedUp(); } -QString TextItem::replaceBR(QString text) const -{ - return text.replace("
","\n"); -} +QString TextItem::replaceBR(QString text) const { return text.replace("
", "\n"); } QString TextItem::replaceReturns(QString text) const { - QString result = text.replace("\r\n","
"); - result = result.replace("\n","
"); + QString result = text.replace("\r\n", "
"); + result = result.replace("\n", "
"); return result; } -void TextItem::setTextFont(TextPtr text, const QFont& value) const { +void TextItem::setTextFont(TextPtr text, const QFont& value) const +{ text->setDefaultFont(value); - if ((m_angle==Angle0)||(m_angle==Angle180)){ - text->setTextWidth(rect().width()-marginSize()*2); + if ((m_angle == Angle0) || (m_angle == Angle180)) { + text->setTextWidth(rect().width() - marginSize() * 2); } else { - text->setTextWidth(rect().height()-marginSize()*2); + text->setTextWidth(rect().height() - marginSize() * 2); } } -void TextItem::adaptFontSize(TextPtr text) const{ +void TextItem::adaptFontSize(TextPtr text) const +{ QFont _font = transformToSceneFont(font()); - do{ -// qApp->processEvents(); - setTextFont(text,_font); - if (_font.pixelSize()>2) - _font.setPixelSize(_font.pixelSize()-1); - else break; - } while(text->size().height()>this->height() || text->size().width()>(this->width()) - marginSize() * 2); + do { + // qApp->processEvents(); + setTextFont(text, _font); + if (_font.pixelSize() > 2) + _font.setPixelSize(_font.pixelSize() - 1); + else + break; + } while (text->size().height() > this->height() + || text->size().width() > (this->width()) - marginSize() * 2); } -int TextItem::underlineLineSize() const -{ - return m_underlineLineSize; -} +int TextItem::underlineLineSize() const { return m_underlineLineSize; } void TextItem::setUnderlineLineSize(int value) { int oldValue = m_underlineLineSize; m_underlineLineSize = value; update(); - notify("underlineLineSize",oldValue,value); + notify("underlineLineSize", oldValue, value); } -int TextItem::lineSpacing() const -{ - return m_lineSpacing; -} +int TextItem::lineSpacing() const { return m_lineSpacing; } void TextItem::setLineSpacing(int value) { int oldValue = m_lineSpacing; m_lineSpacing = value; -// if (autoHeight()) -// initTextSizes(); + // if (autoHeight()) + // initTextSizes(); update(); - notify("lineSpacing",oldValue,value); + notify("lineSpacing", oldValue, value); } - void TextItem::initTextSizes() const { TextPtr text = textDocument(); - m_textSize= text->size(); + m_textSize = text->size(); if (text->begin().isValid() && text->begin().layout()->lineAt(0).isValid()) m_firstLineSize = text->begin().layout()->lineAt(0).height(); } -QString TextItem::formatDateTime(const QDateTime &value) +QString TextItem::formatDateTime(const QDateTime& value) { - if (m_format.isEmpty()) - { + if (m_format.isEmpty()) { return value.toString(); } @@ -444,8 +452,7 @@ QString TextItem::formatNumber(const double value) { QString str = QString::number(value); - if (m_format.contains("%")) - { + if (m_format.contains("%")) { #if QT_VERSION < 0x050500 str.sprintf(m_format.toStdString().c_str(), value); #else @@ -468,44 +475,42 @@ QString TextItem::formatFieldValue() if (m_valueType != Default) { switch (m_valueType) { - case DateTime: - { - QDateTime dt = QDateTime::fromString(value.toString(), Qt::ISODate); - value = (dt.isValid() ? QVariant(dt) : m_varValue); - break; - } - case Double: - { - bool bOk = false; - double dbl = value.toDouble(&bOk); - value = (bOk ? QVariant(dbl) : m_varValue); - } - default: break; + case DateTime: { + QDateTime dt = QDateTime::fromString(value.toString(), Qt::ISODate); + value = (dt.isValid() ? QVariant(dt) : m_varValue); + break; + } + case Double: { + bool bOk = false; + double dbl = value.toDouble(&bOk); + value = (bOk ? QVariant(dbl) : m_varValue); + } + default: + break; } } -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) switch (value.type()) { - case QVariant::Date: - case QVariant::DateTime: - return formatDateTime(value.toDateTime()); - case QVariant::Double: - return formatNumber(value.toDouble()); - default: - return value.toString(); + case QVariant::Date: + case QVariant::DateTime: + return formatDateTime(value.toDateTime()); + case QVariant::Double: + return formatNumber(value.toDouble()); + default: + return value.toString(); } #else switch (value.typeId()) { - case QMetaType::QDate: - case QMetaType::QDateTime: - return formatDateTime(value.toDateTime()); - case QMetaType::Double: - return formatNumber(value.toDouble()); - default: - return value.toString(); + case QMetaType::QDate: + case QMetaType::QDateTime: + return formatDateTime(value.toDateTime()); + case QMetaType::Double: + return formatNumber(value.toDouble()); + default: + return value.toString(); } #endif - } TextItem::TextPtr TextItem::textDocument() const @@ -514,7 +519,7 @@ TextItem::TextPtr TextItem::textDocument() const QString content = m_trimValue ? m_strText.trimmed() : m_strText; if (allowHTML()) - if (isReplaceCarriageReturns()){ + if (isReplaceCarriageReturns()) { text->setHtml(replaceReturns(content)); } else { text->setHtml(content); @@ -526,53 +531,48 @@ TextItem::TextPtr TextItem::textDocument() const to.setAlignment(m_alignment); to.setTextDirection(m_textLayoutDirection); - if (m_autoWidth!=MaxStringLength) + if (m_autoWidth != MaxStringLength) if (m_adaptFontToSize && (!(m_autoHeight || m_autoWidth))) to.setWrapMode(QTextOption::WordWrap); else to.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); - else to.setWrapMode(QTextOption::NoWrap); + else + to.setWrapMode(QTextOption::NoWrap); text->setDocumentMargin(0); text->setDefaultTextOption(to); QFont _font = transformToSceneFont(font()); - if (m_adaptFontToSize && (!(m_autoHeight || m_autoWidth))){ + if (m_adaptFontToSize && (!(m_autoHeight || m_autoWidth))) { adaptFontSize(text); } else { - setTextFont(text,_font); + setTextFont(text, _font); } if (follower()) text->documentLayout(); - if (m_lineSpacing != 1 || m_textIndent !=0 ){ + if (m_lineSpacing != 1 || m_textIndent != 0) { - for ( QTextBlock block = text->begin(); block.isValid(); block = block.next()) - { + for (QTextBlock block = text->begin(); block.isValid(); block = block.next()) { QTextCursor tc = QTextCursor(block); QTextBlockFormat fmt = block.blockFormat(); fmt.setTextIndent(m_textIndent); if (fmt.lineHeight() != m_lineSpacing) { - fmt.setLineHeight(m_lineSpacing,QTextBlockFormat::LineDistanceHeight); + fmt.setLineHeight(m_lineSpacing, QTextBlockFormat::LineDistanceHeight); } - tc.setBlockFormat( fmt ); + tc.setBlockFormat(fmt); } - } return text; - } -int TextItem::fontLetterSpacing() const -{ - return m_fontLetterSpacing; -} +int TextItem::fontLetterSpacing() const { return m_fontLetterSpacing; } void TextItem::setFontLetterSpacing(int value) { - if (m_fontLetterSpacing != value){ + if (m_fontLetterSpacing != value) { int oldValue = m_fontLetterSpacing; m_fontLetterSpacing = value; QFont curFont = font(); @@ -582,42 +582,32 @@ void TextItem::setFontLetterSpacing(int value) } } -bool TextItem::hideIfEmpty() const -{ - return m_hideIfEmpty; -} +bool TextItem::hideIfEmpty() const { return m_hideIfEmpty; } void TextItem::setHideIfEmpty(bool hideEmpty) { - if (m_hideIfEmpty != hideEmpty){ + if (m_hideIfEmpty != hideEmpty) { m_hideIfEmpty = hideEmpty; - notify("hideIfEmpty",!m_hideIfEmpty, m_hideIfEmpty); + notify("hideIfEmpty", !m_hideIfEmpty, m_hideIfEmpty); } } -bool TextItem::isReplaceCarriageReturns() const -{ - return m_replaceCarriageReturns; -} +bool TextItem::isReplaceCarriageReturns() const { return m_replaceCarriageReturns; } void TextItem::setReplaceCarriageReturns(bool replaceCarriageReturns) { - if (replaceCarriageReturns != m_replaceCarriageReturns){ + if (replaceCarriageReturns != m_replaceCarriageReturns) { m_replaceCarriageReturns = replaceCarriageReturns; update(); - notify("replaceCRwithBR",!replaceCarriageReturns, replaceCarriageReturns); + notify("replaceCRwithBR", !replaceCarriageReturns, replaceCarriageReturns); } - } -qreal TextItem::textIndent() const -{ - return m_textIndent; -} +qreal TextItem::textIndent() const { return m_textIndent; } -void TextItem::setTextIndent(const qreal &textIndent) +void TextItem::setTextIndent(const qreal& textIndent) { - if (m_textIndent != textIndent){ + if (m_textIndent != textIndent) { qreal oldValue = m_textIndent; m_textIndent = textIndent; update(); @@ -625,94 +615,74 @@ void TextItem::setTextIndent(const qreal &textIndent) } } -Qt::LayoutDirection TextItem::textLayoutDirection() const -{ - return m_textLayoutDirection; -} +Qt::LayoutDirection TextItem::textLayoutDirection() const { return m_textLayoutDirection; } -void TextItem::setTextLayoutDirection(const Qt::LayoutDirection &textLayoutDirection) +void TextItem::setTextLayoutDirection(const Qt::LayoutDirection& textLayoutDirection) { - if (m_textLayoutDirection != textLayoutDirection){ + if (m_textLayoutDirection != textLayoutDirection) { int oldValue = int(m_textLayoutDirection); m_textLayoutDirection = textLayoutDirection; update(); - notify("textLayoutDirection",oldValue,int(textLayoutDirection)); + notify("textLayoutDirection", oldValue, int(textLayoutDirection)); } } void TextItem::setWatermark(bool watermark) { - if (watermark){ + if (watermark) { setBackgroundMode(TransparentMode); } BaseDesignIntf::setWatermark(watermark); - } +QString TextItem::followTo() const { return m_followTo; } -QString TextItem::followTo() const +void TextItem::setFollowTo(const QString& followTo) { - return m_followTo; -} - -void TextItem::setFollowTo(const QString &followTo) -{ - if (m_followTo != followTo){ + if (m_followTo != followTo) { QString oldValue = m_followTo; m_followTo = followTo; - if (!isLoading()){ + if (!isLoading()) { TextItem* fi = scene()->findChild(oldValue); - if (fi) fi->clearFollower(); + if (fi) + fi->clearFollower(); fi = scene()->findChild(followTo); - if (fi && fi != this){ - if (initFollower(followTo)){ - notify("followTo",oldValue,followTo); + if (fi && fi != this) { + if (initFollower(followTo)) { + notify("followTo", oldValue, followTo); } else { m_followTo = ""; - QMessageBox::critical( - 0, - tr("Error"), - tr("TextItem \" %1 \" already has folower \" %2 \" ") - .arg(fi->objectName()) - .arg(fi->follower()->objectName()) - ); - notify("followTo",followTo,""); + QMessageBox::critical(0, tr("Error"), + tr("TextItem \" %1 \" already has folower \" %2 \" ") + .arg(fi->objectName()) + .arg(fi->follower()->objectName())); + notify("followTo", followTo, ""); } - } else if (m_followTo != ""){ - QMessageBox::critical( - 0, - tr("Error"), - tr("TextItem \" %1 \" not found!") - .arg(m_followTo) - ); - notify("followTo",followTo,""); + } else if (m_followTo != "") { + QMessageBox::critical(0, tr("Error"), + tr("TextItem \" %1 \" not found!").arg(m_followTo)); + notify("followTo", followTo, ""); } } } } -void TextItem::setFollower(TextItem *follower) +void TextItem::setFollower(TextItem* follower) { - if (!m_follower){ + if (!m_follower) { m_follower = follower; } } -void TextItem::clearFollower() -{ - m_follower = 0; -} +void TextItem::clearFollower() { m_follower = 0; } -bool TextItem::hasFollower() const -{ - return m_follower != 0; -} +bool TextItem::hasFollower() const { return m_follower != 0; } bool TextItem::initFollower(QString follower) { TextItem* fi = scene()->findChild(follower); - if (fi){ - if (!fi->hasFollower()){ + if (fi) { + if (!fi->hasFollower()) { fi->setFollower(this); return true; } @@ -722,134 +692,111 @@ bool TextItem::initFollower(QString follower) void TextItem::pageObjectHasBeenLoaded() { - if (!m_followTo.isEmpty()){ + if (!m_followTo.isEmpty()) { initFollower(m_followTo); } } -TextItem::ValueType TextItem::valueType() const -{ - return m_valueType; -} +TextItem::ValueType TextItem::valueType() const { return m_valueType; } -void TextItem::setValueType(const ValueType valueType) -{ - m_valueType = valueType; -} +void TextItem::setValueType(const ValueType valueType) { m_valueType = valueType; } -QString TextItem::format() const -{ - return m_format; -} +QString TextItem::format() const { return m_format; } -void TextItem::setFormat(const QString &format) -{ - m_format = format; -} +void TextItem::setFormat(const QString& format) { m_format = format; } -bool TextItem::allowHTMLInFields() const -{ - return m_allowHTMLInFields; -} +bool TextItem::allowHTMLInFields() const { return m_allowHTMLInFields; } void TextItem::setAllowHTMLInFields(bool allowHTMLInFields) { - if (m_allowHTMLInFields != allowHTMLInFields){ + if (m_allowHTMLInFields != allowHTMLInFields) { m_allowHTMLInFields = allowHTMLInFields; - notify("allowHTMLInFields",!m_allowHTMLInFields,allowHTMLInFields); + notify("allowHTMLInFields", !m_allowHTMLInFields, allowHTMLInFields); update(); } } -bool TextItem::allowHTML() const -{ - return m_allowHTML; -} +bool TextItem::allowHTML() const { return m_allowHTML; } void TextItem::setAllowHTML(bool allowHTML) { - if (m_allowHTML!=allowHTML){ + if (m_allowHTML != allowHTML) { m_allowHTML = allowHTML; -// if (m_text){ -// if (allowHTML) -// m_text->setHtml(m_strText); -// else -// m_text->setPlainText(m_strText); -// update(); -// } + // if (m_text){ + // if (allowHTML) + // m_text->setHtml(m_strText); + // else + // m_text->setPlainText(m_strText); + // update(); + // } update(); - notify("allowHTML",!m_allowHTML,allowHTML); + notify("allowHTML", !m_allowHTML, allowHTML); } } -bool TextItem::trimValue() const -{ - return m_trimValue; -} +bool TextItem::trimValue() const { return m_trimValue; } void TextItem::setTrimValue(bool value) { bool oldValue = m_trimValue; m_trimValue = value; update(); - notify("trimValue",oldValue,value); + notify("trimValue", oldValue, value); } - -void TextItem::geometryChangedEvent(QRectF , QRectF) -{} +void TextItem::geometryChangedEvent(QRectF, QRectF) { } bool TextItem::isNeedUpdateSize(RenderPass pass) const { Q_UNUSED(pass) - if ((autoHeight() || autoWidth()) || hasFollower()){ + if ((autoHeight() || autoWidth()) || hasFollower()) { initTextSizes(); } - bool res = (m_textSize.height()>geometry().height()&&autoHeight()) || - (m_textSize.width()>geometry().width()&&autoWidth()) || - m_follower || - isNeedExpandContent(); + bool res = (m_textSize.height() > geometry().height() && autoHeight()) + || (m_textSize.width() > geometry().width() && autoWidth()) || m_follower + || isNeedExpandContent(); return res; } void TextItem::setAlignment(Qt::Alignment value) { - if (m_alignment!=value){ + if (m_alignment != value) { Qt::Alignment oldValue = m_alignment; - m_alignment=value; - //m_layout.setTextOption(QTextOption(m_alignment)); - if (!isLoading()){ + m_alignment = value; + // m_layout.setTextOption(QTextOption(m_alignment)); + if (!isLoading()) { update(rect()); - notify("alignment",QVariant(oldValue),QVariant(value)); + notify("alignment", QVariant(oldValue), QVariant(value)); } } } void TextItem::expandContent(DataSourceManager* dataManager, RenderPass pass) { - QString context=content(); + QString context = content(); foreach (QString variableName, dataManager->variableNamesByRenderPass(SecondPass)) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(QString(Const::NAMED_VARIABLE_RX).arg(variableName)); #else QRegularExpression rx = getNamedVariableRegEx(variableName); #endif - if (context.contains(rx) && pass == FirstPass){ + if (context.contains(rx) && pass == FirstPass) { backupContent(); break; } } - ExpandType expandType = (allowHTML() && !allowHTMLInFields()) ? ReplaceHTMLSymbols : NoEscapeSymbols; - switch(pass){ + ExpandType expandType + = (allowHTML() && !allowHTMLInFields()) ? ReplaceHTMLSymbols : NoEscapeSymbols; + switch (pass) { case FirstPass: - if (!fillInSecondPass()){ - context=expandUserVariables(context, pass, expandType, dataManager); - context=expandScripts(context, dataManager); - context=expandDataFields(context, expandType, dataManager); + if (!fillInSecondPass()) { + context = expandUserVariables(context, pass, expandType, dataManager); + context = expandScripts(context, dataManager); + context = expandDataFields(context, expandType, dataManager); } else { - context=expandDataFields(context, expandType, dataManager); + context = expandDataFields(context, expandType, dataManager); } break; case SecondPass: @@ -857,44 +804,43 @@ void TextItem::expandContent(DataSourceManager* dataManager, RenderPass pass) restoreContent(); context = content(); } - context=expandUserVariables(context, pass, expandType, dataManager); - context=expandScripts(context, dataManager); + context = expandUserVariables(context, pass, expandType, dataManager); + context = expandScripts(context, dataManager); } - if (expandType == NoEscapeSymbols && !m_varValue.isNull() &&m_valueType != Default) { + if (expandType == NoEscapeSymbols && !m_varValue.isNull() && m_valueType != Default) { setContent(formatFieldValue()); } else { setContent(context); } - } void TextItem::setAutoHeight(bool value) { - if (m_autoHeight!=value){ + if (m_autoHeight != value) { bool oldValue = m_autoHeight; - m_autoHeight=value; - notify("autoHeight",oldValue,value); + m_autoHeight = value; + notify("autoHeight", oldValue, value); } } void TextItem::setAutoWidth(TextItem::AutoWidth value) { - if (m_autoWidth!=value){ + if (m_autoWidth != value) { TextItem::AutoWidth oldValue = m_autoWidth; - m_autoWidth=value; - notify("autoWidth",oldValue,value); + m_autoWidth = value; + notify("autoWidth", oldValue, value); } } void TextItem::setAdaptFontToSize(bool value) { - if (m_adaptFontToSize!=value){ + if (m_adaptFontToSize != value) { bool oldValue = m_adaptFontToSize; - m_adaptFontToSize=value; -// initText(); + m_adaptFontToSize = value; + // initText(); invalidateRect(rect()); - notify("updateFontToSize",oldValue,value); + notify("updateFontToSize", oldValue, value); } } @@ -904,23 +850,29 @@ bool TextItem::canBeSplitted(int height) const return height > m_firstLineSize; } -QString TextItem::extractText(QTextBlock& curBlock, int height){ +QString TextItem::extractText(QTextBlock& curBlock, int height) +{ int curLine = 0; int linesHeight = 0; QString resultText; - for (;curBlock != curBlock.document()->end() || curLine<=curBlock.lineCount(); curBlock = curBlock.next(), curLine = 0, resultText += '\n' ){ - linesHeight+=curBlock.blockFormat().topMargin(); - for (;curLine < curBlock.layout()->lineCount(); curLine++){ + for (; curBlock != curBlock.document()->end() || curLine <= curBlock.lineCount(); + curBlock = curBlock.next(), curLine = 0, resultText += '\n') { + linesHeight += curBlock.blockFormat().topMargin(); + for (; curLine < curBlock.layout()->lineCount(); curLine++) { linesHeight += curBlock.layout()->lineAt(curLine).height() + lineSpacing(); - if (height > 0 && linesHeight > (height-borderLineSize() * 2)) {goto loop_exit;} + if (height > 0 && linesHeight > (height - borderLineSize() * 2)) { + goto loop_exit; + } resultText += curBlock.text().mid(curBlock.layout()->lineAt(curLine).textStart(), - curBlock.layout()->lineAt(curLine).textLength()); + curBlock.layout()->lineAt(curLine).textLength()); } } - loop_exit: return resultText; +loop_exit: + return resultText; } -QString TextItem::getTextPart(int height, int skipHeight){ +QString TextItem::getTextPart(int height, int skipHeight) +{ QString resultText = ""; TextPtr text = textDocument(); @@ -929,7 +881,7 @@ QString TextItem::getTextPart(int height, int skipHeight){ QTextCursor cursor(text.data()); cursor.movePosition(QTextCursor::Start); - if (skipHeight > 0){ + if (skipHeight > 0) { resultText = extractText(curBlock, skipHeight); cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, resultText.length()); } @@ -937,7 +889,7 @@ QString TextItem::getTextPart(int height, int skipHeight){ resultText = extractText(curBlock, height); cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, resultText.length()); - if (allowHTML()){ + if (allowHTML()) { resultText = cursor.selection().toHtml(); resultText.remove(""); resultText.remove(""); @@ -950,13 +902,13 @@ QString TextItem::getTextPart(int height, int skipHeight){ void TextItem::restoreLinksEvent() { - if (!followTo().isEmpty()){ + if (!followTo().isEmpty()) { BaseDesignIntf* pi = dynamic_cast(parentItem()); - if (pi){ + if (pi) { foreach (BaseDesignIntf* bi, pi->childBaseItems()) { - if (bi->patternName().compare(followTo())==0){ + if (bi->patternName().compare(followTo()) == 0) { TextItem* ti = dynamic_cast(bi); - if (ti){ + if (ti) { ti->setFollower(this); } } @@ -965,32 +917,32 @@ void TextItem::restoreLinksEvent() } } -BaseDesignIntf *TextItem::cloneUpperPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* TextItem::cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent) { - TextItem* upperPart = dynamic_cast(cloneItem(itemMode(),owner,parent)); - upperPart->setContent(getTextPart(height,0)); + TextItem* upperPart = dynamic_cast(cloneItem(itemMode(), owner, parent)); + upperPart->setContent(getTextPart(height, 0)); upperPart->initTextSizes(); - upperPart->setHeight(upperPart->textSize().height()+borderLineSize()*2); + upperPart->setHeight(upperPart->textSize().height() + borderLineSize() * 2); return upperPart; } -BaseDesignIntf *TextItem::cloneBottomPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* TextItem::cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent) { - TextItem* bottomPart = dynamic_cast(cloneItem(itemMode(),owner,parent)); - bottomPart->setContent(getTextPart(0,height)); + TextItem* bottomPart = dynamic_cast(cloneItem(itemMode(), owner, parent)); + bottomPart->setContent(getTextPart(0, height)); bottomPart->initTextSizes(); - bottomPart->setHeight(bottomPart->textSize().height()+borderLineSize()*2); + bottomPart->setHeight(bottomPart->textSize().height() + borderLineSize() * 2); return bottomPart; } -BaseDesignIntf *TextItem::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* TextItem::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new TextItem(owner,parent); + return new TextItem(owner, parent); } -BaseDesignIntf *TextItem::cloneEmpty(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* TextItem::cloneEmpty(int height, QObject* owner, QGraphicsItem* parent) { - TextItem* empty=dynamic_cast(cloneItem(itemMode(),owner,parent)); + TextItem* empty = dynamic_cast(cloneItem(itemMode(), owner, parent)); empty->setContent(""); empty->setHeight(height); return empty; @@ -999,112 +951,107 @@ BaseDesignIntf *TextItem::cloneEmpty(int height, QObject *owner, QGraphicsItem * void TextItem::objectLoadFinished() { ItemDesignIntf::objectLoadFinished(); -// if (itemMode() == DesignMode || !isNeedExpandContent()){ -// if (autoHeight() && autoWidth()) -// initTextSizes(); -// } + // if (itemMode() == DesignMode || !isNeedExpandContent()){ + // if (autoHeight() && autoWidth()) + // initTextSizes(); + // } } void TextItem::setTextItemFont(QFont value) { - if (font()!=value){ + if (font() != value) { QFont oldValue = font(); value.setLetterSpacing(QFont::AbsoluteSpacing, m_fontLetterSpacing); setFont(value); - if (!isLoading()) update(); - notify("font",oldValue,value); + if (!isLoading()) + update(); + notify("font", oldValue, value); } } -QWidget *TextItem::defaultEditor() +QWidget* TextItem::defaultEditor() { - QSettings* l_settings = (page()->settings() != 0) ? - page()->settings() : - (page()->reportEditor()!=0) ? page()->reportEditor()->settings() : 0; - QWidget* editor = new TextItemEditor(this,page(),l_settings); + QSettings* l_settings = (page()->settings() != 0) ? page()->settings() + : (page()->reportEditor() != 0) ? page()->reportEditor()->settings() + : 0; + QWidget* editor = new TextItemEditor(this, page(), l_settings); editor->setAttribute(Qt::WA_DeleteOnClose); return editor; } void TextItem::setBackgroundOpacity(int value) { - if (opacity()!=value){ + if (opacity() != value) { int oldValue = opacity(); setOpacity(value); - notify("backgroundOpacity",oldValue,value); + notify("backgroundOpacity", oldValue, value); } } void TextItem::setBackgroundModeProperty(BaseDesignIntf::BGMode value) { - if (value!=backgroundMode()){ + if (value != backgroundMode()) { BaseDesignIntf::BGMode oldValue = backgroundMode(); setBackgroundMode(value); - notify("backgroundMode",oldValue,value); + notify("backgroundMode", oldValue, value); } } void TextItem::setBackgroundColorProperty(QColor value) { - if(value!=backgroundColor()){ + if (value != backgroundColor()) { QColor oldValue = backgroundColor(); setBackgroundColor(value); - notify("backgroundColor",oldValue,value); + notify("backgroundColor", oldValue, value); } } void TextItem::setFontColorProperty(QColor value) { - if(value!=fontColor()){ + if (value != fontColor()) { QColor oldValue = fontColor(); setFontColor(value); - notify("fontColor",oldValue,value); + notify("fontColor", oldValue, value); } } -TextItem::AngleType TextItem::angle() const -{ - return m_angle; -} +TextItem::AngleType TextItem::angle() const { return m_angle; } void TextItem::setAngle(const AngleType& value) { - if (m_angle!=value){ + if (m_angle != value) { AngleType oldValue = m_angle; m_angle = value; - if (!isLoading()){ + if (!isLoading()) { update(); - notify("angle",oldValue,value); + notify("angle", oldValue, value); } } } void TextItem::setForegroundOpacity(int value) { - if (value>100){ - value=100; - } else if(value<0){ - value=0; + if (value > 100) { + value = 100; + } else if (value < 0) { + value = 0; } - if (m_foregroundOpacity != value){ + if (m_foregroundOpacity != value) { int oldValue = m_foregroundOpacity; m_foregroundOpacity = value; update(); - notify("foregroundOpacity",oldValue,value); + notify("foregroundOpacity", oldValue, value); } } void TextItem::setUnderlines(bool value) { - if (m_underlines != value){ + if (m_underlines != value) { bool oldValue = m_underlines; m_underlines = value; update(); - notify("underlines",oldValue,value); + notify("underlines", oldValue, value); } } -} //namespace LimeReport - - - +} // namespace LimeReport diff --git a/limereport/items/lrtextitem.h b/limereport/items/lrtextitem.h index a64142e..4b6c340 100644 --- a/limereport/items/lrtextitem.h +++ b/limereport/items/lrtextitem.h @@ -29,20 +29,19 @@ ****************************************************************************/ #ifndef LRTEXTITEM_H #define LRTEXTITEM_H +#include "lritemdesignintf.h" +#include "lrpageinitintf.h" + #include -#include #include #include #include - -#include "lritemdesignintf.h" -#include "lritemdesignintf.h" -#include "lrpageinitintf.h" +#include namespace LimeReport { class Tag; -class TextItem : public ContentItemDesignIntf, IPageInit { +class TextItem: public ContentItemDesignIntf, IPageInit { Q_OBJECT Q_PROPERTY(QString content READ content WRITE setContent) Q_PROPERTY(int margin READ marginSize WRITE setMarginSize) @@ -66,19 +65,35 @@ class TextItem : public ContentItemDesignIntf, IPageInit { Q_PROPERTY(QString format READ format WRITE setFormat) Q_PROPERTY(ValueType valueType READ valueType WRITE setValueType) Q_PROPERTY(QString followTo READ followTo WRITE setFollowTo) - Q_PROPERTY(BrushStyle backgroundBrushStyle READ backgroundBrushStyle WRITE setBackgroundBrushStyle) + Q_PROPERTY( + BrushStyle backgroundBrushStyle READ backgroundBrushStyle WRITE setBackgroundBrushStyle) Q_PROPERTY(qreal textIndent READ textIndent WRITE setTextIndent) - Q_PROPERTY(Qt::LayoutDirection textLayoutDirection READ textLayoutDirection WRITE setTextLayoutDirection) + Q_PROPERTY(Qt::LayoutDirection textLayoutDirection READ textLayoutDirection WRITE + setTextLayoutDirection) Q_PROPERTY(bool fillInSecondPass READ fillInSecondPass WRITE setFillInSecondPass) Q_PROPERTY(bool watermark READ isWatermark WRITE setWatermark) Q_PROPERTY(bool replaceCRwithBR READ isReplaceCarriageReturns WRITE setReplaceCarriageReturns) Q_PROPERTY(bool hideIfEmpty READ hideIfEmpty WRITE setHideIfEmpty) Q_PROPERTY(int fontLetterSpacing READ fontLetterSpacing WRITE setFontLetterSpacing) public: - - enum AutoWidth{NoneAutoWidth, MaxWordLength, MaxStringLength}; - enum AngleType{Angle0, Angle90, Angle180, Angle270, Angle45, Angle315}; - enum ValueType{Default, DateTime, Double}; + enum AutoWidth { + NoneAutoWidth, + MaxWordLength, + MaxStringLength + }; + enum AngleType { + Angle0, + Angle90, + Angle180, + Angle270, + Angle45, + Angle315 + }; + enum ValueType { + Default, + DateTime, + Double + }; #if QT_VERSION >= 0x050500 Q_ENUM(AutoWidth) Q_ENUM(AngleType) @@ -90,7 +105,7 @@ public: #endif void Init(); - TextItem(QObject* owner=0, QGraphicsItem* parent=0); + TextItem(QObject* owner = 0, QGraphicsItem* parent = 0); ~TextItem(); void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); @@ -98,29 +113,29 @@ public: void setContent(const QString& value); void setAlignment(Qt::Alignment value); - Qt::Alignment alignment(){return m_alignment;} + Qt::Alignment alignment() { return m_alignment; } void geometryChangedEvent(QRectF, QRectF); bool isNeedUpdateSize(RenderPass) const; - void updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight); - void expandContent(DataSourceManager *dataManager, RenderPass pass); + void updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight); + void expandContent(DataSourceManager* dataManager, RenderPass pass); void setAutoHeight(bool value); - bool autoHeight() const {return m_autoHeight;} + bool autoHeight() const { return m_autoHeight; } void setAutoWidth(AutoWidth value); - AutoWidth autoWidth() const {return m_autoWidth;} + AutoWidth autoWidth() const { return m_autoWidth; } void setAdaptFontToSize(bool value); - bool adaptFontToSize() const {return m_adaptFontToSize;} + bool adaptFontToSize() const { return m_adaptFontToSize; } bool canBeSplitted(int height) const; - bool isSplittable() const { return true;} - bool isEmpty() const{return m_strText.trimmed().isEmpty();} - BaseDesignIntf* cloneUpperPart(int height, QObject *owner, QGraphicsItem *parent); - BaseDesignIntf* cloneBottomPart(int height, QObject *owner, QGraphicsItem *parent); - BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); - BaseDesignIntf* cloneEmpty(int height, QObject *owner, QGraphicsItem *parent); + bool isSplittable() const { return true; } + bool isEmpty() const { return m_strText.trimmed().isEmpty(); } + BaseDesignIntf* cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent); + BaseDesignIntf* cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent); + BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); + BaseDesignIntf* cloneEmpty(int height, QObject* owner, QGraphicsItem* parent); void objectLoadFinished(); void setTextItemFont(QFont value); @@ -131,9 +146,9 @@ public: void setFontColorProperty(QColor value); AngleType angle() const; void setAngle(const AngleType& value); - int foregroundOpacity(){return m_foregroundOpacity;} + int foregroundOpacity() { return m_foregroundOpacity; } void setForegroundOpacity(int value); - bool underlines(){return m_underlines;} + bool underlines() { return m_underlines; } void setUnderlines(bool value); bool trimValue() const; @@ -152,18 +167,18 @@ public: void setAllowHTMLInFields(bool allowHTMLInFields); QString format() const; - void setFormat(const QString &format); + void setFormat(const QString& format); ValueType valueType() const; void setValueType(const ValueType valueType); - QSizeF textSize(){ return m_textSize;} + QSizeF textSize() { return m_textSize; } QString followTo() const; - void setFollowTo(const QString &followTo); + void setFollowTo(const QString& followTo); void setFollower(TextItem* follower); void clearFollower(); bool hasFollower() const; - TextItem* follower() const { return m_follower;} + TextItem* follower() const { return m_follower; } bool initFollower(QString follower); // IPageInit interface @@ -172,12 +187,12 @@ public: typedef QSharedPointer TextPtr; qreal textIndent() const; - void setTextIndent(const qreal &textIndent); + void setTextIndent(const qreal& textIndent); Qt::LayoutDirection textLayoutDirection() const; - void setTextLayoutDirection(const Qt::LayoutDirection &textLayoutDirection); + void setTextLayoutDirection(const Qt::LayoutDirection& textLayoutDirection); void setWatermark(bool watermark); - + bool isReplaceCarriageReturns() const; void setReplaceCarriageReturns(bool isReplaceCarriageReturns); @@ -194,24 +209,26 @@ protected: QString replaceReturns(QString text) const; QString getTextPart(int height, int skipHeight); void restoreLinksEvent(); - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: void initTextSizes() const; - void setTextFont(TextPtr text, const QFont &value) const; + void setTextFont(TextPtr text, const QFont& value) const; void adaptFontSize(TextPtr text) const; - QString formatDateTime(const QDateTime &value); + QString formatDateTime(const QDateTime& value); QString formatNumber(const double value); QString formatFieldValue(); QString extractText(QTextBlock& curBlock, int height); TextPtr textDocument() const; + private: QString m_strText; Qt::Alignment m_alignment; bool m_autoHeight; AutoWidth m_autoWidth; QSizeF mutable m_textSize; - qreal mutable m_firstLineSize; + qreal mutable m_firstLineSize; AngleType m_angle; int m_foregroundOpacity; bool m_underlines; @@ -225,7 +242,7 @@ private: QString m_format; ValueType m_valueType; - QString m_followTo; + QString m_followTo; TextItem* m_follower; qreal m_textIndent; Qt::LayoutDirection m_textLayoutDirection; @@ -233,5 +250,5 @@ private: int m_fontLetterSpacing; }; -} +} // namespace LimeReport #endif // LRTEXTITEM_H diff --git a/limereport/items/lrtextitemeditor.cpp b/limereport/items/lrtextitemeditor.cpp index e8c5770..e15ed38 100644 --- a/limereport/items/lrtextitemeditor.cpp +++ b/limereport/items/lrtextitemeditor.cpp @@ -30,25 +30,32 @@ #include "lrtextitemeditor.h" #include "ui_lrtextitemeditor.h" -#include "lrdatasourcemanager.h" -#include "lrscriptenginemanager.h" #include "lrdatadesignintf.h" +#include "lrdatasourcemanager.h" #include "lrscripteditor.h" +#include "lrscriptenginemanager.h" #include #include -namespace LimeReport{ +namespace LimeReport { -TextItemEditor::TextItemEditor(LimeReport::TextItem *item, LimeReport::PageDesignIntf *page, QSettings* settings, QWidget *parent) : +TextItemEditor::TextItemEditor(LimeReport::TextItem* item, LimeReport::PageDesignIntf* page, + QSettings* settings, QWidget* parent): QWidget(parent), - ui(new Ui::TextItemEditor), m_textItem(item), m_page(page), m_settings(settings), m_ownedSettings(false), m_isReadingSetting(false) + ui(new Ui::TextItemEditor), + m_textItem(item), + m_page(page), + m_settings(settings), + m_ownedSettings(false), + m_isReadingSetting(false) { ui->setupUi(this); initUI(); setWindowIcon(QIcon(":/items/images/TextItem")); readSetting(); - connect(ui->codeEditor, SIGNAL(splitterMoved(int,int)), this, SLOT(slotSplitterMoved(int,int)) ); + connect(ui->codeEditor, SIGNAL(splitterMoved(int, int)), this, + SLOT(slotSplitterMoved(int, int))); } TextItemEditor::~TextItemEditor() @@ -66,17 +73,17 @@ void TextItemEditor::setSettings(QSettings* value) { if (m_ownedSettings) delete m_settings; - m_settings=value; - m_ownedSettings=false; + m_settings = value; + m_ownedSettings = false; readSetting(); } -QSettings*TextItemEditor::settings() +QSettings* TextItemEditor::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_settings = new QSettings("LimeReport", QCoreApplication::applicationName()); m_ownedSettings = true; return m_settings; } @@ -98,9 +105,9 @@ void TextItemEditor::moveEvent(QMoveEvent*) void TextItemEditor::closeEvent(QCloseEvent* event) { - if (settings()!=0){ + if (settings() != 0) { settings()->beginGroup("TextItemEditor"); - settings()->setValue("CodeEditorState",ui->codeEditor->saveState()); + settings()->setValue("CodeEditorState", ui->codeEditor->saveState()); settings()->endGroup(); } QWidget::closeEvent(event); @@ -108,7 +115,7 @@ void TextItemEditor::closeEvent(QCloseEvent* event) void TextItemEditor::on_pbOk_clicked() { - if (m_textItem->content()!= ui->codeEditor->toPlainText()){ + if (m_textItem->content() != ui->codeEditor->toPlainText()) { m_textItem->setContent(ui->codeEditor->toPlainText()); } close(); @@ -118,48 +125,46 @@ void TextItemEditor::initUI() { QStringList dataWords; - LimeReport::DataSourceManager* dm = m_page->datasourceManager(); + LimeReport::DataSourceManager* dm = m_page->datasourceManager(); LimeReport::ScriptEngineManager& se = LimeReport::ScriptEngineManager::instance(); se.setDataManager(dm); ScriptEditor* scriptEditor = dynamic_cast(ui->codeEditor); - if (scriptEditor){ + if (scriptEditor) { scriptEditor->setReportPage(m_page); scriptEditor->setPageBand(findParentBand()); scriptEditor->setPlainText(m_textItem->content()); } } -void TextItemEditor::on_pbCancel_clicked() -{ - close(); -} +void TextItemEditor::on_pbCancel_clicked() { close(); } void TextItemEditor::readSetting() { - if (settings()==0) return; + if (settings() == 0) + return; m_isReadingSetting = true; settings()->beginGroup("TextItemEditor"); QVariant v = settings()->value("Geometry"); - if (v.isValid()){ + if (v.isValid()) { restoreGeometry(v.toByteArray()); } v = settings()->value("CodeEditorState"); - if (v.isValid()){ + if (v.isValid()) { ui->codeEditor->restoreState(v.toByteArray()); } settings()->endGroup(); settings()->beginGroup("ScriptEditor"); QVariant fontName = settings()->value("DefaultFontName"); - if (fontName.isValid()){ + if (fontName.isValid()) { QVariant fontSize = settings()->value("DefaultFontSize"); - ui->codeEditor->setEditorFont(QFont(fontName.toString(),fontSize.toInt())); + ui->codeEditor->setEditorFont(QFont(fontName.toString(), fontSize.toInt())); } QVariant tabIndention = settings()->value("TabIndention"); - if (tabIndention.isValid()){ + if (tabIndention.isValid()) { ui->codeEditor->setTabIndention(tabIndention.toInt()); } else { ui->codeEditor->setTabIndention(LimeReport::Const::DEFAULT_TAB_INDENTION); @@ -171,29 +176,28 @@ void TextItemEditor::readSetting() void TextItemEditor::writeSetting() { - if (settings()!=0){ + if (settings() != 0) { settings()->beginGroup("TextItemEditor"); - settings()->setValue("Geometry",saveGeometry()); - settings()->setValue("CodeEditorState",ui->codeEditor->saveState()); + settings()->setValue("Geometry", saveGeometry()); + settings()->setValue("CodeEditorState", ui->codeEditor->saveState()); settings()->endGroup(); } } -void TextItemEditor::slotSplitterMoved(int, int) -{ - writeSetting(); -} +void TextItemEditor::slotSplitterMoved(int, int) { writeSetting(); } -BandDesignIntf *TextItemEditor::findParentBand() +BandDesignIntf* TextItemEditor::findParentBand() { BandDesignIntf* result = 0; BaseDesignIntf* item = m_textItem; - while (true){ + while (true) { item = dynamic_cast(item->parentItem()); - if (item){ + if (item) { result = dynamic_cast(item); - if (result) break; - } else break; + if (result) + break; + } else + break; } return result; } diff --git a/limereport/items/lrtextitemeditor.h b/limereport/items/lrtextitemeditor.h index b2c97ef..c2ea9b3 100644 --- a/limereport/items/lrtextitemeditor.h +++ b/limereport/items/lrtextitemeditor.h @@ -30,61 +30,63 @@ #ifndef LRTEXTITEMEDITOR_H #define LRTEXTITEMEDITOR_H -#include -#include -#include - -#include "lrtextitem.h" #include "lrpagedesignintf.h" +#include "lrtextitem.h" -namespace LimeReport{ +#include +#include +#include + +namespace LimeReport { namespace Ui { -class TextItemEditor; + class TextItemEditor; } -//class CompleaterTextEditor :public QTextEdit +// class CompleaterTextEditor :public QTextEdit //{ // Q_OBJECT -//public: +// public: // CompleaterTextEditor(QWidget* parent=0); // void setCompleter(QCompleter* value); // QCompleter* compleater() const{ return m_compleater;} -//protected: +// protected: // virtual void keyPressEvent(QKeyEvent *e); // virtual void focusInEvent(QFocusEvent *e); -//private: +// private: // QString textUnderCursor() const; -//private slots: +// private slots: // void insertCompletion(const QString& completion); -//private: +// private: // QCompleter* m_compleater; //}; -class TextItemEditor : public QWidget -{ - Q_OBJECT +class TextItemEditor: public QWidget { + Q_OBJECT public: explicit TextItemEditor(LimeReport::TextItem* item, LimeReport::PageDesignIntf* page, - QSettings* settings=0, QWidget *parent = 0); + QSettings* settings = 0, QWidget* parent = 0); ~TextItemEditor(); void setSettings(QSettings* value); - QSettings* settings(); + QSettings* settings(); + protected: - void resizeEvent(QResizeEvent *); - void moveEvent(QMoveEvent *); - void closeEvent(QCloseEvent *event); + void resizeEvent(QResizeEvent*); + void moveEvent(QMoveEvent*); + void closeEvent(QCloseEvent* event); BandDesignIntf* findParentBand(); private slots: void on_pbOk_clicked(); void on_pbCancel_clicked(); void slotSplitterMoved(int, int); + private: void initUI(); void readSetting(); void writeSetting(); + private: - Ui::TextItemEditor *ui; + Ui::TextItemEditor* ui; LimeReport::TextItem* m_textItem; LimeReport::PageDesignIntf* m_page; QSettings* m_settings; diff --git a/limereport/items/lrverticallayout.cpp b/limereport/items/lrverticallayout.cpp index 2fbd19b..81d99ad 100644 --- a/limereport/items/lrverticallayout.cpp +++ b/limereport/items/lrverticallayout.cpp @@ -7,29 +7,28 @@ const QString xmlTag = "VLayout"; namespace { -LimeReport::BaseDesignIntf *createVLayout(QObject *owner, LimeReport::BaseDesignIntf *parent) +LimeReport::BaseDesignIntf* createVLayout(QObject* owner, LimeReport::BaseDesignIntf* parent) { return new LimeReport::VerticalLayout(owner, parent); } bool VARIABLE_IS_NOT_USED registred = LimeReport::DesignElementsFactory::instance().registerCreator( - xmlTag, - LimeReport::ItemAttribs(QObject::tr("VLayout"), LimeReport::Const::bandTAG), - createVLayout - ); + xmlTag, LimeReport::ItemAttribs(QObject::tr("VLayout"), LimeReport::Const::bandTAG), + createVLayout); +} // namespace + +namespace LimeReport { + +bool verticalLessThen(BaseDesignIntf* c1, BaseDesignIntf* c2) +{ + return c1->pos().y() < c2->pos().y(); } -namespace LimeReport{ - -bool verticalLessThen(BaseDesignIntf *c1, BaseDesignIntf* c2){ - return c1->pos().y()pos().y(); +VerticalLayout::VerticalLayout(QObject* owner, QGraphicsItem* parent): + AbstractLayout(xmlTag, owner, parent) +{ } -VerticalLayout::VerticalLayout(QObject* owner, QGraphicsItem* parent) - : AbstractLayout(xmlTag, owner, parent) -{} - -VerticalLayout::~VerticalLayout() -{} +VerticalLayout::~VerticalLayout() { } BaseDesignIntf* VerticalLayout::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { @@ -39,26 +38,29 @@ BaseDesignIntf* VerticalLayout::createSameTypeItem(QObject* owner, QGraphicsItem void VerticalLayout::updateLayoutSize() { int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; - int h = spaceBorder*2; + int h = spaceBorder * 2; qreal w = 0; int visibleItemCount = 0; - foreach(BaseDesignIntf* item, layoutsChildren()){ - if (item->isEmpty() && hideEmptyItems()) item->setVisible(false); - if (item->isVisible()){ - if (w < item->width()) w = item->width(); - h+=item->height(); + foreach (BaseDesignIntf* item, layoutsChildren()) { + if (item->isEmpty() && hideEmptyItems()) + item->setVisible(false); + if (item->isVisible()) { + if (w < item->width()) + w = item->width(); + h += item->height(); visibleItemCount++; } } - if (w>0) setWidth(w+spaceBorder*2); - setHeight(h + layoutSpacingMM() *(visibleItemCount-1)); + if (w > 0) + setWidth(w + spaceBorder * 2); + setHeight(h + layoutSpacingMM() * (visibleItemCount - 1)); } void VerticalLayout::relocateChildren() { int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; QList newChildren; - if (layoutsChildren().count() < childItems().size() - 1){ + if (layoutsChildren().count() < childItems().size() - 1) { auto oldChildren = layoutsChildren(); layoutsChildren().clear(); foreach (BaseDesignIntf* item, childBaseItems()) { @@ -68,13 +70,13 @@ void VerticalLayout::relocateChildren() layoutsChildren().append(item); } } - std::sort(layoutsChildren().begin(),layoutsChildren().end(), verticalLessThen); + std::sort(layoutsChildren().begin(), layoutsChildren().end(), verticalLessThen); qreal curY = spaceBorder; setIsRelocating(true); foreach (BaseDesignIntf* item, layoutsChildren()) { - if (item->isVisible() || itemMode() == DesignMode){ + if (item->isVisible() || itemMode() == DesignMode) { item->setPos(spaceBorder, curY); - curY+=item->height() + layoutSpacingMM(); + curY += item->height() + layoutSpacingMM(); item->setWidth(width() - (spaceBorder * 2)); } } @@ -87,28 +89,30 @@ void VerticalLayout::relocateChildren() bool VerticalLayout::canBeSplitted(int height) const { - if (childItems().isEmpty()) return false; + if (childItems().isEmpty()) + return false; BaseDesignIntf* item = dynamic_cast(childItems().at(0)); - if (item){ - if (item->height() > height ) + if (item) { + if (item->height() > height) return item->canBeSplitted(height); - else return true; + else + return true; } return false; } BaseDesignIntf* VerticalLayout::cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent) { - VerticalLayout* upperPart = dynamic_cast(createSameTypeItem(owner,parent)); + VerticalLayout* upperPart = dynamic_cast(createSameTypeItem(owner, parent)); upperPart->initFromItem(this); - foreach(BaseDesignIntf* item, childBaseItems()){ - if ((item->geometry().bottom() <= height) ){ - item->cloneItem(item->itemMode(),upperPart,upperPart); + foreach (BaseDesignIntf* item, childBaseItems()) { + if ((item->geometry().bottom() <= height)) { + item->cloneItem(item->itemMode(), upperPart, upperPart); } else { - if ((item->geometry().top() < height) && ( item->geometry().bottom() > height)){ + if ((item->geometry().top() < height) && (item->geometry().bottom() > height)) { int sliceHeight = height - item->geometry().top(); - if (item->isSplittable() && item->canBeSplitted(sliceHeight)){ - item->cloneUpperPart(sliceHeight,upperPart,upperPart); + if (item->isSplittable() && item->canBeSplitted(sliceHeight)) { + item->cloneUpperPart(sliceHeight, upperPart, upperPart); } } } @@ -121,14 +125,15 @@ BaseDesignIntf* VerticalLayout::cloneUpperPart(int height, QObject* owner, QGrap BaseDesignIntf* VerticalLayout::cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent) { - VerticalLayout* bottomPart = dynamic_cast(createSameTypeItem(owner,parent)); + VerticalLayout* bottomPart = dynamic_cast(createSameTypeItem(owner, parent)); bottomPart->initFromItem(this); - foreach(BaseDesignIntf* item,childBaseItems()){ - if (item->geometry().bottom() > height){ + foreach (BaseDesignIntf* item, childBaseItems()) { + if (item->geometry().bottom() > height) { int sliceHeight = height - item->geometry().top(); - if ((item->geometry().top() < height) && (item->canBeSplitted(sliceHeight))){ - BaseDesignIntf* tmpItem = item->cloneBottomPart(sliceHeight, bottomPart, bottomPart); + if ((item->geometry().top() < height) && (item->canBeSplitted(sliceHeight))) { + BaseDesignIntf* tmpItem + = item->cloneBottomPart(sliceHeight, bottomPart, bottomPart); tmpItem->setHeight(sliceHeight); bottomPart->addChild(tmpItem); } else { @@ -137,10 +142,10 @@ BaseDesignIntf* VerticalLayout::cloneBottomPart(int height, QObject* owner, QGra } } - if (!bottomPart->isEmpty()){ + if (!bottomPart->isEmpty()) { int currentHeight = 0; foreach (BaseDesignIntf* item, bottomPart->childBaseItems()) { - currentHeight+=item->height(); + currentHeight += item->height(); } bottomPart->setHeight(currentHeight); } @@ -149,7 +154,7 @@ BaseDesignIntf* VerticalLayout::cloneBottomPart(int height, QObject* owner, QGra void VerticalLayout::sortChildren() { - std::sort(layoutsChildren().begin(),layoutsChildren().end(),verticalLessThen); + std::sort(layoutsChildren().begin(), layoutsChildren().end(), verticalLessThen); } void VerticalLayout::divideSpace() @@ -159,22 +164,25 @@ void VerticalLayout::divideSpace() int visibleItemsCount = 0; int spaceBorder = (borderLines() != 0) ? borderLineSize() : 0; - foreach(BaseDesignIntf* item, layoutsChildren()){ - if (item->isVisible() || itemMode() == DesignMode ){ + foreach (BaseDesignIntf* item, layoutsChildren()) { + if (item->isVisible() || itemMode() == DesignMode) { itemsSumSize += item->height(); visibleItemsCount++; } } itemsSumSize += layoutSpacingMM() * (visibleItemsCount - 1); - qreal delta = (height() - (itemsSumSize+spaceBorder*2)) / (visibleItemsCount!=0 ? visibleItemsCount : 1); + qreal delta = (height() - (itemsSumSize + spaceBorder * 2)) + / (visibleItemsCount != 0 ? visibleItemsCount : 1); - for (int i=0; iisVisible() || itemMode() == DesignMode) - layoutsChildren()[i]->setHeight(layoutsChildren()[i]->height()+delta); - if ((i+1)isVisible() || itemMode() == DesignMode) - layoutsChildren()[i+1]->setPos(layoutsChildren()[i+1]->pos().x(), layoutsChildren()[i+1]->pos().y()+delta*(i+1)); + layoutsChildren()[i]->setHeight(layoutsChildren()[i]->height() + delta); + if ((i + 1) < layoutsChildren().size()) + if (layoutsChildren()[i + 1]->isVisible() || itemMode() == DesignMode) + layoutsChildren()[i + 1]->setPos(layoutsChildren()[i + 1]->pos().x(), + layoutsChildren()[i + 1]->pos().y() + + delta * (i + 1)); } setIsRelocating(false); } diff --git a/limereport/items/lrverticallayout.h b/limereport/items/lrverticallayout.h index e276c22..31c0499 100644 --- a/limereport/items/lrverticallayout.h +++ b/limereport/items/lrverticallayout.h @@ -1,28 +1,29 @@ #ifndef LRVERTICALLAYOUT_H #define LRVERTICALLAYOUT_H +#include "lrabstractlayout.h" #include "lritemdesignintf.h" #include "lrlayoutmarker.h" -#include "lrabstractlayout.h" -namespace LimeReport{ +namespace LimeReport { -class VerticalLayout : public AbstractLayout -{ +class VerticalLayout: public AbstractLayout { Q_OBJECT public: friend class BaseDesignIntf; - VerticalLayout(QObject *owner = 0, QGraphicsItem *parent = 0); + VerticalLayout(QObject* owner = 0, QGraphicsItem* parent = 0); ~VerticalLayout(); // BaseDesignIntf interface - BaseDesignIntf*createSameTypeItem(QObject* owner, QGraphicsItem* parent); - bool isSplittable() const { return true;} + BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent); + bool isSplittable() const { return true; } + protected: void updateLayoutSize(); void relocateChildren(); bool canBeSplitted(int height) const; - BaseDesignIntf* cloneUpperPart(int height, QObject* owner=0, QGraphicsItem* parent=0); - BaseDesignIntf* cloneBottomPart(int height, QObject *owner=0, QGraphicsItem *parent=0); + BaseDesignIntf* cloneUpperPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); + BaseDesignIntf* cloneBottomPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); + private: void sortChildren(); void divideSpace(); diff --git a/limereport/lraboutdialog.cpp b/limereport/lraboutdialog.cpp index 3663e31..257ab67 100644 --- a/limereport/lraboutdialog.cpp +++ b/limereport/lraboutdialog.cpp @@ -27,23 +27,19 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include "version.h" #include "lraboutdialog.h" #include "ui_lraboutdialog.h" -namespace LimeReport{ +#include "version.h" -AboutDialog::AboutDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AboutDialog) +namespace LimeReport { + +AboutDialog::AboutDialog(QWidget* parent): QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); ui->lblVersion->setText(QString("Version %1").arg(LIMEREPORT_VERSION_STR)); } -AboutDialog::~AboutDialog() -{ - delete ui; -} +AboutDialog::~AboutDialog() { delete ui; } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lraboutdialog.h b/limereport/lraboutdialog.h index c823be0..b4d0a31 100644 --- a/limereport/lraboutdialog.h +++ b/limereport/lraboutdialog.h @@ -32,24 +32,23 @@ #include -namespace LimeReport{ +namespace LimeReport { namespace Ui { -class AboutDialog; + class AboutDialog; } -class AboutDialog : public QDialog -{ +class AboutDialog: public QDialog { Q_OBJECT public: - explicit AboutDialog(QWidget *parent = 0); + explicit AboutDialog(QWidget* parent = 0); ~AboutDialog(); private: - Ui::AboutDialog *ui; + Ui::AboutDialog* ui; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRABOUTDIALOG_H diff --git a/limereport/lraxisdata.cpp b/limereport/lraxisdata.cpp index 692003c..ac95952 100644 --- a/limereport/lraxisdata.cpp +++ b/limereport/lraxisdata.cpp @@ -1,17 +1,28 @@ #include "lraxisdata.h" -#include #include +#include + namespace LimeReport { -AxisData::AxisData(AxisType type, QObject *parent) - : QObject(parent), m_rangeMin(0), m_rangeMax(0), - m_minValue(0), m_maxValue(0), m_step(0), - m_delta(0), m_segmentCount(4), m_calculateAxisScale(false), - m_reverseDirection(false), m_manualMaximum(0), - m_manualMinimum(0), m_manualStep(0), m_isMaximumAutomatic(true), - m_isMinimumAutomatic(true), m_isStepAutomatic(true), - m_type(type) +AxisData::AxisData(AxisType type, QObject* parent): + QObject(parent), + m_rangeMin(0), + m_rangeMax(0), + m_minValue(0), + m_maxValue(0), + m_step(0), + m_delta(0), + m_segmentCount(4), + m_calculateAxisScale(false), + m_reverseDirection(false), + m_manualMaximum(0), + m_manualMinimum(0), + m_manualStep(0), + m_isMaximumAutomatic(true), + m_isMinimumAutomatic(true), + m_isStepAutomatic(true), + m_type(type) { } @@ -22,16 +33,17 @@ QString AxisData::toString() const QTextStream stream(&str); stream << "{ " << "min: " << m_minValue << ", max: " << m_maxValue << ", step: " << m_step - << ", range min: " << m_rangeMin << ", range max: " << m_rangeMax << ", segments: " << m_segmentCount - << ", reverseDiection: " << m_reverseDirection << ", calculateAxisScale: " << m_calculateAxisScale - << ", manualMaxEnabled: " << !m_isMaximumAutomatic << ", manualMinEnabled: " << !m_isMinimumAutomatic + << ", range min: " << m_rangeMin << ", range max: " << m_rangeMax + << ", segments: " << m_segmentCount << ", reverseDiection: " << m_reverseDirection + << ", calculateAxisScale: " << m_calculateAxisScale + << ", manualMaxEnabled: " << !m_isMaximumAutomatic + << ", manualMinEnabled: " << !m_isMinimumAutomatic << ", manualStepEnabled: " << !m_isStepAutomatic << ", manualMax: " << m_manualMaximum - << ", manualMin: " << m_manualMinimum << ", manualStep: " << m_manualStep - << " }"; + << ", manualMin: " << m_manualMinimum << ", manualStep: " << m_manualStep << " }"; return str; } -void AxisData::copy(AxisData *other) +void AxisData::copy(AxisData* other) { m_calculateAxisScale = other->calculateAxisScale(); m_reverseDirection = other->reverseDirection(); @@ -81,45 +93,21 @@ void AxisData::updateForDesignMode() m_calculateAxisScale = tmp; } -int AxisData::segmentCount() const -{ - return m_segmentCount; -} +int AxisData::segmentCount() const { return m_segmentCount; } -bool AxisData::calculateAxisScale() const -{ - return m_calculateAxisScale; -} +bool AxisData::calculateAxisScale() const { return m_calculateAxisScale; } -qreal AxisData::rangeMin() const -{ - return m_rangeMin; -} +qreal AxisData::rangeMin() const { return m_rangeMin; } -qreal AxisData::rangeMax() const -{ - return m_rangeMax; -} +qreal AxisData::rangeMax() const { return m_rangeMax; } -qreal AxisData::minValue() const -{ - return m_minValue; -} +qreal AxisData::minValue() const { return m_minValue; } -qreal AxisData::maxValue() const -{ - return m_maxValue; -} +qreal AxisData::maxValue() const { return m_maxValue; } -qreal AxisData::step() const -{ - return m_step; -} +qreal AxisData::step() const { return m_step; } -qreal AxisData::delta() const -{ - return m_delta; -} +qreal AxisData::delta() const { return m_delta; } void AxisData::calculateRoundedAxisScale() { @@ -159,12 +147,12 @@ void AxisData::calculateRoundedAxisScale() bool isLoopFinished = false; // Calculate until segment count is below maximum - while( !isLoopFinished ) { + while (!isLoopFinished) { if (calculateStep) { - if(isStepNormalized) { - if( normalizedStep == 1.0 ) { + if (isStepNormalized) { + if (normalizedStep == 1.0) { normalizedStep = 2.0; - } else if( normalizedStep == 2.0 ) { + } else if (normalizedStep == 2.0) { normalizedStep = 5.0; } else { normalizedStep = 1.0; @@ -172,14 +160,14 @@ void AxisData::calculateRoundedAxisScale() } } else { const double startingStep = (temporaryMax - temporaryMin) / maximumSegmentCount; - const int exponent = static_cast< int >( floor( log10( startingStep ) ) ); + const int exponent = static_cast(floor(log10(startingStep))); stepMagnitude = pow(10.0, static_cast(exponent)); normalizedStep = startingStep / stepMagnitude; - if( normalizedStep <= 1.0 ) { + if (normalizedStep <= 1.0) { normalizedStep = 1.0; - } else if( normalizedStep <= 2.0 ) { + } else if (normalizedStep <= 2.0) { normalizedStep = 2.0; - } else if( normalizedStep <= 5.0 ) { + } else if (normalizedStep <= 5.0) { normalizedStep = 5.0; } else { normalizedStep = 1.0; @@ -197,7 +185,8 @@ void AxisData::calculateRoundedAxisScale() currentAxisMinimum = calculateNewMinimum(currentAxisMinimum, m_step); const qreal currentDelta = currentAxisMaximum - currentAxisMinimum; const qreal actualDelta = currentAxisMaximum - minValue(); - if ((currentAxisMinimum != 0.0) && ((actualDelta / currentDelta) > minAndMaxSpacingOffset)) { + if ((currentAxisMinimum != 0.0) + && ((actualDelta / currentDelta) > minAndMaxSpacingOffset)) { currentAxisMinimum -= m_step; } } @@ -206,12 +195,14 @@ void AxisData::calculateRoundedAxisScale() currentAxisMaximum = calculateNewMaximum(currentAxisMaximum, m_step); const qreal currentDelta = currentAxisMaximum - currentAxisMinimum; const qreal actualDelta = maxValue() - currentAxisMinimum; - if ((currentAxisMaximum != 0.0) && ((actualDelta / currentDelta) > minAndMaxSpacingOffset)) { + if ((currentAxisMaximum != 0.0) + && ((actualDelta / currentDelta) > minAndMaxSpacingOffset)) { currentAxisMaximum += m_step; } } - m_segmentCount = static_cast(round((currentAxisMaximum - currentAxisMinimum) / m_step)); + m_segmentCount + = static_cast(round((currentAxisMaximum - currentAxisMinimum) / m_step)); m_rangeMin = currentAxisMinimum; m_rangeMax = currentAxisMaximum; // Check also if step is correctly calucalted. It is possible for float steps that @@ -234,7 +225,7 @@ void AxisData::calculateSimpleAxisScale() m_segmentCount = 4; const int delta = maxValue() - min; int max = delta; - while (max % m_segmentCount != 0){ + while (max % m_segmentCount != 0) { max++; } m_rangeMax = minValue() + max; @@ -271,79 +262,43 @@ void AxisData::setCalculateAxisScale(bool newCalculateAxisScale) m_calculateAxisScale = newCalculateAxisScale; } -bool AxisData::reverseDirection() const -{ - return m_reverseDirection; -} +bool AxisData::reverseDirection() const { return m_reverseDirection; } -void AxisData::setReverseDirection(bool reverseDirection) -{ - m_reverseDirection = reverseDirection; -} +void AxisData::setReverseDirection(bool reverseDirection) { m_reverseDirection = reverseDirection; } -qreal AxisData::manualMaximum() const -{ - return m_manualMaximum; -} +qreal AxisData::manualMaximum() const { return m_manualMaximum; } -void AxisData::setManualMaximum(qreal newManualMaximum) -{ - m_manualMaximum = newManualMaximum; -} +void AxisData::setManualMaximum(qreal newManualMaximum) { m_manualMaximum = newManualMaximum; } -qreal AxisData::manualMinimum() const -{ - return m_manualMinimum; -} +qreal AxisData::manualMinimum() const { return m_manualMinimum; } -void AxisData::setManualMinimum(qreal newManualMinimum) -{ - m_manualMinimum = newManualMinimum; -} +void AxisData::setManualMinimum(qreal newManualMinimum) { m_manualMinimum = newManualMinimum; } -qreal AxisData::manualStep() const -{ - return m_manualStep; -} +qreal AxisData::manualStep() const { return m_manualStep; } -void AxisData::setManualStep(qreal newManualStep) -{ - m_manualStep = newManualStep; -} +void AxisData::setManualStep(qreal newManualStep) { m_manualStep = newManualStep; } -bool AxisData::isMaximumAutomatic() const -{ - return m_isMaximumAutomatic; -} +bool AxisData::isMaximumAutomatic() const { return m_isMaximumAutomatic; } void AxisData::setIsMaximumAutomatic(bool newIsMaximumAutomatic) { m_isMaximumAutomatic = newIsMaximumAutomatic; } -bool AxisData::isMinimumAutomatic() const -{ - return m_isMinimumAutomatic; -} +bool AxisData::isMinimumAutomatic() const { return m_isMinimumAutomatic; } void AxisData::setIsMinimumAutomatic(bool newIsMinimumAutomatic) { m_isMinimumAutomatic = newIsMinimumAutomatic; } -bool AxisData::isStepAutomatic() const -{ - return m_isStepAutomatic; -} +bool AxisData::isStepAutomatic() const { return m_isStepAutomatic; } void AxisData::setIsStepAutomatic(bool newIsStepAutomatic) { m_isStepAutomatic = newIsStepAutomatic; } -AxisData::AxisType AxisData::type() const -{ - return m_type; -} +AxisData::AxisType AxisData::type() const { return m_type; } -} +} // namespace LimeReport diff --git a/limereport/lraxisdata.h b/limereport/lraxisdata.h index d7342a4..e4f17a1 100644 --- a/limereport/lraxisdata.h +++ b/limereport/lraxisdata.h @@ -4,8 +4,7 @@ #include namespace LimeReport { -class AxisData : public QObject -{ +class AxisData: public QObject { Q_OBJECT Q_PROPERTY(bool reverseDirection READ reverseDirection WRITE setReverseDirection) Q_PROPERTY(bool calculateAxisScale READ calculateAxisScale WRITE setCalculateAxisScale) @@ -21,10 +20,10 @@ public: XAxis = 1 }; - AxisData(AxisType type, QObject *parent = nullptr); + AxisData(AxisType type, QObject* parent = nullptr); QString toString() const; - void copy(AxisData *other); + void copy(AxisData* other); void update(); void update(qreal minValue, qreal maxValue); void updateForDesignMode(); @@ -88,6 +87,6 @@ private: bool m_isStepAutomatic; const AxisType m_type; }; -}; +}; // namespace LimeReport #endif // AXISDATA_H diff --git a/limereport/lrbanddesignintf.cpp b/limereport/lrbanddesignintf.cpp index ad13cad..e70735e 100644 --- a/limereport/lrbanddesignintf.cpp +++ b/limereport/lrbanddesignintf.cpp @@ -28,47 +28,49 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrbanddesignintf.h" -#include "lritemdesignintf.h" + #include "lrglobal.h" -#include +#include "lritemdesignintf.h" + #include #include #include +#include + namespace LimeReport { -BandMarker::BandMarker(BandDesignIntf *band, QGraphicsItem* parent) - :QGraphicsItem(parent),m_rect(0,0,30,30),m_band(band) +BandMarker::BandMarker(BandDesignIntf* band, QGraphicsItem* parent): + QGraphicsItem(parent), + m_rect(0, 0, 30, 30), + m_band(band) { setAcceptHoverEvents(true); } -QRectF BandMarker::boundingRect() const -{ - return m_rect; -} +QRectF BandMarker::boundingRect() const { return m_rect; } -void BandMarker::paint(QPainter *painter, const QStyleOptionGraphicsItem* /**option*/, QWidget* /*widget*/) +void BandMarker::paint(QPainter* painter, const QStyleOptionGraphicsItem* /**option*/, + QWidget* /*widget*/) { painter->save(); painter->setOpacity(Const::BAND_MARKER_OPACITY); - painter->fillRect(boundingRect(),m_color); + painter->fillRect(boundingRect(), m_color); painter->setOpacity(1); - painter->setPen(QPen(QBrush(Qt::lightGray),2)); - painter->fillRect(QRectF( - boundingRect().bottomLeft().x(), - boundingRect().bottomLeft().y()-4, - boundingRect().width(),4), Qt::lightGray - ); + painter->setPen(QPen(QBrush(Qt::lightGray), 2)); + painter->fillRect(QRectF(boundingRect().bottomLeft().x(), boundingRect().bottomLeft().y() - 4, + boundingRect().width(), 4), + Qt::lightGray); painter->setRenderHint(QPainter::Antialiasing); - qreal size = (boundingRect().width()setBrush(Qt::white); painter->setPen(Qt::white); - painter->drawEllipse(r.adjusted(5,5,-5,-5)); - if (m_band->isSelected()){ + painter->drawEllipse(r.adjusted(5, 5, -5, -5)); + if (m_band->isSelected()) { painter->setBrush(LimeReport::Const::SELECTION_COLOR); - painter->drawEllipse(r.adjusted(7,7,-7,-7)); + painter->drawEllipse(r.adjusted(7, 7, -7, -7)); } painter->restore(); @@ -76,7 +78,7 @@ void BandMarker::paint(QPainter *painter, const QStyleOptionGraphicsItem* /**opt void BandMarker::setHeight(qreal height) { - if (m_rect.height()!=height){ + if (m_rect.height() != height) { prepareGeometryChange(); m_rect.setHeight(height); } @@ -84,7 +86,7 @@ void BandMarker::setHeight(qreal height) void BandMarker::setWidth(qreal width) { - if (m_rect.width()!=width){ + if (m_rect.width() != width) { prepareGeometryChange(); m_rect.setWidth(width); } @@ -92,32 +94,32 @@ void BandMarker::setWidth(qreal width) void BandMarker::setColor(QColor color) { - if (m_color!=color){ + if (m_color != color) { m_color = color; update(boundingRect()); } } -void BandMarker::mousePressEvent(QGraphicsSceneMouseEvent *event) +void BandMarker::mousePressEvent(QGraphicsSceneMouseEvent* event) { - if (event->button()==Qt::LeftButton) { + if (event->button() == Qt::LeftButton) { if (!(event->modifiers() & Qt::ControlModifier)) m_band->scene()->clearSelection(); m_band->setSelected(true); m_oldBandPos = m_band->pos(); - update(0,0,boundingRect().width(),boundingRect().width()); + update(0, 0, boundingRect().width(), boundingRect().width()); } } -void BandMarker::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +void BandMarker::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { m_band->contextMenuEvent(event); } void BandMarker::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { - if (QRectF(0, height()-10, width(), 10).contains(event->pos())){ - setCursor(Qt::SizeVerCursor); + if (QRectF(0, height() - 10, width(), 10).contains(event->pos())) { + setCursor(Qt::SizeVerCursor); } else { unsetCursor(); } @@ -126,11 +128,11 @@ void BandMarker::hoverMoveEvent(QGraphicsSceneHoverEvent* event) void BandMarker::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { qreal delta = event->pos().y() - event->lastPos().y(); - if (hasCursor()){ + if (hasCursor()) { m_band->setHeight(m_band->height() + delta); } else { if (!m_band->isFixedPos()) - m_band->setItemPos(QPointF(m_band->pos().x(),m_band->pos().y()+delta)); + m_band->setItemPos(QPointF(m_band->pos().x(), m_band->pos().y() + delta)); } } @@ -140,8 +142,9 @@ void BandMarker::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) m_band->posChanged(m_band, m_band->pos(), m_oldBandPos); } -BandDesignIntf::BandDesignIntf(BandsType bandType, const QString &xmlTypeName, QObject* owner, QGraphicsItem *parent) : - ItemsContainerDesignInft(xmlTypeName, owner,parent), +BandDesignIntf::BandDesignIntf(BandsType bandType, const QString& xmlTypeName, QObject* owner, + QGraphicsItem* parent): + ItemsContainerDesignInft(xmlTypeName, owner, parent), m_bandType(bandType), m_bandIndex(static_cast(bandType)), m_dataSourceName(""), @@ -174,7 +177,8 @@ BandDesignIntf::BandDesignIntf(BandsType bandType, const QString &xmlTypeName, Q if (parent) { BaseDesignIntf* parentItem = dynamic_cast(parent); - if (parentItem) setWidth(parentItem->width()); + if (parentItem) + setWidth(parentItem->width()); } setBackgroundMode(BaseDesignIntf::TransparentMode); @@ -185,15 +189,19 @@ BandDesignIntf::BandDesignIntf(BandsType bandType, const QString &xmlTypeName, Q m_bandMarker = new BandMarker(this); m_bandMarker->setColor(Qt::magenta); m_bandMarker->setHeight(height()); - m_bandMarker->setPos(pos().x()-m_bandMarker->width() - (itemMode() == ItemModes::PrintMode?boundingRect().width() : 0),pos().y()); - if (scene()) scene()->addItem(m_bandMarker); + m_bandMarker->setPos(pos().x() - m_bandMarker->width() + - (itemMode() == ItemModes::PrintMode ? boundingRect().width() : 0), + pos().y()); + if (scene()) + scene()->addItem(m_bandMarker); m_bandNameLabel = new BandNameLabel(this); m_bandNameLabel->setVisible(false); - if (scene()) scene()->addItem(m_bandNameLabel); + if (scene()) + scene()->addItem(m_bandNameLabel); m_alternateBackgroundColor = backgroundColor(); - connect(this, SIGNAL(propertyObjectNameChanged(QString, QString)), - this, SLOT(slotPropertyObjectNameChanged(const QString&,const QString&))); + connect(this, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPropertyObjectNameChanged(const QString&, const QString&))); } BandDesignIntf::~BandDesignIntf() @@ -202,16 +210,20 @@ BandDesignIntf::~BandDesignIntf() delete m_bandNameLabel; } -int extractItemIndex(const BaseDesignIntf* item){ +int extractItemIndex(const BaseDesignIntf* item) +{ QString objectName = extractClassName(item->metaObject()->className()); QString value = item->objectName().right(item->objectName().size() - objectName.size()); return value.toInt(); } -QString BandDesignIntf::translateBandName(const BaseDesignIntf* item) const{ - QString defaultBandName = extractClassName(item->metaObject()->className()).toLatin1()+QString::number(extractItemIndex(item)); - if (item->objectName().compare(defaultBandName) == 0){ - return tr(extractClassName(item->metaObject()->className()).toLatin1())+QString::number(extractItemIndex(item)); +QString BandDesignIntf::translateBandName(const BaseDesignIntf* item) const +{ + QString defaultBandName = extractClassName(item->metaObject()->className()).toLatin1() + + QString::number(extractItemIndex(item)); + if (item->objectName().compare(defaultBandName) == 0) { + return tr(extractClassName(item->metaObject()->className()).toLatin1()) + + QString::number(extractItemIndex(item)); } else { return item->objectName(); } @@ -219,75 +231,82 @@ QString BandDesignIntf::translateBandName(const BaseDesignIntf* item) const{ void BandDesignIntf::setBackgroundModeProperty(BaseDesignIntf::BGMode value) { - if (value!=backgroundMode()){ + if (value != backgroundMode()) { BaseDesignIntf::BGMode oldValue = backgroundMode(); setBackgroundMode(value); - notify("backgroundMode",oldValue,value); + notify("backgroundMode", oldValue, value); } } void BandDesignIntf::setBackgroundOpacity(int value) { - if (opacity()!=value){ + if (opacity() != value) { int oldValue = opacity(); setOpacity(value); - notify("backgroundOpacity",oldValue,value); + notify("backgroundOpacity", oldValue, value); } } -bool BandDesignIntf::isNeedUpdateSize(RenderPass pass) const{ - foreach(BaseDesignIntf* item, childBaseItems()){ - if (item->isNeedUpdateSize(pass)) return true; +bool BandDesignIntf::isNeedUpdateSize(RenderPass pass) const +{ + foreach (BaseDesignIntf* item, childBaseItems()) { + if (item->isNeedUpdateSize(pass)) + return true; } return false; } -void BandDesignIntf::copyBandAttributes(BandDesignIntf *source) +void BandDesignIntf::copyBandAttributes(BandDesignIntf* source) { this->copyBookmarks(source); this->setBackgroundColor(source->backgroundColor()); } -void BandDesignIntf::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void BandDesignIntf::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { prepareRect(painter, option, widget); - if (itemMode() & DesignMode){ + if (itemMode() & DesignMode) { painter->save(); QString bandText = bandTitle(); QFont font("Arial", 7 * Const::fontFACTOR, -1, true); QFontMetrics fontMetrics(font); QVector bandNameRects; - bandNameRects.push_back(QRectF(8,8,fontMetrics.boundingRect(" "+bandText+" ").width(),fontMetrics.height())); - //bandNameRects.push_back(QRectF(width()-fontMetrics.width(" "+bandText+" "),2,fontMetrics.width(" "+bandText+" "),fontMetrics.height())); - //bandNameRects.push_back(QRectF(2,height()-fontMetrics.height(),fontMetrics.width(" "+bandText+" "),fontMetrics.height())); - //bandNameRects.push_back(QRectF(width()-fontMetrics.width(" "+bandText+" "),height()-fontMetrics.height(),fontMetrics.width(" "+bandText+" "),fontMetrics.height())); - //if (bandNameRects[0].intersects(bandNameRects[2])) bandNameRects.remove(2,2); - //if (isSelected()) ppainter->setPen(QColor(167,244,167)); - // else ppainter->setPen(QColor(220,220,220)); + bandNameRects.push_back(QRectF(8, 8, fontMetrics.boundingRect(" " + bandText + " ").width(), + fontMetrics.height())); + // bandNameRects.push_back(QRectF(width()-fontMetrics.width(" "+bandText+" + // "),2,fontMetrics.width(" "+bandText+" "),fontMetrics.height())); + // bandNameRects.push_back(QRectF(2,height()-fontMetrics.height(),fontMetrics.width(" + // "+bandText+" "),fontMetrics.height())); + // bandNameRects.push_back(QRectF(width()-fontMetrics.width(" "+bandText+" + // "),height()-fontMetrics.height(),fontMetrics.width(" "+bandText+" + // "),fontMetrics.height())); if (bandNameRects[0].intersects(bandNameRects[2])) + // bandNameRects.remove(2,2); if (isSelected()) ppainter->setPen(QColor(167,244,167)); + // else ppainter->setPen(QColor(220,220,220)); painter->setFont(font); - for (int i=0;isetRenderHint(QPainter::Antialiasing); painter->setBrush(bandColor()); painter->setOpacity(Const::BAND_NAME_AREA_OPACITY); - painter->drawRoundedRect(labelRect,8,8); + painter->drawRoundedRect(labelRect, 8, 8); painter->setOpacity(Const::BAND_NAME_TEXT_OPACITY); painter->setPen(Qt::black); - painter->drawText(bandNameRects[i],Qt::AlignHCenter,bandText); + painter->drawText(bandNameRects[i], Qt::AlignHCenter, bandText); } } painter->restore(); } - BaseDesignIntf::paint(painter,option,widget); + BaseDesignIntf::paint(painter, option, widget); } QRectF BandDesignIntf::boundingRect() const { - return ItemsContainerDesignInft::boundingRect().adjusted(0,-4,0,4); + return ItemsContainerDesignInft::boundingRect().adjusted(0, -4, 0, 4); } void BandDesignIntf::translateBandsName() @@ -307,32 +326,21 @@ void BandDesignIntf::translateBandsName() tr("TearOffBand"); } -BandDesignIntf::BandsType BandDesignIntf::bandType() const -{ - return m_bandType; -} +BandDesignIntf::BandsType BandDesignIntf::bandType() const { return m_bandType; } -QString BandDesignIntf::bandTitle() const +QString BandDesignIntf::bandTitle() const { QString result = translateBandName(this); - if (parentBand()) result +=tr(" connected to ") + translateBandName(parentBand()); + if (parentBand()) + result += tr(" connected to ") + translateBandName(parentBand()); return result; } -QIcon BandDesignIntf::bandIcon() const -{ - return QIcon(); -} +QIcon BandDesignIntf::bandIcon() const { return QIcon(); } -int BandDesignIntf::bandIndex() const -{ - return m_bandIndex; -} +int BandDesignIntf::bandIndex() const { return m_bandIndex; } -void BandDesignIntf::setBandIndex(int value) -{ - m_bandIndex=value; -} +void BandDesignIntf::setBandIndex(int value) { m_bandIndex = value; } void BandDesignIntf::changeBandIndex(int value, bool firstTime) { @@ -343,17 +351,14 @@ void BandDesignIntf::changeBandIndex(int value, bool firstTime) indexOffset = value - m_bandIndex; - foreach(BandDesignIntf* band, childBands()){ - int newIndex = band->bandIndex()+indexOffset; + foreach (BandDesignIntf* band, childBands()) { + int newIndex = band->bandIndex() + indexOffset; band->changeBandIndex(newIndex); } setBandIndex(value); } -bool BandDesignIntf::isUnique() const -{ - return true; -} +bool BandDesignIntf::isUnique() const { return true; } void BandDesignIntf::setItemMode(BaseDesignIntf::ItemMode mode) { @@ -361,78 +366,82 @@ void BandDesignIntf::setItemMode(BaseDesignIntf::ItemMode mode) updateBandMarkerGeometry(); } -QString BandDesignIntf::datasourceName(){ - return m_dataSourceName; -} +QString BandDesignIntf::datasourceName() { return m_dataSourceName; } -void BandDesignIntf::setDataSourceName(const QString &datasource){ - m_dataSourceName=datasource; -} +void BandDesignIntf::setDataSourceName(const QString& datasource) { m_dataSourceName = datasource; } -void BandDesignIntf::setKeepBottomSpace(bool value){ - if (m_keepBottomSpace!=value){ - m_keepBottomSpace=value; +void BandDesignIntf::setKeepBottomSpace(bool value) +{ + if (m_keepBottomSpace != value) { + m_keepBottomSpace = value; if (!isLoading()) - notify("keepBottomSpace",!value,value); + notify("keepBottomSpace", !value, value); } } -void BandDesignIntf::addChildBand(BandDesignIntf *band) +void BandDesignIntf::addChildBand(BandDesignIntf* band) { m_childBands.append(band); - connect(band,SIGNAL(destroyed(QObject*)),this,SLOT(childBandDeleted(QObject*))); + connect(band, SIGNAL(destroyed(QObject*)), this, SLOT(childBandDeleted(QObject*))); } -void BandDesignIntf::removeChildBand(BandDesignIntf *band) +void BandDesignIntf::removeChildBand(BandDesignIntf* band) { m_childBands.removeAt(m_childBands.indexOf(band)); } -void BandDesignIntf::setParentBand(BandDesignIntf *band) +void BandDesignIntf::setParentBand(BandDesignIntf* band) { - m_parentBand=band; - if (band){ - if (parentBandName().compare(band->objectName(),Qt::CaseInsensitive)!=0) - setParentBandName(band->objectName()); + m_parentBand = band; + if (band) { + if (parentBandName().compare(band->objectName(), Qt::CaseInsensitive) != 0) + setParentBandName(band->objectName()); band->addChildBand(this); } } -void BandDesignIntf::setParentBandName(const QString &parentBandName) +void BandDesignIntf::setParentBandName(const QString& parentBandName) { - m_parentBandName=parentBandName; - if (itemMode()&DesignMode && !m_parentBandName.isEmpty()){ - if ((parentBand() == 0 )||(parentBand()->objectName()!= parentBandName)) + m_parentBandName = parentBandName; + if (itemMode() & DesignMode && !m_parentBandName.isEmpty()) { + if ((parentBand() == 0) || (parentBand()->objectName() != parentBandName)) setParentBand(findParentBand()); } } -QString BandDesignIntf::parentBandName(){ - if (!m_parentBand) return m_parentBandName; - else return m_parentBand->objectName(); +QString BandDesignIntf::parentBandName() +{ + if (!m_parentBand) + return m_parentBandName; + else + return m_parentBand->objectName(); } bool BandDesignIntf::isConnectedToBand(BandDesignIntf::BandsType bandType) const { - foreach(BandDesignIntf* band,childBands()) if (band->bandType()==bandType) return true; + foreach (BandDesignIntf* band, childBands()) + if (band->bandType() == bandType) + return true; return false; } -int BandDesignIntf::maxChildIndex(BandDesignIntf::BandsType bandType) const{ +int BandDesignIntf::maxChildIndex(BandDesignIntf::BandsType bandType) const +{ int curIndex = bandIndex(); - foreach(BandDesignIntf* childBand, childBands()){ - if ( (childBand->bandIndex() > bandIndex()) && (childBand->bandType() < bandType) ){ - curIndex = std::max(curIndex,childBand->maxChildIndex()); + foreach (BandDesignIntf* childBand, childBands()) { + if ((childBand->bandIndex() > bandIndex()) && (childBand->bandType() < bandType)) { + curIndex = std::max(curIndex, childBand->maxChildIndex()); } } return curIndex; } -int BandDesignIntf::maxChildIndex(QSet ignoredBands) const{ +int BandDesignIntf::maxChildIndex(QSet ignoredBands) const +{ int curIndex = bandIndex(); - foreach(BandDesignIntf* childBand, childBands()){ - if (!ignoredBands.contains(childBand->bandType())){ - curIndex = std::max(curIndex,childBand->maxChildIndex(ignoredBands)); + foreach (BandDesignIntf* childBand, childBands()) { + if (!ignoredBands.contains(childBand->bandType())) { + curIndex = std::max(curIndex, childBand->maxChildIndex(ignoredBands)); } } return curIndex; @@ -443,7 +452,7 @@ int BandDesignIntf::rootIndex(BandDesignIntf* parentBand) return rootBand(parentBand)->bandIndex(); } -BandDesignIntf *BandDesignIntf::rootBand(BandDesignIntf* parentBand) +BandDesignIntf* BandDesignIntf::rootBand(BandDesignIntf* parentBand) { BandDesignIntf* currentBand = this; while (currentBand->parentBand() && currentBand->parentBand() != parentBand) @@ -451,10 +460,11 @@ BandDesignIntf *BandDesignIntf::rootBand(BandDesignIntf* parentBand) return currentBand; } -int BandDesignIntf::minChildIndex(BandDesignIntf::BandsType bandType){ +int BandDesignIntf::minChildIndex(BandDesignIntf::BandsType bandType) +{ int curIndex = bandIndex(); - foreach(BandDesignIntf* childBand, childBands()){ - if (curIndex > childBand->bandIndex() && (childBand->bandType() > bandType)){ + foreach (BandDesignIntf* childBand, childBands()) { + if (curIndex > childBand->bandIndex() && (childBand->bandType() > bandType)) { curIndex = childBand->bandIndex(); } } @@ -464,33 +474,33 @@ int BandDesignIntf::minChildIndex(BandDesignIntf::BandsType bandType){ int BandDesignIntf::minChildIndex(QSet ignoredBands) { int curIndex = bandIndex(); - foreach(BandDesignIntf* childBand, childBands()){ - if (!ignoredBands.contains(childBand->bandType()) && childBand->bandIndex() < bandIndex()){ + foreach (BandDesignIntf* childBand, childBands()) { + if (!ignoredBands.contains(childBand->bandType()) && childBand->bandIndex() < bandIndex()) { curIndex = std::min(curIndex, childBand->minChildIndex(ignoredBands)); } } return curIndex; } - - -QList BandDesignIntf::childrenByType(BandDesignIntf::BandsType type) +QList BandDesignIntf::childrenByType(BandDesignIntf::BandsType type) { QList resList; - foreach(BandDesignIntf* item,childBands()){ - if (item->bandType()==type) resList<bandType() == type) + resList << item; } - std::sort(resList.begin(),resList.end(),bandIndexLessThen); + std::sort(resList.begin(), resList.end(), bandIndexLessThen); return resList; } bool BandDesignIntf::canBeSplitted(int height) const { - if (isSplittable()){ - foreach(QGraphicsItem* qgItem,childItems()){ - BaseDesignIntf* item=dynamic_cast(qgItem); + if (isSplittable()) { + foreach (QGraphicsItem* qgItem, childItems()) { + BaseDesignIntf* item = dynamic_cast(qgItem); if (item) - if ((item->minHeight()>height) && (item->minHeight()>(this->height()-height))) return false; + if ((item->minHeight() > height) && (item->minHeight() > (this->height() - height))) + return false; } } return isSplittable(); @@ -498,42 +508,41 @@ bool BandDesignIntf::canBeSplitted(int height) const bool BandDesignIntf::isEmpty() const { - if (!isVisible()) return true; - foreach(QGraphicsItem* qgItem,childItems()){ + if (!isVisible()) + return true; + foreach (QGraphicsItem* qgItem, childItems()) { BaseDesignIntf* item = dynamic_cast(qgItem); - if ((item)&&(!item->isEmpty())) return false; + if ((item) && (!item->isEmpty())) + return false; } return true; } -bool BandDesignIntf::isNeedRender() const -{ - return true; -} +bool BandDesignIntf::isNeedRender() const { return true; } void BandDesignIntf::setTryToKeepTogether(bool value) { - if (m_tryToKeepTogether != value){ + if (m_tryToKeepTogether != value) { m_tryToKeepTogether = value; if (!isLoading()) notify("keepSubdetailTogether", !value, value); } } -bool BandDesignIntf::tryToKeepTogether() -{ - return m_tryToKeepTogether; -} +bool BandDesignIntf::tryToKeepTogether() { return m_tryToKeepTogether; } -void BandDesignIntf::checkEmptyTable(){ +void BandDesignIntf::checkEmptyTable() +{ bool isEmpty = true; bool allItemsIsText = true; foreach (QGraphicsItem* qgItem, childItems()) { BaseDesignIntf* item = dynamic_cast(qgItem); - if (item && !item->isEmpty()) isEmpty = false; - if (!item) allItemsIsText = false; + if (item && !item->isEmpty()) + isEmpty = false; + if (!item) + allItemsIsText = false; } - if (isEmpty && allItemsIsText){ + if (isEmpty && allItemsIsText) { foreach (QGraphicsItem* qgItem, childItems()) { ContentItemDesignIntf* item = dynamic_cast(qgItem); item->setHeight(0); @@ -543,46 +552,43 @@ void BandDesignIntf::checkEmptyTable(){ void BandDesignIntf::setColumnsCount(int value) { - if (m_columnsCount!=value && value>0){ + if (m_columnsCount != value && value > 0) { qreal oldValue = m_columnsCount; qreal fullWidth = m_columnsCount * width(); m_columnsCount = value; - if (!isLoading()){ - setWidth(fullWidth/m_columnsCount); - notify("columnsCount",oldValue,value); + if (!isLoading()) { + setWidth(fullWidth / m_columnsCount); + notify("columnsCount", oldValue, value); } } } void BandDesignIntf::setColumnsFillDirection(BandDesignIntf::BandColumnsLayoutType value) { - if (m_columnsFillDirection!=value){ + if (m_columnsFillDirection != value) { qreal oldValue = m_columnsFillDirection; m_columnsFillDirection = value; if (!isLoading()) - notify("columnsFillDirection",oldValue,value); + notify("columnsFillDirection", oldValue, value); } - } -void BandDesignIntf::moveItemsDown(qreal startPos, qreal offset){ - foreach (QGraphicsItem* item, childItems()){ - if (item->pos().y()>=startPos) - item->setPos(item->x(),item->y()+offset); - } +void BandDesignIntf::moveItemsDown(qreal startPos, qreal offset) +{ + foreach (QGraphicsItem* item, childItems()) { + if (item->pos().y() >= startPos) + item->setPos(item->x(), item->y() + offset); + } } -void BandDesignIntf::preparePopUpMenu(QMenu &menu) +void BandDesignIntf::preparePopUpMenu(QMenu& menu) { QList disabledActions; - disabledActions << tr("Bring to top") << - tr("Send to back") << - tr("Cut") << - tr("Copy"); + disabledActions << tr("Bring to top") << tr("Send to back") << tr("Cut") << tr("Copy"); foreach (QAction* action, menu.actions()) { - action->setEnabled(!disabledActions.contains(action->text())); + action->setEnabled(!disabledActions.contains(action->text())); } menu.addSeparator(); @@ -606,70 +612,70 @@ void BandDesignIntf::preparePopUpMenu(QMenu &menu) currAction = menu.addAction(tr("Print if empty")); currAction->setCheckable(true); currAction->setChecked(printIfEmpty()); - } -void BandDesignIntf::processPopUpAction(QAction *action) +void BandDesignIntf::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Auto height")) == 0){ + if (action->text().compare(tr("Auto height")) == 0) { setProperty("autoHeight", action->isChecked()); } - if (action->text().compare(tr("Splittable")) == 0){ + if (action->text().compare(tr("Splittable")) == 0) { setProperty("splittable", action->isChecked()); } - if (action->text().compare(tr("Keep top space")) == 0){ + if (action->text().compare(tr("Keep top space")) == 0) { setProperty("keepTopSpace", action->isChecked()); } - if (action->text().compare(tr("Keep bottom space")) == 0){ + if (action->text().compare(tr("Keep bottom space")) == 0) { setProperty("keepBottomSpace", action->isChecked()); } - if (action->text().compare(tr("Keep top space")) == 0){ - setProperty("keepTopSpace",action->isChecked()); + if (action->text().compare(tr("Keep top space")) == 0) { + setProperty("keepTopSpace", action->isChecked()); } - if (action->text().compare(tr("Print if empty")) == 0){ + if (action->text().compare(tr("Print if empty")) == 0) { setProperty("printIfEmpty", action->isChecked()); } ItemsContainerDesignInft::processPopUpAction(action); } -BaseDesignIntf* BandDesignIntf::cloneUpperPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* BandDesignIntf::cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent) { int maxBottom = 0; - BandDesignIntf* upperPart = dynamic_cast(createSameTypeItem(owner,parent)); + BandDesignIntf* upperPart = dynamic_cast(createSameTypeItem(owner, parent)); BaseDesignIntf* upperItem = 0; upperPart->initFromItem(this); - foreach(QGraphicsItem* qgItem,childItems()){ + foreach (QGraphicsItem* qgItem, childItems()) { BaseDesignIntf* item = dynamic_cast(qgItem); - if (item){ - if (item->geometry().bottom()<=height){ - upperItem = item->cloneItem(item->itemMode(),upperPart,upperPart); - if (maxBottomgeometry().bottom()) maxBottom = upperItem->geometry().bottom(); - } - else if ((item->geometry().top()geometry().bottom()>height)){ - int sliceHeight = height-item->geometry().top(); - if (!item->isSplittable()){ - if (sliceHeight>(this->height()-sliceHeight)){ - upperItem = item->cloneItem(item->itemMode(),upperPart,upperPart); + if (item) { + if (item->geometry().bottom() <= height) { + upperItem = item->cloneItem(item->itemMode(), upperPart, upperPart); + if (maxBottom < upperItem->geometry().bottom()) + maxBottom = upperItem->geometry().bottom(); + } else if ((item->geometry().top() < height) && (item->geometry().bottom() > height)) { + int sliceHeight = height - item->geometry().top(); + if (!item->isSplittable()) { + if (sliceHeight > (this->height() - sliceHeight)) { + upperItem = item->cloneItem(item->itemMode(), upperPart, upperPart); upperItem->setHeight(height); } else { - item->cloneEmpty(sliceHeight,upperPart,upperPart); //for table - //qgItem->setPos(item->pos().x(),item->pos().y()+((height+1)-item->geometry().top())); - moveItemsDown(item->pos().y(),(height+1)-item->geometry().top()); + item->cloneEmpty(sliceHeight, upperPart, upperPart); // for table + // qgItem->setPos(item->pos().x(),item->pos().y()+((height+1)-item->geometry().top())); + moveItemsDown(item->pos().y(), (height + 1) - item->geometry().top()); } - } else if (item->canBeSplitted(sliceHeight)){ - upperItem = item->cloneUpperPart(sliceHeight,upperPart,upperPart); - if (maxBottomgeometry().bottom()) maxBottom = upperItem->geometry().bottom(); - m_slicedItems.insert(upperItem->objectName(),upperItem); + } else if (item->canBeSplitted(sliceHeight)) { + upperItem = item->cloneUpperPart(sliceHeight, upperPart, upperPart); + if (maxBottom < upperItem->geometry().bottom()) + maxBottom = upperItem->geometry().bottom(); + m_slicedItems.insert(upperItem->objectName(), upperItem); } else { - item->cloneEmpty(sliceHeight,upperPart,upperPart); //for table - moveItemsDown(item->pos().y(),(height+1)-item->geometry().top()); - //qgItem->setPos(item->pos().x(),item->pos().y()+((height+1)-item->geometry().top())); + item->cloneEmpty(sliceHeight, upperPart, upperPart); // for table + moveItemsDown(item->pos().y(), (height + 1) - item->geometry().top()); + // qgItem->setPos(item->pos().x(),item->pos().y()+((height+1)-item->geometry().top())); } } } @@ -678,41 +684,43 @@ BaseDesignIntf* BandDesignIntf::cloneUpperPart(int height, QObject *owner, QGrap return upperPart; } -bool itemLessThen(QGraphicsItem* i1, QGraphicsItem* i2){ - return i1->pos().y()pos().y(); -} +bool itemLessThen(QGraphicsItem* i1, QGraphicsItem* i2) { return i1->pos().y() < i2->pos().y(); } -BaseDesignIntf *BandDesignIntf::cloneBottomPart(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* BandDesignIntf::cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent) { - BandDesignIntf* bottomPart = dynamic_cast(createSameTypeItem(owner,parent)); + BandDesignIntf* bottomPart = dynamic_cast(createSameTypeItem(owner, parent)); bottomPart->initFromItem(this); QList bandItems; bandItems = childItems(); - std::sort(bandItems.begin(),bandItems.end(), itemLessThen); + std::sort(bandItems.begin(), bandItems.end(), itemLessThen); - foreach(QGraphicsItem* qgItem, bandItems){ + foreach (QGraphicsItem* qgItem, bandItems) { BaseDesignIntf* item = dynamic_cast(qgItem); - if (item){ - if (item->geometry().top()>height){ - BaseDesignIntf* tmpItem = item->cloneItem(item->itemMode(),bottomPart,bottomPart); - tmpItem->setPos(tmpItem->pos().x(), (tmpItem->pos().y()-height)+borderLineSize()); - } - else if ((item->geometry().top()<=height) && (item->geometry().bottom()>height)){ - int sliceHeight = height-item->geometry().top(); + if (item) { + if (item->geometry().top() > height) { + BaseDesignIntf* tmpItem = item->cloneItem(item->itemMode(), bottomPart, bottomPart); + tmpItem->setPos(tmpItem->pos().x(), + (tmpItem->pos().y() - height) + borderLineSize()); + } else if ((item->geometry().top() <= height) && (item->geometry().bottom() > height)) { + int sliceHeight = height - item->geometry().top(); if (item->isSplittable() && item->canBeSplitted(sliceHeight)) { - BaseDesignIntf* tmpItem=item->cloneBottomPart(sliceHeight,bottomPart,bottomPart); - tmpItem->setPos(tmpItem->pos().x(),borderLineSize()); + BaseDesignIntf* tmpItem + = item->cloneBottomPart(sliceHeight, bottomPart, bottomPart); + tmpItem->setPos(tmpItem->pos().x(), borderLineSize()); BaseDesignIntf* slicedItem = m_slicedItems.value(tmpItem->objectName()); - if (slicedItem){ - qreal sizeOffset = (slicedItem->height()+tmpItem->height()) - item->height(); - qreal bottomOffset = (height - slicedItem->pos().y())-m_slicedItems.value(tmpItem->objectName())->height(); - moveItemsDown(item->pos().y()+item->height(), sizeOffset + bottomOffset); + if (slicedItem) { + qreal sizeOffset + = (slicedItem->height() + tmpItem->height()) - item->height(); + qreal bottomOffset = (height - slicedItem->pos().y()) + - m_slicedItems.value(tmpItem->objectName())->height(); + moveItemsDown(item->pos().y() + item->height(), sizeOffset + bottomOffset); } } else { - BaseDesignIntf* tmpItem = item->cloneItem(item->itemMode(),bottomPart,bottomPart); - tmpItem->setPos(tmpItem->pos().x(),borderLineSize()); + BaseDesignIntf* tmpItem + = item->cloneItem(item->itemMode(), bottomPart, bottomPart); + tmpItem->setPos(tmpItem->pos().x(), borderLineSize()); } } } @@ -733,62 +741,62 @@ void BandDesignIntf::objectLoadFinished() BaseDesignIntf::objectLoadFinished(); } -void BandDesignIntf::emitBandRendered(BandDesignIntf* band) -{ - emit bandRendered(band); -} +void BandDesignIntf::emitBandRendered(BandDesignIntf* band) { emit bandRendered(band); } -void BandDesignIntf::emitBandReRendered(BandDesignIntf *oldBand, BandDesignIntf *newBand) +void BandDesignIntf::emitBandReRendered(BandDesignIntf* oldBand, BandDesignIntf* newBand) { emit bandReRendered(oldBand, newBand); } -void BandDesignIntf::setSplittable(bool value){ - if (m_splitable!=value){ +void BandDesignIntf::setSplittable(bool value) +{ + if (m_splitable != value) { bool oldValue = m_splitable; m_splitable = value; if (!isLoading()) - notify("splittable",oldValue,value); + notify("splittable", oldValue, value); } } bool bandIndexLessThen(const BandDesignIntf* b1, const BandDesignIntf* b2) { - return b1->bandIndex()bandIndex(); + return b1->bandIndex() < b2->bandIndex(); } void BandDesignIntf::trimToMaxHeight(int maxHeight) { - foreach(BaseDesignIntf* item,childBaseItems()){ - if (item->height()>maxHeight) item->setHeight(maxHeight); + foreach (BaseDesignIntf* item, childBaseItems()) { + if (item->height() > maxHeight) + item->setHeight(maxHeight); } } -void BandDesignIntf::setBandTypeText(const QString &value){ - m_bandTypeText=value; +void BandDesignIntf::setBandTypeText(const QString& value) +{ + m_bandTypeText = value; m_bandNameLabel->updateLabel(bandTitle()); } QSet BandDesignIntf::groupBands() { QSet result; - result< BandDesignIntf::subdetailBands() { QSet result; - result<(parent())->isLoading())){ - foreach(QObject* item, parent()->children()){ + if (parent() && (!dynamic_cast(parent())->isLoading())) { + foreach (QObject* item, parent()->children()) { BandDesignIntf* band = dynamic_cast(item); - if(band&&(band->objectName().compare(parentBandName(),Qt::CaseInsensitive)==0)) + if (band && (band->objectName().compare(parentBandName(), Qt::CaseInsensitive) == 0)) return band; } } @@ -797,55 +805,58 @@ BandDesignIntf* BandDesignIntf::findParentBand() void BandDesignIntf::updateBandMarkerGeometry() { - if (parentItem() && m_bandMarker){ - m_bandMarker->setPos(pos().x()-m_bandMarker->width() - (itemMode() == ItemModes::PrintMode?boundingRect().width() : 0),pos().y()); + if (parentItem() && m_bandMarker) { + m_bandMarker->setPos( + pos().x() - m_bandMarker->width() + - (itemMode() == ItemModes::PrintMode ? boundingRect().width() : 0), + pos().y()); m_bandMarker->setHeight(rect().height()); } } -void BandDesignIntf::geometryChangedEvent(QRectF, QRectF ) +void BandDesignIntf::geometryChangedEvent(QRectF, QRectF) { - if (((itemMode()&DesignMode) || (itemMode()&EditMode))&&parentItem()){ + if (((itemMode() & DesignMode) || (itemMode() & EditMode)) && parentItem()) { updateBandMarkerGeometry(); } foreach (BaseDesignIntf* item, childBaseItems()) { - if (item->itemAlign()!=DesignedItemAlign){ + if (item->itemAlign() != DesignedItemAlign) { item->updateItemAlign(); } } } -QVariant BandDesignIntf::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) +QVariant BandDesignIntf::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant& value) { - if ((change==ItemPositionChange)&&((itemMode()&DesignMode)||(itemMode()&EditMode))){ - if (m_bandMarker){ - m_bandMarker->setPos((value.toPointF().x()-m_bandMarker->boundingRect().width() - (itemMode() == ItemModes::PrintMode?boundingRect().width() : 0)), - value.toPointF().y()); + if ((change == ItemPositionChange) && ((itemMode() & DesignMode) || (itemMode() & EditMode))) { + if (m_bandMarker) { + m_bandMarker->setPos( + (value.toPointF().x() - m_bandMarker->boundingRect().width() + - (itemMode() == ItemModes::PrintMode ? boundingRect().width() : 0)), + value.toPointF().y()); } } - if (change==ItemSelectedChange){ - if (m_bandMarker){ - m_bandMarker->update(0,0, - m_bandMarker->boundingRect().width(), + if (change == ItemSelectedChange) { + if (m_bandMarker) { + m_bandMarker->update(0, 0, m_bandMarker->boundingRect().width(), m_bandMarker->boundingRect().width()); m_bandNameLabel->updateLabel(bandTitle()); m_bandNameLabel->setVisible(value.toBool()); - } } - if (change==ItemChildAddedChange || change==ItemChildRemovedChange){ + if (change == ItemChildAddedChange || change == ItemChildRemovedChange) { update(rect()); } - return BaseDesignIntf::itemChange(change,value); + return BaseDesignIntf::itemChange(change, value); } void BandDesignIntf::initMode(ItemMode mode) { BaseDesignIntf::initMode(mode); - if ((mode==PreviewMode)||(mode==PrintMode)){ + if ((mode == PreviewMode) || (mode == PrintMode)) { m_bandMarker->setVisible(false); } else { - if (!m_bandMarker->scene() && this->scene()){ + if (!m_bandMarker->scene() && this->scene()) { this->scene()->addItem(m_bandMarker); m_bandMarker->setParentItem(this->parentItem()); m_bandMarker->setHeight(this->height()); @@ -854,262 +865,212 @@ void BandDesignIntf::initMode(ItemMode mode) } } -QColor BandDesignIntf::bandColor() const -{ - return Qt::darkBlue; -} +QColor BandDesignIntf::bandColor() const { return Qt::darkBlue; } void BandDesignIntf::setMarkerColor(QColor color) { - if (m_bandMarker) m_bandMarker->setColor(color); + if (m_bandMarker) + m_bandMarker->setColor(color); } -void BandDesignIntf::childBandDeleted(QObject *band) +void BandDesignIntf::childBandDeleted(QObject* band) { m_childBands.removeAt(m_childBands.indexOf(reinterpret_cast(band))); } -bool BandDesignIntf::useAlternateBackgroundColor() const -{ - return m_useAlternateBackgroundColor; -} +bool BandDesignIntf::useAlternateBackgroundColor() const { return m_useAlternateBackgroundColor; } void BandDesignIntf::setUseAlternateBackgroundColor(bool useAlternateBackgroundColor) { - if (m_useAlternateBackgroundColor != useAlternateBackgroundColor){ + if (m_useAlternateBackgroundColor != useAlternateBackgroundColor) { QColor oldValue = m_useAlternateBackgroundColor; - m_useAlternateBackgroundColor=useAlternateBackgroundColor; + m_useAlternateBackgroundColor = useAlternateBackgroundColor; if (!isLoading()) - notify("useAlternateBackgroundColor",oldValue,useAlternateBackgroundColor); + notify("useAlternateBackgroundColor", oldValue, useAlternateBackgroundColor); } } QColor BandDesignIntf::alternateBackgroundColor() const { - if (metaObject()->indexOfProperty("alternateBackgroundColor")!=-1) + if (metaObject()->indexOfProperty("alternateBackgroundColor") != -1) return m_alternateBackgroundColor; else return backgroundColor(); } -void BandDesignIntf::setAlternateBackgroundColor(const QColor &alternateBackgroundColor) +void BandDesignIntf::setAlternateBackgroundColor(const QColor& alternateBackgroundColor) { - if (m_alternateBackgroundColor != alternateBackgroundColor){ + if (m_alternateBackgroundColor != alternateBackgroundColor) { QColor oldValue = m_alternateBackgroundColor; - m_alternateBackgroundColor=alternateBackgroundColor; + m_alternateBackgroundColor = alternateBackgroundColor; if (!isLoading()) - notify("alternateBackgroundColor",oldValue,alternateBackgroundColor); + notify("alternateBackgroundColor", oldValue, alternateBackgroundColor); } } -qreal BandDesignIntf::bottomSpace() -{ - return m_bottomSpace; -} +qreal BandDesignIntf::bottomSpace() { return m_bottomSpace; } -void BandDesignIntf::slotPropertyObjectNameChanged(const QString &, const QString& newName) +void BandDesignIntf::slotPropertyObjectNameChanged(const QString&, const QString& newName) { update(); if (m_bandNameLabel) m_bandNameLabel->updateLabel(newName); } -int BandDesignIntf::shiftItems() const -{ - return m_shiftItems; -} +int BandDesignIntf::shiftItems() const { return m_shiftItems; } -void BandDesignIntf::setShiftItems(int shiftItems) -{ - m_shiftItems = shiftItems; -} +void BandDesignIntf::setShiftItems(int shiftItems) { m_shiftItems = shiftItems; } -bool BandDesignIntf::keepTopSpace() const -{ - return m_keepTopSpace; -} +bool BandDesignIntf::keepTopSpace() const { return m_keepTopSpace; } void BandDesignIntf::setKeepTopSpace(bool value) { - if (m_keepTopSpace != value){ + if (m_keepTopSpace != value) { m_keepTopSpace = value; if (!isLoading()) - notify("keepTopSpace",!value,value); + notify("keepTopSpace", !value, value); } } -void BandDesignIntf::setBottomSpace(qreal bottomSpace) -{ - m_bottomSpace = bottomSpace; -} +void BandDesignIntf::setBottomSpace(qreal bottomSpace) { m_bottomSpace = bottomSpace; } -bool BandDesignIntf::repeatOnEachRow() const -{ - return m_repeatOnEachRow; -} +bool BandDesignIntf::repeatOnEachRow() const { return m_repeatOnEachRow; } void BandDesignIntf::setRepeatOnEachRow(bool repeatOnEachRow) { - if (m_repeatOnEachRow != repeatOnEachRow){ + if (m_repeatOnEachRow != repeatOnEachRow) { m_repeatOnEachRow = repeatOnEachRow; if (!isLoading()) notify("repeatOnEachRow", !m_repeatOnEachRow, m_repeatOnEachRow); } } -bool BandDesignIntf::printAlways() const -{ - return m_printAlways; -} +bool BandDesignIntf::printAlways() const { return m_printAlways; } void BandDesignIntf::setPrintAlways(bool printAlways) { - if (m_printAlways != printAlways){ + if (m_printAlways != printAlways) { m_printAlways = printAlways; if (!isLoading()) notify("printAlways", !m_printAlways, m_printAlways); } } -bool BandDesignIntf::startFromNewPage() const -{ - return m_startFromNewPage; -} +bool BandDesignIntf::startFromNewPage() const { return m_startFromNewPage; } void BandDesignIntf::setStartFromNewPage(bool startWithNewPage) { - if (m_startFromNewPage != startWithNewPage){ + if (m_startFromNewPage != startWithNewPage) { m_startFromNewPage = startWithNewPage; if (!isLoading()) notify("startFromNewPage", !startWithNewPage, startWithNewPage); } } -bool BandDesignIntf::startNewPage() const -{ - return m_startNewPage; -} +bool BandDesignIntf::startNewPage() const { return m_startNewPage; } void BandDesignIntf::setStartNewPage(bool startNewPage) { - if (m_startNewPage != startNewPage){ + if (m_startNewPage != startNewPage) { m_startNewPage = startNewPage; if (!isLoading()) notify("startNewPage", !startNewPage, startNewPage); } } -void BandDesignIntf::setAutoHeight(bool value){ - if (m_autoHeight != value){ - m_autoHeight=value; +void BandDesignIntf::setAutoHeight(bool value) +{ + if (m_autoHeight != value) { + m_autoHeight = value; if (!isLoading()) - notify("autoHeight",!value,value); + notify("autoHeight", !value, value); } } -bool BandDesignIntf::reprintOnEachPage() const -{ - return m_reprintOnEachPage; -} +bool BandDesignIntf::reprintOnEachPage() const { return m_reprintOnEachPage; } void BandDesignIntf::setReprintOnEachPage(bool reprintOnEachPage) { - if (m_reprintOnEachPage != reprintOnEachPage){ + if (m_reprintOnEachPage != reprintOnEachPage) { m_reprintOnEachPage = reprintOnEachPage; if (!isLoading()) notify("reprintOnEachPage", !m_reprintOnEachPage, m_reprintOnEachPage); } } -int BandDesignIntf::columnIndex() const -{ - return m_columnIndex; -} +int BandDesignIntf::columnIndex() const { return m_columnIndex; } -void BandDesignIntf::setColumnIndex(int columnIndex) -{ - m_columnIndex = columnIndex; -} +void BandDesignIntf::setColumnIndex(int columnIndex) { m_columnIndex = columnIndex; } -bool BandDesignIntf::printIfEmpty() const -{ - return m_printIfEmpty; -} +bool BandDesignIntf::printIfEmpty() const { return m_printIfEmpty; } void BandDesignIntf::setPrintIfEmpty(bool printIfEmpty) { - if (m_printIfEmpty != printIfEmpty){ + if (m_printIfEmpty != printIfEmpty) { m_printIfEmpty = printIfEmpty; if (!isLoading()) notify("printIfEmpty", !m_printIfEmpty, m_printIfEmpty); } - } -BandDesignIntf *BandDesignIntf::bandHeader() +BandDesignIntf* BandDesignIntf::bandHeader() { foreach (BandDesignIntf* band, childBands()) { - if (band->isHeader() && !band->isGroupHeader()){ - if (band->columnsCount() > 1) band->setColumnsFillDirection(this->columnsFillDirection()); + if (band->isHeader() && !band->isGroupHeader()) { + if (band->columnsCount() > 1) + band->setColumnsFillDirection(this->columnsFillDirection()); return band; } } return 0; } -BandDesignIntf *BandDesignIntf::bandFooter() +BandDesignIntf* BandDesignIntf::bandFooter() { foreach (BandDesignIntf* band, childBands()) { - if (band->isFooter()) return band; + if (band->isFooter()) + return band; } return 0; } -bool BandDesignIntf::sliceLastRow() const -{ - return m_sliceLastRow; -} +bool BandDesignIntf::sliceLastRow() const { return m_sliceLastRow; } void BandDesignIntf::setSliceLastRow(bool sliceLastRow) { - if (m_sliceLastRow != sliceLastRow){ + if (m_sliceLastRow != sliceLastRow) { m_sliceLastRow = sliceLastRow; if (!isLoading()) notify("sliceLastRow", !sliceLastRow, sliceLastRow); } } -int BandDesignIntf::maxScalePercent() const -{ - return m_maxScalePercent; -} +int BandDesignIntf::maxScalePercent() const { return m_maxScalePercent; } void BandDesignIntf::setMaxScalePercent(int maxScalePercent) { m_maxScalePercent = maxScalePercent; } -bool BandDesignIntf::keepFooterTogether() const -{ - return m_keepFooterTogether; -} +bool BandDesignIntf::keepFooterTogether() const { return m_keepFooterTogether; } void BandDesignIntf::setKeepFooterTogether(bool value) { - if (m_keepFooterTogether!=value){ + if (m_keepFooterTogether != value) { bool oldValue = m_keepFooterTogether; m_keepFooterTogether = value; if (!isLoading()) - notify("keepFooterTogether",oldValue,value); + notify("keepFooterTogether", oldValue, value); } } void BandDesignIntf::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { qreal spaceBorder = 0; - if (keepBottomSpace()) spaceBorder = bottomSpace(); + if (keepBottomSpace()) + spaceBorder = bottomSpace(); spaceBorder = spaceBorder > 0 ? spaceBorder : 0; - if (borderLines() != 0){ + if (borderLines() != 0) { spaceBorder += borderLineSize() + 2; } @@ -1117,7 +1078,7 @@ void BandDesignIntf::updateItemSize(DataSourceManager* dataManager, RenderPass p snapshotItemsLayout(); arrangeSubItems(pass, dataManager); - if (autoHeight()){ + if (autoHeight()) { if (!keepTopSpace()) { qreal minTop = findMinTop() + m_shiftItems; foreach (BaseDesignIntf* item, childBaseItems()) { @@ -1126,7 +1087,7 @@ void BandDesignIntf::updateItemSize(DataSourceManager* dataManager, RenderPass p } setHeight(findMaxBottom() + spaceBorder); } - if ((maxHeight > 0) && (height() > maxHeight)){ + if ((maxHeight > 0) && (height() > maxHeight)) { trimToMaxHeight(maxHeight); setHeight(maxHeight); } @@ -1135,78 +1096,71 @@ void BandDesignIntf::updateItemSize(DataSourceManager* dataManager, RenderPass p void BandDesignIntf::updateBandNameLabel() { - if (m_bandNameLabel) m_bandNameLabel->updateLabel(bandTitle()); + if (m_bandNameLabel) + m_bandNameLabel->updateLabel(bandTitle()); } -void BandDesignIntf::initFromItem(BaseDesignIntf *source) +void BandDesignIntf::initFromItem(BaseDesignIntf* source) { ItemsContainerDesignInft::initFromItem(source); BandDesignIntf* source_band = dynamic_cast(source); - if (source_band){ + if (source_band) { this->setBottomSpace(source_band->bottomSpace()); } } -QColor BandDesignIntf::selectionColor() const -{ - return Qt::yellow; -} +QColor BandDesignIntf::selectionColor() const { return Qt::yellow; } -DataBandDesignIntf::DataBandDesignIntf(BandDesignIntf::BandsType bandType, QString xmlTypeName, QObject *owner, QGraphicsItem *parent) - :BandDesignIntf(bandType,xmlTypeName,owner,parent) +DataBandDesignIntf::DataBandDesignIntf(BandDesignIntf::BandsType bandType, QString xmlTypeName, + QObject* owner, QGraphicsItem* parent): + BandDesignIntf(bandType, xmlTypeName, owner, parent) { } -BandNameLabel::BandNameLabel(BandDesignIntf *band, QGraphicsItem *parent) - :QGraphicsItem(parent),m_rect(5,5,30,30),m_band(band) +BandNameLabel::BandNameLabel(BandDesignIntf* band, QGraphicsItem* parent): + QGraphicsItem(parent), + m_rect(5, 5, 30, 30), + m_band(band) { setAcceptHoverEvents(true); } -void BandNameLabel::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void BandNameLabel::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); - painter->setFont(QFont("Arial",7*Const::fontFACTOR,-1,true)); + painter->setFont(QFont("Arial", 7 * Const::fontFACTOR, -1, true)); painter->setOpacity(1); QPen pen(Const::BAND_NAME_BORDER_COLOR); - //pen.setWidth(2); + // pen.setWidth(2); painter->setBrush(Qt::yellow); painter->setPen(pen); - painter->drawRoundedRect(m_rect,8,8); + painter->drawRoundedRect(m_rect, 8, 8); painter->setOpacity(0.8); painter->setPen(Qt::black); - painter->drawText(m_rect,Qt::AlignCenter,m_band->bandTitle()); + painter->drawText(m_rect, Qt::AlignCenter, m_band->bandTitle()); painter->restore(); Q_UNUSED(option) Q_UNUSED(widget) } -QRectF BandNameLabel::boundingRect() const -{ - return m_rect; -} +QRectF BandNameLabel::boundingRect() const { return m_rect; } void BandNameLabel::updateLabel(const QString& bandName) { - QFont font("Arial",7*Const::fontFACTOR,-1,true); + QFont font("Arial", 7 * Const::fontFACTOR, -1, true); QFontMetrics fontMetrics(font); prepareGeometryChange(); - m_rect = QRectF( - m_band->pos().x()+10, - m_band->pos().y()-(fontMetrics.height()+10), - fontMetrics.boundingRect(bandName).width()+20,fontMetrics.height()+10 - ); + m_rect = QRectF(m_band->pos().x() + 10, m_band->pos().y() - (fontMetrics.height() + 10), + fontMetrics.boundingRect(bandName).width() + 20, fontMetrics.height() + 10); update(); } -void BandNameLabel::hoverEnterEvent(QGraphicsSceneHoverEvent *event) +void BandNameLabel::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { setVisible(false); Q_UNUSED(event) } -} - - - +} // namespace LimeReport diff --git a/limereport/lrbanddesignintf.h b/limereport/lrbanddesignintf.h index 584260f..9f88cc9 100644 --- a/limereport/lrbanddesignintf.h +++ b/limereport/lrbanddesignintf.h @@ -32,42 +32,44 @@ #include "lrbasedesignintf.h" #include "lrdatasourcemanager.h" #include "lritemscontainerdesignitf.h" + #include namespace LimeReport { -class IGroupBand -{ +class IGroupBand { public: virtual void startGroup(DataSourceManager* dataManager) = 0; virtual bool isNeedToClose(DataSourceManager* dataManager) = 0; virtual bool isStarted() = 0; virtual void closeGroup() = 0; - virtual int index() = 0; - virtual bool startNewPage() const = 0 ; - virtual bool resetPageNumber() const = 0 ; - virtual ~IGroupBand(){} + virtual int index() = 0; + virtual bool startNewPage() const = 0; + virtual bool resetPageNumber() const = 0; + virtual ~IGroupBand() { } }; class BandDesignIntf; -class BandMarker : public QGraphicsItem{ +class BandMarker: public QGraphicsItem { public: - explicit BandMarker(BandDesignIntf* band, QGraphicsItem *parent=0); + explicit BandMarker(BandDesignIntf* band, QGraphicsItem* parent = 0); QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); + void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); void setHeight(qreal height); void setWidth(qreal width); void setColor(QColor color); - qreal width(){return m_rect.width();} - qreal height(){return m_rect.height();} -protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + qreal width() { return m_rect.width(); } + qreal height() { return m_rect.height(); } + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent* event); + void contextMenuEvent(QGraphicsSceneContextMenuEvent* event); + + void hoverMoveEvent(QGraphicsSceneHoverEvent* event); + void mouseMoveEvent(QGraphicsSceneMouseEvent* event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); - void hoverMoveEvent(QGraphicsSceneHoverEvent* event); - void mouseMoveEvent(QGraphicsSceneMouseEvent* event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); private: QRectF m_rect; QColor m_color; @@ -75,33 +77,38 @@ private: QPointF m_oldBandPos; }; -class BandNameLabel : public QGraphicsItem{ +class BandNameLabel: public QGraphicsItem { public: - explicit BandNameLabel(BandDesignIntf* band, QGraphicsItem* parent=0); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + explicit BandNameLabel(BandDesignIntf* band, QGraphicsItem* parent = 0); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QRectF boundingRect() const; - void updateLabel(const QString &bandName); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void updateLabel(const QString& bandName); + void hoverEnterEvent(QGraphicsSceneHoverEvent* event); + private: QRectF m_rect; QColor m_color; BandDesignIntf* m_band; }; -class InitializedValue{ +class InitializedValue { public: - InitializedValue(): m_value(-1), m_isInitialized(false){} - InitializedValue(qreal value): m_value(value), m_isInitialized(true){} - qreal value() const { return m_value;} - void setValue( qreal value){ m_value = value; m_isInitialized = true;} - bool isValid() const{ return m_isInitialized;} + InitializedValue(): m_value(-1), m_isInitialized(false) { } + InitializedValue(qreal value): m_value(value), m_isInitialized(true) { } + qreal value() const { return m_value; } + void setValue(qreal value) + { + m_value = value; + m_isInitialized = true; + } + bool isValid() const { return m_isInitialized; } + private: - qreal m_value; - bool m_isInitialized; + qreal m_value; + bool m_isInitialized; }; -class BandDesignIntf : public ItemsContainerDesignInft -{ +class BandDesignIntf: public ItemsContainerDesignInft { Q_OBJECT Q_PROPERTY(bool autoHeight READ autoHeight WRITE setAutoHeight) Q_PROPERTY(int bandIndex READ bandIndex WRITE setBandIndex DESIGNABLE false) @@ -109,7 +116,8 @@ class BandDesignIntf : public ItemsContainerDesignInft Q_PROPERTY(bool keepTopSpace READ keepTopSpace WRITE setKeepTopSpace) Q_PROPERTY(QString parentBand READ parentBandName WRITE setParentBandName DESIGNABLE false) Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) - Q_PROPERTY(BrushStyle backgroundBrushStyle READ backgroundBrushStyle WRITE setBackgroundBrushStyle) + Q_PROPERTY( + BrushStyle backgroundBrushStyle READ backgroundBrushStyle WRITE setBackgroundBrushStyle) Q_PROPERTY(bool printIfEmpty READ printIfEmpty WRITE setPrintIfEmpty) Q_PROPERTY(BGMode backgroundMode READ backgroundMode WRITE setBackgroundModeProperty) Q_PROPERTY(int backgroundOpacity READ opacity WRITE setBackgroundOpacity) @@ -117,26 +125,28 @@ class BandDesignIntf : public ItemsContainerDesignInft friend class BandMarker; friend class BandNameLabel; friend class ReportRender; -public: +public: enum BandsType { - PageHeader=0, - ReportHeader=1, - DataHeader=2, - GroupHeader=3, - Data=4, - SubDetailHeader=5, - SubDetailBand=6, - SubDetailFooter=7, - GroupFooter=8, - DataFooter=9, - ReportFooter=10, - TearOffBand=11, - PageFooter=12 + PageHeader = 0, + ReportHeader = 1, + DataHeader = 2, + GroupHeader = 3, + Data = 4, + SubDetailHeader = 5, + SubDetailBand = 6, + SubDetailFooter = 7, + GroupFooter = 8, + DataFooter = 9, + ReportFooter = 10, + TearOffBand = 11, + PageFooter = 12 }; - enum BandColumnsLayoutType{ - Horizontal, Vertical, VerticalUniform + enum BandColumnsLayoutType { + Horizontal, + Vertical, + VerticalUniform }; #if QT_VERSION >= 0x050500 Q_ENUM(BandColumnsLayoutType) @@ -144,10 +154,11 @@ public: Q_ENUMS(BandColumnsLayoutType) #endif - BandDesignIntf(BandsType bandType, const QString& xmlTypeName, QObject* owner = 0, QGraphicsItem* parent=0); + BandDesignIntf(BandsType bandType, const QString& xmlTypeName, QObject* owner = 0, + QGraphicsItem* parent = 0); ~BandDesignIntf(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QRectF boundingRect() const; void translateBandsName(); virtual BandsType bandType() const; @@ -155,7 +166,8 @@ public: virtual QIcon bandIcon() const; virtual bool isUnique() const; void setItemMode(BaseDesignIntf::ItemMode mode); - void updateItemSize(DataSourceManager *dataManager, RenderPass pass=FirstPass, int maxHeight=0); + void updateItemSize(DataSourceManager* dataManager, RenderPass pass = FirstPass, + int maxHeight = 0); void updateBandNameLabel(); void initFromItem(BaseDesignIntf* source); @@ -163,19 +175,19 @@ public: int bandIndex() const; void setBandIndex(int value); void changeBandIndex(int value, bool firstTime = false); - void setBandType(BandsType value){m_bandType=value;} + void setBandType(BandsType value) { m_bandType = value; } QString datasourceName(); void setDataSourceName(const QString& datasourceName); void setKeepBottomSpace(bool value); - bool keepBottomSpace() const {return m_keepBottomSpace;} + bool keepBottomSpace() const { return m_keepBottomSpace; } bool keepTopSpace() const; void setKeepTopSpace(bool value); void addChildBand(BandDesignIntf* band); - bool hasChildren(){return !m_childBands.isEmpty();} + bool hasChildren() { return !m_childBands.isEmpty(); } void removeChildBand(BandDesignIntf* band); void setParentBand(BandDesignIntf* band); @@ -189,35 +201,35 @@ public: int maxChildIndex(BandDesignIntf::BandsType bandType) const; int maxChildIndex(QSet ignoredBands = QSet()) const; - int rootIndex(BandDesignIntf *parentBand); - BandDesignIntf* rootBand(BandDesignIntf *parentBand); + int rootIndex(BandDesignIntf* parentBand); + BandDesignIntf* rootBand(BandDesignIntf* parentBand); - BandDesignIntf* parentBand() const {return m_parentBand;} + BandDesignIntf* parentBand() const { return m_parentBand; } - QList childBands() const{return m_childBands;} + QList childBands() const { return m_childBands; } QList childrenByType(BandDesignIntf::BandsType type); bool canBeSplitted(int height) const; bool isEmpty() const; virtual bool isNeedRender() const; - virtual bool isFooter() const {return false;} - virtual bool isHeader() const {return false;} - virtual bool isGroupHeader() const {return false;} - virtual bool isData() const {return false;} - virtual int bandNestingLevel(){return 0;} - bool isBand(){return true;} + virtual bool isFooter() const { return false; } + virtual bool isHeader() const { return false; } + virtual bool isGroupHeader() const { return false; } + virtual bool isData() const { return false; } + virtual int bandNestingLevel() { return 0; } + bool isBand() { return true; } void setTryToKeepTogether(bool value); bool tryToKeepTogether(); - BaseDesignIntf* cloneUpperPart(int height, QObject* owner=0, QGraphicsItem* parent=0); - BaseDesignIntf* cloneBottomPart(int height, QObject *owner=0, QGraphicsItem *parent=0); + BaseDesignIntf* cloneUpperPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); + BaseDesignIntf* cloneBottomPart(int height, QObject* owner = 0, QGraphicsItem* parent = 0); void parentObjectLoadFinished(); void objectLoadFinished(); - void emitBandRendered(BandDesignIntf *band); + void emitBandRendered(BandDesignIntf* band); void emitBandReRendered(BandDesignIntf* oldBand, BandDesignIntf* newBand); - bool isSplittable() const {return m_splitable;} + bool isSplittable() const { return m_splitable; } void setSplittable(bool value); bool keepFooterTogether() const; @@ -235,11 +247,11 @@ public: virtual BandDesignIntf* bandHeader(); virtual BandDesignIntf* bandFooter(); - int columnsCount() const {return m_columnsCount;} - BandColumnsLayoutType columnsFillDirection(){ return m_columnsFillDirection;} + int columnsCount() const { return m_columnsCount; } + BandColumnsLayoutType columnsFillDirection() { return m_columnsFillDirection; } int columnIndex() const; void setColumnIndex(int columnIndex); - + bool reprintOnEachPage() const; void setReprintOnEachPage(bool reprintOnEachPage); @@ -247,27 +259,27 @@ public: void setStartNewPage(bool startNewPage); void setAutoHeight(bool value); - bool autoHeight(){return m_autoHeight;} + bool autoHeight() { return m_autoHeight; } bool startFromNewPage() const; void setStartFromNewPage(bool startFromNewPage); - bool canContainChildren() const{ return true;} - bool canAcceptPaste() const{ return true;} + bool canContainChildren() const { return true; } + bool canAcceptPaste() const { return true; } bool printAlways() const; void setPrintAlways(bool printAlways); bool repeatOnEachRow() const; void setRepeatOnEachRow(bool repeatOnEachRow); QColor alternateBackgroundColor() const; - void setAlternateBackgroundColor(const QColor &alternateBackgroundColor); + void setAlternateBackgroundColor(const QColor& alternateBackgroundColor); bool useAlternateBackgroundColor() const; - void setUseAlternateBackgroundColor(bool useAlternateBackgroundColor); + void setUseAlternateBackgroundColor(bool useAlternateBackgroundColor); qreal bottomSpace(); void setBottomSpace(qreal bottomSpace); void setBackgroundModeProperty(BGMode value); void setBackgroundOpacity(int value); void updateBandMarkerGeometry(); int shiftItems() const; - void setShiftItems(int shiftItems); + void setShiftItems(int shiftItems); bool isNeedUpdateSize(RenderPass) const; void copyBandAttributes(BandDesignIntf* source); signals: @@ -275,17 +287,18 @@ signals: void bandReRendered(BandDesignIntf* oldBand, BandDesignIntf* newBand); void preparedForRender(); void bandRegistred(); + protected: - void trimToMaxHeight(int maxHeight); - void setBandTypeText(const QString& value); - QString bandTypeText(){return m_bandTypeText;} - void moveDown(){} - void moveUp(){} + void trimToMaxHeight(int maxHeight); + void setBandTypeText(const QString& value); + QString bandTypeText() { return m_bandTypeText; } + void moveDown() { } + void moveUp() { } QSet groupBands(); QSet subdetailBands(); - BandDesignIntf *findParentBand(); + BandDesignIntf* findParentBand(); void geometryChangedEvent(QRectF, QRectF); - QVariant itemChange(GraphicsItemChange change, const QVariant &value); + QVariant itemChange(GraphicsItemChange change, const QVariant& value); void initMode(ItemMode mode); virtual QColor bandColor() const; void setMarkerColor(QColor color); @@ -293,54 +306,56 @@ protected: void setColumnsCount(int value); void setColumnsFillDirection(BandColumnsLayoutType value); void moveItemsDown(qreal startPos, qreal offset); - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); - QString translateBandName(const BaseDesignIntf *item) const; + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + QString translateBandName(const BaseDesignIntf* item) const; private slots: void childBandDeleted(QObject* band); - void slotPropertyObjectNameChanged(const QString&,const QString&); + void slotPropertyObjectNameChanged(const QString&, const QString&); + private: - QString m_bandTypeText; - BandsType m_bandType; - int m_bandIndex; - QString m_dataSourceName; - bool m_autoHeight; - bool m_keepBottomSpace; - bool m_keepTopSpace; - BandDesignIntf* m_parentBand; - QString m_parentBandName; - QList m_childBands; + QString m_bandTypeText; + BandsType m_bandType; + int m_bandIndex; + QString m_dataSourceName; + bool m_autoHeight; + bool m_keepBottomSpace; + bool m_keepTopSpace; + BandDesignIntf* m_parentBand; + QString m_parentBandName; + QList m_childBands; QVector m_bandItems; - BandMarker* m_bandMarker; - bool m_tryToKeepTogether; - bool m_splitable; - bool m_keepFooterTogether; - int m_maxScalePercent; - bool m_sliceLastRow; - bool m_printIfEmpty; - BandNameLabel* m_bandNameLabel; - int m_columnsCount; - int m_columnIndex; - BandColumnsLayoutType m_columnsFillDirection; - bool m_reprintOnEachPage; - bool m_startNewPage; - bool m_startFromNewPage; - bool m_printAlways; - bool m_repeatOnEachRow; - QMap m_slicedItems; - QColor m_alternateBackgroundColor; - bool m_useAlternateBackgroundColor; - int m_bottomSpace; - QMap m_bookmarks; - int m_shiftItems; + BandMarker* m_bandMarker; + bool m_tryToKeepTogether; + bool m_splitable; + bool m_keepFooterTogether; + int m_maxScalePercent; + bool m_sliceLastRow; + bool m_printIfEmpty; + BandNameLabel* m_bandNameLabel; + int m_columnsCount; + int m_columnIndex; + BandColumnsLayoutType m_columnsFillDirection; + bool m_reprintOnEachPage; + bool m_startNewPage; + bool m_startFromNewPage; + bool m_printAlways; + bool m_repeatOnEachRow; + QMap m_slicedItems; + QColor m_alternateBackgroundColor; + bool m_useAlternateBackgroundColor; + int m_bottomSpace; + QMap m_bookmarks; + int m_shiftItems; }; -class DataBandDesignIntf : public BandDesignIntf{ +class DataBandDesignIntf: public BandDesignIntf { Q_OBJECT Q_PROPERTY(QString datasource READ datasourceName WRITE setDataSourceName) public: - DataBandDesignIntf(BandsType bandType, QString xmlTypeName, QObject* owner = 0, QGraphicsItem* parent=0); + DataBandDesignIntf(BandsType bandType, QString xmlTypeName, QObject* owner = 0, + QGraphicsItem* parent = 0); }; bool bandIndexLessThen(const BandDesignIntf* b1, const BandDesignIntf* b2); diff --git a/limereport/lrbandsmanager.cpp b/limereport/lrbandsmanager.cpp index 881aa90..aff4eec 100644 --- a/limereport/lrbandsmanager.cpp +++ b/limereport/lrbandsmanager.cpp @@ -28,61 +28,66 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrbandsmanager.h" -#include "lrglobal.h" -#include "lrpageheader.h" -#include "lrpagefooter.h" -#include "lrreportheader.h" -#include "lrreportfooter.h" #include "lrdataband.h" -#include "lrsubdetailband.h" +#include "lrglobal.h" #include "lrgroupbands.h" +#include "lrpagefooter.h" +#include "lrpageheader.h" +#include "lrreportfooter.h" +#include "lrreportheader.h" +#include "lrsubdetailband.h" #include "lrtearoffband.h" -namespace LimeReport{ +namespace LimeReport { -BandsManager::BandsManager(){} +BandsManager::BandsManager() { } QStringList BandsManager::bandNames() { QStringList bandsList; - bandsList<(LimeReport::DesignElementsFactory::instance().objectCreator(identity)(owner,parent)); + QString identity = LimeReport::DesignElementsFactory::instance().attribsMap().key( + LimeReport::ItemAttribs(type, LimeReport::Const::bandTAG)); + return dynamic_cast( + LimeReport::DesignElementsFactory::instance().objectCreator(identity)(owner, parent)); } -BandDesignIntf *BandsManager::createBand(BandDesignIntf::BandsType bandType, QObject *owner, BaseDesignIntf *parent) +BandDesignIntf* BandsManager::createBand(BandDesignIntf::BandsType bandType, QObject* owner, + BaseDesignIntf* parent) { - switch(bandType){ + switch (bandType) { case BandDesignIntf::ReportHeader: - return new ReportHeader(owner,parent); + return new ReportHeader(owner, parent); case BandDesignIntf::ReportFooter: - return new ReportFooter(owner,parent); + return new ReportFooter(owner, parent); case BandDesignIntf::PageHeader: - return new PageHeader(owner,parent); + return new PageHeader(owner, parent); case BandDesignIntf::PageFooter: - return new PageFooter(owner,parent); + return new PageFooter(owner, parent); case BandDesignIntf::Data: - return new DataBand(owner,parent); + return new DataBand(owner, parent); case BandDesignIntf::SubDetailBand: - return new SubDetailBand(owner,parent); + return new SubDetailBand(owner, parent); case BandDesignIntf::SubDetailHeader: - return new SubDetailHeaderBand(owner,parent); + return new SubDetailHeaderBand(owner, parent); case BandDesignIntf::SubDetailFooter: - return new SubDetailFooterBand(owner,parent); + return new SubDetailFooterBand(owner, parent); case BandDesignIntf::GroupHeader: return new GroupBandHeader(owner, parent); case BandDesignIntf::GroupFooter: @@ -98,4 +103,4 @@ BandDesignIntf *BandsManager::createBand(BandDesignIntf::BandsType bandType, QOb return 0; } -} +} // namespace LimeReport diff --git a/limereport/lrbandsmanager.h b/limereport/lrbandsmanager.h index be4646b..231ee6f 100644 --- a/limereport/lrbandsmanager.h +++ b/limereport/lrbandsmanager.h @@ -30,21 +30,23 @@ #ifndef LRBANDSMANAGER_H #define LRBANDSMANAGER_H -#include -#include -#include -#include "lrdesignelementsfactory.h" #include "lrbanddesignintf.h" #include "lrbasedesignintf.h" +#include "lrdesignelementsfactory.h" -namespace LimeReport{ -class BandsManager -{ +#include +#include +#include + +namespace LimeReport { +class BandsManager { public: BandsManager(); QStringList bandNames(); - BandDesignIntf * createBand(const QString& type, QObject* owner, LimeReport::BaseDesignIntf* parent ); - BandDesignIntf * createBand(BandDesignIntf::BandsType bandType, QObject* owner, LimeReport::BaseDesignIntf* parent ); + BandDesignIntf* createBand(const QString& type, QObject* owner, + LimeReport::BaseDesignIntf* parent); + BandDesignIntf* createBand(BandDesignIntf::BandsType bandType, QObject* owner, + LimeReport::BaseDesignIntf* parent); }; -} +} // namespace LimeReport #endif // LRBANDSMANAGER_H diff --git a/limereport/lrbasedesignintf.cpp b/limereport/lrbasedesignintf.cpp index 62d47c2..80741e1 100644 --- a/limereport/lrbasedesignintf.cpp +++ b/limereport/lrbasedesignintf.cpp @@ -27,32 +27,36 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include #include "lrbasedesignintf.h" + +#include "lrbordereditor.h" +#include "lrdesignelementsfactory.h" #include "lrglobal.h" +#include "lrhorizontallayout.h" #include "lrpagedesignintf.h" #include "lrreportdesignwidget.h" #include "qgraphicsitem.h" -#include "lrdesignelementsfactory.h" -#include "lrhorizontallayout.h" #include "serializators/lrstorageintf.h" #include "serializators/lrxmlreader.h" -#include "lrbordereditor.h" -#include -#include -#include + #include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include -namespace LimeReport -{ +#include -BaseDesignIntf::BaseDesignIntf(const QString &storageTypeName, QObject *owner, QGraphicsItem *parent) : - QObject(owner), QGraphicsItem(parent), - m_resizeHandleSize(Const::RESIZE_HANDLE_SIZE*2), +namespace LimeReport { + +BaseDesignIntf::BaseDesignIntf(const QString& storageTypeName, QObject* owner, + QGraphicsItem* parent): + QObject(owner), + QGraphicsItem(parent), + m_resizeHandleSize(Const::RESIZE_HANDLE_SIZE * 2), m_selectionPenSize(Const::SELECTION_PEN_SIZE), m_possibleResizeDirectionFlags(ResizeTop | ResizeBottom | ResizeLeft | ResizeRight), m_possibleMoveDirectionFlags(All), @@ -90,13 +94,12 @@ BaseDesignIntf::BaseDesignIntf(const QString &storageTypeName, QObject *owner, Q m_isMoveable(false), m_shadow(false) - { setGeometry(QRectF(0, 0, m_width, m_height)); - if (BaseDesignIntf *item = dynamic_cast(parent)) { + if (BaseDesignIntf* item = dynamic_cast(parent)) { m_font = item->font(); - } else{ - m_font = QFont("Arial",10); + } else { + m_font = QFont("Arial", 10); } initFlags(); } @@ -108,14 +111,12 @@ QRectF BaseDesignIntf::boundingRect() const return rect().adjusted(-halfpw, -halfpw, halfpw, halfpw); } -BaseDesignIntf::~BaseDesignIntf(void) { +BaseDesignIntf::~BaseDesignIntf(void) { } -} - -void BaseDesignIntf::setParentReportItem(const QString &value) +void BaseDesignIntf::setParentReportItem(const QString& value) { if (page() && !value.isEmpty()) { - BaseDesignIntf *p = page()->reportItemByName(value); + BaseDesignIntf* p = page()->reportItemByName(value); if (p) { setParentItem(p); setParent(p); @@ -125,64 +126,60 @@ void BaseDesignIntf::setParentReportItem(const QString &value) QString BaseDesignIntf::parentReportItemName() const { - BaseDesignIntf *parent = dynamic_cast(parentItem()); - if (parent) return parent->objectName(); - else return ""; + BaseDesignIntf* parent = dynamic_cast(parentItem()); + if (parent) + return parent->objectName(); + else + return ""; } void BaseDesignIntf::setBackgroundBrushStyle(BrushStyle value) { - if ( value != m_backgroundBrushStyle ){ + if (value != m_backgroundBrushStyle) { BrushStyle oldValue = m_backgroundBrushStyle; - m_backgroundBrushStyle=value; - if (!isLoading()) update(); + m_backgroundBrushStyle = value; + if (!isLoading()) + update(); notify("backgroundBrushStyle", static_cast(oldValue), static_cast(value)); } } void BaseDesignIntf::setBackgroundColor(QColor value) { - if (value != m_backgroundColor){ + if (value != m_backgroundColor) { QColor oldValue = m_backgroundColor; - m_backgroundColor=value; - if (!isLoading()) update(); + m_backgroundColor = value; + if (!isLoading()) + update(); notify("backgroundColor", oldValue, value); } } -QPen BaseDesignIntf::pen() const -{ - return m_pen; -} +QPen BaseDesignIntf::pen() const { return m_pen; } -void BaseDesignIntf::setPen(QPen &pen) +void BaseDesignIntf::setPen(QPen& pen) { m_pen = pen; update(); } -QFont BaseDesignIntf::font() const -{ - return m_font; -} +QFont BaseDesignIntf::font() const { return m_font; } -void BaseDesignIntf::setFont(QFont &font) +void BaseDesignIntf::setFont(QFont& font) { - if (m_font != font){ + if (m_font != font) { m_font = font; - if (!isLoading()) update(); + if (!isLoading()) + update(); } } -qreal BaseDesignIntf::width() const -{ - return rect().width(); -} +qreal BaseDesignIntf::width() const { return rect().width(); } void BaseDesignIntf::setWidth(qreal width) { setGeometry(QRectF(rect().x(), rect().y(), width, rect().height())); - if (!m_changingItemAlign) + if (!m_changingItemAlign) updateItemAlign(); } @@ -192,15 +189,9 @@ QString BaseDesignIntf::setItemWidth(qreal width) return QString(); } -qreal BaseDesignIntf::height() const -{ - return rect().height(); -} +qreal BaseDesignIntf::height() const { return rect().height(); } -QRect BaseDesignIntf::geometry() const -{ - return QRect(pos().x(), pos().y(), width(), height()); -} +QRect BaseDesignIntf::geometry() const { return QRect(pos().x(), pos().y(), width(), height()); } void BaseDesignIntf::setHeight(qreal height) { @@ -213,81 +204,66 @@ QString BaseDesignIntf::setItemHeight(qreal height) return QString(); } -qreal BaseDesignIntf::getItemWidth() -{ - return width() / unitFactor(); -} +qreal BaseDesignIntf::getItemWidth() { return width() / unitFactor(); } -qreal BaseDesignIntf::getItemHeight() -{ - return height() / unitFactor(); -} +qreal BaseDesignIntf::getItemHeight() { return height() / unitFactor(); } -qreal BaseDesignIntf::getItemPosX() -{ - return x() / unitFactor(); -} +qreal BaseDesignIntf::getItemPosX() { return x() / unitFactor(); } -qreal BaseDesignIntf::getItemPosY() -{ - return y() / unitFactor(); -} +qreal BaseDesignIntf::getItemPosY() { return y() / unitFactor(); } -qreal BaseDesignIntf::getAbsolutePosX() -{ - return calcAbsolutePosX(0,this); -} +qreal BaseDesignIntf::getAbsolutePosX() { return calcAbsolutePosX(0, this); } -qreal BaseDesignIntf::getAbsolutePosY() -{ - return calcAbsolutePosY(0,this); -} +qreal BaseDesignIntf::getAbsolutePosY() { return calcAbsolutePosY(0, this); } QString BaseDesignIntf::setItemPosX(qreal xValue) { - setItemPos(xValue * unitFactor(),y()); + setItemPos(xValue * unitFactor(), y()); return QString(); } QString BaseDesignIntf::setItemPosY(qreal yValue) { - setItemPos(x(),yValue * unitFactor()); + setItemPos(x(), yValue * unitFactor()); return QString(); } QFont BaseDesignIntf::transformToSceneFont(const QFont& value) const { QFont f = value; - f.setPixelSize(f.pointSize()*Const::fontFACTOR); + f.setPixelSize(f.pointSize() * Const::fontFACTOR); return f; } -QString BaseDesignIntf::expandDataFields(QString context, ExpandType expandType, DataSourceManager* dataManager) +QString BaseDesignIntf::expandDataFields(QString context, ExpandType expandType, + DataSourceManager* dataManager) { ScriptEngineManager& sm = ScriptEngineManager::instance(); - if (sm.dataManager() != dataManager) sm.setDataManager(dataManager); + if (sm.dataManager() != dataManager) + sm.setDataManager(dataManager); return sm.expandDataFields(context, expandType, m_varValue, this); } -QString BaseDesignIntf::expandUserVariables(QString context, RenderPass pass, ExpandType expandType, DataSourceManager* dataManager) +QString BaseDesignIntf::expandUserVariables(QString context, RenderPass pass, ExpandType expandType, + DataSourceManager* dataManager) { ScriptEngineManager& sm = ScriptEngineManager::instance(); - if (sm.dataManager() != dataManager) sm.setDataManager(dataManager); + if (sm.dataManager() != dataManager) + sm.setDataManager(dataManager); return sm.expandUserVariables(context, pass, expandType, m_varValue); - } QString BaseDesignIntf::expandScripts(QString context, DataSourceManager* dataManager) { ScriptEngineManager& sm = ScriptEngineManager::instance(); - if (sm.dataManager() != dataManager) sm.setDataManager(dataManager); - return sm.expandScripts(context,m_varValue,this); - + if (sm.dataManager() != dataManager) + sm.setDataManager(dataManager); + return sm.expandScripts(context, m_varValue, this); } -void BaseDesignIntf::setupPainter(QPainter *painter) const +void BaseDesignIntf::setupPainter(QPainter* painter) const { if (!painter) { return; @@ -296,32 +272,24 @@ void BaseDesignIntf::setupPainter(QPainter *painter) const painter->setPen(m_fontColor); } -BaseDesignIntf::BGMode BaseDesignIntf::backgroundMode() const -{ - return m_BGMode; -} +BaseDesignIntf::BGMode BaseDesignIntf::backgroundMode() const { return m_BGMode; } void BaseDesignIntf::setBackgroundMode(BGMode bgMode) { m_BGMode = bgMode; update(boundingRect()); } -int BaseDesignIntf::opacity() const -{ - return m_opacity; -} +int BaseDesignIntf::opacity() const { return m_opacity; } void BaseDesignIntf::setOpacity(int opacity) { - if (m_opacity!=opacity){ + if (m_opacity != opacity) { if (opacity < 0) { m_opacity = 0; - } - else if (opacity > 100) { + } else if (opacity > 100) { m_opacity = 100; - } - else { - m_opacity = opacity; + } else { + m_opacity = opacity; } update(); } @@ -333,70 +301,51 @@ void BaseDesignIntf::setSize(QSizeF size) setHeight(size.height()); } -QSizeF BaseDesignIntf::size() const -{ - return QSizeF(width(), height()); -} +QSizeF BaseDesignIntf::size() const { return QSizeF(width(), height()); } QSizeF BaseDesignIntf::sizeMM() const { return QSizeF(width() / Const::mmFACTOR, height() / Const::mmFACTOR); } -qreal BaseDesignIntf::widthMM() const -{ - return width() / Const::mmFACTOR; -} +qreal BaseDesignIntf::widthMM() const { return width() / Const::mmFACTOR; } -qreal BaseDesignIntf::heightMM() const -{ - return height() / Const::mmFACTOR; -} +qreal BaseDesignIntf::heightMM() const { return height() / Const::mmFACTOR; } -//void BaseDesignIntf::setUnitFactor(qreal unitFactor) +// void BaseDesignIntf::setUnitFactor(qreal unitFactor) //{ // m_unitFactor = unitFactor; //} qreal BaseDesignIntf::unitFactor() const { - if (m_unitType == Millimeters) + if (m_unitType == Millimeters) return Const::mmFACTOR; - else return Const::mmFACTOR * 2.54; + else + return Const::mmFACTOR * 2.54; } void BaseDesignIntf::setUnitType(BaseDesignIntf::UnitType value) { - foreach(BaseDesignIntf* child, childBaseItems()) + foreach (BaseDesignIntf* child, childBaseItems()) child->setUnitType(value); m_unitType = value; } -BaseDesignIntf::UnitType BaseDesignIntf::unitType() -{ - return m_unitType; -} +BaseDesignIntf::UnitType BaseDesignIntf::unitType() { return m_unitType; } QPointF BaseDesignIntf::posMM() const { return QPointF(pos().x() / Const::mmFACTOR, pos().y() / Const::mmFACTOR); } -QRectF BaseDesignIntf::rect() const -{ - return m_rect; -} +QRectF BaseDesignIntf::rect() const { return m_rect; } -void BaseDesignIntf::setFixedPos(bool fixedPos) -{ - m_fixedPos = fixedPos; -} +void BaseDesignIntf::setFixedPos(bool fixedPos) { m_fixedPos = fixedPos; } -void BaseDesignIntf::onChangeGeometryTimeOut(){ - m_isMoveable = true; -} +void BaseDesignIntf::onChangeGeometryTimeOut() { m_isMoveable = true; } -void BaseDesignIntf::mousePressEvent(QGraphicsSceneMouseEvent *event) +void BaseDesignIntf::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (event->button() == Qt::LeftButton) { m_isChangingPos = true; @@ -407,11 +356,11 @@ void BaseDesignIntf::mousePressEvent(QGraphicsSceneMouseEvent *event) emit itemSelected(this); m_isMoveable = false; QTimer::singleShot(200, this, SLOT(onChangeGeometryTimeOut())); - } - else QGraphicsItem::mousePressEvent(event); + } else + QGraphicsItem::mousePressEvent(event); } -void BaseDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +void BaseDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { QRectF newGeometry = geometry(); m_isChangingPos = false; @@ -422,7 +371,8 @@ void BaseDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) QGraphicsItem::mouseReleaseEvent(event); } -void BaseDesignIntf::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void BaseDesignIntf::paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { Q_UNUSED(option); Q_UNUSED(widget); @@ -430,41 +380,42 @@ void BaseDesignIntf::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *o ppainter->save(); setupPainter(ppainter); drawBorder(ppainter, rect()); - if(m_shadow) + if (m_shadow) drawShadow(ppainter, rect(), 6); drawResizeZone(ppainter); ppainter->restore(); } -QColor calcColor(QColor color){ +QColor calcColor(QColor color) +{ int R = color.red(); int G = color.green(); int B = color.blue(); - if (0.222*R + 0.707*G + 0.071*B <= 127) + if (0.222 * R + 0.707 * G + 0.071 * B <= 127) return Qt::white; else return Qt::black; } -void BaseDesignIntf::prepareRect(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) +void BaseDesignIntf::prepareRect(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, + QWidget* /*widget*/) { painter->save(); QRectF r = rect().adjusted(0, 0, borderLineSize(), borderLineSize()); - QBrush brush(m_backgroundColor,static_cast(m_backgroundBrushStyle)); + QBrush brush(m_backgroundColor, static_cast(m_backgroundBrushStyle)); brush.setTransform(painter->worldTransform().inverted()); - if (isSelected() && (opacity() == 100) && (m_BGMode!=TransparentMode)) { + if (isSelected() && (opacity() == 100) && (m_BGMode != TransparentMode)) { painter->fillRect(r, brush); - } - else { + } else { if (m_BGMode == OpaqueMode) { qreal o = (itemMode() & DesignMode) ? 0.5 : qreal(m_opacity) / 100; painter->setOpacity(o); painter->fillRect(r, brush); - } else if ((itemMode() & DesignMode) && fillTransparentInDesignMode()){ + } else if ((itemMode() & DesignMode) && fillTransparentInDesignMode()) { painter->setOpacity(0.1); painter->fillRect(r, QBrush(QPixmap(":/report/images/empty"))); } @@ -472,13 +423,13 @@ void BaseDesignIntf::prepareRect(QPainter *painter, const QStyleOptionGraphicsIt painter->restore(); } -void BaseDesignIntf::hoverMoveEvent(QGraphicsSceneHoverEvent *event) +void BaseDesignIntf::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { if (page()) { if (!page()->isItemInsertMode() && isSelected()) { if (m_resizeDirectionFlags != resizeDirectionFlags(event->pos())) { m_resizeDirectionFlags = resizeDirectionFlags(event->pos()); - QVectoroldResizeAreas(m_resizeAreas); + QVector oldResizeAreas(m_resizeAreas); initResizeZones(); invalidateRects(oldResizeAreas); invalidateRects(m_resizeAreas); @@ -492,10 +443,10 @@ void BaseDesignIntf::hoverMoveEvent(QGraphicsSceneHoverEvent *event) setCursor(Qt::SizeVerCursor); break; case ResizeRight | ResizeBottom: - case ResizeLeft | ResizeTop: + case ResizeLeft | ResizeTop: setCursor(Qt::SizeFDiagCursor); break; - case ResizeLeft | ResizeBottom: + case ResizeLeft | ResizeBottom: case ResizeRight | ResizeTop: setCursor(Qt::SizeBDiagCursor); break; @@ -508,13 +459,13 @@ void BaseDesignIntf::hoverMoveEvent(QGraphicsSceneHoverEvent *event) } } -void BaseDesignIntf::invalidateRects(QVector rects) +void BaseDesignIntf::invalidateRects(QVector rects) { - foreach(QRectF * rect, rects) + foreach (QRectF* rect, rects) scene()->update(mapToScene(*rect).boundingRect()); } -void BaseDesignIntf::hoverLeaveEvent(QGraphicsSceneHoverEvent *) +void BaseDesignIntf::hoverLeaveEvent(QGraphicsSceneHoverEvent*) { setCursor(QCursor(Qt::ArrowCursor)); m_resizeDirectionFlags = 0; @@ -524,17 +475,17 @@ void BaseDesignIntf::hoverLeaveEvent(QGraphicsSceneHoverEvent *) update(); } -void BaseDesignIntf::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/) +void BaseDesignIntf::hoverEnterEvent(QGraphicsSceneHoverEvent* /*event*/) { m_hovered = true; update(); } - -void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { - if (!m_isMoveable) return; - if (!isSelected()){ + if (!m_isMoveable) + return; + if (!isSelected()) { QGraphicsItem::mouseMoveEvent(event); return; } @@ -543,12 +494,13 @@ void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) int vStep = dynamic_cast(scene())->verticalGridStep(); if (m_resizeDirectionFlags & ResizeLeft) { - if ((event->scenePos().x()) <= (mapToScene(0, 0).x() + (width() - Const::MINIMUM_ITEM_WIDTH)) && - (width() + (event->lastScenePos().x() - event->scenePos().x()) > Const::MINIMUM_ITEM_WIDTH) - ) { + if ((event->scenePos().x()) + <= (mapToScene(0, 0).x() + (width() - Const::MINIMUM_ITEM_WIDTH)) + && (width() + (event->lastScenePos().x() - event->scenePos().x()) + > Const::MINIMUM_ITEM_WIDTH)) { qreal posRightCorner = mapToScene(0, 0).x() + width(); qreal posLeftCorner = div(mapToParent(event->pos()).x(), hStep).quot * hStep; - if (posLeftCorner < 0 ) + if (posLeftCorner < 0) posLeftCorner = 0; setItemPos(posLeftCorner, y()); setWidth(div(posRightCorner - mapToScene(0, 0).x(), hStep).quot * hStep); @@ -556,19 +508,20 @@ void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) } if (m_resizeDirectionFlags & ResizeRight) { - if ((event->scenePos().x() >= (mapToScene(0, 0).x() + Const::MINIMUM_ITEM_WIDTH)) || - (event->scenePos().x() >= (mapToScene(0, 0).x() + width()))) { + if ((event->scenePos().x() >= (mapToScene(0, 0).x() + Const::MINIMUM_ITEM_WIDTH)) + || (event->scenePos().x() >= (mapToScene(0, 0).x() + width()))) { setWidth(div(event->scenePos().x() - mapToScene(0, 0).x(), hStep).quot * hStep); } } if (m_resizeDirectionFlags & ResizeTop) { - if ((event->scenePos().y()) <= (mapToScene(0, 0).y() + (height() - Const::MINIMUM_ITEM_HEIGHT)) && - (height() + (event->lastScenePos().y() - event->scenePos().y()) > Const::MINIMUM_ITEM_HEIGHT) - ) { + if ((event->scenePos().y()) + <= (mapToScene(0, 0).y() + (height() - Const::MINIMUM_ITEM_HEIGHT)) + && (height() + (event->lastScenePos().y() - event->scenePos().y()) + > Const::MINIMUM_ITEM_HEIGHT)) { qreal posBottomCorner = mapToScene(0, 0).y() + height(); qreal posTopCorner = div(mapToParent(event->pos()).y(), vStep).quot * vStep; - if (posTopCorner < 0 ) + if (posTopCorner < 0) posTopCorner = 0; setItemPos(x(), posTopCorner); setHeight(div(posBottomCorner - mapToScene(0, 0).y(), vStep).quot * vStep); @@ -576,9 +529,8 @@ void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) } if (m_resizeDirectionFlags & ResizeBottom) { - if ((event->scenePos().y() > (mapToScene(0, 0).y() + height())) || - (event->scenePos().y() > (mapToScene(0, 0).y() + Const::MINIMUM_ITEM_HEIGHT)) - ) { + if ((event->scenePos().y() > (mapToScene(0, 0).y() + height())) + || (event->scenePos().y() > (mapToScene(0, 0).y() + Const::MINIMUM_ITEM_HEIGHT))) { setHeight(div(event->scenePos().y() - mapToScene(0, 0).y(), vStep).quot * vStep); } } @@ -589,59 +541,67 @@ void BaseDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) QPointF delta; switch (possibleMoveDirectionFlags()) { case LeftRight: { - delta = QPoint(div(event->buttonDownScenePos(Qt::LeftButton).x() - event->scenePos().x(), hStep).quot * hStep, 0); + delta = QPoint( + div(event->buttonDownScenePos(Qt::LeftButton).x() - event->scenePos().x(), hStep) + .quot + * hStep, + 0); break; } case TopBotom: { - delta = QPoint(0, div(event->buttonDownScenePos(Qt::LeftButton).y() - event->scenePos().y(), vStep).quot * vStep); + delta = QPoint( + 0, + div(event->buttonDownScenePos(Qt::LeftButton).y() - event->scenePos().y(), vStep) + .quot + * vStep); break; } case All: { - delta = QPoint(div(event->buttonDownScenePos(Qt::LeftButton).x() - event->scenePos().x(), hStep).quot * hStep, - div(event->buttonDownScenePos(Qt::LeftButton).y() - event->scenePos().y(), vStep).quot * vStep); + delta = QPoint( + div(event->buttonDownScenePos(Qt::LeftButton).x() - event->scenePos().x(), hStep) + .quot + * hStep, + div(event->buttonDownScenePos(Qt::LeftButton).y() - event->scenePos().y(), vStep) + .quot + * vStep); break; } }; - setItemPos(QPointF(div(m_startPos.x(), hStep).quot * hStep, div(m_startPos.y(), vStep).quot * vStep) - delta); + setItemPos(QPointF(div(m_startPos.x(), hStep).quot * hStep, + div(m_startPos.y(), vStep).quot * vStep) + - delta); - if (page()){ - if (!isBand() && page()->selectedItems().count()>1) + if (page()) { + if (!isBand() && page()->selectedItems().count() > 1) moveSelectedItems(tmpPos - pos()); - if (page()->selectedItems().count()==1 && (page()->magneticMovement())) + if (page()->selectedItems().count() == 1 && (page()->magneticMovement())) page()->itemMoved(this); - } } } -int BaseDesignIntf::possibleResizeDirectionFlags() const -{ - return m_possibleResizeDirectionFlags; -} +int BaseDesignIntf::possibleResizeDirectionFlags() const { return m_possibleResizeDirectionFlags; } -int BaseDesignIntf::resizeHandleSize() const -{ - return m_resizeHandleSize; -} +int BaseDesignIntf::resizeHandleSize() const { return m_resizeHandleSize; } int BaseDesignIntf::resizeDirectionFlags(QPointF position) { int flags = Fixed; - if (possibleResizeDirectionFlags()&ResizeTop && m_topRect.contains(position)) { + if (possibleResizeDirectionFlags() & ResizeTop && m_topRect.contains(position)) { flags |= ResizeTop; } - if (possibleResizeDirectionFlags()&ResizeLeft && m_leftRect.contains(position)) { + if (possibleResizeDirectionFlags() & ResizeLeft && m_leftRect.contains(position)) { flags |= ResizeLeft; } - if (possibleResizeDirectionFlags()&ResizeBottom && m_bottomRect.contains(position)) { + if (possibleResizeDirectionFlags() & ResizeBottom && m_bottomRect.contains(position)) { flags |= ResizeBottom; } - if (possibleResizeDirectionFlags()&ResizeRight && m_rightRect.contains(position)) { + if (possibleResizeDirectionFlags() & ResizeRight && m_rightRect.contains(position)) { flags |= ResizeRight; } @@ -651,46 +611,49 @@ int BaseDesignIntf::resizeDirectionFlags(QPointF position) Qt::CursorShape BaseDesignIntf::getPossibleCursor(int cursorFlags) { - if ((cursorFlags == Fixed) || (scene()->selectedItems().count() > 1)) return Qt::ArrowCursor; + if ((cursorFlags == Fixed) || (scene()->selectedItems().count() > 1)) + return Qt::ArrowCursor; - if (((cursorFlags & ResizeRight) && (cursorFlags & ResizeTop)) || - ((cursorFlags & ResizeLeft) && (cursorFlags & ResizeBottom))) { + if (((cursorFlags & ResizeRight) && (cursorFlags & ResizeTop)) + || ((cursorFlags & ResizeLeft) && (cursorFlags & ResizeBottom))) { return Qt::SizeBDiagCursor; } - if (((cursorFlags & ResizeLeft) && (cursorFlags & ResizeTop)) || - ((cursorFlags & ResizeRight) && (cursorFlags & ResizeBottom))) { + if (((cursorFlags & ResizeLeft) && (cursorFlags & ResizeTop)) + || ((cursorFlags & ResizeRight) && (cursorFlags & ResizeBottom))) { return Qt::SizeFDiagCursor; } - if ((cursorFlags & ResizeLeft) || (cursorFlags & ResizeRight)) { return Qt::SizeHorCursor; } - if ((cursorFlags & ResizeBottom) || (cursorFlags & ResizeTop)) { return Qt::SizeVerCursor; } + if ((cursorFlags & ResizeLeft) || (cursorFlags & ResizeRight)) { + return Qt::SizeHorCursor; + } + if ((cursorFlags & ResizeBottom) || (cursorFlags & ResizeTop)) { + return Qt::SizeVerCursor; + } return Qt::ArrowCursor; } void BaseDesignIntf::setZValueProperty(qreal value) { - if (zValue()!=value){ + if (zValue() != value) { qreal oldValue = zValue(); setZValue(value); - notify("zOrder",oldValue,value); + notify("zOrder", oldValue, value); } } -BaseDesignIntf::ItemAlign BaseDesignIntf::itemAlign() const -{ - return m_itemAlign; -} +BaseDesignIntf::ItemAlign BaseDesignIntf::itemAlign() const { return m_itemAlign; } -QPointF BaseDesignIntf::modifyPosForAlignedItem(const QPointF& pos){ +QPointF BaseDesignIntf::modifyPosForAlignedItem(const QPointF& pos) +{ QPointF result = pos; BaseDesignIntf* parent = dynamic_cast(parentItem()); PageItemDesignIntf* parentPage = dynamic_cast(parentItem()); - if (parent){ + if (parent) { qreal leftBorder = parentPage ? parentPage->leftMargin() * Const::mmFACTOR : 0; qreal rightBorder = parentPage ? parentPage->rightMargin() * Const::mmFACTOR : 0; - qreal avaibleSpace = parent->width()-(leftBorder+rightBorder); + qreal avaibleSpace = parent->width() - (leftBorder + rightBorder); - switch(m_itemAlign){ + switch (m_itemAlign) { case LeftItemAlign: result.setX(leftBorder); break; @@ -698,7 +661,7 @@ QPointF BaseDesignIntf::modifyPosForAlignedItem(const QPointF& pos){ result.setX(parent->width() - (rightBorder + width())); break; case CenterItemAlign: - result.setX((avaibleSpace-width()) / 2 + leftBorder); + result.setX((avaibleSpace - width()) / 2 + leftBorder); break; case ParentWidthItemAlign: result.setX(leftBorder); @@ -712,7 +675,7 @@ QPointF BaseDesignIntf::modifyPosForAlignedItem(const QPointF& pos){ void BaseDesignIntf::turnOnJoinMarker(bool value) { m_joinMarkerOn = value; - if (value){ + if (value) { m_joinMarker = new Marker(this, this); m_joinMarker->setColor(Const::JOIN_COLOR); m_joinMarker->setRect(rect()); @@ -723,14 +686,15 @@ void BaseDesignIntf::turnOnJoinMarker(bool value) } } -void BaseDesignIntf::updateItemAlign(){ +void BaseDesignIntf::updateItemAlign() +{ BaseDesignIntf* parent = dynamic_cast(parentItem()); PageItemDesignIntf* parentPage = dynamic_cast(parentItem()); m_changingItemAlign = true; - if (parent){ + if (parent) { qreal leftBorder = parentPage ? parentPage->leftMargin() * Const::mmFACTOR : 0; qreal rightBorder = parentPage ? parentPage->rightMargin() * Const::mmFACTOR : 0; - qreal aviableSpace = parent->width()-(leftBorder+rightBorder); + qreal aviableSpace = parent->width() - (leftBorder + rightBorder); setPos(modifyPosForAlignedItem(pos())); if (m_itemAlign == ParentWidthItemAlign) setWidth(aviableSpace); @@ -738,63 +702,52 @@ void BaseDesignIntf::updateItemAlign(){ m_changingItemAlign = false; } -void BaseDesignIntf::updatePossibleDirectionFlags(){ +void BaseDesignIntf::updatePossibleDirectionFlags() +{ setPossibleResizeDirectionFlags(AllDirections); - switch(m_itemAlign){ + switch (m_itemAlign) { case LeftItemAlign: - setPossibleResizeDirectionFlags(AllDirections^ResizeLeft); + setPossibleResizeDirectionFlags(AllDirections ^ ResizeLeft); break; case RightItemAlign: - setPossibleResizeDirectionFlags(AllDirections^ResizeRight); + setPossibleResizeDirectionFlags(AllDirections ^ ResizeRight); break; case ParentWidthItemAlign: - setPossibleResizeDirectionFlags(ResizeBottom|ResizeTop); + setPossibleResizeDirectionFlags(ResizeBottom | ResizeTop); case CenterItemAlign: case DesignedItemAlign: break; } } -bool BaseDesignIntf::isChangingPos() const -{ - return m_isChangingPos; -} +bool BaseDesignIntf::isChangingPos() const { return m_isChangingPos; } -void BaseDesignIntf::setIsChangingPos(bool isChangingPos) -{ - m_isChangingPos = isChangingPos; -} +void BaseDesignIntf::setIsChangingPos(bool isChangingPos) { m_isChangingPos = isChangingPos; } bool BaseDesignIntf::isShapeItem() const { return QString(metaObject()->className()) == "LimeReport::ShapeItem"; } -bool BaseDesignIntf::hasShadow() -{ - return m_shadow; -} +bool BaseDesignIntf::hasShadow() { return m_shadow; } void BaseDesignIntf::setShadow(bool sh) { - if (m_shadow != sh){ + if (m_shadow != sh) { bool oldValue = m_shadow; m_shadow = sh; - notify("shadow",oldValue,m_shadow); + notify("shadow", oldValue, m_shadow); update(); } } -bool BaseDesignIntf::isGeometryLocked() const -{ - return m_itemGeometryLocked; -} +bool BaseDesignIntf::isGeometryLocked() const { return m_itemGeometryLocked; } void BaseDesignIntf::setGeometryLocked(bool itemLocked) { - if (m_itemGeometryLocked != itemLocked){ + if (m_itemGeometryLocked != itemLocked) { m_itemGeometryLocked = itemLocked; - if (itemLocked){ + if (itemLocked) { m_savedPossibleMoveDirectionFlags = m_possibleMoveDirectionFlags; m_savedPossibleResizeDirectionFlags = m_possibleResizeDirectionFlags; m_possibleMoveDirectionFlags = None; @@ -806,7 +759,7 @@ void BaseDesignIntf::setGeometryLocked(bool itemLocked) m_possibleResizeDirectionFlags = m_savedPossibleResizeDirectionFlags; m_fixedPos = m_savedFixedPos; } - if (!isLoading()){ + if (!isLoading()) { update(); m_selectionMarker->update(); notify("geometryLocked", !itemLocked, itemLocked); @@ -814,10 +767,7 @@ void BaseDesignIntf::setGeometryLocked(bool itemLocked) } } -bool BaseDesignIntf::fillTransparentInDesignMode() const -{ - return m_fillTransparentInDesignMode; -} +bool BaseDesignIntf::fillTransparentInDesignMode() const { return m_fillTransparentInDesignMode; } void BaseDesignIntf::setFillTransparentInDesignMode(bool fillTransparentInDesignMode) { @@ -829,48 +779,42 @@ void BaseDesignIntf::emitPosChanged(QPointF oldPos, QPointF newPos) emit posChanged(this, oldPos, newPos); } -bool BaseDesignIntf::fillInSecondPass() const -{ - return m_fillInSecondPass; -} +bool BaseDesignIntf::fillInSecondPass() const { return m_fillInSecondPass; } void BaseDesignIntf::setFillInSecondPass(bool fillInSecondPass) { - if (m_fillInSecondPass != fillInSecondPass){ + if (m_fillInSecondPass != fillInSecondPass) { m_fillInSecondPass = fillInSecondPass; - notify("fillInSecondPass",!fillInSecondPass,fillInSecondPass); + notify("fillInSecondPass", !fillInSecondPass, fillInSecondPass); } - } -bool BaseDesignIntf::isWatermark() const -{ - return m_watermark; -} +bool BaseDesignIntf::isWatermark() const { return m_watermark; } void BaseDesignIntf::setWatermark(bool watermark) { - if (m_watermark != watermark){ + if (m_watermark != watermark) { m_watermark = watermark; - notify("watermark",!watermark,watermark); + notify("watermark", !watermark, watermark); } } void BaseDesignIntf::updateSelectionMarker() { if (m_selectionMarker && (itemMode() & DesignMode || itemMode() & EditMode)) { - if ((!m_selectionMarker->scene()) && scene()) scene()->addItem(m_selectionMarker); + if ((!m_selectionMarker->scene()) && scene()) + scene()->addItem(m_selectionMarker); if (parentItem()) { m_selectionMarker->setRect(rect()); - m_selectionMarker->setPos(0,0); + m_selectionMarker->setPos(0, 0); } } } void BaseDesignIntf::turnOnSelectionMarker(bool value) { - if (value && !m_selectionMarker){ + if (value && !m_selectionMarker) { m_selectionMarker = new SelectionMarker(this, this); m_selectionMarker->setColor(selectionMarkerColor()); updateSelectionMarker(); @@ -886,95 +830,71 @@ QString BaseDesignIntf::patternName() const return (m_patternName.isEmpty()) ? objectName() : m_patternName; } -void BaseDesignIntf::setPatternName(const QString &patternName) -{ - m_patternName = patternName; -} +void BaseDesignIntf::setPatternName(const QString& patternName) { m_patternName = patternName; } -BaseDesignIntf* BaseDesignIntf::patternItem() const -{ - return m_patternItem; -} +BaseDesignIntf* BaseDesignIntf::patternItem() const { return m_patternItem; } -void BaseDesignIntf::setPatternItem(BaseDesignIntf *patternItem) -{ - m_patternItem = patternItem; -} +void BaseDesignIntf::setPatternItem(BaseDesignIntf* patternItem) { m_patternItem = patternItem; } -ReportSettings *BaseDesignIntf::reportSettings() const -{ - return m_reportSettings; -} +ReportSettings* BaseDesignIntf::reportSettings() const { return m_reportSettings; } -void BaseDesignIntf::setReportSettings(ReportSettings *reportSettings) +void BaseDesignIntf::setReportSettings(ReportSettings* reportSettings) { m_reportSettings = reportSettings; - foreach(BaseDesignIntf* child, childBaseItems()){ + foreach (BaseDesignIntf* child, childBaseItems()) { child->setReportSettings(reportSettings); } } -QColor BaseDesignIntf::borderColor() const -{ - return m_borderColor; -} +QColor BaseDesignIntf::borderColor() const { return m_borderColor; } -void BaseDesignIntf::setBorderColor(const QColor &borderColor) +void BaseDesignIntf::setBorderColor(const QColor& borderColor) { - if (m_borderColor != borderColor){ + if (m_borderColor != borderColor) { QColor oldValue = m_borderColor; m_borderColor = borderColor; - notify("borderColor",oldValue,borderColor); + notify("borderColor", oldValue, borderColor); update(); } } -void BaseDesignIntf::setItemVisible(const bool &value) +void BaseDesignIntf::setItemVisible(const bool& value) { - if (isVisible()!=value){ + if (isVisible() != value) { setVisible(value); emit itemVisibleHasChanged(this); } } -void BaseDesignIntf::setItemAlign(const ItemAlign &itemAlign) +void BaseDesignIntf::setItemAlign(const ItemAlign& itemAlign) { - if (m_itemAlign != itemAlign){ + if (m_itemAlign != itemAlign) { ItemAlign oldValue = m_itemAlign; m_itemAlign = itemAlign; - notify("itemAlign",oldValue,itemAlign); + notify("itemAlign", oldValue, itemAlign); updatePossibleDirectionFlags(); updateItemAlign(); emit itemAlignChanged(this, oldValue, itemAlign); } } -QString BaseDesignIntf::itemTypeName() const +QString BaseDesignIntf::itemTypeName() const { return m_itemTypeName; } + +void BaseDesignIntf::setItemTypeName(const QString& itemTypeName) { m_itemTypeName = itemTypeName; } + +void BaseDesignIntf::emitObjectNamePropertyChanged(const QString& oldName, const QString& newName) { - return m_itemTypeName; + emit propertyObjectNameChanged(oldName, newName); } -void BaseDesignIntf::setItemTypeName(const QString &itemTypeName) -{ - m_itemTypeName = itemTypeName; -} - -void BaseDesignIntf::emitObjectNamePropertyChanged(const QString &oldName, const QString &newName) -{ - emit propertyObjectNameChanged(oldName,newName); -} - -qreal BaseDesignIntf::borderLineSize() const -{ - return m_borderLineSize; -} +qreal BaseDesignIntf::borderLineSize() const { return m_borderLineSize; } void BaseDesignIntf::setBorderStyle(BorderStyle b) { BorderStyle oldValue = m_borderStyle; m_borderStyle = b; update(); - notify("borderStyle",(BorderStyle)oldValue,(BorderStyle)b); + notify("borderStyle", (BorderStyle)oldValue, (BorderStyle)b); } void BaseDesignIntf::setBorderLineSize(qreal value) @@ -982,137 +902,134 @@ void BaseDesignIntf::setBorderLineSize(qreal value) qreal oldValue = m_borderLineSize; m_borderLineSize = value; update(); - notify("borderLineSize",oldValue,value); + notify("borderLineSize", oldValue, value); } - void BaseDesignIntf::moveRight() { - if (!m_fixedPos && page()) setItemPos(pos().x() + page()->horizontalGridStep(), pos().y()); + if (!m_fixedPos && page()) + setItemPos(pos().x() + page()->horizontalGridStep(), pos().y()); } void BaseDesignIntf::moveLeft() { - if (!m_fixedPos && page()) setItemPos(pos().x() - page()->horizontalGridStep(), pos().y()); + if (!m_fixedPos && page()) + setItemPos(pos().x() - page()->horizontalGridStep(), pos().y()); } void BaseDesignIntf::moveDown() { - if (!m_fixedPos && page()) setItemPos(pos().x(), pos().y() + page()->verticalGridStep()); + if (!m_fixedPos && page()) + setItemPos(pos().x(), pos().y() + page()->verticalGridStep()); } void BaseDesignIntf::moveUp() { - if (!m_fixedPos && page()) setItemPos(pos().x(), pos().y() - page()->verticalGridStep()); + if (!m_fixedPos && page()) + setItemPos(pos().x(), pos().y() - page()->verticalGridStep()); } void BaseDesignIntf::sizeRight() { - if ((m_possibleResizeDirectionFlags & ResizeLeft) || - (m_possibleResizeDirectionFlags & ResizeRight)) { - if (page()) setWidth(width() + page()->horizontalGridStep()); + if ((m_possibleResizeDirectionFlags & ResizeLeft) + || (m_possibleResizeDirectionFlags & ResizeRight)) { + if (page()) + setWidth(width() + page()->horizontalGridStep()); } } void BaseDesignIntf::sizeLeft() { - if ((m_possibleResizeDirectionFlags & ResizeLeft) || - (m_possibleResizeDirectionFlags & ResizeRight)) { - if(page()) setWidth(width() - page()->horizontalGridStep()); + if ((m_possibleResizeDirectionFlags & ResizeLeft) + || (m_possibleResizeDirectionFlags & ResizeRight)) { + if (page()) + setWidth(width() - page()->horizontalGridStep()); } } void BaseDesignIntf::sizeUp() { - if ((m_possibleResizeDirectionFlags & ResizeTop) || - (m_possibleResizeDirectionFlags & ResizeBottom)) { - if (page()) setHeight(height() - page()->verticalGridStep()); + if ((m_possibleResizeDirectionFlags & ResizeTop) + || (m_possibleResizeDirectionFlags & ResizeBottom)) { + if (page()) + setHeight(height() - page()->verticalGridStep()); } } void BaseDesignIntf::sizeDown() { - if ((m_possibleResizeDirectionFlags & ResizeTop) || - (m_possibleResizeDirectionFlags & ResizeBottom)) { - if (page()) setHeight(height() + page()->verticalGridStep()); + if ((m_possibleResizeDirectionFlags & ResizeTop) + || (m_possibleResizeDirectionFlags & ResizeBottom)) { + if (page()) + setHeight(height() + page()->verticalGridStep()); } } void BaseDesignIntf::setBorderLinesFlags(BorderLines flags) { - if (m_borderLinesFlags!=flags){ + if (m_borderLinesFlags != flags) { BorderLines oldValue = m_borderLinesFlags; m_borderLinesFlags = flags; if (!isLoading()) { update(rect()); - notify("borders",QVariant(oldValue),QVariant(flags)); + notify("borders", QVariant(oldValue), QVariant(flags)); } } } -BaseDesignIntf::BorderLines BaseDesignIntf::borderLines() const -{ - return m_borderLinesFlags; -} +BaseDesignIntf::BorderLines BaseDesignIntf::borderLines() const { return m_borderLinesFlags; } - -void BaseDesignIntf::drawTopLine(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawTopLine(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; painter->setPen(borderPen(TopLine)); painter->drawLine(rect.x(), rect.y(), rect.width(), rect.y()); - if(borderStyle() == BorderStyle::Doubled) - painter->drawLine(rect.x()+3+m_borderLineSize, - rect.y()+3+m_borderLineSize, - rect.width()-3-m_borderLineSize, - rect.y()+3+m_borderLineSize); + if (borderStyle() == BorderStyle::Doubled) + painter->drawLine(rect.x() + 3 + m_borderLineSize, rect.y() + 3 + m_borderLineSize, + rect.width() - 3 - m_borderLineSize, rect.y() + 3 + m_borderLineSize); } -void BaseDesignIntf::drawBootomLine(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawBootomLine(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; painter->setPen(borderPen(BottomLine)); painter->drawLine(rect.x(), rect.height(), rect.width(), rect.height()); - if(borderStyle() == BorderStyle::Doubled) - painter->drawLine(rect.x()+3+m_borderLineSize, - rect.height()-3-m_borderLineSize, - rect.width()-3-m_borderLineSize, - rect.height()-3-m_borderLineSize); + if (borderStyle() == BorderStyle::Doubled) + painter->drawLine(rect.x() + 3 + m_borderLineSize, rect.height() - 3 - m_borderLineSize, + rect.width() - 3 - m_borderLineSize, + rect.height() - 3 - m_borderLineSize); } -void BaseDesignIntf::drawRightLine(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawRightLine(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; painter->setPen(borderPen(RightLine)); painter->drawLine(rect.width(), rect.y(), rect.width(), rect.height()); - if(borderStyle() == BorderStyle::Doubled) - painter->drawLine(rect.width()-3 - m_borderLineSize, - rect.y()+3+m_borderLineSize, - rect.width()-3-m_borderLineSize, - rect.height()-3-m_borderLineSize); + if (borderStyle() == BorderStyle::Doubled) + painter->drawLine(rect.width() - 3 - m_borderLineSize, rect.y() + 3 + m_borderLineSize, + rect.width() - 3 - m_borderLineSize, + rect.height() - 3 - m_borderLineSize); } -void BaseDesignIntf::drawLeftLine(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawLeftLine(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; painter->setPen(borderPen(LeftLine)); painter->drawLine(rect.x(), rect.y(), rect.x(), rect.height()); - if(borderStyle() == BorderStyle::Doubled) - painter->drawLine(rect.x()+3+m_borderLineSize, - rect.y()+3+m_borderLineSize, - rect.x()+3+m_borderLineSize, - rect.height()-3-m_borderLineSize); + if (borderStyle() == BorderStyle::Doubled) + painter->drawLine(rect.x() + 3 + m_borderLineSize, rect.y() + 3 + m_borderLineSize, + rect.x() + 3 + m_borderLineSize, rect.height() - 3 - m_borderLineSize); } -void BaseDesignIntf::drawDesignModeBorder(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawDesignModeBorder(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; drawTopLine(painter, rect); drawBootomLine(painter, rect); @@ -1120,63 +1037,70 @@ void BaseDesignIntf::drawDesignModeBorder(QPainter *painter, QRectF rect) const drawRightLine(painter, rect); } -void BaseDesignIntf::drawRenderModeBorder(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawRenderModeBorder(QPainter* painter, QRectF rect) const { - if(isShapeItem()) + if (isShapeItem()) return; - if (m_borderLinesFlags & RightLine) drawRightLine(painter, rect); - if (m_borderLinesFlags & LeftLine) drawLeftLine(painter, rect); - if (m_borderLinesFlags & TopLine ) drawTopLine(painter, rect); - if (m_borderLinesFlags & BottomLine) drawBootomLine(painter, rect); + if (m_borderLinesFlags & RightLine) + drawRightLine(painter, rect); + if (m_borderLinesFlags & LeftLine) + drawLeftLine(painter, rect); + if (m_borderLinesFlags & TopLine) + drawTopLine(painter, rect); + if (m_borderLinesFlags & BottomLine) + drawBootomLine(painter, rect); } -void BaseDesignIntf::drawBorder(QPainter *painter, QRectF rect) const +void BaseDesignIntf::drawBorder(QPainter* painter, QRectF rect) const { painter->save(); if (itemMode() & DesignMode && drawDesignBorders()) { drawDesignModeBorder(painter, rect); - } - else drawRenderModeBorder(painter, rect); + } else + drawRenderModeBorder(painter, rect); painter->restore(); } -void BaseDesignIntf::drawShadow(QPainter *painter, QRectF rect, qreal shadowSize) const +void BaseDesignIntf::drawShadow(QPainter* painter, QRectF rect, qreal shadowSize) const { qreal shWidth = shadowSize; - QRectF rshadow(rect.topRight() + QPointF(0, shWidth), - rect.bottomRight() + QPointF(shWidth, 0)); + QRectF rshadow(rect.topRight() + QPointF(0, shWidth), rect.bottomRight() + QPointF(shWidth, 0)); QLinearGradient rgrad(rshadow.topLeft(), rshadow.topRight()); - rgrad.setColorAt(0.0, QColor(0,0,0,255)); - rgrad.setColorAt(1.0, QColor(0,0,0,0)); + rgrad.setColorAt(0.0, QColor(0, 0, 0, 255)); + rgrad.setColorAt(1.0, QColor(0, 0, 0, 0)); painter->fillRect(rshadow, QBrush(rgrad)); QRectF bshadow(rect.bottomLeft() + QPointF(shWidth, 0), rect.bottomRight() + QPointF(0, shWidth)); QLinearGradient bgrad(bshadow.topLeft(), bshadow.bottomLeft()); - bgrad.setColorAt(0.0, QColor(0,0,0,255)); - bgrad.setColorAt(1.0, QColor(0,0,0,0)); + bgrad.setColorAt(0.0, QColor(0, 0, 0, 255)); + bgrad.setColorAt(1.0, QColor(0, 0, 0, 0)); painter->fillRect(bshadow, QBrush(bgrad)); - QRectF cshadow(rect.bottomRight(), - rect.bottomRight() + QPointF(shWidth, shWidth)); + QRectF cshadow(rect.bottomRight(), rect.bottomRight() + QPointF(shWidth, shWidth)); QRadialGradient cgrad(cshadow.topLeft(), shWidth, cshadow.topLeft()); - cgrad.setColorAt(0.0, QColor(0,0,0,255)); - cgrad.setColorAt(1.0, QColor(0,0,0,0)); + cgrad.setColorAt(0.0, QColor(0, 0, 0, 255)); + cgrad.setColorAt(1.0, QColor(0, 0, 0, 0)); painter->fillRect(cshadow, QBrush(cgrad)); } void BaseDesignIntf::setGeometry(QRectF rect) { - if (m_rect == rect) return; + if (m_rect == rect) + return; m_oldGeometry = m_rect; if (!isLoading()) prepareGeometryChange(); m_rect = rect; - m_topRect = QRectF(0-resizeHandleSize(), 0-resizeHandleSize(), width()+resizeHandleSize()*2, resizeHandleSize()*2); - m_bottomRect = QRectF(0-resizeHandleSize(), height() - resizeHandleSize(), width()+resizeHandleSize()*2, resizeHandleSize()*2); - m_leftRect = QRectF(0-resizeHandleSize(), 0-resizeHandleSize(), resizeHandleSize()*2, height()+resizeHandleSize()*2); - m_rightRect = QRectF(width() - resizeHandleSize(), 0-resizeHandleSize(), resizeHandleSize()*2, height()+resizeHandleSize()*2); + m_topRect = QRectF(0 - resizeHandleSize(), 0 - resizeHandleSize(), + width() + resizeHandleSize() * 2, resizeHandleSize() * 2); + m_bottomRect = QRectF(0 - resizeHandleSize(), height() - resizeHandleSize(), + width() + resizeHandleSize() * 2, resizeHandleSize() * 2); + m_leftRect = QRectF(0 - resizeHandleSize(), 0 - resizeHandleSize(), resizeHandleSize() * 2, + height() + resizeHandleSize() * 2); + m_rightRect = QRectF(width() - resizeHandleSize(), 0 - resizeHandleSize(), + resizeHandleSize() * 2, height() + resizeHandleSize() * 2); m_boundingRect = QRectF(); updateSelectionMarker(); - if (!isLoading()){ + if (!isLoading()) { geometryChangedEvent(geometry(), m_oldGeometry); emit geometryChanged(this, geometry(), m_oldGeometry); } @@ -1188,14 +1112,11 @@ void BaseDesignIntf::geometryChangedEvent(QRectF newRect, QRectF oldRect) Q_UNUSED(newRect); } -void BaseDesignIntf::beforeDelete() -{ - -} +void BaseDesignIntf::beforeDelete() { } void BaseDesignIntf::setGeometryProperty(QRect rect) { - if ( rect != m_itemGeometry ){ + if (rect != m_itemGeometry) { QRectF oldValue = geometry(); if ((rect.x() != geometry().x()) || (rect.y() != geometry().y())) setPos(rect.x(), rect.y()); @@ -1204,30 +1125,28 @@ void BaseDesignIntf::setGeometryProperty(QRect rect) if (rect.height() != geometry().height()) setHeight(rect.height()); if (!isLoading()) { - notify("geometry",oldValue,rect); + notify("geometry", oldValue, rect); } } } -PageDesignIntf *BaseDesignIntf::page() -{ - return dynamic_cast(scene()); -} +PageDesignIntf* BaseDesignIntf::page() { return dynamic_cast(scene()); } void BaseDesignIntf::setPossibleResizeDirectionFlags(int directionsFlags) { m_possibleResizeDirectionFlags = directionsFlags; } -QPen BaseDesignIntf::borderPen(BorderSide side/*, bool selected*/) const +QPen BaseDesignIntf::borderPen(BorderSide side /*, bool selected*/) const { QPen pen; if (m_borderLinesFlags & side) { pen.setColor(m_borderColor); - if(borderStyle() != BorderStyle::Doubled) - pen.setStyle(static_cast(m_borderStyle)); - //pen.setCosmetic(true); - pen.setWidthF(m_borderLineSize+1); //To draw with point precision (By default: 2px = 1 pt) + if (borderStyle() != BorderStyle::Doubled) + pen.setStyle(static_cast(m_borderStyle)); + // pen.setCosmetic(true); + pen.setWidthF(m_borderLineSize + + 1); // To draw with point precision (By default: 2px = 1 pt) } else { pen.setColor(Qt::darkGray); @@ -1237,31 +1156,23 @@ QPen BaseDesignIntf::borderPen(BorderSide side/*, bool selected*/) const return pen; } -QColor BaseDesignIntf::selectionColor() const -{ - return Const::SELECTION_COLOR; -} +QColor BaseDesignIntf::selectionColor() const { return Const::SELECTION_COLOR; } void BaseDesignIntf::initFlags() { - if ((itemMode()&DesignMode) || (itemMode()&EditMode)) { + if ((itemMode() & DesignMode) || (itemMode() & EditMode)) { setFlag(QGraphicsItem::ItemIsSelectable); setFlag(QGraphicsItem::ItemSendsGeometryChanges); setAcceptHoverEvents(true); - } - else { + } else { setFlag(QGraphicsItem::ItemIsSelectable, false); setAcceptHoverEvents(false); } - } -void BaseDesignIntf::initMode(ItemMode mode) -{ - Q_UNUSED(mode); -} +void BaseDesignIntf::initMode(ItemMode mode) { Q_UNUSED(mode); } -QVariant BaseDesignIntf::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) +QVariant BaseDesignIntf::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant& value) { if (change == QGraphicsItem::ItemPositionHasChanged) { @@ -1280,25 +1191,21 @@ QVariant BaseDesignIntf::itemChange(QGraphicsItem::GraphicsItemChange change, co return QGraphicsItem::itemChange(change, value); } -void BaseDesignIntf::childAddedEvent(BaseDesignIntf *child) -{ - Q_UNUSED(child) -} +void BaseDesignIntf::childAddedEvent(BaseDesignIntf* child) { Q_UNUSED(child) } -void BaseDesignIntf::parentChangedEvent(BaseDesignIntf *) -{ - -} +void BaseDesignIntf::parentChangedEvent(BaseDesignIntf*) { } void BaseDesignIntf::restoreLinks() { #ifdef HAVE_QT5 - foreach(QObject * child, children()) { + foreach (QObject* child, children()) { #else - foreach(QObject * child, QObject::children()) { + foreach (QObject* child, QObject::children()) { #endif - BaseDesignIntf *childItem = dynamic_cast(child); - if (childItem) {childItem->restoreLinks();} + BaseDesignIntf* childItem = dynamic_cast(child); + if (childItem) { + childItem->restoreLinks(); + } } restoreLinksEvent(); } @@ -1310,7 +1217,7 @@ QPainterPath BaseDesignIntf::shape() const return path; } -void BaseDesignIntf::drawMarker(QPainter *painter, QColor color) const +void BaseDesignIntf::drawMarker(QPainter* painter, QColor color) const { painter->save(); @@ -1319,18 +1226,23 @@ void BaseDesignIntf::drawMarker(QPainter *painter, QColor color) const painter->setBrush(QBrush(color)); painter->setOpacity(1); const int markerSize = Const::RESIZE_HANDLE_SIZE; - painter->drawRect(QRectF(-markerSize,-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize,rect().bottom()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize,rect().top()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()-markerSize,rect().bottom()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()-markerSize, - rect().bottom()-rect().height()/2-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize, - rect().bottom()-rect().height()/2-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()+rect().width()/2-markerSize, - rect().top()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()+rect().width()/2-markerSize, - rect().bottom()-markerSize,markerSize*2,markerSize*2)); + painter->drawRect(QRectF(-markerSize, -markerSize, markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, rect().bottom() - markerSize, + markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, rect().top() - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().left() - markerSize, rect().bottom() - markerSize, + markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().left() - markerSize, + rect().bottom() - rect().height() / 2 - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, + rect().bottom() - rect().height() / 2 - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().left() + rect().width() / 2 - markerSize, + rect().top() - markerSize, markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().left() + rect().width() / 2 - markerSize, + rect().bottom() - markerSize, markerSize * 2, markerSize * 2)); pen.setStyle(Qt::DotLine); painter->setPen(pen); @@ -1341,12 +1253,12 @@ void BaseDesignIntf::drawMarker(QPainter *painter, QColor color) const void BaseDesignIntf::moveSelectedItems(QPointF delta) { - QList selectedItems; + QList selectedItems; selectedItems = scene()->selectedItems(); - BaseDesignIntf *selectedItem; - foreach(QGraphicsItem * item, selectedItems) { + BaseDesignIntf* selectedItem; + foreach (QGraphicsItem* item, selectedItems) { if (item != this) { - selectedItem = dynamic_cast(item); + selectedItem = dynamic_cast(item); if (selectedItem && !selectedItem->isBand()) { if (!selectedItem->m_fixedPos) selectedItem->setItemPos(selectedItem->pos() - delta); @@ -1355,22 +1267,20 @@ void BaseDesignIntf::moveSelectedItems(QPointF delta) } } -void BaseDesignIntf::setItemPos(qreal x, qreal y) -{ - setItemPos(QPointF(x, y)); -} +void BaseDesignIntf::setItemPos(qreal x, qreal y) { setItemPos(QPointF(x, y)); } void BaseDesignIntf::setItemMode(ItemMode mode) { m_itemMode = mode; - foreach(QGraphicsItem * item, childItems()) { - BaseDesignIntf *ri = dynamic_cast(item); - if (ri) ri->setItemMode(mode); + foreach (QGraphicsItem* item, childItems()) { + BaseDesignIntf* ri = dynamic_cast(item); + if (ri) + ri->setItemMode(mode); } initMode(mode); initFlags(); } -void BaseDesignIntf::setItemPos(const QPointF &newPos) +void BaseDesignIntf::setItemPos(const QPointF& newPos) { QPointF oldPos = pos(); QPointF finalPos = modifyPosForAlignedItem(newPos); @@ -1378,7 +1288,6 @@ void BaseDesignIntf::setItemPos(const QPointF &newPos) emit posChanging(this, finalPos, oldPos); } - QWidget* BaseDesignIntf::findRootWidget(QWidget* widget) { while (widget->parentWidget()) { @@ -1387,13 +1296,13 @@ QWidget* BaseDesignIntf::findRootWidget(QWidget* widget) return widget; } -void BaseDesignIntf::showDialog(QWidget *widget) +void BaseDesignIntf::showDialog(QWidget* widget) { if (!widget) { return; } widget->setStyleSheet(findRootWidget(scene()->views().at(0))->styleSheet()); - QDialog *dialog = new QDialog(QApplication::activeWindow()); + QDialog* dialog = new QDialog(QApplication::activeWindow()); widget->setParent(dialog); widget->setAttribute(Qt::WA_DeleteOnClose); #ifdef Q_OS_MAC @@ -1403,34 +1312,31 @@ void BaseDesignIntf::showDialog(QWidget *widget) #endif dialog->setLayout(new QVBoxLayout()); dialog->resize(widget->size()); - dialog->layout()->setContentsMargins(2,2,2,2); + dialog->layout()->setContentsMargins(2, 2, 2, 2); dialog->layout()->addWidget(widget); - connect(widget,SIGNAL(destroyed()),dialog,SLOT(close())); + connect(widget, SIGNAL(destroyed()), dialog, SLOT(close())); dialog->setWindowTitle(widget->windowTitle()); dialog->exec(); dialog->deleteLater(); } -void BaseDesignIntf::showEditorDialog() -{ - showDialog(defaultEditor()); -} +void BaseDesignIntf::showEditorDialog() { showDialog(defaultEditor()); } -void BaseDesignIntf::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +void BaseDesignIntf::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { - if (event->button() == Qt::LeftButton && - ((itemMode()&EditMode)||(itemMode()&DesignMode)) - ) { + if (event->button() == Qt::LeftButton + && ((itemMode() & EditMode) || (itemMode() & DesignMode))) { showEditorDialog(); } QGraphicsItem::mouseDoubleClickEvent(event); } -void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { - if (!(flags() & QGraphicsItem::ItemIsSelectable)) return; + if (!(flags() & QGraphicsItem::ItemIsSelectable)) + return; PageDesignIntf* page = dynamic_cast(scene()); - if (!page->selectedItems().contains(this)){ + if (!page->selectedItems().contains(this)) { page->clearSelection(); this->setSelected(true); } @@ -1443,11 +1349,11 @@ void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) menu.addSeparator(); QAction* copyAction = menu.addAction(QIcon(":/report/images/copy"), tr("Copy")); - QAction* cutAction = menu.addAction(QIcon(":/report/images/cut"), tr("Cut")); + QAction* cutAction = menu.addAction(QIcon(":/report/images/cut"), tr("Cut")); QAction* pasteAction = menu.addAction(QIcon(":/report/images/paste"), tr("Paste")); pasteAction->setEnabled(false); -#if QT_VERSION >=QT_VERSION_CHECK(5,0,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) lockGeometryAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L)); copyAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C)); cutAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X)); @@ -1459,31 +1365,36 @@ void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) pasteAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_V)); #endif - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); ItemsReaderIntf::Ptr reader = StringXMLreader::create(clipboard->text()); - if (reader->first() && reader->itemType() == "Object"){ + if (reader->first() && reader->itemType() == "Object") { pasteAction->setEnabled(true); } menu.addSeparator(); - QAction* bringToTopAction = menu.addAction(QIcon(":/report/images/bringToTop"), tr("Bring to top")); - QAction* sendToBackAction = menu.addAction(QIcon(":/report/images/sendToBack"), tr("Send to back")); + QAction* bringToTopAction + = menu.addAction(QIcon(":/report/images/bringToTop"), tr("Bring to top")); + QAction* sendToBackAction + = menu.addAction(QIcon(":/report/images/sendToBack"), tr("Send to back")); QAction* createHLayout = 0; - if( page->selectedItems().count()>1){ - createHLayout = menu.addAction(QIcon(":/report/images/hlayout"), tr("Create Horizontal Layout")); + if (page->selectedItems().count() > 1) { + createHLayout + = menu.addAction(QIcon(":/report/images/hlayout"), tr("Create Horizontal Layout")); } QAction* createVLayout = 0; - if( page->selectedItems().count()>1){ - createVLayout = menu.addAction(QIcon(":/report/images/vlayout"), tr("Create Vertical Layout")); + if (page->selectedItems().count() > 1) { + createVLayout + = menu.addAction(QIcon(":/report/images/vlayout"), tr("Create Vertical Layout")); } menu.addSeparator(); QAction* noBordersAction = menu.addAction(QIcon(":/report/images/noLines"), tr("No borders")); - QAction* allBordersAction = menu.addAction(QIcon(":/report/images/allLines"), tr("All borders")); - QAction* editBorderAction = menu.addAction(QIcon(":/report/images/borderEditor"), tr("Edit borders...")); + QAction* allBordersAction + = menu.addAction(QIcon(":/report/images/allLines"), tr("All borders")); + QAction* editBorderAction + = menu.addAction(QIcon(":/report/images/borderEditor"), tr("Edit borders...")); preparePopUpMenu(menu); QAction* a = menu.exec(event->screenPos()); - if (a){ - if (a == cutAction) - { + if (a) { + if (a == cutAction) { page->cut(); return; } @@ -1499,12 +1410,14 @@ void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) page->setBorders(BaseDesignIntf::NoLine); if (a == allBordersAction) page->setBorders(BaseDesignIntf::AllLines); - if (a == editBorderAction) - { + if (a == editBorderAction) { BorderEditor be; be.loadItem(this); - if (be.exec() == QDialog::Rejected) return; - page->setBordersExt(be.borderSides(), be.borderWidth(), (LimeReport::BaseDesignIntf::BorderStyle)be.borderStyle(), be.borderColor()); + if (be.exec() == QDialog::Rejected) + return; + page->setBordersExt(be.borderSides(), be.borderWidth(), + (LimeReport::BaseDesignIntf::BorderStyle)be.borderStyle(), + be.borderColor()); } if (a == createHLayout) page->addHLayout(); @@ -1514,26 +1427,24 @@ void BaseDesignIntf::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) } } -int BaseDesignIntf::possibleMoveDirectionFlags() const -{ - return m_possibleMoveDirectionFlags; -} +int BaseDesignIntf::possibleMoveDirectionFlags() const { return m_possibleMoveDirectionFlags; } void BaseDesignIntf::setPossibleMoveFlags(int directionsFlags) { m_possibleMoveDirectionFlags = directionsFlags; } -int BaseDesignIntf::marginSize() const { +int BaseDesignIntf::marginSize() const +{ return m_margin + (m_reportSettings != 0 ? m_reportSettings->baseItemPadding() : 0); } void BaseDesignIntf::setMarginSize(int value) { - if (m_margin!=value){ + if (m_margin != value) { int oldValue = m_margin; - m_margin=value; - if (!isLoading()){ + m_margin = value; + if (!isLoading()) { update(rect()); notify("margin", oldValue, value); } @@ -1546,37 +1457,43 @@ void BaseDesignIntf::drawResizeZone(QPainter* /*painter*/) // if (m_resizeAreas.count() > 0) { // painter->save(); // painter->setPen(QPen(Const::RESIZE_ZONE_COLOR)); - // (isSelected()) ? painter->setOpacity(Const::SELECTED_RESIZE_ZONE_OPACITY) : painter->setOpacity(Const::RESIZE_ZONE_OPACITY); + // (isSelected()) ? painter->setOpacity(Const::SELECTED_RESIZE_ZONE_OPACITY) : + // painter->setOpacity(Const::RESIZE_ZONE_OPACITY); // painter->setBrush(QBrush(Qt::green, Qt::SolidPattern)); // foreach(QRectF * resizeArea, m_resizeAreas) painter->drawRect(*resizeArea); // painter->restore(); // } - } void BaseDesignIntf::initResizeZones() { m_resizeAreas.clear(); - if (m_resizeDirectionFlags & ResizeBottom) m_resizeAreas.append(&m_bottomRect); - if (m_resizeDirectionFlags & ResizeTop) m_resizeAreas.append(&m_topRect); - if (m_resizeDirectionFlags & ResizeLeft) m_resizeAreas.append(&m_leftRect); - if (m_resizeDirectionFlags & ResizeRight) m_resizeAreas.append(&m_rightRect); + if (m_resizeDirectionFlags & ResizeBottom) + m_resizeAreas.append(&m_bottomRect); + if (m_resizeDirectionFlags & ResizeTop) + m_resizeAreas.append(&m_topRect); + if (m_resizeDirectionFlags & ResizeLeft) + m_resizeAreas.append(&m_leftRect); + if (m_resizeDirectionFlags & ResizeRight) + m_resizeAreas.append(&m_rightRect); } -void BaseDesignIntf::invalidateRect(const QRectF &rect) +void BaseDesignIntf::invalidateRect(const QRectF& rect) { if (scene()) scene()->update(mapToScene(rect).boundingRect()); } -ReportEnginePrivate *BaseDesignIntf::reportEditor() +ReportEnginePrivate* BaseDesignIntf::reportEditor() { - PageDesignIntf *page = dynamic_cast(scene()); - if (page) return page->reportEditor(); - else return 0; + PageDesignIntf* page = dynamic_cast(scene()); + if (page) + return page->reportEditor(); + else + return 0; } -void BaseDesignIntf::updateItemSize(DataSourceManager *dataManager, RenderPass pass, int maxHeight) +void BaseDesignIntf::updateItemSize(DataSourceManager* dataManager, RenderPass pass, int maxHeight) { Q_UNUSED(maxHeight); Q_UNUSED(dataManager); @@ -1584,26 +1501,27 @@ void BaseDesignIntf::updateItemSize(DataSourceManager *dataManager, RenderPass p updateItemAlign(); } -bool BaseDesignIntf::isNeedUpdateSize(RenderPass /*pass*/) const -{return false;} +bool BaseDesignIntf::isNeedUpdateSize(RenderPass /*pass*/) const { return false; } -void BaseDesignIntf::drawPinArea(QPainter *painter) const +void BaseDesignIntf::drawPinArea(QPainter* painter) const { painter->drawRect(QRect(0, 0, 16, 16)); } -QObject *BaseDesignIntf::createElement(const QString& /*collectionName*/, const QString &elementType) +QObject* BaseDesignIntf::createElement(const QString& /*collectionName*/, + const QString& elementType) { BaseDesignIntf* obj = 0; - try{ - if (LimeReport::DesignElementsFactory::instance().objectCreator(elementType)){ - obj = LimeReport::DesignElementsFactory::instance().objectCreator(elementType)(this, this); + try { + if (LimeReport::DesignElementsFactory::instance().objectCreator(elementType)) { + obj = LimeReport::DesignElementsFactory::instance().objectCreator(elementType)(this, + this); if (page()) - connect(obj, SIGNAL(propertyChanged(QString,QVariant,QVariant)), - page(), SLOT(slotItemPropertyChanged(QString,QVariant,QVariant))); + connect(obj, SIGNAL(propertyChanged(QString, QVariant, QVariant)), page(), + SLOT(slotItemPropertyChanged(QString, QVariant, QVariant))); } - } catch (ReportError &error){ - qDebug()<(obj); + BaseDesignIntf* item = dynamic_cast(obj); if (item && page()) { page()->registerItem(item); } @@ -1637,99 +1555,117 @@ void BaseDesignIntf::collectionLoadFinished(const QString &collectionName) emit loadCollectionFinished(collectionName); } -BaseDesignIntf *BaseDesignIntf::cloneItem(ItemMode mode, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* BaseDesignIntf::cloneItem(ItemMode mode, QObject* owner, QGraphicsItem* parent) { - BaseDesignIntf *clone = cloneItemWOChild(mode, owner, parent); + BaseDesignIntf* clone = cloneItemWOChild(mode, owner, parent); clone->setPatternName(this->objectName()); clone->setPatternItem(this); #ifdef HAVE_QT5 - foreach(QObject * child, children()) { + foreach (QObject* child, children()) { #else - foreach(QObject * child, QObject::children()) { + foreach (QObject* child, QObject::children()) { #endif - BaseDesignIntf *childItem = dynamic_cast(child); - if (childItem) {clone->childAddedEvent(childItem->cloneItem(mode, clone, clone));} + BaseDesignIntf* childItem = dynamic_cast(child); + if (childItem) { + clone->childAddedEvent(childItem->cloneItem(mode, clone, clone)); + } } return clone; } -BaseDesignIntf *BaseDesignIntf::cloneItemWOChild(ItemMode mode, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* BaseDesignIntf::cloneItemWOChild(ItemMode mode, QObject* owner, + QGraphicsItem* parent) { - BaseDesignIntf *clone = createSameTypeItem(owner, parent); + BaseDesignIntf* clone = createSameTypeItem(owner, parent); clone->setObjectName(this->objectName()); clone->setItemMode(mode); clone->objectLoadStarted(); clone->setReportSettings(this->reportSettings()); for (int i = 0; i < clone->metaObject()->propertyCount(); i++) { if (clone->metaObject()->property(i).isWritable()) - clone->setProperty(clone->metaObject()->property(i).name(), property(clone->metaObject()->property(i).name())); + clone->setProperty(clone->metaObject()->property(i).name(), + property(clone->metaObject()->property(i).name())); } clone->objectLoadFinished(); return clone; } -void BaseDesignIntf::initFromItem(BaseDesignIntf *source) +void BaseDesignIntf::initFromItem(BaseDesignIntf* source) { objectLoadStarted(); for (int i = 0; i < metaObject()->propertyCount(); i++) { - if (strcmp(metaObject()->property(i).name(),"objectName")!=0) + if (strcmp(metaObject()->property(i).name(), "objectName") != 0) if (source->property(metaObject()->property(i).name()).isValid()) { if (metaObject()->property(i).isWritable()) - setProperty(metaObject()->property(i).name(), source->property(metaObject()->property(i).name())); + setProperty(metaObject()->property(i).name(), + source->property(metaObject()->property(i).name())); } } objectLoadFinished(); } bool BaseDesignIntf::canBeSplitted(int height) const -{Q_UNUSED(height); return false;} - -bool BaseDesignIntf::isEmpty() const -{return false;} - -BaseDesignIntf *BaseDesignIntf::cloneUpperPart(int height, QObject *owner, QGraphicsItem *parent) -{Q_UNUSED(height); Q_UNUSED(owner); Q_UNUSED(parent); return 0;} - -BaseDesignIntf *BaseDesignIntf::cloneBottomPart(int height, QObject *owner, QGraphicsItem *parent) -{Q_UNUSED(height); Q_UNUSED(owner); Q_UNUSED(parent); return 0;} - -BaseDesignIntf *BaseDesignIntf::cloneEmpty(int height, QObject *owner, QGraphicsItem *parent) -{Q_UNUSED(height); Q_UNUSED(owner); Q_UNUSED(parent); return 0;} - - -void BaseDesignIntf::objectLoadStarted() { - m_objectState = ObjectLoading; + Q_UNUSED(height); + return false; } +bool BaseDesignIntf::isEmpty() const { return false; } + +BaseDesignIntf* BaseDesignIntf::cloneUpperPart(int height, QObject* owner, QGraphicsItem* parent) +{ + Q_UNUSED(height); + Q_UNUSED(owner); + Q_UNUSED(parent); + return 0; +} + +BaseDesignIntf* BaseDesignIntf::cloneBottomPart(int height, QObject* owner, QGraphicsItem* parent) +{ + Q_UNUSED(height); + Q_UNUSED(owner); + Q_UNUSED(parent); + return 0; +} + +BaseDesignIntf* BaseDesignIntf::cloneEmpty(int height, QObject* owner, QGraphicsItem* parent) +{ + Q_UNUSED(height); + Q_UNUSED(owner); + Q_UNUSED(parent); + return 0; +} + +void BaseDesignIntf::objectLoadStarted() { m_objectState = ObjectLoading; } + void BaseDesignIntf::objectLoadFinished() { m_objectState = ObjectLoaded; emit objectLoaded(this); } -void BaseDesignIntf::parentObjectLoadFinished() -{} +void BaseDesignIntf::parentObjectLoadFinished() { } -QList BaseDesignIntf::childBaseItems() const +QList BaseDesignIntf::childBaseItems() const { - QList resList; - foreach(QGraphicsItem * item, childItems()) { - BaseDesignIntf *baseItem = dynamic_cast(item); - if (baseItem) resList << baseItem; + QList resList; + foreach (QGraphicsItem* item, childItems()) { + BaseDesignIntf* baseItem = dynamic_cast(item); + if (baseItem) + resList << baseItem; } return resList; } - -void BaseDesignIntf::addChildItems(QList* list){ - foreach(BaseDesignIntf* item, childBaseItems()){ +void BaseDesignIntf::addChildItems(QList* list) +{ + foreach (BaseDesignIntf* item, childBaseItems()) { list->append(item); item->addChildItems(list); } } -qreal BaseDesignIntf::calcAbsolutePosY(qreal currentOffset, BaseDesignIntf *item) +qreal BaseDesignIntf::calcAbsolutePosY(qreal currentOffset, BaseDesignIntf* item) { BaseDesignIntf* parent = dynamic_cast(item->parent()); if (parent) @@ -1738,7 +1674,7 @@ qreal BaseDesignIntf::calcAbsolutePosY(qreal currentOffset, BaseDesignIntf *item return currentOffset + item->getItemPosY(); } -qreal BaseDesignIntf::calcAbsolutePosX(qreal currentOffset, BaseDesignIntf *item) +qreal BaseDesignIntf::calcAbsolutePosX(qreal currentOffset, BaseDesignIntf* item) { BaseDesignIntf* parent = dynamic_cast(item->parent()); if (parent) @@ -1749,30 +1685,29 @@ qreal BaseDesignIntf::calcAbsolutePosX(qreal currentOffset, BaseDesignIntf *item QList BaseDesignIntf::allChildBaseItems() { - QList resList; + QList resList; addChildItems(&resList); return resList; } -BaseDesignIntf *BaseDesignIntf::childByName(const QString &name) +BaseDesignIntf* BaseDesignIntf::childByName(const QString& name) { - foreach(BaseDesignIntf* item, childBaseItems()){ - if (item->objectName().compare(name,Qt::CaseInsensitive)==0){ + foreach (BaseDesignIntf* item, childBaseItems()) { + if (item->objectName().compare(name, Qt::CaseInsensitive) == 0) { return item; } else { BaseDesignIntf* child = item->childByName(name); - if (child) return child; + if (child) + return child; } } return 0; } -QWidget *BaseDesignIntf::defaultEditor() -{ - return 0; -} +QWidget* BaseDesignIntf::defaultEditor() { return 0; } -void BaseDesignIntf::notify(const QString &propertyName, const QVariant& oldValue, const QVariant& newValue) +void BaseDesignIntf::notify(const QString& propertyName, const QVariant& oldValue, + const QVariant& newValue) { if (!isLoading()) emit propertyChanged(propertyName, oldValue, newValue); @@ -1784,29 +1719,27 @@ void BaseDesignIntf::notify(const QVector& propertyNames) emit propertyesChanged(propertyNames); } - -QMap BaseDesignIntf::getStringForTranslation(){ - return QMap(); +QMap BaseDesignIntf::getStringForTranslation() +{ + return QMap(); } QVariant BookmarkContainerDesignIntf::getBookMark(const QString& key) { if (m_bookmarks.contains(key)) return m_bookmarks.value(key); - else return QVariant(); + else + return QVariant(); } void BookmarkContainerDesignIntf::copyBookmarks(BookmarkContainerDesignIntf* source) { - foreach(QString key, source->bookmarks()){ - addBookmark(key,source->getBookMark(key)); + foreach (QString key, source->bookmarks()) { + addBookmark(key, source->getBookMark(key)); } } -QRectF Marker::boundingRect() const -{ - return m_rect.adjusted(-15,-15,15,15); -} +QRectF Marker::boundingRect() const { return m_rect.adjusted(-15, -15, 15, 15); } void Marker::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) { @@ -1822,26 +1755,29 @@ void Marker::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) painter->setPen(Qt::transparent); painter->setOpacity(1); - painter->drawRect(QRectF(-markerSize,-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize,rect().bottom()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize,rect().top()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()-markerSize,rect().bottom()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()-markerSize, - rect().bottom()-rect().height()/2-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().right()-markerSize, - rect().bottom()-rect().height()/2-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()+rect().width()/2-markerSize, - rect().top()-markerSize,markerSize*2,markerSize*2)); - painter->drawRect(QRectF(rect().left()+rect().width()/2-markerSize, - rect().bottom()-markerSize,markerSize*2,markerSize*2)); + painter->drawRect(QRectF(-markerSize, -markerSize, markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, rect().bottom() - markerSize, + markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, rect().top() - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().left() - markerSize, rect().bottom() - markerSize, + markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().left() - markerSize, + rect().bottom() - rect().height() / 2 - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().right() - markerSize, + rect().bottom() - rect().height() / 2 - markerSize, markerSize * 2, + markerSize * 2)); + painter->drawRect(QRectF(rect().left() + rect().width() / 2 - markerSize, + rect().top() - markerSize, markerSize * 2, markerSize * 2)); + painter->drawRect(QRectF(rect().left() + rect().width() / 2 - markerSize, + rect().bottom() - markerSize, markerSize * 2, markerSize * 2)); } -QColor Marker::color() const { - return m_color; -} +QColor Marker::color() const { return m_color; } -SelectionMarker::SelectionMarker(QGraphicsItem* parent, BaseDesignIntf* owner) - : Marker(parent, owner) +SelectionMarker::SelectionMarker(QGraphicsItem* parent, BaseDesignIntf* owner): + Marker(parent, owner) { setAcceptHoverEvents(true); } @@ -1851,44 +1787,49 @@ QColor SelectionMarker::color() const return owner()->isGeometryLocked() ? Qt::darkGray : Marker::color(); } -void SelectionMarker::hoverMoveEvent(QGraphicsSceneHoverEvent *event) +void SelectionMarker::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { - if (owner()) owner()->hoverMoveEvent(event); + if (owner()) + owner()->hoverMoveEvent(event); QGraphicsItem::hoverMoveEvent(event); } -void SelectionMarker::mousePressEvent(QGraphicsSceneMouseEvent *event) +void SelectionMarker::mousePressEvent(QGraphicsSceneMouseEvent* event) { - if (owner()){ + if (owner()) { owner()->setSelected(true); owner()->mousePressEvent(event); } QGraphicsItem::mousePressEvent(event); } -void SelectionMarker::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +void SelectionMarker::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { - if (owner()) owner()->mouseReleaseEvent(event); + if (owner()) + owner()->mouseReleaseEvent(event); } -void SelectionMarker::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +void SelectionMarker::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { - if (owner()) owner()->mouseDoubleClickEvent(event); + if (owner()) + owner()->mouseDoubleClickEvent(event); QGraphicsItem::mouseDoubleClickEvent(event); } -void SelectionMarker::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +void SelectionMarker::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { qDebug() << "mouse move"; - if (owner()) owner()->mouseMoveEvent(event); + if (owner()) + owner()->mouseMoveEvent(event); } -void BaseDesignIntf::processPopUpAction(QAction *action){ - if (page()){ - if (action->text().compare(tr("Lock item geometry")) == 0){ - page()->setPropertyToSelectedItems("geometryLocked",action->isChecked()); +void BaseDesignIntf::processPopUpAction(QAction* action) +{ + if (page()) { + if (action->text().compare(tr("Lock item geometry")) == 0) { + page()->setPropertyToSelectedItems("geometryLocked", action->isChecked()); } } } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrbasedesignintf.h b/limereport/lrbasedesignintf.h index f3d563d..5c90c9c 100644 --- a/limereport/lrbasedesignintf.h +++ b/limereport/lrbasedesignintf.h @@ -29,59 +29,79 @@ ****************************************************************************/ #ifndef LRBASEDESIGNINTF_H #define LRBASEDESIGNINTF_H -#include -#include -#include -#include -#include -#include #include "lrcollection.h" #include "lrglobal.h" #include "serializators/lrstorageintf.h" +#include +#include +#include +#include +#include +#include + Q_DECLARE_METATYPE(QList*) namespace LimeReport { -enum ItemModes{ DesignMode=1, PreviewMode=2, PrintMode=4, EditMode=8, LayoutEditMode=16 }; +enum ItemModes { + DesignMode = 1, + PreviewMode = 2, + PrintMode = 4, + EditMode = 8, + LayoutEditMode = 16 +}; class ReportEnginePrivate; class PageDesignIntf; -class BaseDesignIntf; +class BaseDesignIntf; -class LIMEREPORT_EXPORT Marker : public QGraphicsItem{ +class LIMEREPORT_EXPORT Marker: public QGraphicsItem { public: - Marker(QGraphicsItem* parent = 0, BaseDesignIntf* owner = 0): QGraphicsItem(parent), m_owner(owner){} + Marker(QGraphicsItem* parent = 0, BaseDesignIntf* owner = 0): + QGraphicsItem(parent), + m_owner(owner) + { + } QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); - void setRect(QRectF rect){prepareGeometryChange();m_rect=rect;} - void setColor(QColor color){m_color=color;} - QRectF rect() const {return m_rect;} + void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); + void setRect(QRectF rect) + { + prepareGeometryChange(); + m_rect = rect; + } + void setColor(QColor color) { m_color = color; } + QRectF rect() const { return m_rect; } virtual QColor color() const; - BaseDesignIntf* owner() const {return m_owner;} + BaseDesignIntf* owner() const { return m_owner; } + private: QRectF m_rect; QColor m_color; BaseDesignIntf* m_owner; }; -class LIMEREPORT_EXPORT SelectionMarker : public Marker{ +class LIMEREPORT_EXPORT SelectionMarker: public Marker { public: - SelectionMarker(QGraphicsItem* parent=0, BaseDesignIntf* owner = 0); + SelectionMarker(QGraphicsItem* parent = 0, BaseDesignIntf* owner = 0); QColor color() const; + protected: - void hoverMoveEvent(QGraphicsSceneHoverEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void hoverMoveEvent(QGraphicsSceneHoverEvent* event); + void mousePressEvent(QGraphicsSceneMouseEvent* event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event); + void mouseMoveEvent(QGraphicsSceneMouseEvent* event); }; class DataSourceManager; class ReportRender; -class LIMEREPORT_EXPORT BaseDesignIntf : - public QObject, public QGraphicsItem, public ICollectionContainer, public ObjectLoadingStateIntf { +class LIMEREPORT_EXPORT BaseDesignIntf: + public QObject, + public QGraphicsItem, + public ICollectionContainer, + public ObjectLoadingStateIntf { Q_OBJECT Q_INTERFACES(QGraphicsItem) Q_FLAGS(BorderLines) @@ -89,7 +109,8 @@ class LIMEREPORT_EXPORT BaseDesignIntf : Q_PROPERTY(ACollectionProperty children READ fakeCollectionReader DESIGNABLE false) Q_PROPERTY(qreal zOrder READ zValue WRITE setZValueProperty DESIGNABLE false) Q_PROPERTY(BorderLines borders READ borderLines WRITE setBorderLinesFlags) - Q_PROPERTY(QString parentName READ parentReportItemName WRITE setParentReportItem DESIGNABLE false) + Q_PROPERTY( + QString parentName READ parentReportItemName WRITE setParentReportItem DESIGNABLE false) Q_PROPERTY(qreal borderLineSize READ borderLineSize WRITE setBorderLineSize) Q_PROPERTY(bool isVisible READ isVisible WRITE setItemVisible DESIGNABLE false) Q_PROPERTY(bool shadow READ hasShadow WRITE setShadow) @@ -98,63 +119,83 @@ class LIMEREPORT_EXPORT BaseDesignIntf : Q_PROPERTY(BorderStyle borderStyle READ borderStyle WRITE setBorderStyle) friend class ReportRender; + public: - enum BGMode { TransparentMode, OpaqueMode}; - enum BorderStyle { NoStyle = Qt::NoPen, - Solid = Qt::SolidLine, - Dashed = Qt::DashLine, - Dot = Qt::DotLine, + enum BGMode { + TransparentMode, + OpaqueMode + }; + enum BorderStyle { + NoStyle = Qt::NoPen, + Solid = Qt::SolidLine, + Dashed = Qt::DashLine, + Dot = Qt::DotLine, - DashDot = Qt::DashDotLine, - DashDotDot = Qt::DashDotDotLine, - Doubled = 7 - }; + DashDot = Qt::DashDotLine, + DashDotDot = Qt::DashDotDotLine, + Doubled = 7 + }; + enum BrushStyle { + NoBrush, + SolidPattern, + Dense1Pattern, + Dense2Pattern, + Dense3Pattern, + Dense4Pattern, + Dense5Pattern, + Dense6Pattern, + Dense7Pattern, + HorPattern, + VerPattern, + CrossPattern, + BDiagPattern, + FDiagPattern + }; - enum BrushStyle{ NoBrush, - SolidPattern, - Dense1Pattern, - Dense2Pattern, - Dense3Pattern, - Dense4Pattern, - Dense5Pattern, - Dense6Pattern, - Dense7Pattern, - HorPattern, - VerPattern, - CrossPattern, - BDiagPattern, - FDiagPattern }; + enum ResizeFlags { + Fixed = 0, + ResizeLeft = 1, + ResizeRight = 2, + ResizeTop = 4, + ResizeBottom = 8, + AllDirections = 15 + }; - - enum ResizeFlags { Fixed = 0, - ResizeLeft = 1, - ResizeRight = 2, - ResizeTop = 4, - ResizeBottom = 8, - AllDirections = 15 - }; - - enum MoveFlags { None = 0, - LeftRight=1, - TopBotom=2, - All=3 - }; + enum MoveFlags { + None = 0, + LeftRight = 1, + TopBotom = 2, + All = 3 + }; enum BorderSide { - NoLine = 0, - TopLine = 1, - BottomLine = 2, - LeftLine = 4, - RightLine = 8, - AllLines = 15 - }; + NoLine = 0, + TopLine = 1, + BottomLine = 2, + LeftLine = 4, + RightLine = 8, + AllLines = 15 + }; - enum ObjectState {ObjectLoading, ObjectLoaded, ObjectCreated}; + enum ObjectState { + ObjectLoading, + ObjectLoaded, + ObjectCreated + }; - enum ItemAlign {LeftItemAlign,RightItemAlign,CenterItemAlign,ParentWidthItemAlign,DesignedItemAlign}; + enum ItemAlign { + LeftItemAlign, + RightItemAlign, + CenterItemAlign, + ParentWidthItemAlign, + DesignedItemAlign + }; - enum UnitType {Millimeters, Inches}; + enum UnitType { + Millimeters, + Inches + }; #if QT_VERSION >= 0x050500 Q_ENUM(BGMode) Q_ENUM(BrushStyle) @@ -178,61 +219,62 @@ public: Q_ENUMS(UnitType) #endif -// enum ExpandType {EscapeSymbols, NoEscapeSymbols, ReplaceHTMLSymbols}; + // enum ExpandType {EscapeSymbols, NoEscapeSymbols, ReplaceHTMLSymbols}; Q_DECLARE_FLAGS(BorderLines, BorderSide) - Q_DECLARE_FLAGS(ItemMode,ItemModes) + Q_DECLARE_FLAGS(ItemMode, ItemModes) friend class SelectionMarker; + public: BaseDesignIntf(const QString& storageTypeName, QObject* owner = 0, QGraphicsItem* parent = 0); virtual ~BaseDesignIntf(); - void setParentReportItem(const QString& value); + void setParentReportItem(const QString& value); QString parentReportItemName() const; - BrushStyle backgroundBrushStyle() const {return m_backgroundBrushStyle;} - BorderStyle borderStyle() const {return m_borderStyle;} - void setBackgroundBrushStyle(BrushStyle value); - QColor backgroundColor() const {return m_backgroundColor;} - void setBackgroundColor(QColor value); + BrushStyle backgroundBrushStyle() const { return m_backgroundBrushStyle; } + BorderStyle borderStyle() const { return m_borderStyle; } + void setBackgroundBrushStyle(BrushStyle value); + QColor backgroundColor() const { return m_backgroundColor; } + void setBackgroundColor(QColor value); - QPen pen() const; - void setPen(QPen& pen); - QFont font() const; - void setFont(QFont& font); - QColor fontColor() const {return m_fontColor;} - void setFontColor(QColor value){m_fontColor=value;} + QPen pen() const; + void setPen(QPen& pen); + QFont font() const; + void setFont(QFont& font); + QColor fontColor() const { return m_fontColor; } + void setFontColor(QColor value) { m_fontColor = value; } - virtual BGMode backgroundMode() const; - virtual void setBackgroundMode(BGMode bgMode); - virtual qreal width() const; - virtual qreal widthMM() const; - virtual void setWidth(qreal width); - virtual qreal height() const; - virtual qreal heightMM() const; - virtual void setHeight(qreal height); + virtual BGMode backgroundMode() const; + virtual void setBackgroundMode(BGMode bgMode); + virtual qreal width() const; + virtual qreal widthMM() const; + virtual void setWidth(qreal width); + virtual qreal height() const; + virtual qreal heightMM() const; + virtual void setHeight(qreal height); virtual QPointF posMM() const; - virtual int opacity() const; - virtual void setOpacity(int opacity); - virtual void setSize(QSizeF size); - virtual QSizeF size() const; - virtual QSizeF sizeMM() const; + virtual int opacity() const; + virtual void setOpacity(int opacity); + virtual void setSize(QSizeF size); + virtual QSizeF size() const; + virtual QSizeF sizeMM() const; - void paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, QWidget* widget); - void prepareRect(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); + void paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, QWidget* widget); + void prepareRect(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); virtual QPainterPath shape() const; void setFixedPos(bool fixedPos); - bool isFixedPos(){return m_fixedPos;} + bool isFixedPos() { return m_fixedPos; } int resizeHandleSize() const; - qreal unitFactor() const; - void setUnitType(UnitType unitType); + qreal unitFactor() const; + void setUnitType(UnitType unitType); UnitType unitType(); - virtual QRect geometry() const; - void setGeometry(QRectF rect); + virtual QRect geometry() const; + void setGeometry(QRectF rect); - QRectF rect() const; - void setupPainter(QPainter* painter) const; + QRectF rect() const; + void setupPainter(QPainter* painter) const; virtual QRectF boundingRect() const; virtual void moveRight(); @@ -245,11 +287,11 @@ public: virtual void sizeUp(); virtual void sizeDown(); - void setItemPos(const QPointF &newPos); + void setItemPos(const QPointF& newPos); void setItemPos(qreal x, qreal y); virtual void setItemMode(LimeReport::BaseDesignIntf::ItemMode mode); - ItemMode itemMode() const {return m_itemMode;} + ItemMode itemMode() const { return m_itemMode; } virtual void setBorderLinesFlags(LimeReport::BaseDesignIntf::BorderLines flags); void setGeometryProperty(QRect rect); @@ -257,26 +299,31 @@ public: BorderLines borderLines() const; - QString storageTypeName() const {return m_storageTypeName;} - ReportEnginePrivate *reportEditor(); + QString storageTypeName() const { return m_storageTypeName; } + ReportEnginePrivate* reportEditor(); - virtual void updateItemSize(DataSourceManager* dataManager, RenderPass pass=FirstPass, int maxHeight=0); + virtual void updateItemSize(DataSourceManager* dataManager, RenderPass pass = FirstPass, + int maxHeight = 0); virtual bool isNeedUpdateSize(RenderPass) const; - virtual BaseDesignIntf* cloneItem(LimeReport::BaseDesignIntf::ItemMode mode, QObject* owner=0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* cloneItemWOChild(LimeReport::BaseDesignIntf::ItemMode mode, QObject* owner=0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0) = 0; + virtual BaseDesignIntf* cloneItem(LimeReport::BaseDesignIntf::ItemMode mode, QObject* owner = 0, + QGraphicsItem* parent = 0); + virtual BaseDesignIntf* cloneItemWOChild(LimeReport::BaseDesignIntf::ItemMode mode, + QObject* owner = 0, QGraphicsItem* parent = 0); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0) = 0; virtual void initFromItem(BaseDesignIntf* source); virtual bool canBeSplitted(int height) const; - virtual qreal minHeight() const {return 0;} - virtual bool isSplittable() const {return false;} + virtual qreal minHeight() const { return 0; } + virtual bool isSplittable() const { return false; } virtual bool isEmpty() const; - virtual BaseDesignIntf* cloneUpperPart(int height, QObject* owner=0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* cloneBottomPart(int height, QObject* owner=0, QGraphicsItem* parent=0); - virtual BaseDesignIntf* cloneEmpty(int height, QObject* owner=0, QGraphicsItem* parent=0); + virtual BaseDesignIntf* cloneUpperPart(int height, QObject* owner = 0, + QGraphicsItem* parent = 0); + virtual BaseDesignIntf* cloneBottomPart(int height, QObject* owner = 0, + QGraphicsItem* parent = 0); + virtual BaseDesignIntf* cloneEmpty(int height, QObject* owner = 0, QGraphicsItem* parent = 0); - bool isLoaded(){return m_objectState==ObjectLoaded;} - bool isLoading(){return m_objectState==ObjectLoading;} + bool isLoaded() { return m_objectState == ObjectLoaded; } + bool isLoading() { return m_objectState == ObjectLoading; } void objectLoadStarted(); void objectLoadFinished(); virtual void parentObjectLoadFinished(); @@ -286,9 +333,9 @@ public: QList allChildBaseItems(); BaseDesignIntf* childByName(const QString& name); - virtual QWidget *defaultEditor(); - void notify(const QString &propertyName, const QVariant &oldValue, const QVariant &newValue); - void notify(const QVector &propertyNames); + virtual QWidget* defaultEditor(); + void notify(const QString& propertyName, const QVariant& oldValue, const QVariant& newValue); + void notify(const QVector& propertyNames); int possibleResizeDirectionFlags() const; void setPossibleResizeDirectionFlags(int directionsFlags); @@ -299,28 +346,28 @@ public: void setMarginSize(int value); QString itemTypeName() const; - void setItemTypeName(const QString &itemTypeName); + void setItemTypeName(const QString& itemTypeName); qreal borderLineSize() const; void setBorderStyle(BorderStyle b); void setBorderLineSize(qreal value); void showEditorDialog(); ItemAlign itemAlign() const; - virtual void setItemAlign(const ItemAlign &itemAlign); + virtual void setItemAlign(const ItemAlign& itemAlign); void updateItemAlign(); - QPointF modifyPosForAlignedItem(const QPointF &pos); + QPointF modifyPosForAlignedItem(const QPointF& pos); void turnOnJoinMarker(bool value); - virtual bool isBand(){return false;} + virtual bool isBand() { return false; } QColor borderColor() const; - void setBorderColor(const QColor &borderColor); + void setBorderColor(const QColor& borderColor); void setItemVisible(const bool& value); - virtual bool canContainChildren() const { return false;} - virtual bool canAcceptPaste() const{ return false;} + virtual bool canContainChildren() const { return false; } + virtual bool canAcceptPaste() const { return false; } ReportSettings* reportSettings() const; - void setReportSettings(ReportSettings *reportSettings); + void setReportSettings(ReportSettings* reportSettings); void setZValueProperty(qreal value); QString patternName() const; - void setPatternName(const QString &patternName); + void setPatternName(const QString& patternName); BaseDesignIntf* patternItem() const; void setPatternItem(BaseDesignIntf* patternItem); virtual QMap getStringForTranslation(); @@ -353,66 +400,66 @@ public: Q_INVOKABLE QString setItemPosY(qreal yValue); protected: - - //ICollectionContainer + // ICollectionContainer QObject* createElement(const QString&, const QString& elementType); int elementsCount(const QString&); QObject* elementAt(const QString&, int index); void collectionLoadFinished(const QString& collectionName); - //ICollectionContainer + // ICollectionContainer - void mousePressEvent(QGraphicsSceneMouseEvent* event); - void hoverMoveEvent(QGraphicsSceneHoverEvent* event); - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent* ); - void mouseMoveEvent(QGraphicsSceneMouseEvent* event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent* event); + void hoverMoveEvent(QGraphicsSceneHoverEvent* event); + void hoverLeaveEvent(QGraphicsSceneHoverEvent* event); + void hoverEnterEvent(QGraphicsSceneHoverEvent*); + void mouseMoveEvent(QGraphicsSceneMouseEvent* event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event); - void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + void contextMenuEvent(QGraphicsSceneContextMenuEvent* event); virtual void geometryChangedEvent(QRectF newRect, QRectF oldRect); virtual QPen borderPen(BorderSide side) const; virtual QColor selectionColor() const; virtual void initFlags(); virtual void initMode(LimeReport::BaseDesignIntf::ItemMode mode); - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); + virtual QVariant itemChange(GraphicsItemChange change, const QVariant& value); virtual void childAddedEvent(BaseDesignIntf* child); virtual void parentChangedEvent(BaseDesignIntf*); void restoreLinks(); - virtual void restoreLinksEvent(){} - - void drawTopLine(QPainter *painter, QRectF rect) const; - void drawBootomLine(QPainter *painter, QRectF rect) const; - void drawRightLine(QPainter *painter, QRectF rect) const; - void drawLeftLine(QPainter *painter, QRectF rect) const; + virtual void restoreLinksEvent() { } + void drawTopLine(QPainter* painter, QRectF rect) const; + void drawBootomLine(QPainter* painter, QRectF rect) const; + void drawRightLine(QPainter* painter, QRectF rect) const; + void drawLeftLine(QPainter* painter, QRectF rect) const; void drawBorder(QPainter* painter, QRectF rect) const; void drawShadow(QPainter* painter, QRectF rect, qreal shadowSize) const; void drawDesignModeBorder(QPainter* painter, QRectF rect) const; - void drawRenderModeBorder(QPainter *painter, QRectF rect) const; + void drawRenderModeBorder(QPainter* painter, QRectF rect) const; void drawResizeZone(QPainter*); void drawMarker(QPainter* painter, QColor color) const; void drawPinArea(QPainter* painter) const; void initResizeZones(); - void invalidateRect(const QRectF &rect); + void invalidateRect(const QRectF& rect); void invalidateRects(QVector rects); - QFont transformToSceneFont(const QFont &value) const; + QFont transformToSceneFont(const QFont& value) const; - RenderPass currentRenderPass(){return m_currentPass;} + RenderPass currentRenderPass() { return m_currentPass; } - virtual bool drawDesignBorders() const {return true;} - virtual QColor selectionMarkerColor(){ return Const::SELECTION_COLOR;} + virtual bool drawDesignBorders() const { return true; } + virtual QColor selectionMarkerColor() { return Const::SELECTION_COLOR; } - QString expandUserVariables(QString context, RenderPass pass, ExpandType expandType, DataSourceManager *dataManager); - QString expandDataFields(QString context, ExpandType expandType, DataSourceManager *dataManager); - QString expandScripts(QString context, DataSourceManager *dataManager); + QString expandUserVariables(QString context, RenderPass pass, ExpandType expandType, + DataSourceManager* dataManager); + QString expandDataFields(QString context, ExpandType expandType, + DataSourceManager* dataManager); + QString expandScripts(QString context, DataSourceManager* dataManager); QVariant m_varValue; - virtual void preparePopUpMenu(QMenu& menu){Q_UNUSED(menu)} + virtual void preparePopUpMenu(QMenu& menu) { Q_UNUSED(menu) } virtual void processPopUpAction(QAction* action); void addChildItems(QList* list); @@ -420,7 +467,7 @@ protected: qreal calcAbsolutePosX(qreal currentOffset, BaseDesignIntf* item); QWidget* findRootWidget(QWidget* widget); - void showDialog(QWidget *widget); + void showDialog(QWidget* widget); private: int resizeDirectionFlags(QPointF position); @@ -433,29 +480,28 @@ private slots: private: QPointF m_startPos; - int m_resizeHandleSize; - int m_selectionPenSize; - int m_possibleResizeDirectionFlags; - int m_possibleMoveDirectionFlags; - int m_savedPossibleResizeDirectionFlags; - int m_savedPossibleMoveDirectionFlags; - int m_savedFixedPos; - int m_resizeDirectionFlags; - qreal m_width; - qreal m_height; - QPen m_pen; - QFont m_font; - QColor m_fontColor; - bool m_fixedPos; - qreal m_borderLineSize; + int m_resizeHandleSize; + int m_selectionPenSize; + int m_possibleResizeDirectionFlags; + int m_possibleMoveDirectionFlags; + int m_savedPossibleResizeDirectionFlags; + int m_savedPossibleMoveDirectionFlags; + int m_savedFixedPos; + int m_resizeDirectionFlags; + qreal m_width; + qreal m_height; + QPen m_pen; + QFont m_font; + QColor m_fontColor; + bool m_fixedPos; + qreal m_borderLineSize; + QRectF m_rect; + mutable QRectF m_boundingRect; - QRectF m_rect; - mutable QRectF m_boundingRect; - - QRectF m_oldGeometry; - BGMode m_BGMode; - int m_opacity; + QRectF m_oldGeometry; + BGMode m_BGMode; + int m_opacity; BorderLines m_borderLinesFlags; BorderStyle m_borderStyle; @@ -470,64 +516,70 @@ private: ObjectState m_objectState; - BrushStyle m_backgroundBrushStyle; - QColor m_backgroundColor; + BrushStyle m_backgroundBrushStyle; + QColor m_backgroundColor; RenderPass m_currentPass; - int m_margin; + int m_margin; QString m_itemTypeName; ItemAlign m_itemAlign; - bool m_changingItemAlign; - QColor m_borderColor; + bool m_changingItemAlign; + QColor m_borderColor; ReportSettings* m_reportSettings; QString m_patternName; BaseDesignIntf* m_patternItem; - bool m_fillInSecondPass; - bool m_watermark; - bool m_hovered; - bool m_joinMarkerOn; + bool m_fillInSecondPass; + bool m_watermark; + bool m_hovered; + bool m_joinMarkerOn; SelectionMarker* m_selectionMarker; - Marker* m_joinMarker; - bool m_fillTransparentInDesignMode; - QRect m_itemGeometry; + Marker* m_joinMarker; + bool m_fillTransparentInDesignMode; + QRect m_itemGeometry; UnitType m_unitType; - bool m_itemGeometryLocked; - bool m_isChangingPos; - bool m_isMoveable; - bool m_shadow; + bool m_itemGeometryLocked; + bool m_isChangingPos; + bool m_isMoveable; + bool m_shadow; signals: void geometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry); void posChanging(QObject* object, QPointF newPos, QPointF oldPos); void posChanged(QObject* object, QPointF newPos, QPointF oldPos); - void itemSelected(LimeReport::BaseDesignIntf *item); - void itemSelectedHasBeenChanged(BaseDesignIntf *item, bool value); + void itemSelected(LimeReport::BaseDesignIntf* item); + void itemSelectedHasBeenChanged(BaseDesignIntf* item, bool value); void loadCollectionFinished(const QString& collectionName); void objectLoaded(QObject* object); void objectChanged(QObject* object); - void propertyChanged(const QString& propertName, const QVariant& oldValue,const QVariant& newValue); + void propertyChanged(const QString& propertName, const QVariant& oldValue, + const QVariant& newValue); void propertyObjectNameChanged(const QString& oldValue, const QString& newValue); void propertyesChanged(QVector propertyNames); - void itemAlignChanged(BaseDesignIntf* item, const ItemAlign& oldValue, const ItemAlign& newValue); + void itemAlignChanged(BaseDesignIntf* item, const ItemAlign& oldValue, + const ItemAlign& newValue); void itemVisibleHasChanged(BaseDesignIntf* item); void beforeRender(); void afterData(); void afterRender(); }; -class LIMEREPORT_EXPORT BookmarkContainerDesignIntf: public BaseDesignIntf{ +class LIMEREPORT_EXPORT BookmarkContainerDesignIntf: public BaseDesignIntf { Q_OBJECT public: - BookmarkContainerDesignIntf(const QString& storageTypeName, QObject* owner = 0, QGraphicsItem* parent = 0) - :BaseDesignIntf(storageTypeName, owner, parent){} - void addBookmark(const QString& key, const QVariant& value){ m_bookmarks.insert(key, value);} - QList bookmarks(){ return m_bookmarks.keys();} + BookmarkContainerDesignIntf(const QString& storageTypeName, QObject* owner = 0, + QGraphicsItem* parent = 0): + BaseDesignIntf(storageTypeName, owner, parent) + { + } + void addBookmark(const QString& key, const QVariant& value) { m_bookmarks.insert(key, value); } + QList bookmarks() { return m_bookmarks.keys(); } QVariant getBookMark(const QString& key); void copyBookmarks(BookmarkContainerDesignIntf* source); + private: - QHash m_bookmarks; + QHash m_bookmarks; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRBASEDESIGNINTF_H diff --git a/limereport/lrcallbackdatasourceintf.h b/limereport/lrcallbackdatasourceintf.h index e59c71c..d37e502 100644 --- a/limereport/lrcallbackdatasourceintf.h +++ b/limereport/lrcallbackdatasourceintf.h @@ -3,22 +3,31 @@ #include namespace LimeReport { -struct CallbackInfo{ - enum DataType{IsEmpty, HasNext, ColumnHeaderData, ColumnData, ColumnCount, RowCount}; - enum ChangePosType{First, Next}; +struct CallbackInfo { + enum DataType { + IsEmpty, + HasNext, + ColumnHeaderData, + ColumnData, + ColumnCount, + RowCount + }; + enum ChangePosType { + First, + Next + }; DataType dataType; int index; QString columnName; }; -class ICallbackDatasource :public QObject{ +class ICallbackDatasource: public QObject { Q_OBJECT signals: void getCallbackData(const LimeReport::CallbackInfo& info, QVariant& data); void changePos(const LimeReport::CallbackInfo::ChangePosType& type, bool& result); }; -} +} // namespace LimeReport #endif // LRVIRTUALDATASOURCEINTF - diff --git a/limereport/lrcollection.h b/limereport/lrcollection.h index db9285e..1e72f55 100644 --- a/limereport/lrcollection.h +++ b/limereport/lrcollection.h @@ -30,33 +30,33 @@ #ifndef LRCOLLECTION_H #define LRCOLLECTION_H -#include -#include - #include "lrglobal.h" -class LIMEREPORT_EXPORT ACollectionProperty{ +#include +#include + +class LIMEREPORT_EXPORT ACollectionProperty { public: - ACollectionProperty(){} - ACollectionProperty(const ACollectionProperty& ){} - virtual ~ACollectionProperty(){} + ACollectionProperty() { } + ACollectionProperty(const ACollectionProperty&) { } + virtual ~ACollectionProperty() { } }; Q_DECLARE_METATYPE(ACollectionProperty) -namespace LimeReport{ +namespace LimeReport { #if __cplusplus >= 201703L const int inline COLLECTION_TYPE_ID = qMetaTypeId(); #else const int COLLECTION_TYPE_ID = qMetaTypeId(); #endif -class LIMEREPORT_EXPORT ICollectionContainer{ +class LIMEREPORT_EXPORT ICollectionContainer { public: - virtual QObject* createElement(const QString& collectionName,const QString& elementType)=0; - virtual int elementsCount(const QString& collectionName)=0; - virtual QObject* elementAt(const QString& collectionName,int index)=0; - virtual void collectionLoadFinished(const QString& collectionName){Q_UNUSED(collectionName)} - ACollectionProperty fakeCollectionReader(){return ACollectionProperty();} + virtual QObject* createElement(const QString& collectionName, const QString& elementType) = 0; + virtual int elementsCount(const QString& collectionName) = 0; + virtual QObject* elementAt(const QString& collectionName, int index) = 0; + virtual void collectionLoadFinished(const QString& collectionName) { Q_UNUSED(collectionName) } + ACollectionProperty fakeCollectionReader() { return ACollectionProperty(); } }; -} +} // namespace LimeReport #endif // LRCOLLECTION_H diff --git a/limereport/lrcolorindicator.cpp b/limereport/lrcolorindicator.cpp index 4844330..bc4e36a 100644 --- a/limereport/lrcolorindicator.cpp +++ b/limereport/lrcolorindicator.cpp @@ -1,6 +1,7 @@ #include "lrcolorindicator.h" -#include + #include +#include void ColorIndicator::paintEvent(QPaintEvent* event) { @@ -9,16 +10,16 @@ void ColorIndicator::paintEvent(QPaintEvent* event) painter.setBrush(m_color); painter.setPen(Qt::gray); - QRect rect = event->rect().adjusted(3,3,-3,-3); + QRect rect = event->rect().adjusted(3, 3, -3, -3); - if (rect.height() < rect.width()){ - qreal offset = (rect.width()-rect.height()) / 2; + if (rect.height() < rect.width()) { + qreal offset = (rect.width() - rect.height()) / 2; rect.setWidth(rect.height()); - rect.adjust(offset,0,offset,0); + rect.adjust(offset, 0, offset, 0); } else { - qreal offset = (rect.height()-rect.width()) / 2; + qreal offset = (rect.height() - rect.width()) / 2; rect.setHeight(rect.width()); - rect.adjust(0,offset,0,offset); + rect.adjust(0, offset, 0, offset); } painter.setRenderHint(QPainter::Antialiasing); @@ -26,25 +27,19 @@ void ColorIndicator::paintEvent(QPaintEvent* event) painter.restore(); } -ColorIndicator::ColorIndicator(QWidget *parent) - :QWidget(parent), m_color(Qt::white){ +ColorIndicator::ColorIndicator(QWidget* parent): QWidget(parent), m_color(Qt::white) +{ setAttribute(Qt::WA_StaticContents); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); setFocusPolicy(Qt::NoFocus); } -QColor ColorIndicator::color() const -{ - return m_color; -} +QColor ColorIndicator::color() const { return m_color; } -void ColorIndicator::setColor(const QColor &color) +void ColorIndicator::setColor(const QColor& color) { m_color = color; update(); } -QSize ColorIndicator::sizeHint() const -{ - return QSize(20,20); -} +QSize ColorIndicator::sizeHint() const { return QSize(20, 20); } diff --git a/limereport/lrcolorindicator.h b/limereport/lrcolorindicator.h index 5ed1754..29c25c9 100644 --- a/limereport/lrcolorindicator.h +++ b/limereport/lrcolorindicator.h @@ -1,18 +1,20 @@ #ifndef COLORINDICATOR_H #define COLORINDICATOR_H -#include #include +#include -class ColorIndicator : public QWidget{ +class ColorIndicator: public QWidget { Q_OBJECT public: ColorIndicator(QWidget* parent = 0); QColor color() const; - void setColor(const QColor &color); + void setColor(const QColor& color); QSize sizeHint() const; + protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent* event); + private: QColor m_color; }; diff --git a/limereport/lrdatadesignintf.cpp b/limereport/lrdatadesignintf.cpp index f7b3aa2..b8ee7e2 100644 --- a/limereport/lrdatadesignintf.cpp +++ b/limereport/lrdatadesignintf.cpp @@ -29,41 +29,44 @@ ****************************************************************************/ #include "lrdatadesignintf.h" -#include -#include -#include -#include -#include #include "lrdatasourcemanager.h" -namespace LimeReport{ +#include +#include +#include +#include -ModelHolder::ModelHolder(QAbstractItemModel *model, bool owned /*false*/) +#include + +namespace LimeReport { + +ModelHolder::ModelHolder(QAbstractItemModel* model, bool owned /*false*/) { - ModelToDataSource* mh = new ModelToDataSource(model,owned); + ModelToDataSource* mh = new ModelToDataSource(model, owned); m_dataSource = mh; - m_owned=owned; + m_owned = owned; connect(mh, SIGNAL(modelStateChanged()), this, SIGNAL(modelStateChanged())); } -ModelHolder::~ModelHolder(){ - delete m_dataSource; -} +ModelHolder::~ModelHolder() { delete m_dataSource; } -IDataSource * ModelHolder::dataSource(IDataSource::DatasourceMode mode) +IDataSource* ModelHolder::dataSource(IDataSource::DatasourceMode mode) { Q_UNUSED(mode); return m_dataSource; } -QueryHolder::QueryHolder(QString queryText, QString connectionName, DataSourceManager *dataManager) - : m_queryText(queryText), m_connectionName(connectionName), - m_mode(IDataSource::RENDER_MODE), m_dataManager(dataManager), m_prepared(true) +QueryHolder::QueryHolder(QString queryText, QString connectionName, DataSourceManager* dataManager): + m_queryText(queryText), + m_connectionName(connectionName), + m_mode(IDataSource::RENDER_MODE), + m_dataManager(dataManager), + m_prepared(true) { extractParams(); } -QueryHolder::~QueryHolder(){} +QueryHolder::~QueryHolder() { } bool QueryHolder::runQuery(IDataSource::DatasourceMode mode) { @@ -78,13 +81,14 @@ bool QueryHolder::runQuery(IDataSource::DatasourceMode mode) } extractParams(); - if (!m_prepared) return false; + if (!m_prepared) + return false; query.prepare(m_preparedSQL); fillParams(&query); query.exec(); - QSqlQueryModel *model = new QSqlQueryModel; + QSqlQueryModel* model = new QSqlQueryModel; #if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) model->setQuery(std::move(query)); @@ -95,67 +99,61 @@ bool QueryHolder::runQuery(IDataSource::DatasourceMode mode) while (model->canFetchMore()) model->fetchMore(); - if (model->lastError().isValid()){ + if (model->lastError().isValid()) { if (m_dataSource) - m_dataSource.clear(); + m_dataSource.clear(); setLastError(model->lastError().text()); delete model; return false; - } else { setLastError("");} + } else { + setLastError(""); + } - setDatasource(IDataSource::Ptr(new ModelToDataSource(model,true))); + setDatasource(IDataSource::Ptr(new ModelToDataSource(model, true))); return true; } -QString QueryHolder::connectionName() -{ - return m_connectionName; -} +QString QueryHolder::connectionName() { return m_connectionName; } -void QueryHolder::setConnectionName(QString connectionName) -{ - m_connectionName=connectionName; -} +void QueryHolder::setConnectionName(QString connectionName) { m_connectionName = connectionName; } -void QueryHolder::invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed){ +void QueryHolder::invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed) +{ QSqlDatabase db = QSqlDatabase::database(m_connectionName); - if (!db.isValid() || dbWillBeClosed){ + if (!db.isValid() || dbWillBeClosed) { setLastError(QObject::tr("Invalid connection! %1").arg(m_connectionName)); m_dataSource.clear(); } else { runQuery(mode); } - } -void QueryHolder::update() +void QueryHolder::update() { runQuery(m_mode); } + +void QueryHolder::setDatasource(IDataSource::Ptr value) { - runQuery(m_mode); -} - -void QueryHolder::setDatasource(IDataSource::Ptr value){ m_dataSource.clear(); - m_dataSource=value; + m_dataSource = value; } -void QueryHolder::fillParams(QSqlQuery *query) +void QueryHolder::fillParams(QSqlQuery* query) { - foreach(QString param,m_aliasesToParam.keys()){ + foreach (QString param, m_aliasesToParam.keys()) { QVariant value; - if (param.contains(".")){ + if (param.contains(".")) { value = dataManager()->fieldData(m_aliasesToParam.value(param)); - param=param.right(param.length()-param.indexOf('.')-1); + param = param.right(param.length() - param.indexOf('.') - 1); } else { value = dataManager()->variable(m_aliasesToParam.value(param)); } if (value.isValid() || m_mode == IDataSource::DESIGN_MODE) - query->bindValue(':'+param,value); + query->bindValue(':' + param, value); } } void QueryHolder::extractParams() { - m_preparedSQL = dataManager()->replaceVariables(m_queryText, m_aliasesToParam); + m_preparedSQL = dataManager()->replaceVariables(m_queryText, m_aliasesToParam); m_prepared = true; } @@ -164,40 +162,43 @@ QString QueryHolder::replaceVariables(QString query) return dataManager()->replaceVariables(query, m_aliasesToParam); } -QString QueryHolder::queryText() -{ - return m_queryText; -} +QString QueryHolder::queryText() { return m_queryText; } void QueryHolder::setQueryText(QString queryText) { - m_queryText=queryText; + m_queryText = queryText; m_prepared = false; } IDataSource* QueryHolder::dataSource(IDataSource::DatasourceMode mode) { - if ((m_mode != mode && m_mode == IDataSource::DESIGN_MODE) || m_dataSource==0) { + if ((m_mode != mode && m_mode == IDataSource::DESIGN_MODE) || m_dataSource == 0) { m_mode = mode; runQuery(mode); } if (m_dataSource) return m_dataSource.data(); - else return 0; + else + return 0; } // QueryHolder // ModelToDataSource -ModelToDataSource::ModelToDataSource(QAbstractItemModel* model, bool owned) - : QObject(), m_model(model), m_owned(owned), m_curRow(-1), m_lastError("") +ModelToDataSource::ModelToDataSource(QAbstractItemModel* model, bool owned): + QObject(), + m_model(model), + m_owned(owned), + m_curRow(-1), + m_lastError("") { Q_ASSERT(model); - if (model){ - while (model->canFetchMore(QModelIndex())){ + if (model) { + while (model->canFetchMore(QModelIndex())) { model->fetchMore(QModelIndex()); - if (model->rowCount() <= 0) break; + if (model->rowCount() <= 0) + break; } connect(model, SIGNAL(destroyed()), this, SLOT(slotModelDestroed())); connect(model, SIGNAL(modelReset()), this, SIGNAL(modelStateChanged())); @@ -206,156 +207,165 @@ ModelToDataSource::ModelToDataSource(QAbstractItemModel* model, bool owned) ModelToDataSource::~ModelToDataSource() { - if ((m_owned) && m_model!=0) + if ((m_owned) && m_model != 0) delete m_model; } bool ModelToDataSource::next() { - if (isInvalid()) return false; - if (m_curRow<(m_model->rowCount())) { - if (bof()) m_curRow++; + if (isInvalid()) + return false; + if (m_curRow < (m_model->rowCount())) { + if (bof()) + m_curRow++; m_curRow++; return true; - } else return false; + } else + return false; } bool ModelToDataSource::hasNext() { - if (isInvalid()) return false; - return m_curRowrowCount()-1; + if (isInvalid()) + return false; + return m_curRow < m_model->rowCount() - 1; } bool ModelToDataSource::prior() { - if (isInvalid()) return false; - if (m_curRow>-1){ - if (eof()) m_curRow--; + if (isInvalid()) + return false; + if (m_curRow > -1) { + if (eof()) + m_curRow--; m_curRow--; return true; - } else return false; + } else + return false; } -void ModelToDataSource::first() -{ - m_curRow=0; -} +void ModelToDataSource::first() { m_curRow = 0; } void ModelToDataSource::last() { - if (isInvalid()) m_curRow=0; - else m_curRow=m_model->rowCount()-1; + if (isInvalid()) + m_curRow = 0; + else + m_curRow = m_model->rowCount() - 1; } bool ModelToDataSource::eof() { - if (isInvalid()) return true; - return (m_curRow==m_model->rowCount())||(m_model->rowCount()==0); + if (isInvalid()) + return true; + return (m_curRow == m_model->rowCount()) || (m_model->rowCount() == 0); } bool ModelToDataSource::bof() { - if (isInvalid()) return true; - return (m_curRow==-1)||(m_model->rowCount()==0); + if (isInvalid()) + return true; + return (m_curRow == -1) || (m_model->rowCount() == 0); } -QVariant ModelToDataSource::data(const QString &columnName) +QVariant ModelToDataSource::data(const QString& columnName) { - if (isInvalid()) return QVariant(); - return m_model->data(m_model->index(currentRow(),columnIndexByName(columnName))); + if (isInvalid()) + return QVariant(); + return m_model->data(m_model->index(currentRow(), columnIndexByName(columnName))); } -QVariant ModelToDataSource::dataByRowIndex(const QString &columnName, int rowIndex) +QVariant ModelToDataSource::dataByRowIndex(const QString& columnName, int rowIndex) { if (m_model->rowCount() > rowIndex) return m_model->data(m_model->index(rowIndex, columnIndexByName(columnName))); return QVariant(); } -QVariant ModelToDataSource::dataByRowIndex(const QString &columnName, int rowIndex, int roleName) +QVariant ModelToDataSource::dataByRowIndex(const QString& columnName, int rowIndex, int roleName) { - if(m_model->rowCount() > rowIndex) + if (m_model->rowCount() > rowIndex) return m_model->data(m_model->index(rowIndex, columnIndexByName(columnName))); return QVariant(); } -QVariant ModelToDataSource::dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName) +QVariant ModelToDataSource::dataByRowIndex(const QString& columnName, int rowIndex, + const QString& roleName) { - if(m_model->rowCount() > rowIndex) { - int roleCode{roleName.isEmpty() ? Qt::DisplayRole - : m_model->roleNames().key(roleName.toUtf8(), Qt::DisplayRole)}; + if (m_model->rowCount() > rowIndex) { + int roleCode { roleName.isEmpty() + ? Qt::DisplayRole + : m_model->roleNames().key(roleName.toUtf8(), Qt::DisplayRole) }; return m_model->data(m_model->index(rowIndex, columnIndexByName(columnName)), roleCode); } return QVariant(); } -QVariant ModelToDataSource::dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData) +QVariant ModelToDataSource::dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData) { - for( int i=0; i < m_model->rowCount(); ++i ){ - if (m_model->data(m_model->index(i, columnIndexByName(keyColumnName))) == keyData){ - return m_model->data(m_model->index(i, columnIndexByName(columnName))); - } - } - return QVariant(); + for (int i = 0; i < m_model->rowCount(); ++i) { + if (m_model->data(m_model->index(i, columnIndexByName(keyColumnName))) == keyData) { + return m_model->data(m_model->index(i, columnIndexByName(columnName))); + } + } + return QVariant(); } int ModelToDataSource::columnCount() { - if (isInvalid()) return 0; + if (isInvalid()) + return 0; return m_model->columnCount(); } QString ModelToDataSource::columnNameByIndex(int columnIndex) { - if (isInvalid()) return ""; - QString result = m_model->headerData(columnIndex,Qt::Horizontal, Qt::UserRole).isValid()? - m_model->headerData(columnIndex,Qt::Horizontal, Qt::UserRole).toString(): - m_model->headerData(columnIndex,Qt::Horizontal).toString(); - return result; + if (isInvalid()) + return ""; + QString result = m_model->headerData(columnIndex, Qt::Horizontal, Qt::UserRole).isValid() + ? m_model->headerData(columnIndex, Qt::Horizontal, Qt::UserRole).toString() + : m_model->headerData(columnIndex, Qt::Horizontal).toString(); + return result; } int ModelToDataSource::columnIndexByName(QString name) { - if (isInvalid()) return 0; - for(int i=0;icolumnCount();i++){ - QString columnName = m_model->headerData(i,Qt::Horizontal, Qt::UserRole).isValid()? - m_model->headerData(i,Qt::Horizontal, Qt::UserRole).toString(): - m_model->headerData(i,Qt::Horizontal).toString(); - if (columnName.compare(name,Qt::CaseInsensitive)==0) + if (isInvalid()) + return 0; + for (int i = 0; i < m_model->columnCount(); i++) { + QString columnName = m_model->headerData(i, Qt::Horizontal, Qt::UserRole).isValid() + ? m_model->headerData(i, Qt::Horizontal, Qt::UserRole).toString() + : m_model->headerData(i, Qt::Horizontal).toString(); + if (columnName.compare(name, Qt::CaseInsensitive) == 0) return i; } return -1; } -QVariant ModelToDataSource::headerData(const QString &columnName, const QString &roleName) +QVariant ModelToDataSource::headerData(const QString& columnName, const QString& roleName) { - int roleCode{roleName.isEmpty() ? Qt::DisplayRole - : m_model->roleNames().key(roleName.toUtf8(), Qt::DisplayRole)}; + int roleCode { roleName.isEmpty() + ? Qt::DisplayRole + : m_model->roleNames().key(roleName.toUtf8(), Qt::DisplayRole) }; return m_model->headerData(columnIndexByName(columnName), Qt::Horizontal, roleCode); } -QString ModelToDataSource::lastError() -{ - return m_lastError; -} +QString ModelToDataSource::lastError() { return m_lastError; } -QAbstractItemModel * ModelToDataSource::model() -{ - return m_model; -} +QAbstractItemModel* ModelToDataSource::model() { return m_model; } int ModelToDataSource::currentRow() { - if (eof()) return m_curRow-1; - if (bof()) return m_curRow+1; + if (eof()) + return m_curRow - 1; + if (bof()) + return m_curRow + 1; return m_curRow; } -bool ModelToDataSource::isInvalid() const -{ - return m_model==0; -} +bool ModelToDataSource::isInvalid() const { return m_model == 0; } void ModelToDataSource::slotModelDestroed() { @@ -364,89 +374,103 @@ void ModelToDataSource::slotModelDestroed() emit modelStateChanged(); } -ConnectionDesc::ConnectionDesc(QSqlDatabase db, QObject *parent) - : QObject(parent), m_connectionName(db.connectionName()), m_connectionHost(db.hostName()), m_connectionDriver(db.driverName()), - m_databaseName(db.databaseName()), m_user(db.userName()), m_password(db.password()), m_port(""), m_autoconnect(false), - m_internal(false), m_keepDBCredentials(true) -{} - -ConnectionDesc::ConnectionDesc(QObject *parent) - :QObject(parent),m_connectionName(""),m_connectionHost(""), m_connectionDriver(""), - m_databaseName(""), m_user(""), m_password(""), m_port(""), m_autoconnect(false), - m_internal(false), m_keepDBCredentials(true) -{} - -ConnectionDesc::Ptr ConnectionDesc::create(QSqlDatabase db, QObject *parent) +ConnectionDesc::ConnectionDesc(QSqlDatabase db, QObject* parent): + QObject(parent), + m_connectionName(db.connectionName()), + m_connectionHost(db.hostName()), + m_connectionDriver(db.driverName()), + m_databaseName(db.databaseName()), + m_user(db.userName()), + m_password(db.password()), + m_port(""), + m_autoconnect(false), + m_internal(false), + m_keepDBCredentials(true) { - return Ptr(new ConnectionDesc(db,parent)); } -void ConnectionDesc::setName(const QString &value) +ConnectionDesc::ConnectionDesc(QObject* parent): + QObject(parent), + m_connectionName(""), + m_connectionHost(""), + m_connectionDriver(""), + m_databaseName(""), + m_user(""), + m_password(""), + m_port(""), + m_autoconnect(false), + m_internal(false), + m_keepDBCredentials(true) { - if (m_connectionName!=value) emit nameChanged(m_connectionName,value); - m_connectionName=value; } -bool ConnectionDesc::isEqual(const QSqlDatabase &db) +ConnectionDesc::Ptr ConnectionDesc::create(QSqlDatabase db, QObject* parent) { - return (db.databaseName() == m_databaseName) && - (db.driverName() == m_connectionDriver) && - (db.hostName() == m_connectionHost) && - (db.connectionName() == m_connectionName) && - (db.userName() == m_user) && - (db.password() == m_password); + return Ptr(new ConnectionDesc(db, parent)); } -QString ConnectionDesc::connectionNameForUser(const QString &connectionName) +void ConnectionDesc::setName(const QString& value) { - return connectionName.compare(QSqlDatabase::defaultConnection) == 0 ? tr("defaultConnection") : connectionName; + if (m_connectionName != value) + emit nameChanged(m_connectionName, value); + m_connectionName = value; } -QString ConnectionDesc::connectionNameForReport(const QString &connectionName) +bool ConnectionDesc::isEqual(const QSqlDatabase& db) { - return connectionName.compare(tr("defaultConnection")) == 0 ? QSqlDatabase::defaultConnection : connectionName; + return (db.databaseName() == m_databaseName) && (db.driverName() == m_connectionDriver) + && (db.hostName() == m_connectionHost) && (db.connectionName() == m_connectionName) + && (db.userName() == m_user) && (db.password() == m_password); } -QString ConnectionDesc::port() const +QString ConnectionDesc::connectionNameForUser(const QString& connectionName) { - return m_port; + return connectionName.compare(QSqlDatabase::defaultConnection) == 0 ? tr("defaultConnection") + : connectionName; } -void ConnectionDesc::setPort(QString port) +QString ConnectionDesc::connectionNameForReport(const QString& connectionName) { - m_port = port; + return connectionName.compare(tr("defaultConnection")) == 0 ? QSqlDatabase::defaultConnection + : connectionName; } -bool ConnectionDesc::keepDBCredentials() const -{ - return m_keepDBCredentials; -} +QString ConnectionDesc::port() const { return m_port; } + +void ConnectionDesc::setPort(QString port) { m_port = port; } + +bool ConnectionDesc::keepDBCredentials() const { return m_keepDBCredentials; } void ConnectionDesc::setKeepDBCredentials(bool keepDBCredentals) { m_keepDBCredentials = keepDBCredentals; } -QueryDesc::QueryDesc(QString queryName, QString queryText, QString connection) - :m_queryName(queryName), m_queryText(queryText), m_connectionName(connection) -{} +QueryDesc::QueryDesc(QString queryName, QString queryText, QString connection): + m_queryName(queryName), + m_queryText(queryText), + m_connectionName(connection) +{ +} -SubQueryHolder::SubQueryHolder(QString queryText, QString connectionName, QString masterDatasource, DataSourceManager* dataManager) - : QueryHolder(queryText, connectionName, dataManager), m_masterDatasource(masterDatasource)/*, m_invalid(false)*/ +SubQueryHolder::SubQueryHolder(QString queryText, QString connectionName, QString masterDatasource, + DataSourceManager* dataManager): + QueryHolder(queryText, connectionName, dataManager), + m_masterDatasource(masterDatasource) /*, m_invalid(false)*/ { extractParams(); } -void SubQueryHolder::setMasterDatasource(const QString &value) +void SubQueryHolder::setMasterDatasource(const QString& value) { - if (dataManager()->dataSource(value)){ + if (dataManager()->dataSource(value)) { m_masterDatasource = value; } } void SubQueryHolder::extractParams() { - if (!dataManager()->containsDatasource(m_masterDatasource)){ + if (!dataManager()->containsDatasource(m_masterDatasource)) { setLastError(QObject::tr("Master datasource \"%1\" not found!").arg(m_masterDatasource)); setPrepared(false); } else { @@ -458,7 +482,7 @@ void SubQueryHolder::extractParams() QString SubQueryHolder::extractField(QString source) { if (source.contains('.')) { - return source.right(source.length()-(source.indexOf('.')+1)); + return source.right(source.length() - (source.indexOf('.') + 1)); } return source; } @@ -468,14 +492,16 @@ QString SubQueryHolder::replaceFields(QString query) return dataManager()->replaceFields(query, m_aliasesToParam); } -SubQueryDesc::SubQueryDesc(QString queryName, QString queryText, QString connection, QString masterDatasourceName) - :QueryDesc(queryName,queryText,connection), m_masterDatasourceName(masterDatasourceName) +SubQueryDesc::SubQueryDesc(QString queryName, QString queryText, QString connection, + QString masterDatasourceName): + QueryDesc(queryName, queryText, connection), + m_masterDatasourceName(masterDatasourceName) { } -QObject *ProxyDesc::createElement(const QString &collectionName, const QString &) +QObject* ProxyDesc::createElement(const QString& collectionName, const QString&) { - if (collectionName=="fields"){ + if (collectionName == "fields") { FieldMapDesc* fieldMapDesc = new FieldMapDesc; m_maps.append(fieldMapDesc); return fieldMapDesc; @@ -483,46 +509,53 @@ QObject *ProxyDesc::createElement(const QString &collectionName, const QString & return 0; } -int ProxyDesc::elementsCount(const QString &collectionName) +int ProxyDesc::elementsCount(const QString& collectionName) { Q_UNUSED(collectionName) return m_maps.count(); } -QObject *ProxyDesc::elementAt(const QString &collectionName, int index) +QObject* ProxyDesc::elementAt(const QString& collectionName, int index) { Q_UNUSED(collectionName) return m_maps.at(index); } -ProxyHolder::ProxyHolder(ProxyDesc* desc, DataSourceManager* dataManager) - :m_model(0), m_desc(desc), m_lastError(""), m_mode(IDataSource::RENDER_MODE), - m_invalid(false), m_dataManager(dataManager) -{} +ProxyHolder::ProxyHolder(ProxyDesc* desc, DataSourceManager* dataManager): + m_model(0), + m_desc(desc), + m_lastError(""), + m_mode(IDataSource::RENDER_MODE), + m_invalid(false), + m_dataManager(dataManager) +{ +} QString ProxyHolder::masterDatasource() { - if (m_desc) return m_desc->master(); + if (m_desc) + return m_desc->master(); return QString(); } void ProxyHolder::filterModel() { - if (!m_datasource){ + if (!m_datasource) { - if (dataManager()){ + if (dataManager()) { IDataSource* master = dataManager()->dataSource(m_desc->master()); IDataSource* child = dataManager()->dataSource(m_desc->child()); - if (master&&child){ + if (master && child) { m_model = new MasterDetailProxyModel(dataManager()); - connect(child->model(),SIGNAL(destroyed()), this, SLOT(slotChildModelDestoroyed())); + connect(child->model(), SIGNAL(destroyed()), this, + SLOT(slotChildModelDestoroyed())); m_model->setSourceModel(child->model()); m_model->setMaster(m_desc->master()); m_model->setChildName(m_desc->child()); m_model->setFieldsMap(m_desc->fieldsMap()); - try{ + try { m_model->rowCount(); - m_datasource = IDataSource::Ptr(new ModelToDataSource(m_model,true)); + m_datasource = IDataSource::Ptr(new ModelToDataSource(m_model, true)); } catch (ReportError& exception) { m_lastError = exception.what(); } @@ -530,22 +563,26 @@ void ProxyHolder::filterModel() m_lastError.clear(); } else { m_lastError.clear(); - if(!master) m_lastError+=QObject::tr("Master datasouce \"%1\" not found!").arg(m_desc->master()); - if(!child) m_lastError+=((m_lastError.isEmpty())?QObject::tr("Child"):QObject::tr(" and child "))+ - QObject::tr("datasouce \"%1\" not found!").arg(m_desc->child()); + if (!master) + m_lastError + += QObject::tr("Master datasouce \"%1\" not found!").arg(m_desc->master()); + if (!child) + m_lastError += ((m_lastError.isEmpty()) ? QObject::tr("Child") + : QObject::tr(" and child ")) + + QObject::tr("datasouce \"%1\" not found!").arg(m_desc->child()); } } } else { - if (!isInvalid()){ + if (!isInvalid()) { m_model->invalidate(); m_datasource->first(); } } } -IDataSource *ProxyHolder::dataSource(IDataSource::DatasourceMode mode) +IDataSource* ProxyHolder::dataSource(IDataSource::DatasourceMode mode) { - if ((m_mode != mode && m_mode == IDataSource::DESIGN_MODE) || m_datasource==0) { + if ((m_mode != mode && m_mode == IDataSource::DESIGN_MODE) || m_datasource == 0) { m_mode = mode; m_datasource.clear(); filterModel(); @@ -557,7 +594,7 @@ void ProxyHolder::invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClos { Q_UNUSED(mode) Q_UNUSED(dbWillBeClosed); - if (m_model && m_model->isInvalid()){ + if (m_model && m_model->isInvalid()) { m_invalid = true; m_lastError = tr("Datasource has been invalidated"); } else { @@ -565,7 +602,8 @@ void ProxyHolder::invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClos } } -void ProxyHolder::slotChildModelDestoroyed(){ +void ProxyHolder::slotChildModelDestoroyed() +{ m_datasource.clear(); m_model = 0; } @@ -575,26 +613,27 @@ void ProxyDesc::addFieldsCorrelation(const FieldsCorrelation& fieldsCorrelation) m_maps.append(new FieldMapDesc(fieldsCorrelation)); } -void MasterDetailProxyModel::setMaster(QString name){ - m_masterName=name; -} +void MasterDetailProxyModel::setMaster(QString name) { m_masterName = name; } bool MasterDetailProxyModel::isInvalid() const { - if (m_masterName.isEmpty() || m_childName.isEmpty()) return true; + if (m_masterName.isEmpty() || m_childName.isEmpty()) + return true; IDataSource* masterData = dataManager()->dataSource(m_masterName); IDataSource* childData = dataManager()->dataSource(m_childName); - if (!masterData || !childData) return true; + if (!masterData || !childData) + return true; return masterData->isInvalid() || childData->isInvalid(); } -bool MasterDetailProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool MasterDetailProxyModel::filterAcceptsRow(int source_row, + const QModelIndex& source_parent) const { Q_UNUSED(source_parent) foreach (FieldMapDesc* fieldCorrelation, *m_maps) { QVariant master = masterData(fieldCorrelation->master()); - QVariant detail = sourceData(fieldCorrelation->detail(),source_row); - if (master==detail) + QVariant detail = sourceData(fieldCorrelation->detail(), source_row); + if (master == detail) return true; } return false; @@ -602,12 +641,13 @@ bool MasterDetailProxyModel::filterAcceptsRow(int source_row, const QModelIndex int MasterDetailProxyModel::fieldIndexByName(QString fieldName) const { - for(int i=0;icolumnCount();++i){ - QString sourceFieldName = sourceModel()->headerData(i,Qt::Horizontal,Qt::UserRole).isValid()? - sourceModel()->headerData(i,Qt::Horizontal,Qt::UserRole).toString(): - sourceModel()->headerData(i,Qt::Horizontal).toString(); - if (sourceFieldName.compare(fieldName,Qt::CaseInsensitive)==0){ - return i; + for (int i = 0; i < sourceModel()->columnCount(); ++i) { + QString sourceFieldName + = sourceModel()->headerData(i, Qt::Horizontal, Qt::UserRole).isValid() + ? sourceModel()->headerData(i, Qt::Horizontal, Qt::UserRole).toString() + : sourceModel()->headerData(i, Qt::Horizontal).toString(); + if (sourceFieldName.compare(fieldName, Qt::CaseInsensitive) == 0) { + return i; } } return -1; @@ -616,53 +656,53 @@ int MasterDetailProxyModel::fieldIndexByName(QString fieldName) const QVariant MasterDetailProxyModel::sourceData(QString fieldName, int row) const { int fieldIndex = fieldIndexByName(fieldName); - if (fieldIndex!=-1){ - return sourceModel()->index(row,fieldIndex).data(); + if (fieldIndex != -1) { + return sourceModel()->index(row, fieldIndex).data(); } else { - throw ReportError( - tr("Field: \"%1\" not found in \"%2\" child datasource").arg(fieldName).arg(m_childName) - ); + throw ReportError(tr("Field: \"%1\" not found in \"%2\" child datasource") + .arg(fieldName) + .arg(m_childName)); } } QVariant MasterDetailProxyModel::masterData(QString fieldName) const { IDataSource* master = dataManager()->dataSource(m_masterName); - if (master){ + if (master) { int columnIndex = master->columnIndexByName(fieldName); - if (columnIndex!=-1){ + if (columnIndex != -1) { return master->data(fieldName); } else { - throw ReportError( - tr("Field: \"%1\" not found in \"%2\" master datasource").arg(fieldName).arg(m_masterName) - ); + throw ReportError(tr("Field: \"%1\" not found in \"%2\" master datasource") + .arg(fieldName) + .arg(m_masterName)); } } return QVariant(); } -bool CallbackDatasource::next(){ - if (!m_eof){ +bool CallbackDatasource::next() +{ + if (!m_eof) { bool nextRowExists = checkNextRecord(m_currentRow); - if (m_currentRow>-1){ - if (!m_getDataFromCache && nextRowExists){ - for (int i = 0; i < m_columnCount; ++i ){ + if (m_currentRow > -1) { + if (!m_getDataFromCache && nextRowExists) { + for (int i = 0; i < m_columnCount; ++i) { m_valuesCache[columnNameByIndex(i)] = data(columnNameByIndex(i)); } - } } - if (!nextRowExists){ + if (!nextRowExists) { m_eof = true; return false; } m_currentRow++; bool result = true; if (!m_getDataFromCache) - emit changePos(CallbackInfo::Next,result); + emit changePos(CallbackInfo::Next, result); m_getDataFromCache = false; - if (m_rowCount != -1){ - if (m_rowCount > 0 && m_currentRow < m_rowCount){ + if (m_rowCount != -1) { + if (m_rowCount > 0 && m_currentRow < m_rowCount) { m_eof = false; } else { m_eof = true; @@ -672,12 +712,14 @@ bool CallbackDatasource::next(){ m_eof = !result; return result; } - } else return false; + } else + return false; } -bool CallbackDatasource::prior(){ - if (m_currentRow !=-1) { - if (!m_getDataFromCache && !m_valuesCache.isEmpty()){ +bool CallbackDatasource::prior() +{ + if (m_currentRow != -1) { + if (!m_getDataFromCache && !m_valuesCache.isEmpty()) { m_getDataFromCache = true; m_currentRow--; m_eof = false; @@ -685,26 +727,30 @@ bool CallbackDatasource::prior(){ } else { return false; } - } else { - return false; - } + } else { + return false; + } } -void CallbackDatasource::first(){ +void CallbackDatasource::first() +{ m_currentRow = 0; m_getDataFromCache = false; - m_eof=checkIfEmpty(); - bool result=false; + m_eof = checkIfEmpty(); + bool result = false; QVariant rowCount; CallbackInfo info; info.dataType = CallbackInfo::RowCount; - emit getCallbackData(info,rowCount); - if (rowCount.isValid()) m_rowCount = rowCount.toInt(); + emit getCallbackData(info, rowCount); + if (rowCount.isValid()) + m_rowCount = rowCount.toInt(); - emit changePos(CallbackInfo::First,result); - if (m_rowCount>0) m_eof = false; - else m_eof = !result; + emit changePos(CallbackInfo::First, result); + if (m_rowCount > 0) + m_eof = false; + else + m_eof = !result; } QVariant CallbackDatasource::callbackData(const QString& columnName, int row) @@ -721,9 +767,8 @@ QVariant CallbackDatasource::callbackData(const QString& columnName, int row) QVariant CallbackDatasource::data(const QString& columnName) { QVariant result; - if (!bof()) - { - if (!m_getDataFromCache){ + if (!bof()) { + if (!m_getDataFromCache) { result = callbackData(columnName, m_currentRow); } else { result = m_valuesCache[columnName]; @@ -732,57 +777,61 @@ QVariant CallbackDatasource::data(const QString& columnName) return result; } -QVariant CallbackDatasource::dataByRowIndex(const QString &columnName, int rowIndex) +QVariant CallbackDatasource::dataByRowIndex(const QString& columnName, int rowIndex) { int backupCurrentRow = m_currentRow; QVariant result = QVariant(); first(); - for (int i = 0; i < rowIndex && !eof(); ++i, next()){} - if (!eof()) result = callbackData(columnName, rowIndex); + for (int i = 0; i < rowIndex && !eof(); ++i, next()) { } + if (!eof()) + result = callbackData(columnName, rowIndex); first(); - if (backupCurrentRow != -1){ + if (backupCurrentRow != -1) { for (int i = 0; i < backupCurrentRow; ++i) next(); } return result; } -QVariant CallbackDatasource::dataByRowIndex(const QString &columnName, int rowIndex, int roleName) +QVariant CallbackDatasource::dataByRowIndex(const QString& columnName, int rowIndex, int roleName) { Q_UNUSED(roleName) return dataByRowIndex(columnName, rowIndex); } -QVariant CallbackDatasource::dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName) +QVariant CallbackDatasource::dataByRowIndex(const QString& columnName, int rowIndex, + const QString& roleName) { Q_UNUSED(roleName) return dataByRowIndex(columnName, rowIndex); } -QVariant CallbackDatasource::dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData) +QVariant CallbackDatasource::dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData) { int backupCurrentRow = m_currentRow; QVariant result = QVariant(); m_currentRow = m_lastKeyRow; - if (next()){ - for (int i = 0; i < 10; ++i){ + if (next()) { + for (int i = 0; i < 10; ++i) { QVariant key = callbackData(keyColumnName, m_currentRow); - if (key == keyData){ + if (key == keyData) { result = callbackData(columnName, m_currentRow); m_lastKeyRow = m_currentRow; m_currentRow = backupCurrentRow; return result; } - if (!next()) break; + if (!next()) + break; } } first(); - if (!checkIfEmpty()){ + if (!checkIfEmpty()) { do { QVariant key = callbackData(keyColumnName, m_currentRow); - if (key == keyData){ + if (key == keyData) { result = callbackData(columnName, m_currentRow); m_lastKeyRow = m_currentRow; m_currentRow = backupCurrentRow; @@ -795,21 +844,22 @@ QVariant CallbackDatasource::dataByKeyField(const QString& columnName, const QSt return result; } -int CallbackDatasource::columnCount(){ +int CallbackDatasource::columnCount() +{ CallbackInfo info; - if (m_columnCount == -1){ + if (m_columnCount == -1) { QVariant columnCount; info.dataType = CallbackInfo::ColumnCount; - emit getCallbackData(info,columnCount); - if (columnCount.isValid()){ + emit getCallbackData(info, columnCount); + if (columnCount.isValid()) { m_columnCount = columnCount.toInt(); } - if (m_columnCount != -1){ - for(int i=0;i0) m_columnCount = m_headers.size(); + if (m_headers.size() > 0) + m_columnCount = m_headers.size(); return m_columnCount; } @@ -835,45 +887,49 @@ QString CallbackDatasource::columnNameByIndex(int columnIndex) { if (columnIndex < m_headers.size()) return m_headers[columnIndex]; - else return QString(); + else + return QString(); } int CallbackDatasource::columnIndexByName(QString name) { - for (int i=0;i 0) { - return (recordNum < (m_rowCount-1)); + return (recordNum < (m_rowCount - 1)); } else { QVariant result = false; CallbackInfo info; info.dataType = CallbackInfo::HasNext; info.index = recordNum; - emit getCallbackData(info,result); + emit getCallbackData(info, result); return result.toBool(); } } -bool CallbackDatasource::checkIfEmpty(){ +bool CallbackDatasource::checkIfEmpty() +{ if (m_rowCount == 0) { return true; } else { @@ -882,56 +938,35 @@ bool CallbackDatasource::checkIfEmpty(){ CallbackInfo info; info.dataType = CallbackInfo::RowCount; emit getCallbackData(info, recordCount); - if (recordCount.toInt()>0) { + if (recordCount.toInt() > 0) { m_rowCount = recordCount.toInt(); return false; } info.dataType = CallbackInfo::IsEmpty; - emit getCallbackData(info,isEmpty); + emit getCallbackData(info, isEmpty); return isEmpty.toBool(); } } -QString CSVDesc::name() const -{ - return m_csvName; -} +QString CSVDesc::name() const { return m_csvName; } -void CSVDesc::setName(const QString &csvName) -{ - m_csvName = csvName; -} +void CSVDesc::setName(const QString& csvName) { m_csvName = csvName; } -QString CSVDesc::csvText() const -{ - return m_csvText; -} +QString CSVDesc::csvText() const { return m_csvText; } -void CSVDesc::setCsvText(const QString &csvText) +void CSVDesc::setCsvText(const QString& csvText) { m_csvText = csvText; emit cvsTextChanged(m_csvName, m_csvText); } -QString CSVDesc::separator() const -{ - return m_separator; -} +QString CSVDesc::separator() const { return m_separator; } -void CSVDesc::setSeparator(const QString &separator) -{ - m_separator = separator; -} +void CSVDesc::setSeparator(const QString& separator) { m_separator = separator; } -bool CSVDesc::firstRowIsHeader() const -{ - return m_firstRowIsHeader; -} +bool CSVDesc::firstRowIsHeader() const { return m_firstRowIsHeader; } -void CSVDesc::setFirstRowIsHeader(bool firstRowIsHeader) -{ - m_firstRowIsHeader = firstRowIsHeader; -} +void CSVDesc::setFirstRowIsHeader(bool firstRowIsHeader) { m_firstRowIsHeader = firstRowIsHeader; } void CSVHolder::updateModel() { @@ -940,15 +975,16 @@ void CSVHolder::updateModel() bool firstRow = true; QList columns; QStringList headers; - foreach(QString line, m_csvText.split('\n')){ + foreach (QString line, m_csvText.split('\n')) { columns.clear(); - foreach(QString item, line.split(sep)){ + foreach (QString item, line.split(sep)) { columns.append(new QStandardItem(item)); - if (firstRow && m_firstRowIsHeader) headers.append(item); + if (firstRow && m_firstRowIsHeader) + headers.append(item); } - if (firstRow){ - if (!headers.isEmpty()){ + if (firstRow) { + if (!headers.isEmpty()) { m_model.setHorizontalHeaderLabels(headers); firstRow = false; } else { @@ -957,27 +993,18 @@ void CSVHolder::updateModel() } else { m_model.appendRow(columns); } - } - - } -bool CSVHolder::firsRowIsHeader() const -{ - return m_firstRowIsHeader; -} +bool CSVHolder::firsRowIsHeader() const { return m_firstRowIsHeader; } -void CSVHolder::setFirsRowIsHeader(bool firstRowIsHeader) -{ - m_firstRowIsHeader = firstRowIsHeader; -} +void CSVHolder::setFirsRowIsHeader(bool firstRowIsHeader) { m_firstRowIsHeader = firstRowIsHeader; } -CSVHolder::CSVHolder(const CSVDesc &desc, DataSourceManager *dataManager) - : m_csvText(desc.csvText()), - m_separator(desc.separator()), - m_dataManager(dataManager), - m_firstRowIsHeader(desc.firstRowIsHeader()) +CSVHolder::CSVHolder(const CSVDesc& desc, DataSourceManager* dataManager): + m_csvText(desc.csvText()), + m_separator(desc.separator()), + m_dataManager(dataManager), + m_firstRowIsHeader(desc.firstRowIsHeader()) { m_dataSource = IDataSource::Ptr(new ModelToDataSource(&m_model, false)); updateModel(); @@ -989,21 +1016,18 @@ void CSVHolder::setCSVText(QString csvText) updateModel(); } -QString CSVHolder::separator() const -{ - return m_separator; -} +QString CSVHolder::separator() const { return m_separator; } -void CSVHolder::setSeparator(const QString &separator) +void CSVHolder::setSeparator(const QString& separator) { m_separator = separator; updateModel(); } -IDataSource *CSVHolder::dataSource(IDataSource::DatasourceMode mode) +IDataSource* CSVHolder::dataSource(IDataSource::DatasourceMode mode) { Q_UNUSED(mode); return m_dataSource.data(); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrdatadesignintf.h b/limereport/lrdatadesignintf.h index f070f7a..2417df9 100644 --- a/limereport/lrdatadesignintf.h +++ b/limereport/lrdatadesignintf.h @@ -30,27 +30,28 @@ #ifndef LRDATADESIGNINTF_H #define LRDATADESIGNINTF_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "lrcollection.h" #include "lrcallbackdatasourceintf.h" +#include "lrcollection.h" #include "lrdatasourceintf.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace LimeReport { class DataSourceManager; -class ModelHolder: public QObject, public IDataSourceHolder{ +class ModelHolder: public QObject, public IDataSourceHolder { Q_OBJECT public: - ModelHolder(QAbstractItemModel* model, bool owned=false); + ModelHolder(QAbstractItemModel* model, bool owned = false); ~ModelHolder(); IDataSource* dataSource(IDataSource::DatasourceMode mode); bool isOwned() const { return m_owned; } @@ -58,17 +59,22 @@ public: QString lastError() const { return m_dataSource->lastError(); } bool isEditable() const { return false; } bool isRemovable() const { return false; } - void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false){Q_UNUSED(mode) Q_UNUSED(dbWillBeClosed)} - void update(){} - void clearErrors(){} + void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false) + { + Q_UNUSED(mode) + Q_UNUSED(dbWillBeClosed) + } + void update() { } + void clearErrors() { } signals: void modelStateChanged(); + private: IDataSource* m_dataSource; bool m_owned; }; -class ConnectionDesc : public QObject{ +class ConnectionDesc: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString driver READ driver WRITE setDriver) @@ -81,35 +87,37 @@ class ConnectionDesc : public QObject{ Q_PROPERTY(QString port READ port WRITE setPort) public: typedef QSharedPointer Ptr; - ConnectionDesc(QSqlDatabase db, QObject* parent=0); - ConnectionDesc(QObject* parent=0); - Ptr create(QSqlDatabase db, QObject* parent=0); - void setName(const QString &value); - QString name(){return m_connectionName;} - void setDriver(const QString &value){m_connectionDriver=value;} - QString driver(){return m_connectionDriver;} - void setHost(const QString &value){m_connectionHost=value;} - QString host(){return m_connectionHost;} - void setDatabaseName(const QString &value){m_databaseName=value;} - QString databaseName(){return m_databaseName;} - void setUserName(const QString &value){m_user=value;} - QString userName(){ return m_user; } - void setPassword(const QString &value){m_password=value;} - QString password(){ return m_password; } - void setAutoconnect(bool value){m_autoconnect=value;} - bool autoconnect(){return m_autoconnect;} - bool isEqual(const QSqlDatabase& db); - bool isInternal(){ return m_internal; } - void setInternal(bool value) {m_internal = value;} - bool keepDBCredentials() const; - void setKeepDBCredentials(bool keepDBCredentials); + ConnectionDesc(QSqlDatabase db, QObject* parent = 0); + ConnectionDesc(QObject* parent = 0); + Ptr create(QSqlDatabase db, QObject* parent = 0); + void setName(const QString& value); + QString name() { return m_connectionName; } + void setDriver(const QString& value) { m_connectionDriver = value; } + QString driver() { return m_connectionDriver; } + void setHost(const QString& value) { m_connectionHost = value; } + QString host() { return m_connectionHost; } + void setDatabaseName(const QString& value) { m_databaseName = value; } + QString databaseName() { return m_databaseName; } + void setUserName(const QString& value) { m_user = value; } + QString userName() { return m_user; } + void setPassword(const QString& value) { m_password = value; } + QString password() { return m_password; } + void setAutoconnect(bool value) { m_autoconnect = value; } + bool autoconnect() { return m_autoconnect; } + bool isEqual(const QSqlDatabase& db); + bool isInternal() { return m_internal; } + void setInternal(bool value) { m_internal = value; } + bool keepDBCredentials() const; + void setKeepDBCredentials(bool keepDBCredentials); QString port() const; - void setPort(QString port); + void setPort(QString port); + public: static QString connectionNameForUser(const QString& connectionName); - static QString connectionNameForReport(const QString& connectionName); + static QString connectionNameForReport(const QString& connectionName); signals: - void nameChanged(const QString& oldName,const QString& newName); + void nameChanged(const QString& oldName, const QString& newName); + private: QString m_connectionName; QString m_connectionHost; @@ -118,12 +126,12 @@ private: QString m_user; QString m_password; QString m_port; - bool m_autoconnect; - bool m_internal; - bool m_keepDBCredentials; + bool m_autoconnect; + bool m_internal; + bool m_keepDBCredentials; }; -class IConnectionController{ +class IConnectionController { public: virtual void addConnectionDesc(ConnectionDesc* connection) = 0; virtual void changeConnectionDesc(ConnectionDesc* connection) = 0; @@ -132,26 +140,32 @@ public: virtual QString lastError() const = 0; }; -class CSVDesc: public QObject{ +class CSVDesc: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString csvText READ csvText WRITE setCsvText) Q_PROPERTY(QString separator READ separator WRITE setSeparator) Q_PROPERTY(bool firstRowIsHeader READ firstRowIsHeader WRITE setFirstRowIsHeader) public: - CSVDesc(const QString name, const QString csvText, QString separator, bool firstRowIsHeader) - : m_csvName(name), m_csvText(csvText), m_separator(separator), m_firstRowIsHeader(firstRowIsHeader){} - explicit CSVDesc(QObject* parent = 0):QObject(parent) {} + CSVDesc(const QString name, const QString csvText, QString separator, bool firstRowIsHeader): + m_csvName(name), + m_csvText(csvText), + m_separator(separator), + m_firstRowIsHeader(firstRowIsHeader) + { + } + explicit CSVDesc(QObject* parent = 0): QObject(parent) { } QString name() const; - void setName(const QString &name); + void setName(const QString& name); QString csvText() const; - void setCsvText(const QString &csvText); + void setCsvText(const QString& csvText); QString separator() const; - void setSeparator(const QString &separator); + void setSeparator(const QString& separator); bool firstRowIsHeader() const; void setFirstRowIsHeader(bool firstRowIsHeader); signals: void cvsTextChanged(const QString& cvsName, const QString& cvsText); + private: QString m_csvName; QString m_csvText; @@ -159,28 +173,33 @@ private: bool m_firstRowIsHeader; }; -class CSVHolder: public IDataSourceHolder{ +class CSVHolder: public IDataSourceHolder { public: CSVHolder(const CSVDesc& desc, DataSourceManager* dataManager); void setCSVText(QString csvText); - QString csvText() { return m_csvText;} + QString csvText() { return m_csvText; } QString separator() const; - void setSeparator(const QString &separator); + void setSeparator(const QString& separator); bool firsRowIsHeader() const; void setFirsRowIsHeader(bool firstRowIsHeader); // IDataSourceHolder interface public: - IDataSource *dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE); - QString lastError() const {return "";} - bool isInvalid() const {return false;} - bool isOwned() const {return true;} - bool isEditable() const {return true;} - bool isRemovable() const {return true;} - void invalidate(IDataSource::DatasourceMode /*mode*/, bool /*dbWillBeClosed*/){ updateModel();} - void update(){ updateModel(); } - void clearErrors(){} + IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE); + QString lastError() const { return ""; } + bool isInvalid() const { return false; } + bool isOwned() const { return true; } + bool isEditable() const { return true; } + bool isRemovable() const { return true; } + void invalidate(IDataSource::DatasourceMode /*mode*/, bool /*dbWillBeClosed*/) + { + updateModel(); + } + void update() { updateModel(); } + void clearErrors() { } + private: void updateModel(); + private: QString m_csvText; QStandardItemModel m_model; @@ -190,29 +209,34 @@ private: bool m_firstRowIsHeader; }; -class QueryDesc : public QObject{ +class QueryDesc: public QObject { Q_OBJECT Q_PROPERTY(QString queryName READ queryName WRITE setQueryName) Q_PROPERTY(QString queryText READ queryText WRITE setQueryText) Q_PROPERTY(QString connectionName READ connectionName WRITE setConnectionName) public: QueryDesc(QString queryName, QString queryText, QString connection); - explicit QueryDesc(QObject* parent=0):QObject(parent){} - void setQueryName(QString value){m_queryName=value;} - QString queryName() const {return m_queryName;} - void setQueryText(QString value){m_queryText=value; emit queryTextChanged(m_queryName, m_queryText);} - QString queryText() const {return m_queryText;} - void setConnectionName(QString value){m_connectionName=value;} - QString connectionName() const {return m_connectionName;} + explicit QueryDesc(QObject* parent = 0): QObject(parent) { } + void setQueryName(QString value) { m_queryName = value; } + QString queryName() const { return m_queryName; } + void setQueryText(QString value) + { + m_queryText = value; + emit queryTextChanged(m_queryName, m_queryText); + } + QString queryText() const { return m_queryText; } + void setConnectionName(QString value) { m_connectionName = value; } + QString connectionName() const { return m_connectionName; } signals: void queryTextChanged(const QString& queryName, const QString& queryText); + private: QString m_queryName; QString m_queryText; QString m_connectionName; }; -class QueryHolder:public IDataSourceHolder{ +class QueryHolder: public IDataSourceHolder { public: QueryHolder(QString queryText, QString connectionName, DataSourceManager* dataManager); ~QueryHolder(); @@ -226,21 +250,23 @@ public: bool isInvalid() const { return !m_lastError.isEmpty(); } bool isEditable() const { return true; } bool isRemovable() const { return true; } - bool isPrepared() const {return m_prepared;} + bool isPrepared() const { return m_prepared; } QString lastError() const { return m_lastError; } - void setLastError(QString value){m_lastError=value;} + void setLastError(QString value) { m_lastError = value; } void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false); void update(); - void clearErrors(){setLastError("");} - DataSourceManager* dataManager() const {return m_dataManager;} + void clearErrors() { setLastError(""); } + DataSourceManager* dataManager() const { return m_dataManager; } + protected: void setDatasource(IDataSource::Ptr value); - void setPrepared(bool prepared){ m_prepared = prepared;} + void setPrepared(bool prepared) { m_prepared = prepared; } virtual void fillParams(QSqlQuery* query); virtual void extractParams(); QString replaceVariables(QString query); - QMap m_aliasesToParam; + QMap m_aliasesToParam; QString m_preparedSQL; + private: QString m_queryText; QString m_connectionName; @@ -251,73 +277,79 @@ private: bool m_prepared; }; -class SubQueryDesc : public QueryDesc{ +class SubQueryDesc: public QueryDesc { Q_OBJECT Q_PROPERTY(QString master READ master WRITE setMaster) public: SubQueryDesc(QString queryName, QString queryText, QString connection, QString master); - explicit SubQueryDesc(QObject* parent=0):QueryDesc(parent){} - void setMaster(QString value){m_masterDatasourceName=value;} - QString master(){return m_masterDatasourceName;} + explicit SubQueryDesc(QObject* parent = 0): QueryDesc(parent) { } + void setMaster(QString value) { m_masterDatasourceName = value; } + QString master() { return m_masterDatasourceName; } + private: QString m_masterDatasourceName; }; -class SubQueryHolder:public QueryHolder{ +class SubQueryHolder: public QueryHolder { public: - SubQueryHolder(QString queryText, QString connectionName, QString masterDatasource, DataSourceManager *dataManager); - QString masterDatasource(){return m_masterDatasource;} + SubQueryHolder(QString queryText, QString connectionName, QString masterDatasource, + DataSourceManager* dataManager); + QString masterDatasource() { return m_masterDatasource; } void setMasterDatasource(const QString& value); - //void invalidate(){m_invalid = true;} - bool isInvalid() const{ return QueryHolder::isInvalid(); /*|| m_invalid;*/} + // void invalidate(){m_invalid = true;} + bool isInvalid() const { return QueryHolder::isInvalid(); /*|| m_invalid;*/ } + protected: void extractParams(); QString extractField(QString source); QString replaceFields(QString query); + private: QString m_masterDatasource; - //bool m_invalid; + // bool m_invalid; }; -struct FieldsCorrelation{ +struct FieldsCorrelation { QString master; QString detail; }; -class FieldMapDesc : public QObject{ +class FieldMapDesc: public QObject { Q_OBJECT Q_PROPERTY(QString master READ master WRITE setMaster) Q_PROPERTY(QString detail READ detail WRITE setDetail) public: - FieldMapDesc(){} - FieldMapDesc(FieldsCorrelation correlation):m_fieldsCorrelation(correlation){} - QString master(){return m_fieldsCorrelation.master;} - void setMaster(QString value){m_fieldsCorrelation.master=value;} - QString detail(){return m_fieldsCorrelation.detail;} - void setDetail(QString value){m_fieldsCorrelation.detail=value;} + FieldMapDesc() { } + FieldMapDesc(FieldsCorrelation correlation): m_fieldsCorrelation(correlation) { } + QString master() { return m_fieldsCorrelation.master; } + void setMaster(QString value) { m_fieldsCorrelation.master = value; } + QString detail() { return m_fieldsCorrelation.detail; } + void setDetail(QString value) { m_fieldsCorrelation.detail = value; } + private: FieldsCorrelation m_fieldsCorrelation; }; -class ProxyDesc : public QObject, public ICollectionContainer{ +class ProxyDesc: public QObject, public ICollectionContainer { Q_OBJECT Q_PROPERTY(ACollectionProperty fields READ fakeCollectionReader) Q_PROPERTY(QString master READ master WRITE setMaster) Q_PROPERTY(QString child READ child WRITE setDetail) Q_PROPERTY(QString name READ name WRITE setName) public: - void setMaster(QString value){m_master=value;} - QString master(){return m_master;} - void setDetail(QString value){m_detail=value;} - QString child(){return m_detail;} - QString name(){return m_name;} - void setName(QString value){m_name=value;} - void addFieldsCorrelation(const FieldsCorrelation &fieldsCorrelation); - QList* fieldsMap(){return &m_maps;} - //ICollectionContainer - virtual QObject* createElement(const QString& collectionName,const QString&); + void setMaster(QString value) { m_master = value; } + QString master() { return m_master; } + void setDetail(QString value) { m_detail = value; } + QString child() { return m_detail; } + QString name() { return m_name; } + void setName(QString value) { m_name = value; } + void addFieldsCorrelation(const FieldsCorrelation& fieldsCorrelation); + QList* fieldsMap() { return &m_maps; } + // ICollectionContainer + virtual QObject* createElement(const QString& collectionName, const QString&); virtual int elementsCount(const QString& collectionName); - virtual QObject *elementAt(const QString& collectionName,int index); + virtual QObject* elementAt(const QString& collectionName, int index); + private: QList m_maps; QString m_master; @@ -325,20 +357,24 @@ private: QString m_name; }; -class MasterDetailProxyModel : public QSortFilterProxyModel{ +class MasterDetailProxyModel: public QSortFilterProxyModel { Q_OBJECT public: - MasterDetailProxyModel(DataSourceManager* dataManager):m_maps(0),m_dataManager(dataManager){} + MasterDetailProxyModel(DataSourceManager* dataManager): + m_maps(0), + m_dataManager(dataManager) { } void setMaster(QString name); - void setChildName(QString name){m_childName=name;} - void setFieldsMap(QList *fieldsMap){m_maps=fieldsMap;} + void setChildName(QString name) { m_childName = name; } + void setFieldsMap(QList* fieldsMap) { m_maps = fieldsMap; } bool isInvalid() const; - DataSourceManager* dataManager() const {return m_dataManager;} + DataSourceManager* dataManager() const { return m_dataManager; } + protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; int fieldIndexByName(QString fieldName) const; QVariant sourceData(QString fieldName, int row) const; QVariant masterData(QString fieldName) const; + private: QList* m_maps; QString m_masterName; @@ -346,10 +382,10 @@ private: DataSourceManager* m_dataManager; }; -class ProxyHolder: public QObject, public IDataSourceHolder{ +class ProxyHolder: public QObject, public IDataSourceHolder { Q_OBJECT public: - ProxyHolder(ProxyDesc *desc, DataSourceManager *dataManager); + ProxyHolder(ProxyDesc* desc, DataSourceManager* dataManager); QString masterDatasource(); void filterModel(); IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE); @@ -359,22 +395,23 @@ public: bool isRemovable() const { return true; } QString lastError() const { return m_lastError; } void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false); - void update(){} - void clearErrors(){m_lastError = "";} - DataSourceManager* dataManager() const {return m_dataManager;} + void update() { } + void clearErrors() { m_lastError = ""; } + DataSourceManager* dataManager() const { return m_dataManager; } private slots: void slotChildModelDestoroyed(); + private: IDataSource::Ptr m_datasource; - MasterDetailProxyModel *m_model; - ProxyDesc *m_desc; + MasterDetailProxyModel* m_model; + ProxyDesc* m_desc; QString m_lastError; IDataSource::DatasourceMode m_mode; bool m_invalid; DataSourceManager* m_dataManager; }; -class ModelToDataSource : public QObject, public IDataSource{ +class ModelToDataSource: public QObject, public IDataSource { Q_OBJECT public: ModelToDataSource(QAbstractItemModel* model, bool owned); @@ -387,14 +424,15 @@ public: bool eof(); bool bof(); QVariant data(const QString& columnName); - QVariant dataByRowIndex(const QString &columnName, int rowIndex); - QVariant dataByRowIndex(const QString &columnName, int rowIndex, int roleName); - QVariant dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName); - QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData); + QVariant dataByRowIndex(const QString& columnName, int rowIndex); + QVariant dataByRowIndex(const QString& columnName, int rowIndex, int roleName); + QVariant dataByRowIndex(const QString& columnName, int rowIndex, const QString& roleName); + QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData); int columnCount(); QString columnNameByIndex(int columnIndex); int columnIndexByName(QString name); - QVariant headerData(const QString &columnName, const QString &roleName); + QVariant headerData(const QString& columnName, const QString& roleName); QString lastError(); virtual QAbstractItemModel* model(); int currentRow(); @@ -403,41 +441,58 @@ signals: void modelStateChanged(); private slots: void slotModelDestroed(); + private: QAbstractItemModel* m_model; bool m_owned; - int m_curRow; + int m_curRow; QString m_lastError; }; -class CallbackDatasource :public ICallbackDatasource, public IDataSource { +class CallbackDatasource: public ICallbackDatasource, public IDataSource { Q_OBJECT public: - CallbackDatasource(): m_currentRow(-1), m_eof(false), m_columnCount(-1), - m_rowCount(-1), m_getDataFromCache(false), m_lastKeyRow(0){} + CallbackDatasource(): + m_currentRow(-1), + m_eof(false), + m_columnCount(-1), + m_rowCount(-1), + m_getDataFromCache(false), + m_lastKeyRow(0) + { + } bool next(); - bool hasNext(){ if (!m_eof) return checkNextRecord(m_currentRow); else return false;} + bool hasNext() + { + if (!m_eof) + return checkNextRecord(m_currentRow); + else + return false; + } bool prior(); void first(); - void last(){} - bool bof(){return m_currentRow == -1;} - bool eof(){return m_eof;} - QVariant data(const QString &columnName); + void last() { } + bool bof() { return m_currentRow == -1; } + bool eof() { return m_eof; } + QVariant data(const QString& columnName); QVariant dataByRowIndex(const QString& columnName, int rowIndex); - QVariant dataByRowIndex(const QString &columnName, int rowIndex, int roleName); - QVariant dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName); - QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData); + QVariant dataByRowIndex(const QString& columnName, int rowIndex, int roleName); + QVariant dataByRowIndex(const QString& columnName, int rowIndex, const QString& roleName); + QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData); int columnCount(); QString columnNameByIndex(int columnIndex); int columnIndexByName(QString name); - bool isInvalid() const{ return false;} - QString lastError(){ return "";} - QAbstractItemModel *model(){return 0;} - QVariant headerData(const QString &columnName, const QString &roleName); + bool isInvalid() const { return false; } + QString lastError() { return ""; } + QAbstractItemModel* model() { return 0; } + QVariant headerData(const QString& columnName, const QString& roleName); + private: bool checkNextRecord(int recordNum); bool checkIfEmpty(); QVariant callbackData(const QString& columnName, int row); + private: QVector m_headers; int m_currentRow; @@ -447,28 +502,35 @@ private: QHash m_valuesCache; bool m_getDataFromCache; int m_lastKeyRow; - }; -class CallbackDatasourceHolder :public QObject, public IDataSourceHolder{ +class CallbackDatasourceHolder: public QObject, public IDataSourceHolder { Q_OBJECT // IDataSourceHolder interface public: - CallbackDatasourceHolder(IDataSource* datasource, bool owned):m_owned(owned){ m_datasource = datasource;} - IDataSource *dataSource(IDataSource::DatasourceMode){ return m_datasource;} - QString lastError() const{ return m_datasource->lastError();} - bool isInvalid() const {return m_datasource->isInvalid();} - bool isOwned() const {return m_owned;} - bool isEditable() const {return false;} - bool isRemovable() const {return false;} - void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false){Q_UNUSED(mode) Q_UNUSED(dbWillBeClosed)} - ~CallbackDatasourceHolder(){delete m_datasource;} - void update(){} - void clearErrors(){} + CallbackDatasourceHolder(IDataSource* datasource, bool owned): m_owned(owned) + { + m_datasource = datasource; + } + IDataSource* dataSource(IDataSource::DatasourceMode) { return m_datasource; } + QString lastError() const { return m_datasource->lastError(); } + bool isInvalid() const { return m_datasource->isInvalid(); } + bool isOwned() const { return m_owned; } + bool isEditable() const { return false; } + bool isRemovable() const { return false; } + void invalidate(IDataSource::DatasourceMode mode, bool dbWillBeClosed = false) + { + Q_UNUSED(mode) + Q_UNUSED(dbWillBeClosed) + } + ~CallbackDatasourceHolder() { delete m_datasource; } + void update() { } + void clearErrors() { } + private: IDataSource* m_datasource; bool m_owned; }; -} +} // namespace LimeReport #endif // LRDATADESIGNINTF_H diff --git a/limereport/lrdatasourceintf.h b/limereport/lrdatasourceintf.h index 481787c..5633a8a 100644 --- a/limereport/lrdatasourceintf.h +++ b/limereport/lrdatasourceintf.h @@ -1,14 +1,17 @@ #ifndef LRDATASOURCEINTF_H #define LRDATASOURCEINTF_H -#include #include +#include namespace LimeReport { class IDataSource { public: - enum DatasourceMode{DESIGN_MODE,RENDER_MODE}; + enum DatasourceMode { + DESIGN_MODE, + RENDER_MODE + }; typedef QSharedPointer Ptr; - virtual ~IDataSource() {} + virtual ~IDataSource() { } virtual bool next() = 0; virtual bool hasNext() = 0; virtual bool prior() = 0; @@ -18,12 +21,16 @@ public: virtual bool eof() = 0; virtual QVariant data(const QString& columnName) = 0; virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex) = 0; - virtual QVariant dataByRowIndex(const QString &columnName, int rowIndex, int roleName) = 0; - virtual QVariant dataByRowIndex(const QString &columnName, int rowIndex, const QString &roleName) = 0; - virtual QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, QVariant keyData) = 0; + virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex, int roleName) = 0; + virtual QVariant dataByRowIndex(const QString& columnName, int rowIndex, + const QString& roleName) + = 0; + virtual QVariant dataByKeyField(const QString& columnName, const QString& keyColumnName, + QVariant keyData) + = 0; virtual int columnCount() = 0; virtual QString columnNameByIndex(int columnIndex) = 0; - virtual QVariant headerData(const QString &columnName, const QString &roleName) = 0; + virtual QVariant headerData(const QString& columnName, const QString& roleName) = 0; virtual int columnIndexByName(QString name) = 0; virtual bool isInvalid() const = 0; virtual QString lastError() = 0; @@ -32,8 +39,9 @@ public: class IDataSourceHolder { public: - virtual ~IDataSourceHolder(){} - virtual IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE) = 0; + virtual ~IDataSourceHolder() { } + virtual IDataSource* dataSource(IDataSource::DatasourceMode mode = IDataSource::RENDER_MODE) + = 0; virtual QString lastError() const = 0; virtual bool isInvalid() const = 0; virtual bool isOwned() const = 0; @@ -47,5 +55,3 @@ public: } // namespace LimeReport #endif // LRDATASOURCEINTF_H - - diff --git a/limereport/lrdatasourcemanager.cpp b/limereport/lrdatasourcemanager.cpp index a532c1e..eb07c01 100644 --- a/limereport/lrdatasourcemanager.cpp +++ b/limereport/lrdatasourcemanager.cpp @@ -28,43 +28,46 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrdatasourcemanager.h" + #include "lrdatadesignintf.h" -#include + #include +#include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include #endif +#include #include #include -#include + #include #ifdef BUILD_WITH_EASY_PROFILER #include "easy/profiler.h" #else -# define EASY_BLOCK(...) -# define EASY_END_BLOCK +#define EASY_BLOCK(...) +#define EASY_END_BLOCK #endif -namespace LimeReport{ +namespace LimeReport { DataNode::~DataNode() { - for (int i = 0; im_childs.indexOf(const_cast(this)); } return 0; @@ -72,60 +75,62 @@ int DataNode::row() void DataNode::clear() { - for (int i=0; ichild(row); - if (childNode){ - return createIndex(row,column,childNode); - } else return QModelIndex(); + if (childNode) { + return createIndex(row, column, childNode); + } else + return QModelIndex(); } QModelIndex DataSourceModel::parent(const QModelIndex& child) const { - if (!child.isValid()) return QModelIndex(); + if (!child.isValid()) + return QModelIndex(); DataNode* childNode = nodeFromIndex(child); - if (!childNode) return QModelIndex(); + if (!childNode) + return QModelIndex(); DataNode* parentNode = childNode->parent(); - if ((parentNode == m_rootNode) || (!parentNode)) return QModelIndex(); - return createIndex(parentNode->row(),0,parentNode); + if ((parentNode == m_rootNode) || (!parentNode)) + return QModelIndex(); + return createIndex(parentNode->row(), 0, parentNode); } int DataSourceModel::rowCount(const QModelIndex& parent) const { - if (!m_rootNode) return 0; + if (!m_rootNode) + return 0; DataNode* parentNode; if (parent.isValid()) parentNode = nodeFromIndex(parent); @@ -142,14 +147,16 @@ int DataSourceModel::columnCount(const QModelIndex& parent) const QVariant DataSourceModel::data(const QModelIndex& index, int role) const { - DataNode *node = nodeFromIndex(index); + DataNode* node = nodeFromIndex(index); switch (role) { case Qt::DisplayRole: - if (!node) return QVariant(); + if (!node) + return QVariant(); return node->name(); break; - case Qt::DecorationRole : - if (!node) return QIcon(); + case Qt::DecorationRole: + if (!node) + return QIcon(); return node->icon(); break; default: @@ -160,7 +167,7 @@ QVariant DataSourceModel::data(const QModelIndex& index, int role) const void DataSourceModel::setDataSourceManager(DataSourceManager* dataManager) { m_dataManager = dataManager; - connect(m_dataManager,SIGNAL(datasourcesChanged()),this,SLOT(slotDatasourcesChanged())); + connect(m_dataManager, SIGNAL(datasourcesChanged()), this, SLOT(slotDatasourcesChanged())); updateModel(); } @@ -173,103 +180,119 @@ void DataSourceModel::slotDatasourcesChanged() DataNode* DataSourceModel::nodeFromIndex(const QModelIndex& index) const { - if (index.isValid()){ + if (index.isValid()) { return static_cast(index.internalPointer()); - } else return m_rootNode; + } else + return m_rootNode; } void DataSourceModel::fillFields(DataNode* parent) { - foreach(QString name, m_dataManager->fieldNames(parent->name())){ - parent->addChild(name, DataNode::Field,QIcon(":/report/images/field")); + foreach (QString name, m_dataManager->fieldNames(parent->name())) { + parent->addChild(name, DataNode::Field, QIcon(":/report/images/field")); } } void DataSourceModel::updateModel() { - QMap connections; + QMap connections; m_rootNode->clear(); - DataNode* ds = m_rootNode->addChild(tr("Datasources"),DataNode::DataSources,QIcon(":/report/images/databases")); + DataNode* ds = m_rootNode->addChild(tr("Datasources"), DataNode::DataSources, + QIcon(":/report/images/databases")); - - foreach (QString name,m_dataManager->connectionNames()) { - DataNode* connection = ds->addChild(name,DataNode::Connection,QIcon(":/report/images/database")); - connections.insert(name,connection); + foreach (QString name, m_dataManager->connectionNames()) { + DataNode* connection + = ds->addChild(name, DataNode::Connection, QIcon(":/report/images/database")); + connections.insert(name, connection); } foreach (QString name, m_dataManager->dataSourceNames()) { DataNode* datasource; - if (m_dataManager->isQuery(name)){ - DataNode* connection = connections.value(m_dataManager->queryByName(name)->connectionName()); - if (connection) datasource=connection->addChild(name,DataNode::Query,QIcon(":/report/images/table")); - else datasource=ds->addChild(name,DataNode::Query); - } else if (m_dataManager->isSubQuery(name)){ - DataNode* connection = connections.value(m_dataManager->subQueryByName(name)->connectionName()); - if (connection) datasource=connection->addChild(name,DataNode::SubQuery,QIcon(":/report/images/table")); - else datasource=ds->addChild(name,DataNode::SubQuery); + if (m_dataManager->isQuery(name)) { + DataNode* connection + = connections.value(m_dataManager->queryByName(name)->connectionName()); + if (connection) + datasource + = connection->addChild(name, DataNode::Query, QIcon(":/report/images/table")); + else + datasource = ds->addChild(name, DataNode::Query); + } else if (m_dataManager->isSubQuery(name)) { + DataNode* connection + = connections.value(m_dataManager->subQueryByName(name)->connectionName()); + if (connection) + datasource = connection->addChild(name, DataNode::SubQuery, + QIcon(":/report/images/table")); + else + datasource = ds->addChild(name, DataNode::SubQuery); } else { - datasource=ds->addChild(name,DataNode::Model,QIcon(":/report/images/table")); + datasource = ds->addChild(name, DataNode::Model, QIcon(":/report/images/table")); } fillFields(datasource); } - DataNode* vars = m_rootNode->addChild(tr("Variables"),DataNode::Variables,QIcon(":/report/images/folder")); - foreach (QString name, m_dataManager->variableNames()){ - vars->addChild(name,DataNode::Variable,QIcon(":/report/images/value")); + DataNode* vars = m_rootNode->addChild(tr("Variables"), DataNode::Variables, + QIcon(":/report/images/folder")); + foreach (QString name, m_dataManager->variableNames()) { + vars->addChild(name, DataNode::Variable, QIcon(":/report/images/value")); } - vars = m_rootNode->addChild(tr("External variables"),DataNode::Variables,QIcon(":/report/images/folder")); - foreach (QString name, m_dataManager->userVariableNames()){ - vars->addChild(name,DataNode::Variable,QIcon(":/report/images/value")); + vars = m_rootNode->addChild(tr("External variables"), DataNode::Variables, + QIcon(":/report/images/folder")); + foreach (QString name, m_dataManager->userVariableNames()) { + vars->addChild(name, DataNode::Variable, QIcon(":/report/images/value")); } } -DataSourceManager::DataSourceManager(QObject *parent) : - QObject(parent), m_lastError(""), m_designTime(false), m_needUpdate(false), - m_dbCredentialsProvider(0), m_hasChanges(false) +DataSourceManager::DataSourceManager(QObject* parent): + QObject(parent), + m_lastError(""), + m_designTime(false), + m_needUpdate(false), + m_dbCredentialsProvider(0), + m_hasChanges(false) { - m_groupFunctionFactory.registerFunctionCreator(QLatin1String("COUNT"),new ConstructorGroupFunctionCreator); - m_groupFunctionFactory.registerFunctionCreator(QLatin1String("SUM"),new ConstructorGroupFunctionCreator); - m_groupFunctionFactory.registerFunctionCreator(QLatin1String("AVG"),new ConstructorGroupFunctionCreator); - m_groupFunctionFactory.registerFunctionCreator(QLatin1String("MIN"),new ConstructorGroupFunctionCreator); - m_groupFunctionFactory.registerFunctionCreator(QLatin1String("MAX"),new ConstructorGroupFunctionCreator); - setSystemVariable(QLatin1String("#PAGE"),1,SecondPass); - setSystemVariable(QLatin1String("#PAGE_COUNT"),0,SecondPass); - setSystemVariable(QLatin1String("#IS_LAST_PAGEFOOTER"),false,FirstPass); - setSystemVariable(QLatin1String("#IS_FIRST_PAGEFOOTER"),false,FirstPass); + m_groupFunctionFactory.registerFunctionCreator( + QLatin1String("COUNT"), new ConstructorGroupFunctionCreator); + m_groupFunctionFactory.registerFunctionCreator( + QLatin1String("SUM"), new ConstructorGroupFunctionCreator); + m_groupFunctionFactory.registerFunctionCreator( + QLatin1String("AVG"), new ConstructorGroupFunctionCreator); + m_groupFunctionFactory.registerFunctionCreator( + QLatin1String("MIN"), new ConstructorGroupFunctionCreator); + m_groupFunctionFactory.registerFunctionCreator( + QLatin1String("MAX"), new ConstructorGroupFunctionCreator); + setSystemVariable(QLatin1String("#PAGE"), 1, SecondPass); + setSystemVariable(QLatin1String("#PAGE_COUNT"), 0, SecondPass); + setSystemVariable(QLatin1String("#IS_LAST_PAGEFOOTER"), false, FirstPass); + setSystemVariable(QLatin1String("#IS_FIRST_PAGEFOOTER"), false, FirstPass); m_datasourcesModel.setDataSourceManager(this); - connect(&m_reportVariables, SIGNAL(variableHasBeenAdded(QString)), - this, SLOT(slotVariableHasBeenAdded(QString))); - connect(&m_reportVariables, SIGNAL(variableHasBeenChanged(QString)), - this, SLOT(slotVariableHasBeenChanged(QString))); - connect(&m_userVariables, SIGNAL(variableHasBeenAdded(QString)), - this, SLOT(slotVariableHasBeenAdded(QString))); - connect(&m_userVariables, SIGNAL(variableHasBeenChanged(QString)), - this, SLOT(slotVariableHasBeenChanged(QString))); - - + connect(&m_reportVariables, SIGNAL(variableHasBeenAdded(QString)), this, + SLOT(slotVariableHasBeenAdded(QString))); + connect(&m_reportVariables, SIGNAL(variableHasBeenChanged(QString)), this, + SLOT(slotVariableHasBeenChanged(QString))); + connect(&m_userVariables, SIGNAL(variableHasBeenAdded(QString)), this, + SLOT(slotVariableHasBeenAdded(QString))); + connect(&m_userVariables, SIGNAL(variableHasBeenChanged(QString)), this, + SLOT(slotVariableHasBeenChanged(QString))); } -QString DataSourceManager::defaultDatabasePath() const -{ - return m_defaultDatabasePath; -} +QString DataSourceManager::defaultDatabasePath() const { return m_defaultDatabasePath; } -void DataSourceManager::setDefaultDatabasePath(const QString &defaultDatabasePath) +void DataSourceManager::setDefaultDatabasePath(const QString& defaultDatabasePath) { m_defaultDatabasePath = defaultDatabasePath; } QString DataSourceManager::putGroupFunctionsExpressions(QString expression) { - if (m_groupFunctionsExpressionsMap.contains(expression)){ + if (m_groupFunctionsExpressionsMap.contains(expression)) { return QString::number(m_groupFunctionsExpressionsMap.value(expression)); } else { m_groupFunctionsExpressions.append(expression); - m_groupFunctionsExpressionsMap.insert(expression, m_groupFunctionsExpressions.size()-1); - return QString::number(m_groupFunctionsExpressions.size()-1); + m_groupFunctionsExpressionsMap.insert(expression, m_groupFunctionsExpressions.size() - 1); + return QString::number(m_groupFunctionsExpressions.size() - 1); } } @@ -283,21 +306,15 @@ QString DataSourceManager::getExpression(QString index) { bool ok = false; int i = index.toInt(&ok); - if (ok && m_groupFunctionsExpressions.size()>i) + if (ok && m_groupFunctionsExpressions.size() > i) return m_groupFunctionsExpressions.at(index.toInt()); - else return ""; + else + return ""; } -bool DataSourceManager::designTime() const -{ - return m_designTime; -} - -void DataSourceManager::setDesignTime(bool designTime) -{ - m_designTime = designTime; -} +bool DataSourceManager::designTime() const { return m_designTime; } +void DataSourceManager::setDesignTime(bool designTime) { m_designTime = designTime; } DataSourceManager::~DataSourceManager() { @@ -307,26 +324,26 @@ DataSourceManager::~DataSourceManager() void DataSourceManager::connectAllDatabases() { - foreach(ConnectionDesc* conn,m_connections){ - try{ + foreach (ConnectionDesc* conn, m_connections) { + try { connectConnection(conn); - } catch (ReportError &e){ + } catch (ReportError& e) { putError(e.what()); setLastError(e.what()); - qDebug()<(ds),true); - putHolder(name,holder); + IDataSourceHolder* holder = new CallbackDatasourceHolder(dynamic_cast(ds), true); + putHolder(name, holder); emit datasourcesChanged(); m_needUpdate = true; return ds; } -void DataSourceManager::registerDbCredentialsProvider(IDbCredentialsProvider *provider) +void DataSourceManager::registerDbCredentialsProvider(IDbCredentialsProvider* provider) { m_dbCredentialsProvider = provider; } -void DataSourceManager::addCallbackDatasource(ICallbackDatasource *datasource, const QString& name) +void DataSourceManager::addCallbackDatasource(ICallbackDatasource* datasource, const QString& name) { IDataSource* datasourceIntf = dynamic_cast(datasource); - if (datasourceIntf){ - IDataSourceHolder* holder = new CallbackDatasourceHolder(datasourceIntf,true); - putHolder(name,holder); + if (datasourceIntf) { + IDataSourceHolder* holder = new CallbackDatasourceHolder(datasourceIntf, true); + putHolder(name, holder); emit datasourcesChanged(); } } -QSharedPointerDataSourceManager::previewSQL(const QString &connectionName, const QString &sqlText, QString masterDatasource) +QSharedPointer DataSourceManager::previewSQL(const QString& connectionName, + const QString& sqlText, + QString masterDatasource) { QSqlDatabase db = QSqlDatabase::database(connectionName); - if (db.isValid() && db.isOpen()){ + if (db.isValid() && db.isOpen()) { QSqlQueryModel* model = new QSqlQueryModel(); - QMap aliasesToParam; - QString queryText = replaceVariables(sqlText,aliasesToParam); - queryText = replaceFields(queryText,aliasesToParam,masterDatasource); + QMap aliasesToParam; + QString queryText = replaceVariables(sqlText, aliasesToParam); + queryText = replaceFields(queryText, aliasesToParam, masterDatasource); QSqlQuery query(db); query.prepare(queryText); - foreach(QString param,aliasesToParam.keys()){ + foreach (QString param, aliasesToParam.keys()) { QVariant value; - if (param.contains(".")){ + if (param.contains(".")) { value = fieldData(aliasesToParam.value(param)); - param=param.right(param.length()-param.indexOf('.')-1); + param = param.right(param.length() - param.indexOf('.') - 1); } else { value = variable(aliasesToParam.value(param)); } if (value.isValid() || m_designTime) - query.bindValue(':'+param,value); + query.bindValue(':' + param, value); } query.exec(); @@ -406,7 +425,7 @@ QSharedPointerDataSourceManager::previewSQL(const QString &c else return QSharedPointer(0); } - if (!db.isOpen()){ + if (!db.isOpen()) { m_lastError = tr("Connection \"%1\" is not open").arg(connectionName); putError(m_lastError); } @@ -423,12 +442,13 @@ void DataSourceManager::updateDatasourceModel() QString DataSourceManager::extractField(QString source) { if (source.contains('.')) { - return source.right(source.length()-(source.indexOf('.')+1)); + return source.right(source.length() - (source.indexOf('.') + 1)); } return source; } -QString DataSourceManager::replaceVariables(QString value){ +QString DataSourceManager::replaceVariables(QString value) +{ #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getVariableRegEx(); QRegularExpressionMatchIterator iter = rx.globalMatch(value); @@ -440,7 +460,7 @@ QString DataSourceManager::replaceVariables(QString value){ var.remove("$V{"); var.remove("}"); result += value.mid(pos, match.capturedStart(0)); - if (variable(var).isValid()){ + if (variable(var).isValid()) { result += variable(var).toString(); } else { result += QString(tr("Variable \"%1\" not found!").arg(var)); @@ -452,62 +472,66 @@ QString DataSourceManager::replaceVariables(QString value){ #else QRegExp rx(Const::VARIABLE_RX); - if (value.contains(rx)){ + if (value.contains(rx)) { int pos = -1; - while ((pos=rx.indexIn(value))!=-1){ - QString var=rx.cap(0); + while ((pos = rx.indexIn(value)) != -1) { + QString var = rx.cap(0); var.remove("$V{"); var.remove("}"); - if (variable(var).isValid()){ - value.replace(pos,rx.cap(0).length(),variable(var).toString()); + if (variable(var).isValid()) { + value.replace(pos, rx.cap(0).length(), variable(var).toString()); } else { - value.replace(pos,rx.cap(0).length(),QString(tr("Variable \"%1\" not found!").arg(var))); + value.replace(pos, rx.cap(0).length(), + QString(tr("Variable \"%1\" not found!").arg(var))); } } } - return value; + return value; #endif return QString(); } -QString DataSourceManager::replaceVariables(QString query, QMap &aliasesToParam) +QString DataSourceManager::replaceVariables(QString query, QMap& aliasesToParam) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getVariableRegEx(); int curentAliasIndex = 0; - if (query.contains(rx)){ + if (query.contains(rx)) { int pos = -1; QRegularExpressionMatch match = rx.match(query); - while ((pos=match.capturedStart())!=-1){ + while ((pos = match.capturedStart()) != -1) { - QString var=match.captured(0); + QString var = match.captured(0); var.remove("$V{"); var.remove("}"); - if (!match.captured(1).isEmpty()){ - if (aliasesToParam.contains(var)){ + if (!match.captured(1).isEmpty()) { + if (aliasesToParam.contains(var)) { curentAliasIndex++; - aliasesToParam.insert(var+"_v_alias"+QString::number(curentAliasIndex),var); - var += "_v_alias"+QString::number(curentAliasIndex); + aliasesToParam.insert(var + "_v_alias" + QString::number(curentAliasIndex), + var); + var += "_v_alias" + QString::number(curentAliasIndex); } else { - aliasesToParam.insert(var,var); + aliasesToParam.insert(var, var); } - query.replace(pos,match.captured(0).length(),":"+var); + query.replace(pos, match.captured(0).length(), ":" + var); } else { QString varName = match.captured(2).trimmed(); QString varParam = match.captured(3).trimmed(); - if (!varName.isEmpty()){ - if (!varParam.isEmpty() && varParam.compare("nobind") == 0 ){ - query.replace(pos,match.captured(0).length(), variable(varName).toString()); + if (!varName.isEmpty()) { + if (!varParam.isEmpty() && varParam.compare("nobind") == 0) { + query.replace(pos, match.captured(0).length(), + variable(varName).toString()); } else { - query.replace(pos,match.captured(0).length(), - QString(tr("Unknown parameter \"%1\" for variable \"%2\" found!") - .arg(varName) - .arg(varParam)) - ); + query.replace( + pos, match.captured(0).length(), + QString(tr("Unknown parameter \"%1\" for variable \"%2\" found!") + .arg(varName) + .arg(varParam))); } } else { - query.replace(pos,match.captured(0).length(),QString(tr("Variable \"%1\" not found!").arg(var))); + query.replace(pos, match.captured(0).length(), + QString(tr("Variable \"%1\" not found!").arg(var))); } } match = rx.match(query); @@ -516,37 +540,39 @@ QString DataSourceManager::replaceVariables(QString query, QMap #else QRegExp rx(Const::VARIABLE_RX); int curentAliasIndex = 0; - if (query.contains(rx)){ + if (query.contains(rx)) { int pos = -1; - while ((pos=rx.indexIn(query))!=-1){ + while ((pos = rx.indexIn(query)) != -1) { - QString var=rx.cap(0); + QString var = rx.cap(0); var.remove("$V{"); var.remove("}"); - if (!rx.cap(1).isEmpty()){ - if (aliasesToParam.contains(var)){ + if (!rx.cap(1).isEmpty()) { + if (aliasesToParam.contains(var)) { curentAliasIndex++; - aliasesToParam.insert(var+"_v_alias"+QString::number(curentAliasIndex),var); - var += "_v_alias"+QString::number(curentAliasIndex); + aliasesToParam.insert(var + "_v_alias" + QString::number(curentAliasIndex), + var); + var += "_v_alias" + QString::number(curentAliasIndex); } else { - aliasesToParam.insert(var,var); + aliasesToParam.insert(var, var); } - query.replace(pos,rx.cap(0).length(),":"+var); + query.replace(pos, rx.cap(0).length(), ":" + var); } else { QString varName = rx.cap(2).trimmed(); QString varParam = rx.cap(3).trimmed(); - if (!varName.isEmpty()){ - if (!varParam.isEmpty() && varParam.compare("nobind") == 0 ){ - query.replace(pos,rx.cap(0).length(), variable(varName).toString()); + if (!varName.isEmpty()) { + if (!varParam.isEmpty() && varParam.compare("nobind") == 0) { + query.replace(pos, rx.cap(0).length(), variable(varName).toString()); } else { - query.replace(pos,rx.cap(0).length(), - QString(tr("Unknown parameter \"%1\" for variable \"%2\" found!") - .arg(varName) - .arg(varParam)) - ); + query.replace( + pos, rx.cap(0).length(), + QString(tr("Unknown parameter \"%1\" for variable \"%2\" found!") + .arg(varName) + .arg(varParam))); } } else { - query.replace(pos,rx.cap(0).length(),QString(tr("Variable \"%1\" not found!").arg(var))); + query.replace(pos, rx.cap(0).length(), + QString(tr("Variable \"%1\" not found!").arg(var))); } } } @@ -555,111 +581,122 @@ QString DataSourceManager::replaceVariables(QString query, QMap return query; } -QString DataSourceManager::replaceFields(QString query, QMap &aliasesToParam, QString masterDatasource) +QString DataSourceManager::replaceFields(QString query, QMap& aliasesToParam, + QString masterDatasource) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getFieldRegEx(); int curentAliasIndex = 0; - if (query.contains(rx)){ + if (query.contains(rx)) { int pos = -1; QRegularExpressionMatch match = rx.match(query); - while ((pos=match.capturedStart())!=-1){ + while ((pos = match.capturedStart()) != -1) { - QString field=match.captured(0); + QString field = match.captured(0); field.remove("$D{"); field.remove("}"); - if (!aliasesToParam.contains(field)){ + if (!aliasesToParam.contains(field)) { if (field.contains(".")) aliasesToParam.insert(field, field); else - aliasesToParam.insert(field, masterDatasource+"."+field); + aliasesToParam.insert(field, masterDatasource + "." + field); } else { curentAliasIndex++; if (field.contains(".")) - aliasesToParam.insert(field+"_f_alias"+QString::number(curentAliasIndex), field); + aliasesToParam.insert(field + "_f_alias" + QString::number(curentAliasIndex), + field); else - aliasesToParam.insert(field+"_f_alias"+QString::number(curentAliasIndex), masterDatasource+"."+field); - field+="_f_alias"+QString::number(curentAliasIndex); + aliasesToParam.insert(field + "_f_alias" + QString::number(curentAliasIndex), + masterDatasource + "." + field); + field += "_f_alias" + QString::number(curentAliasIndex); } - query.replace(pos,match.capturedLength(),":"+extractField(field)); + query.replace(pos, match.capturedLength(), ":" + extractField(field)); match = rx.match(query); } } #else QRegExp rx(Const::FIELD_RX); - if (query.contains(rx)){ - int curentAliasIndex=0; + if (query.contains(rx)) { + int curentAliasIndex = 0; int pos; - while ((pos=rx.indexIn(query))!=-1){ - QString field=rx.cap(0); + while ((pos = rx.indexIn(query)) != -1) { + QString field = rx.cap(0); field.remove("$D{"); field.remove("}"); - if (!aliasesToParam.contains(field)){ + if (!aliasesToParam.contains(field)) { if (field.contains(".")) - aliasesToParam.insert(field,field); + aliasesToParam.insert(field, field); else - aliasesToParam.insert(field,masterDatasource+"."+field); + aliasesToParam.insert(field, masterDatasource + "." + field); } else { curentAliasIndex++; if (field.contains(".")) - aliasesToParam.insert(field+"_f_alias"+QString::number(curentAliasIndex),field); + aliasesToParam.insert(field + "_f_alias" + QString::number(curentAliasIndex), + field); else - aliasesToParam.insert(field+"_f_alias"+QString::number(curentAliasIndex),masterDatasource+"."+field); - field+="_f_alias"+QString::number(curentAliasIndex); + aliasesToParam.insert(field + "_f_alias" + QString::number(curentAliasIndex), + masterDatasource + "." + field); + field += "_f_alias" + QString::number(curentAliasIndex); } - query.replace(pos,rx.cap(0).length(),":"+extractField(field)); + query.replace(pos, rx.cap(0).length(), ":" + extractField(field)); } } - return query; + return query; #endif return query; } -void DataSourceManager::setReportVariable(const QString &name, const QVariant &value) -{ - if (!containsVariable(name)){ - addVariable(name,value); - } else changeVariable(name,value); +void DataSourceManager::setReportVariable(const QString& name, const QVariant& value) +{ + if (!containsVariable(name)) { + addVariable(name, value); + } else + changeVariable(name, value); } -void DataSourceManager::addQuery(const QString &name, const QString &sqlText, const QString &connectionName) +void DataSourceManager::addQuery(const QString& name, const QString& sqlText, + const QString& connectionName) { - QueryDesc *queryDecs = new QueryDesc(name,sqlText,connectionName); + QueryDesc* queryDecs = new QueryDesc(name, sqlText, connectionName); putQueryDesc(queryDecs); - putHolder(name,new QueryHolder(sqlText, connectionName, this)); + putHolder(name, new QueryHolder(sqlText, connectionName, this)); m_hasChanges = true; m_varToDataSource.clear(); emit datasourcesChanged(); } -void DataSourceManager::addSubQuery(const QString &name, const QString &sqlText, const QString &connectionName, const QString &masterDatasource) +void DataSourceManager::addSubQuery(const QString& name, const QString& sqlText, + const QString& connectionName, const QString& masterDatasource) { - SubQueryDesc *subQueryDesc = new SubQueryDesc(name.toLower(),sqlText,connectionName,masterDatasource); + SubQueryDesc* subQueryDesc + = new SubQueryDesc(name.toLower(), sqlText, connectionName, masterDatasource); putSubQueryDesc(subQueryDesc); - putHolder(name,new SubQueryHolder(sqlText, connectionName, masterDatasource, this)); + putHolder(name, new SubQueryHolder(sqlText, connectionName, masterDatasource, this)); m_hasChanges = true; m_varToDataSource.clear(); emit datasourcesChanged(); } -void DataSourceManager::addProxy(const QString &name, const QString &master, const QString &detail, QList fields) +void DataSourceManager::addProxy(const QString& name, const QString& master, const QString& detail, + QList fields) { - ProxyDesc *proxyDesc = new ProxyDesc(); + ProxyDesc* proxyDesc = new ProxyDesc(); proxyDesc->setName(name); proxyDesc->setMaster(master); proxyDesc->setDetail(detail); - foreach(FieldsCorrelation correlation,fields){ + foreach (FieldsCorrelation correlation, fields) { proxyDesc->addFieldsCorrelation(correlation); } putProxyDesc(proxyDesc); - putHolder(name,new ProxyHolder(proxyDesc, this)); + putHolder(name, new ProxyHolder(proxyDesc, this)); m_hasChanges = true; emit datasourcesChanged(); } -void DataSourceManager::addCSV(const QString& name, const QString& csvText, const QString &separator, bool firstRowIsHeader) +void DataSourceManager::addCSV(const QString& name, const QString& csvText, + const QString& separator, bool firstRowIsHeader) { CSVDesc* csvDesc = new CSVDesc(name, csvText, separator, firstRowIsHeader); putCSVDesc(csvDesc); @@ -668,141 +705,157 @@ void DataSourceManager::addCSV(const QString& name, const QString& csvText, cons emit datasourcesChanged(); } -QString DataSourceManager::queryText(const QString &dataSourceName) +QString DataSourceManager::queryText(const QString& dataSourceName) { - if (isQuery(dataSourceName)) return queryByName(dataSourceName)->queryText(); - if (isSubQuery(dataSourceName)) return subQueryByName(dataSourceName)->queryText(); - else return QString(); + if (isQuery(dataSourceName)) + return queryByName(dataSourceName)->queryText(); + if (isSubQuery(dataSourceName)) + return subQueryByName(dataSourceName)->queryText(); + else + return QString(); } -QueryDesc *DataSourceManager::queryByName(const QString &datasourceName) +QueryDesc* DataSourceManager::queryByName(const QString& datasourceName) { int queryIndex = queryIndexByName(datasourceName); - if (queryIndex!=-1) return m_queries.at(queryIndex); + if (queryIndex != -1) + return m_queries.at(queryIndex); return 0; } -SubQueryDesc* DataSourceManager::subQueryByName(const QString &datasourceName) +SubQueryDesc* DataSourceManager::subQueryByName(const QString& datasourceName) { int queryIndex = subQueryIndexByName(datasourceName); - if (queryIndex!=-1) return m_subqueries.at(queryIndex); + if (queryIndex != -1) + return m_subqueries.at(queryIndex); return 0; } -ConnectionDesc* DataSourceManager::connectionByName(const QString &connectionName) +ConnectionDesc* DataSourceManager::connectionByName(const QString& connectionName) { int queryIndex = connectionIndexByName(connectionName); - if (queryIndex!=-1) return m_connections.at(queryIndex); + if (queryIndex != -1) + return m_connections.at(queryIndex); return 0; } -int DataSourceManager::queryIndexByName(const QString &dataSourceName) +int DataSourceManager::queryIndexByName(const QString& dataSourceName) { - for(int i=0;iqueryName().compare(dataSourceName,Qt::CaseInsensitive)==0) return i; + for (int i = 0; i < m_queries.count(); i++) { + QueryDesc* desc = m_queries.at(i); + if (desc->queryName().compare(dataSourceName, Qt::CaseInsensitive) == 0) + return i; } return -1; } -int DataSourceManager::subQueryIndexByName(const QString &dataSourceName) +int DataSourceManager::subQueryIndexByName(const QString& dataSourceName) { - for(int i=0;iqueryName().compare(dataSourceName,Qt::CaseInsensitive)==0) return i; + for (int i = 0; i < m_subqueries.count(); ++i) { + QueryDesc* desc = m_subqueries.at(i); + if (desc->queryName().compare(dataSourceName, Qt::CaseInsensitive) == 0) + return i; } return -1; } -int DataSourceManager::proxyIndexByName(const QString &dataSourceName) +int DataSourceManager::proxyIndexByName(const QString& dataSourceName) { - for(int i=0;iname().compare(dataSourceName,Qt::CaseInsensitive)==0) return i; + for (int i = 0; i < m_proxies.count(); ++i) { + ProxyDesc* desc = m_proxies.at(i); + if (desc->name().compare(dataSourceName, Qt::CaseInsensitive) == 0) + return i; } return -1; } -int DataSourceManager::csvIndexByName(const QString &dataSourceName) +int DataSourceManager::csvIndexByName(const QString& dataSourceName) { - for(int i=0; i < m_csvs.count();++i){ - CSVDesc* desc=m_csvs.at(i); - if (desc->name().compare(dataSourceName,Qt::CaseInsensitive)==0) return i; + for (int i = 0; i < m_csvs.count(); ++i) { + CSVDesc* desc = m_csvs.at(i); + if (desc->name().compare(dataSourceName, Qt::CaseInsensitive) == 0) + return i; } return -1; } -int DataSourceManager::connectionIndexByName(const QString &connectionName) +int DataSourceManager::connectionIndexByName(const QString& connectionName) { - for(int i=0;iname().compare(connectionName,Qt::CaseInsensitive)==0) return i; + for (int i = 0; i < m_connections.count(); ++i) { + ConnectionDesc* desc = m_connections.at(i); + if (desc->name().compare(connectionName, Qt::CaseInsensitive) == 0) + return i; } return -1; } -QList& DataSourceManager::conections() +QList& DataSourceManager::conections() { return m_connections; } + +bool DataSourceManager::dataSourceIsValid(const QString& name) { - return m_connections; + if (m_datasources.value(name.toLower())) + return !m_datasources.value(name.toLower())->isInvalid(); + else + throw ReportError(tr("Datasource \"%1\" not found!").arg(name)); } -bool DataSourceManager::dataSourceIsValid(const QString &name) -{ - if (m_datasources.value(name.toLower())) return !m_datasources.value(name.toLower())->isInvalid(); - else throw ReportError(tr("Datasource \"%1\" not found!").arg(name)); -} - -bool DataSourceManager::isQuery(const QString &dataSourceName) +bool DataSourceManager::isQuery(const QString& dataSourceName) { return (queryByName(dataSourceName)); } -QString DataSourceManager::connectionName(const QString &dataSourceName) +QString DataSourceManager::connectionName(const QString& dataSourceName) { - if (isQuery(dataSourceName)) return queryByName(dataSourceName)->connectionName(); - if (isSubQuery(dataSourceName)) return subQueryByName(dataSourceName)->connectionName(); + if (isQuery(dataSourceName)) + return queryByName(dataSourceName)->connectionName(); + if (isSubQuery(dataSourceName)) + return subQueryByName(dataSourceName)->connectionName(); return QString(); } -ProxyDesc *DataSourceManager::proxyByName(const QString &datasourceName) +ProxyDesc* DataSourceManager::proxyByName(const QString& datasourceName) { int proxyIndex = proxyIndexByName(datasourceName); - if (proxyIndex > -1) return m_proxies.at(proxyIndex); - else return 0; + if (proxyIndex > -1) + return m_proxies.at(proxyIndex); + else + return 0; } -CSVDesc *DataSourceManager::csvByName(const QString &datasourceName) +CSVDesc* DataSourceManager::csvByName(const QString& datasourceName) { - int csvIndex = csvIndexByName(datasourceName); - if (csvIndex > -1) return m_csvs.at(csvIndex); - else return 0; + int csvIndex = csvIndexByName(datasourceName); + if (csvIndex > -1) + return m_csvs.at(csvIndex); + else + return 0; } -void DataSourceManager::removeDatasource(const QString &name) +void DataSourceManager::removeDatasource(const QString& name) { - if (m_datasources.contains(name)){ - IDataSourceHolder *holder; - holder=m_datasources.value(name); + if (m_datasources.contains(name)) { + IDataSourceHolder* holder; + holder = m_datasources.value(name); m_datasources.remove(name); delete holder; } - if (isQuery(name)){ - int queryIndex=queryIndexByName(name); + if (isQuery(name)) { + int queryIndex = queryIndexByName(name); delete m_queries.at(queryIndex); m_queries.removeAt(queryIndex); } - if (isSubQuery(name)){ - int queryIndex=subQueryIndexByName(name); + if (isSubQuery(name)) { + int queryIndex = subQueryIndexByName(name); delete m_subqueries.at(queryIndex); m_subqueries.removeAt(queryIndex); } - if (isProxy(name)){ - int proxyIndex=proxyIndexByName(name); + if (isProxy(name)) { + int proxyIndex = proxyIndexByName(name); delete m_proxies.at(proxyIndex); m_proxies.removeAt(proxyIndex); } - if (isCSV(name)){ - int csvIndex=csvIndexByName(name); + if (isCSV(name)) { + int csvIndex = csvIndexByName(name); delete m_csvs.at(csvIndex); m_csvs.removeAt(csvIndex); } @@ -811,13 +864,12 @@ void DataSourceManager::removeDatasource(const QString &name) emit datasourcesChanged(); } -void DataSourceManager::removeConnection(const QString &connectionName) +void DataSourceManager::removeConnection(const QString& connectionName) { QList::iterator cit = m_connections.begin(); - while( cit != m_connections.end() ){ - if ( ((*cit)->name().compare(connectionName) == 0) ){ - if ((*cit)->isInternal()) - { + while (cit != m_connections.end()) { + if (((*cit)->name().compare(connectionName) == 0)) { + if ((*cit)->isInternal()) { QSqlDatabase db = QSqlDatabase::database(connectionName); db.close(); } @@ -832,30 +884,33 @@ void DataSourceManager::removeConnection(const QString &connectionName) emit datasourcesChanged(); } -void DataSourceManager::addConnectionDesc(ConnectionDesc * connection) +void DataSourceManager::addConnectionDesc(ConnectionDesc* connection) { if (!isConnection(connection->name())) { - connect(connection,SIGNAL(nameChanged(QString,QString)),this,SLOT(slotConnectionRenamed(QString,QString))); + connect(connection, SIGNAL(nameChanged(QString, QString)), this, + SLOT(slotConnectionRenamed(QString, QString))); m_connections.append(connection); m_hasChanges = true; - if (connection->autoconnect()){ - try{ - connectConnection(connection); - } catch(ReportError &exception) { - qDebug()<autoconnect()) { + try { + connectConnection(connection); + } catch (ReportError& exception) { + qDebug() << exception.what(); } } } else { - throw ReportError(tr("Connection with name \"%1\" already exists!").arg(connection->name())); + throw ReportError( + tr("Connection with name \"%1\" already exists!").arg(connection->name())); } } -bool DataSourceManager::checkConnectionDesc(ConnectionDesc *connection) +bool DataSourceManager::checkConnectionDesc(ConnectionDesc* connection) { - if (connectConnection(connection)){ - if (connection->isInternal()){ + if (connectConnection(connection)) { + if (connection->isInternal()) { QSqlDatabase::removeDatabase(connection->name()); - if (designTime()) emit datasourcesChanged(); + if (designTime()) + emit datasourcesChanged(); } return true; } @@ -864,51 +919,56 @@ bool DataSourceManager::checkConnectionDesc(ConnectionDesc *connection) return false; } -void DataSourceManager::putHolder(const QString& name, IDataSourceHolder *dataSource) +void DataSourceManager::putHolder(const QString& name, IDataSourceHolder* dataSource) { - if (!m_datasources.contains(name.toLower())){ - m_datasources.insert( - name.toLower(), - dataSource - ); - } else throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(name)); + if (!m_datasources.contains(name.toLower())) { + m_datasources.insert(name.toLower(), dataSource); + } else + throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(name)); } void DataSourceManager::putQueryDesc(QueryDesc* queryDesc) { - if (!containsDatasource(queryDesc->queryName())){ + if (!containsDatasource(queryDesc->queryName())) { m_queries.append(queryDesc); - connect(queryDesc, SIGNAL(queryTextChanged(QString,QString)), - this, SLOT(slotQueryTextChanged(QString,QString))); - } else throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(queryDesc->queryName())); + connect(queryDesc, SIGNAL(queryTextChanged(QString, QString)), this, + SLOT(slotQueryTextChanged(QString, QString))); + } else + throw ReportError( + tr("Datasource with name \"%1\" already exists!").arg(queryDesc->queryName())); } -void DataSourceManager::putSubQueryDesc(SubQueryDesc *subQueryDesc) +void DataSourceManager::putSubQueryDesc(SubQueryDesc* subQueryDesc) { - if (!containsDatasource(subQueryDesc->queryName())){ + if (!containsDatasource(subQueryDesc->queryName())) { m_subqueries.append(subQueryDesc); - connect(subQueryDesc, SIGNAL(queryTextChanged(QString,QString)), - this, SLOT(slotQueryTextChanged(QString,QString))); - } else throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(subQueryDesc->queryName())); + connect(subQueryDesc, SIGNAL(queryTextChanged(QString, QString)), this, + SLOT(slotQueryTextChanged(QString, QString))); + } else + throw ReportError( + tr("Datasource with name \"%1\" already exists!").arg(subQueryDesc->queryName())); } -void DataSourceManager::putProxyDesc(ProxyDesc *proxyDesc) +void DataSourceManager::putProxyDesc(ProxyDesc* proxyDesc) { - if (!containsDatasource(proxyDesc->name())){ + if (!containsDatasource(proxyDesc->name())) { m_proxies.append(proxyDesc); - } else throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(proxyDesc->name())); + } else + throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(proxyDesc->name())); } -void DataSourceManager::putCSVDesc(CSVDesc *csvDesc) +void DataSourceManager::putCSVDesc(CSVDesc* csvDesc) { - if (!containsDatasource(csvDesc->name())){ + if (!containsDatasource(csvDesc->name())) { m_csvs.append(csvDesc); - connect(csvDesc, SIGNAL(cvsTextChanged(QString, QString)), - this, SLOT(slotCSVTextChanged(QString, QString))); - } else throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(csvDesc->name())); + connect(csvDesc, SIGNAL(cvsTextChanged(QString, QString)), this, + SLOT(slotCSVTextChanged(QString, QString))); + } else + throw ReportError(tr("Datasource with name \"%1\" already exists!").arg(csvDesc->name())); } -bool DataSourceManager::initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connectionDesc){ +bool DataSourceManager::initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connectionDesc) +{ bool connected = false; @@ -916,10 +976,10 @@ bool DataSourceManager::initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connecti db.setUserName(replaceVariables(connectionDesc.userName())); db.setPassword(replaceVariables(connectionDesc.password())); db.setDatabaseName(replaceVariables(connectionDesc.databaseName())); - if (connectionDesc.port()!="") + if (connectionDesc.port() != "") db.setPort(replaceVariables(connectionDesc.port()).toInt()); - if (!connectionDesc.keepDBCredentials() && m_dbCredentialsProvider){ + if (!connectionDesc.keepDBCredentials() && m_dbCredentialsProvider) { if (!m_dbCredentialsProvider->getUserName(connectionDesc.name()).isEmpty()) db.setUserName(m_dbCredentialsProvider->getUserName(connectionDesc.name())); if (!m_dbCredentialsProvider->getPassword(connectionDesc.name()).isEmpty()) @@ -927,13 +987,13 @@ bool DataSourceManager::initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connecti } QString dbName = replaceVariables(connectionDesc.databaseName()); - if (connectionDesc.driver().compare("QSQLITE")==0){ - if (!defaultDatabasePath().isEmpty()){ - dbName = !QFileInfo(dbName).exists() ? - defaultDatabasePath()+QFileInfo(dbName).fileName() : - dbName; + if (connectionDesc.driver().compare("QSQLITE") == 0) { + if (!defaultDatabasePath().isEmpty()) { + dbName = !QFileInfo(dbName).exists() + ? defaultDatabasePath() + QFileInfo(dbName).fileName() + : dbName; } - if (QFileInfo(dbName).exists()){ + if (QFileInfo(dbName).exists()) { db.setDatabaseName(dbName); } else { setLastError(tr("Database \"%1\" not found").arg(dbName)); @@ -943,46 +1003,46 @@ bool DataSourceManager::initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connecti db.setDatabaseName(dbName); } - connected=db.open(); - if (!connected) setLastError(db.lastError().text()); - return connected; + connected = db.open(); + if (!connected) + setLastError(db.lastError().text()); + return connected; } -ReportSettings *DataSourceManager::reportSettings() const -{ - return m_reportSettings; -} +ReportSettings* DataSourceManager::reportSettings() const { return m_reportSettings; } -void DataSourceManager::setReportSettings(ReportSettings *reportSettings) +void DataSourceManager::setReportSettings(ReportSettings* reportSettings) { m_reportSettings = reportSettings; } -bool DataSourceManager::checkConnection(QSqlDatabase db){ - QSqlQuery query("Select 1",db); +bool DataSourceManager::checkConnection(QSqlDatabase db) +{ + QSqlQuery query("Select 1", db); return query.first(); } -bool DataSourceManager::connectConnection(ConnectionDesc *connectionDesc) +bool DataSourceManager::connectConnection(ConnectionDesc* connectionDesc) { bool connected = false; clearErrors(); - QString lastError =""; + QString lastError = ""; - foreach(QString datasourceName, dataSourceNames()){ + foreach (QString datasourceName, dataSourceNames()) { dataSourceHolder(datasourceName)->clearErrors(); } - if (!QSqlDatabase::contains(connectionDesc->name())){ + if (!QSqlDatabase::contains(connectionDesc->name())) { QString dbError; { - QSqlDatabase db = QSqlDatabase::addDatabase(connectionDesc->driver(),connectionDesc->name()); + QSqlDatabase db + = QSqlDatabase::addDatabase(connectionDesc->driver(), connectionDesc->name()); connectionDesc->setInternal(true); - connected=initAndOpenDB(db, *connectionDesc); + connected = initAndOpenDB(db, *connectionDesc); dbError = db.lastError().text(); } - if (!connected){ + if (!connected) { if (!dbError.trimmed().isEmpty()) setLastError(dbError); QSqlDatabase::removeDatabase(connectionDesc->name()); @@ -990,7 +1050,7 @@ bool DataSourceManager::connectConnection(ConnectionDesc *connectionDesc) } } else { QSqlDatabase db = QSqlDatabase::database(connectionDesc->name()); - if (!connectionDesc->isEqual(db) && connectionDesc->isInternal()){ + if (!connectionDesc->isEqual(db) && connectionDesc->isInternal()) { db.close(); connected = initAndOpenDB(db, *connectionDesc); } else { @@ -1005,55 +1065,56 @@ bool DataSourceManager::connectConnection(ConnectionDesc *connectionDesc) QSqlDatabase::removeDatabase(connectionDesc->name()); return false; } else { - foreach(QString datasourceName, dataSourceNames()){ - if (isQuery(datasourceName)){ - QueryHolder* qh = dynamic_cast(dataSourceHolder(datasourceName)); - if (qh){ - qh->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); - invalidateChildren(datasourceName); - } + foreach (QString datasourceName, dataSourceNames()) { + if (isQuery(datasourceName)) { + QueryHolder* qh = dynamic_cast(dataSourceHolder(datasourceName)); + if (qh) { + qh->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); + invalidateChildren(datasourceName); + } } } - foreach(QString datasourceName, dataSourceNames()){ - if (isProxy(datasourceName)){ - ProxyHolder* ph = dynamic_cast(dataSourceHolder(datasourceName)); - if (ph){ - ph->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); - } + foreach (QString datasourceName, dataSourceNames()) { + if (isProxy(datasourceName)) { + ProxyHolder* ph = dynamic_cast(dataSourceHolder(datasourceName)); + if (ph) { + ph->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); + } } } - if (designTime()) emit datasourcesChanged(); + if (designTime()) + emit datasourcesChanged(); } return true; } -void DataSourceManager::clearReportVariables() -{ - m_reportVariables.clearUserVariables(); -} +void DataSourceManager::clearReportVariables() { m_reportVariables.clearUserVariables(); } void DataSourceManager::connectAutoConnections() { - foreach(ConnectionDesc* conn,m_connections){ + foreach (ConnectionDesc* conn, m_connections) { if (conn->autoconnect()) { try { connectConnection(conn); - } catch(ReportError &e){ + } catch (ReportError& e) { setLastError(e.what()); putError(e.what()); - qDebug()< DataSourceManager::childDatasources(const QString &parentDatasourceName) +QList DataSourceManager::childDatasources(const QString& parentDatasourceName) { QList result; - foreach(QString datasourceName, dataSourceNames()){ - if (isSubQuery(datasourceName)){ + foreach (QString datasourceName, dataSourceNames()) { + if (isSubQuery(datasourceName)) { SubQueryHolder* sh = dynamic_cast(dataSourceHolder(datasourceName)); - if (sh && sh->masterDatasource().compare(parentDatasourceName,Qt::CaseInsensitive)==0){ + if (sh + && sh->masterDatasource().compare(parentDatasourceName, Qt::CaseInsensitive) == 0) { result.append(datasourceName); } } @@ -1061,44 +1122,44 @@ QList DataSourceManager::childDatasources(const QString &parentDatasour return result; } -void DataSourceManager::invalidateChildren(const QString &parentDatasourceName) +void DataSourceManager::invalidateChildren(const QString& parentDatasourceName) { - foreach(QString datasourceName, childDatasources(parentDatasourceName)){ + foreach (QString datasourceName, childDatasources(parentDatasourceName)) { SubQueryHolder* sh = dynamic_cast(dataSourceHolder(datasourceName)); if (sh) - sh->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); + sh->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE); invalidateChildren(datasourceName); } } -bool DataSourceManager::containsDatasource(const QString &dataSourceName) +bool DataSourceManager::containsDatasource(const QString& dataSourceName) { return m_datasources.contains(dataSourceName.toLower()); } -bool DataSourceManager::isSubQuery(const QString &dataSourceName) +bool DataSourceManager::isSubQuery(const QString& dataSourceName) { return subQueryIndexByName(dataSourceName) != -1; } -bool DataSourceManager::isProxy(const QString &dataSourceName) +bool DataSourceManager::isProxy(const QString& dataSourceName) { return proxyIndexByName(dataSourceName) != -1; } -bool DataSourceManager::isCSV(const QString &datasourceName) +bool DataSourceManager::isCSV(const QString& datasourceName) { return csvIndexByName(datasourceName) != -1; } -bool DataSourceManager::isConnection(const QString &connectionName) +bool DataSourceManager::isConnection(const QString& connectionName) { return connectionIndexByName(connectionName) != -1; } -bool DataSourceManager::isConnectionConnected(const QString &connectionName) +bool DataSourceManager::isConnectionConnected(const QString& connectionName) { - if (isConnection(connectionName) && QSqlDatabase::contains(connectionName)){ + if (isConnection(connectionName) && QSqlDatabase::contains(connectionName)) { QSqlDatabase db = QSqlDatabase::database(connectionName); return db.isValid() && QSqlDatabase::database(connectionName).isOpen(); } @@ -1112,11 +1173,12 @@ bool DataSourceManager::connectConnection(const QString& connectionName) void DataSourceManager::disconnectConnection(const QString& connectionName) { - foreach(QString datasourceName, dataSourceNames()){ - if (isQuery(datasourceName) || isSubQuery(datasourceName)){ + foreach (QString datasourceName, dataSourceNames()) { + if (isQuery(datasourceName) || isSubQuery(datasourceName)) { QueryHolder* qh = dynamic_cast(dataSourceHolder(datasourceName)); - if (qh && qh->connectionName().compare(connectionName, Qt::CaseInsensitive) == 0){ - qh->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE, true); + if (qh && qh->connectionName().compare(connectionName, Qt::CaseInsensitive) == 0) { + qh->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE, + true); qh->setLastError(tr("invalid connection")); } } @@ -1124,25 +1186,27 @@ void DataSourceManager::disconnectConnection(const QString& connectionName) ConnectionDesc* connectionDesc = connectionByName(connectionName); - if (connectionDesc->isInternal()){ + if (connectionDesc->isInternal()) { { QSqlDatabase db = QSqlDatabase::database(connectionName); - if (db.isOpen()) db.close(); + if (db.isOpen()) + db.close(); } - if (QSqlDatabase::contains(connectionName)) QSqlDatabase::removeDatabase(connectionName); + if (QSqlDatabase::contains(connectionName)) + QSqlDatabase::removeDatabase(connectionName); } - } -IDataSource *DataSourceManager::dataSource(const QString &name) +IDataSource* DataSourceManager::dataSource(const QString& name) { IDataSourceHolder* holder = m_datasources.value(name.toLower()); if (holder) { if (holder->isInvalid()) { - setLastError(name+" : "+holder->lastError()); + setLastError(name + " : " + holder->lastError()); return 0; } else { - return holder->dataSource(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); + return holder->dataSource(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); } } else { setLastError(tr("Datasource \"%1\" not found!").arg(name)); @@ -1150,17 +1214,19 @@ IDataSource *DataSourceManager::dataSource(const QString &name) } } -IDataSourceHolder *DataSourceManager::dataSourceHolder(const QString &name) +IDataSourceHolder* DataSourceManager::dataSourceHolder(const QString& name) { - if (m_datasources.value(name.toLower())) return m_datasources.value(name.toLower()); - else return 0; + if (m_datasources.value(name.toLower())) + return m_datasources.value(name.toLower()); + else + return 0; } QStringList DataSourceManager::dataSourceNames() { QStringList result; - for (int i=0;iconnectionName().compare(connectionName,Qt::CaseInsensitive)==0){ + if (query->connectionName().compare(connectionName, Qt::CaseInsensitive) == 0) { result.append(query->queryName()); } } foreach (QueryDesc* query, m_subqueries) { - if (query->connectionName().compare(connectionName,Qt::CaseInsensitive)==0){ + if (query->connectionName().compare(connectionName, Qt::CaseInsensitive) == 0) { result.append(query->queryName()); } } @@ -1185,18 +1251,18 @@ QStringList DataSourceManager::dataSourceNames(const QString& connectionName) QStringList DataSourceManager::connectionNames() { QStringList result; - foreach(ConnectionDesc* conDesc,m_connections){ - result.append(conDesc->name()); + foreach (ConnectionDesc* conDesc, m_connections) { + result.append(conDesc->name()); } return result; } -QStringList DataSourceManager::fieldNames(const QString &datasourceName) +QStringList DataSourceManager::fieldNames(const QString& datasourceName) { QStringList result; IDataSource* ds = dataSource(datasourceName); - if (ds && !ds->isInvalid()){ - for(int i=0; i < ds->columnCount(); i++){ + if (ds && !ds->isInvalid()) { + for (int i = 0; i < ds->columnCount(); i++) { result.append(ds->columnNameByIndex(i)); } result.sort(); @@ -1204,151 +1270,146 @@ QStringList DataSourceManager::fieldNames(const QString &datasourceName) return result; } -void DataSourceManager::addConnection(const QString &connectionName) +void DataSourceManager::addConnection(const QString& connectionName) { addConnectionDesc(new ConnectionDesc(QSqlDatabase::database(connectionName))); m_hasChanges = true; emit datasourcesChanged(); } -QObject *DataSourceManager::createElement(const QString& collectionName, const QString&) +QObject* DataSourceManager::createElement(const QString& collectionName, const QString&) { - if (collectionName=="connections"){ + if (collectionName == "connections") { ConnectionDesc* connection = new ConnectionDesc; m_connections.append(connection); return connection; } - if (collectionName=="queries"){ + if (collectionName == "queries") { QueryDesc* queryDesc = new QueryDesc; m_queries.append(queryDesc); return queryDesc; } - if (collectionName=="subqueries"){ + if (collectionName == "subqueries") { SubQueryDesc* subQueryDesc = new SubQueryDesc; m_subqueries.append(subQueryDesc); return subQueryDesc; } - if (collectionName=="subproxies"){ + if (collectionName == "subproxies") { ProxyDesc* proxyDesc = new ProxyDesc; m_proxies.append(proxyDesc); return proxyDesc; } - if (collectionName=="variables"){ + if (collectionName == "variables") { VarDesc* var = new VarDesc; m_tempVars.append(var); return var; } - if (collectionName=="csvs"){ + if (collectionName == "csvs") { CSVDesc* csvDesc = new CSVDesc; m_csvs.append(csvDesc); - return csvDesc; + return csvDesc; } return 0; } -int DataSourceManager::elementsCount(const QString &collectionName) +int DataSourceManager::elementsCount(const QString& collectionName) { - if (collectionName=="connections"){ - return m_connections.count(); + if (collectionName == "connections") { + return m_connections.count(); } - if (collectionName=="queries"){ + if (collectionName == "queries") { return m_queries.count(); } - if (collectionName=="subqueries"){ + if (collectionName == "subqueries") { return m_subqueries.count(); } - if (collectionName=="subproxies"){ + if (collectionName == "subproxies") { return m_proxies.count(); } - if (collectionName=="variables"){ + if (collectionName == "variables") { return m_reportVariables.variablesCount(); } - if (collectionName=="csvs"){ + if (collectionName == "csvs") { return m_csvs.count(); } return 0; } -QObject* DataSourceManager::elementAt(const QString &collectionName, int index) +QObject* DataSourceManager::elementAt(const QString& collectionName, int index) { - if (collectionName=="connections"){ + if (collectionName == "connections") { return m_connections.at(index); } - if (collectionName=="queries"){ + if (collectionName == "queries") { return m_queries.at(index); } - if (collectionName=="subqueries"){ + if (collectionName == "subqueries") { return m_subqueries.at(index); } - if (collectionName=="subproxies"){ + if (collectionName == "subproxies") { return m_proxies.at(index); } - if (collectionName=="variables"){ + if (collectionName == "variables") { return m_reportVariables.variableAt(index); } - if (collectionName=="csvs"){ + if (collectionName == "csvs") { return m_csvs.at(index); } return 0; } -void DataSourceManager::collectionLoadFinished(const QString &collectionName) +void DataSourceManager::collectionLoadFinished(const QString& collectionName) { EASY_BLOCK("DataSourceManager::collectionLoadFinished"); - if (collectionName.compare("connections",Qt::CaseInsensitive) == 0){ - - } + if (collectionName.compare("connections", Qt::CaseInsensitive) == 0) { } EASY_BLOCK("queryes"); - if (collectionName.compare("queries",Qt::CaseInsensitive) == 0){ + if (collectionName.compare("queries", Qt::CaseInsensitive) == 0) { QMutableListIterator it(m_queries); - while (it.hasNext()){ + while (it.hasNext()) { it.next(); - if (!m_datasources.contains(it.value()->queryName().toLower())){ - connect(it.value(), SIGNAL(queryTextChanged(QString,QString)), - this, SLOT(slotQueryTextChanged(QString,QString))); - putHolder(it.value()->queryName(),new QueryHolder(it.value()->queryText(), it.value()->connectionName(), this)); + if (!m_datasources.contains(it.value()->queryName().toLower())) { + connect(it.value(), SIGNAL(queryTextChanged(QString, QString)), this, + SLOT(slotQueryTextChanged(QString, QString))); + putHolder( + it.value()->queryName(), + new QueryHolder(it.value()->queryText(), it.value()->connectionName(), this)); } else { delete it.value(); it.remove(); } } - } EASY_END_BLOCK; EASY_BLOCK("subqueries") - if (collectionName.compare("subqueries",Qt::CaseInsensitive) == 0){ + if (collectionName.compare("subqueries", Qt::CaseInsensitive) == 0) { QMutableListIterator it(m_subqueries); - while (it.hasNext()){ + while (it.hasNext()) { it.next(); - if (!m_datasources.contains(it.value()->queryName().toLower())){ - connect(it.value(), SIGNAL(queryTextChanged(QString,QString)), - this, SLOT(slotQueryTextChanged(QString,QString))); - putHolder(it.value()->queryName(),new SubQueryHolder( - it.value()->queryText(), - it.value()->connectionName(), - it.value()->master(), - this) - ); + if (!m_datasources.contains(it.value()->queryName().toLower())) { + connect(it.value(), SIGNAL(queryTextChanged(QString, QString)), this, + SLOT(slotQueryTextChanged(QString, QString))); + putHolder(it.value()->queryName(), + new SubQueryHolder(it.value()->queryText(), it.value()->connectionName(), + it.value()->master(), this)); } else { delete it.value(); it.remove(); } } - } EASY_END_BLOCK; EASY_BLOCK("subproxies"); - if (collectionName.compare("subproxies",Qt::CaseInsensitive) == 0){ + if (collectionName.compare("subproxies", Qt::CaseInsensitive) == 0) { QMutableListIterator it(m_proxies); - while (it.hasNext()){ + while (it.hasNext()) { it.next(); - if (!m_datasources.contains(it.value()->name().toLower())){ - putHolder(it.value()->name(),new ProxyHolder(it.value(), this)); + if (!m_datasources.contains(it.value()->name().toLower())) { + putHolder(it.value()->name(), new ProxyHolder(it.value(), this)); } else { delete it.value(); it.remove(); @@ -1357,10 +1418,11 @@ void DataSourceManager::collectionLoadFinished(const QString &collectionName) } EASY_END_BLOCK; EASY_BLOCK("variables"); - if (collectionName.compare("variables",Qt::CaseInsensitive) == 0){ + if (collectionName.compare("variables", Qt::CaseInsensitive) == 0) { foreach (VarDesc* item, m_tempVars) { - if (!m_reportVariables.containsVariable(item->name())){ - m_reportVariables.addVariable(item->name(),item->value(),VarDesc::Report,FirstPass); + if (!m_reportVariables.containsVariable(item->name())) { + m_reportVariables.addVariable(item->name(), item->value(), VarDesc::Report, + FirstPass); VarDesc* currentVar = m_reportVariables.variableByName(item->name()); currentVar->initFrom(item); } @@ -1370,17 +1432,14 @@ void DataSourceManager::collectionLoadFinished(const QString &collectionName) } EASY_END_BLOCK; - if (collectionName.compare("csvs", Qt::CaseInsensitive) == 0){ + if (collectionName.compare("csvs", Qt::CaseInsensitive) == 0) { QMutableListIterator it(m_csvs); - while (it.hasNext()){ + while (it.hasNext()) { it.next(); - if (!m_datasources.contains(it.value()->name().toLower())){ - connect(it.value(), SIGNAL(cvsTextChanged(QString,QString)), - this, SLOT(slotCSVTextChanged(QString,QString))); - putHolder( - it.value()->name(), - new CSVHolder(*it.value(), this) - ); + if (!m_datasources.contains(it.value()->name().toLower())) { + connect(it.value(), SIGNAL(cvsTextChanged(QString, QString)), this, + SLOT(slotCSVTextChanged(QString, QString))); + putHolder(it.value()->name(), new CSVHolder(*it.value(), this)); } else { delete it.value(); it.remove(); @@ -1388,7 +1447,7 @@ void DataSourceManager::collectionLoadFinished(const QString &collectionName) } } - if (designTime()){ + if (designTime()) { EASY_BLOCK("emit datasourcesChanged()"); emit datasourcesChanged(); EASY_END_BLOCK; @@ -1399,14 +1458,15 @@ void DataSourceManager::collectionLoadFinished(const QString &collectionName) EASY_END_BLOCK; } -void DataSourceManager::addVariable(const QString &name, const QVariant &value, VarDesc::VarType type, RenderPass pass) +void DataSourceManager::addVariable(const QString& name, const QVariant& value, + VarDesc::VarType type, RenderPass pass) { - if (type == VarDesc::User){ + if (type == VarDesc::User) { m_userVariables.addVariable(name, value, type, pass); } else { - m_reportVariables.addVariable(name,value,type,pass); + m_reportVariables.addVariable(name, value, type, pass); } - if (designTime()){ + if (designTime()) { EASY_BLOCK("DataSourceManager::addVariable emit ds changed"); emit datasourcesChanged(); EASY_END_BLOCK; @@ -1416,33 +1476,35 @@ void DataSourceManager::addVariable(const QString &name, const QVariant &value, void DataSourceManager::deleteVariable(const QString& name) { m_userVariables.deleteVariable(name); - if (m_reportVariables.containsVariable(name)&&m_reportVariables.variableType(name)==VarDesc::Report){ + if (m_reportVariables.containsVariable(name) + && m_reportVariables.variableType(name) == VarDesc::Report) { m_reportVariables.deleteVariable(name); - if (designTime()){ + if (designTime()) { m_hasChanges = true; emit datasourcesChanged(); } } } -void DataSourceManager::changeVariable(const QString& name,const QVariant& value) +void DataSourceManager::changeVariable(const QString& name, const QVariant& value) { - if (m_userVariables.containsVariable(name)){ - m_userVariables.changeVariable(name,value); + if (m_userVariables.containsVariable(name)) { + m_userVariables.changeVariable(name, value); } - if (m_reportVariables.containsVariable(name)){ - m_reportVariables.changeVariable(name,value); + if (m_reportVariables.containsVariable(name)) { + m_reportVariables.changeVariable(name, value); } - } -void DataSourceManager::setSystemVariable(const QString &name, const QVariant &value, RenderPass pass) +void DataSourceManager::setSystemVariable(const QString& name, const QVariant& value, + RenderPass pass) { - addVariable(name,value,VarDesc::System,pass); + addVariable(name, value, VarDesc::System, pass); } -void DataSourceManager::setLastError(const QString &value){ - m_lastError = value; +void DataSourceManager::setLastError(const QString& value) +{ + m_lastError = value; if (!value.isEmpty() && !m_errorsList.contains(value)) { m_errorsList.append(value); } @@ -1450,34 +1512,38 @@ void DataSourceManager::setLastError(const QString &value){ void DataSourceManager::invalidateLinkedDatasources(QString datasourceName) { - foreach(QString name, dataSourceNames()){ - if (isSubQuery(name)){ - if (subQueryByName(name)->master().compare(datasourceName) == 0) - dataSourceHolder(name)->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); + foreach (QString name, dataSourceNames()) { + if (isSubQuery(name)) { + if (subQueryByName(name)->master().compare(datasourceName) == 0) + dataSourceHolder(name)->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); } - if (isProxy(name)){ + if (isProxy(name)) { ProxyDesc* proxy = proxyByName(name); - if ((proxy->master().compare(datasourceName) == 0) || (proxy->child().compare(datasourceName) == 0)) - dataSourceHolder(name)->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); - + if ((proxy->master().compare(datasourceName) == 0) + || (proxy->child().compare(datasourceName) == 0)) + dataSourceHolder(name)->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); } } } -void DataSourceManager::slotConnectionRenamed(const QString &oldName, const QString &newName) +void DataSourceManager::slotConnectionRenamed(const QString& oldName, const QString& newName) { - foreach(QueryDesc* query, m_queries){ - if (query->connectionName().compare(oldName,Qt::CaseInsensitive)==0) query->setConnectionName(newName); + foreach (QueryDesc* query, m_queries) { + if (query->connectionName().compare(oldName, Qt::CaseInsensitive) == 0) + query->setConnectionName(newName); } - foreach(SubQueryDesc* query, m_subqueries){ - if (query->connectionName().compare(oldName,Qt::CaseInsensitive)==0) query->setConnectionName(newName); + foreach (SubQueryDesc* query, m_subqueries) { + if (query->connectionName().compare(oldName, Qt::CaseInsensitive) == 0) + query->setConnectionName(newName); } } -void DataSourceManager::slotQueryTextChanged(const QString &queryName, const QString &queryText) +void DataSourceManager::slotQueryTextChanged(const QString& queryName, const QString& queryText) { QueryHolder* holder = dynamic_cast(m_datasources.value(queryName)); - if (holder){ + if (holder) { holder->setQueryText(queryText); } m_varToDataSource.clear(); @@ -1485,25 +1551,30 @@ void DataSourceManager::slotQueryTextChanged(const QString &queryName, const QSt void DataSourceManager::invalidateQueriesContainsVariable(const QString& variableName) { - if (!variableIsSystem(variableName)){ + if (!variableIsSystem(variableName)) { - if (m_varToDataSource.contains(variableName)){ - foreach(QString datasourceName, m_varToDataSource.value(variableName)){ - QueryHolder* holder = dynamic_cast(m_datasources.value(datasourceName)); - if (holder) holder->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE); + if (m_varToDataSource.contains(variableName)) { + foreach (QString datasourceName, m_varToDataSource.value(variableName)) { + QueryHolder* holder + = dynamic_cast(m_datasources.value(datasourceName)); + if (holder) + holder->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); } } else { QVector datasources; - foreach (const QString& datasourceName, dataSourceNames()){ - QueryHolder* holder = dynamic_cast(m_datasources.value(datasourceName)); - if (holder){ + foreach (const QString& datasourceName, dataSourceNames()) { + QueryHolder* holder + = dynamic_cast(m_datasources.value(datasourceName)); + if (holder) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(QString(Const::NAMED_VARIABLE_RX).arg(variableName)); #else QRegularExpression rx = getNamedVariableRegEx(variableName); #endif - if (holder->queryText().contains(rx)){ - holder->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE); + if (holder->queryText().contains(rx)) { + holder->invalidate(designTime() ? IDataSource::DESIGN_MODE + : IDataSource::RENDER_MODE); datasources.append(datasourceName); } } @@ -1527,10 +1598,10 @@ void DataSourceManager::slotVariableHasBeenChanged(const QString& variableName) m_hasChanges = true; } -void DataSourceManager::slotCSVTextChanged(const QString &csvName, const QString &csvText) +void DataSourceManager::slotCSVTextChanged(const QString& csvName, const QString& csvText) { CSVHolder* holder = dynamic_cast(m_datasources.value(csvName)); - if (holder){ + if (holder) { holder->setCSVText(csvText); } } @@ -1540,16 +1611,16 @@ void DataSourceManager::clear(ClearMethod method) m_varToDataSource.clear(); DataSourcesMap::iterator dit; - for( dit = m_datasources.begin(); dit != m_datasources.end(); ){ + for (dit = m_datasources.begin(); dit != m_datasources.end();) { bool owned = (*dit)->isOwned() && (*dit)->isRemovable(); - switch(method){ + switch (method) { case All: invalidateLinkedDatasources(dit.key()); delete dit.value(); dit = m_datasources.erase(dit); break; default: - if (owned){ + if (owned) { invalidateLinkedDatasources(dit.key()); delete dit.value(); dit = m_datasources.erase(dit); @@ -1557,27 +1628,29 @@ void DataSourceManager::clear(ClearMethod method) ++dit; } } - } QList::iterator cit = m_connections.begin(); - while( cit != m_connections.end() ){ - if ( (*cit)->isInternal() ) - QSqlDatabase::removeDatabase( (*cit)->name() ); + while (cit != m_connections.end()) { + if ((*cit)->isInternal()) + QSqlDatabase::removeDatabase((*cit)->name()); delete (*cit); cit = m_connections.erase(cit); } - //TODO: add smart pointes to collections - foreach(QueryDesc *desc, m_queries) delete desc; - foreach(SubQueryDesc* desc, m_subqueries) delete desc; - foreach(ProxyDesc* desc, m_proxies) delete desc; + // TODO: add smart pointes to collections + foreach (QueryDesc* desc, m_queries) + delete desc; + foreach (SubQueryDesc* desc, m_subqueries) + delete desc; + foreach (ProxyDesc* desc, m_proxies) + delete desc; m_queries.clear(); m_subqueries.clear(); m_proxies.clear(); -// if (method == All) -// clearUserVariables(); + // if (method == All) + // clearUserVariables(); clearReportVariables(); emit cleared(); @@ -1585,7 +1658,7 @@ void DataSourceManager::clear(ClearMethod method) void DataSourceManager::clearGroupFunction() { - foreach(GroupFunction* gf ,m_groupFunctions.values()){ + foreach (GroupFunction* gf, m_groupFunctions.values()) { delete gf; } m_groupFunctions.clear(); @@ -1593,73 +1666,79 @@ void DataSourceManager::clearGroupFunction() void DataSourceManager::clearGroupFunctionValues(const QString& bandObjectName) { - foreach(GroupFunction* gf, m_groupFunctions.values(bandObjectName)){ + foreach (GroupFunction* gf, m_groupFunctions.values(bandObjectName)) { gf->values().clear(); } } -GroupFunction* DataSourceManager::addGroupFunction(const QString &name, const QString &expression, const QString &band, const QString& dataBand) +GroupFunction* DataSourceManager::addGroupFunction(const QString& name, const QString& expression, + const QString& band, const QString& dataBand) { - GroupFunction* gf = m_groupFunctionFactory.createGroupFunction(name,expression,dataBand,this); - if (gf){ - m_groupFunctions.insert(band,gf); + GroupFunction* gf + = m_groupFunctionFactory.createGroupFunction(name, expression, dataBand, this); + if (gf) { + m_groupFunctions.insert(band, gf); } return gf; } -GroupFunction *DataSourceManager::groupFunction(const QString &name, const QString &expression, const QString &band) +GroupFunction* DataSourceManager::groupFunction(const QString& name, const QString& expression, + const QString& band) { - foreach(GroupFunction* gf,m_groupFunctions.values(band)){ - if ((gf->name().compare(name,Qt::CaseInsensitive)==0)&& - (gf->data().compare(expression,Qt::CaseInsensitive)==0) - ) return gf; + foreach (GroupFunction* gf, m_groupFunctions.values(band)) { + if ((gf->name().compare(name, Qt::CaseInsensitive) == 0) + && (gf->data().compare(expression, Qt::CaseInsensitive) == 0)) + return gf; } return 0; } -QList DataSourceManager::groupFunctionsByBand(const QString &band) +QList DataSourceManager::groupFunctionsByBand(const QString& band) { return m_groupFunctions.values(band); } -void DataSourceManager::updateChildrenData(const QString &datasourceName) +void DataSourceManager::updateChildrenData(const QString& datasourceName) { - foreach(SubQueryDesc* subquery,m_subqueries){ - if (subquery->master().compare(datasourceName,Qt::CaseInsensitive)==0){ - SubQueryHolder* holder=dynamic_cast(dataSourceHolder(subquery->queryName())); - if (holder) holder->runQuery(); + foreach (SubQueryDesc* subquery, m_subqueries) { + if (subquery->master().compare(datasourceName, Qt::CaseInsensitive) == 0) { + SubQueryHolder* holder + = dynamic_cast(dataSourceHolder(subquery->queryName())); + if (holder) + holder->runQuery(); } } - foreach(ProxyDesc* subproxy,m_proxies){ - if(subproxy->master().compare(datasourceName,Qt::CaseInsensitive)==0){ + foreach (ProxyDesc* subproxy, m_proxies) { + if (subproxy->master().compare(datasourceName, Qt::CaseInsensitive) == 0) { ProxyHolder* holder = dynamic_cast(dataSourceHolder(subproxy->name())); holder->filterModel(); } } } -QString DataSourceManager::extractDataSource(const QString &fieldName) +QString DataSourceManager::extractDataSource(const QString& fieldName) { return fieldName.left(fieldName.indexOf('.')); } -QString DataSourceManager::extractFieldName(const QString &fieldName) +QString DataSourceManager::extractFieldName(const QString& fieldName) { - return fieldName.right((fieldName.length()-fieldName.indexOf('.'))-1); + return fieldName.right((fieldName.length() - fieldName.indexOf('.')) - 1); } -bool DataSourceManager::containsField(const QString &fieldName) +bool DataSourceManager::containsField(const QString& fieldName) { IDataSource* ds = dataSource(extractDataSource(fieldName)); if (ds) { - return ds->columnIndexByName(extractFieldName(fieldName))!=-1; + return ds->columnIndexByName(extractFieldName(fieldName)) != -1; } return false; } bool DataSourceManager::containsVariable(const QString& variableName) { - if (m_userVariables.containsVariable(variableName)) return true; + if (m_userVariables.containsVariable(variableName)) + return true; return m_reportVariables.containsVariable(variableName); } @@ -1669,81 +1748,85 @@ void DataSourceManager::clearUserVariables() m_reportVariables.clearUserVariables(); } -QVariant DataSourceManager::fieldData(const QString &fieldName) +QVariant DataSourceManager::fieldData(const QString& fieldName) { - if (containsField(fieldName)){ + if (containsField(fieldName)) { IDataSource* ds = dataSource(extractDataSource(fieldName)); - if (ds) return ds->data(extractFieldName(fieldName)); + if (ds) + return ds->data(extractFieldName(fieldName)); } return QVariant(); } -QVariant DataSourceManager::fieldDataByRowIndex(const QString &fieldName, int rowIndex) +QVariant DataSourceManager::fieldDataByRowIndex(const QString& fieldName, int rowIndex) { - if (containsField(fieldName)){ + if (containsField(fieldName)) { IDataSource* ds = dataSource(extractDataSource(fieldName)); - if (ds){ + if (ds) { return ds->dataByRowIndex(extractFieldName(fieldName), rowIndex); } } return QVariant(); } -QVariant DataSourceManager::fieldDataByRowIndex(const QString &fieldName, int rowIndex, int role) +QVariant DataSourceManager::fieldDataByRowIndex(const QString& fieldName, int rowIndex, int role) { - if(containsField(fieldName)) { - IDataSource *ds = dataSource(extractDataSource(fieldName)); - if(ds) { + if (containsField(fieldName)) { + IDataSource* ds = dataSource(extractDataSource(fieldName)); + if (ds) { return ds->dataByRowIndex(extractFieldName(fieldName), rowIndex, role); } } return QVariant(); } -QVariant DataSourceManager::fieldDataByRowIndex(const QString &fieldName, int rowIndex, const QString &roleName) +QVariant DataSourceManager::fieldDataByRowIndex(const QString& fieldName, int rowIndex, + const QString& roleName) { - if(containsField(fieldName)) { - IDataSource *ds = dataSource(extractDataSource(fieldName)); - if(ds) { + if (containsField(fieldName)) { + IDataSource* ds = dataSource(extractDataSource(fieldName)); + if (ds) { return ds->dataByRowIndex(extractFieldName(fieldName), rowIndex, roleName); } } return QVariant(); } -QVariant DataSourceManager::fieldDataByKey(const QString& datasourceName, const QString& valueFieldName, const QString& keyFieldName, QVariant keyValue) +QVariant DataSourceManager::fieldDataByKey(const QString& datasourceName, + const QString& valueFieldName, + const QString& keyFieldName, QVariant keyValue) { IDataSource* ds = dataSource(datasourceName); - if (ds){ + if (ds) { return ds->dataByKeyField(valueFieldName, keyFieldName, keyValue); } return QVariant(); } -QVariant DataSourceManager::headerData(const QString &fieldName, const QString &roleName) +QVariant DataSourceManager::headerData(const QString& fieldName, const QString& roleName) { - if(containsField(fieldName)) { - IDataSource *ds = dataSource(extractDataSource(fieldName)); - if(ds) { + if (containsField(fieldName)) { + IDataSource* ds = dataSource(extractDataSource(fieldName)); + if (ds) { return ds->headerData(extractFieldName(fieldName), roleName); } } return QVariant(); } -QString DataSourceManager::columnName(const QString &datasourceName, int index) +QString DataSourceManager::columnName(const QString& datasourceName, int index) { - IDataSource *ds = dataSource(datasourceName); - if(ds && !ds->isInvalid() && ds->columnCount() > index) { + IDataSource* ds = dataSource(datasourceName); + if (ds && !ds->isInvalid() && ds->columnCount() > index) { return ds->columnNameByIndex(index); } return QString("unknown"); } -int DataSourceManager::columnCount(const QString &datasourceName) +int DataSourceManager::columnCount(const QString& datasourceName) { - IDataSource *ds = dataSource(datasourceName); - if(ds && !ds->isInvalid()) { + IDataSource* ds = dataSource(datasourceName); + if (ds && !ds->isInvalid()) { return ds->columnCount(); } @@ -1753,30 +1836,30 @@ int DataSourceManager::columnCount(const QString &datasourceName) void DataSourceManager::reopenDatasource(const QString& datasourceName) { QueryHolder* qh = dynamic_cast(dataSourceHolder(datasourceName)); - if (qh){ - qh->invalidate(designTime()?IDataSource::DESIGN_MODE:IDataSource::RENDER_MODE); + if (qh) { + qh->invalidate(designTime() ? IDataSource::DESIGN_MODE : IDataSource::RENDER_MODE); invalidateChildren(datasourceName); } } -QVariant DataSourceManager::variable(const QString &variableName) +QVariant DataSourceManager::variable(const QString& variableName) { if (m_userVariables.containsVariable(variableName)) return m_userVariables.variable(variableName); return m_reportVariables.variable(variableName); } -RenderPass DataSourceManager::variablePass(const QString &name) +RenderPass DataSourceManager::variablePass(const QString& name) { if (m_userVariables.containsVariable(name)) return m_userVariables.variablePass(name); return m_reportVariables.variablePass(name); } -bool DataSourceManager::variableIsSystem(const QString &name) +bool DataSourceManager::variableIsSystem(const QString& name) { if (m_reportVariables.containsVariable(name)) - return (m_reportVariables.variableType(name)==VarDesc::System); + return (m_reportVariables.variableType(name) == VarDesc::System); return false; } @@ -1793,27 +1876,22 @@ void DataSourceManager::setVarableMandatory(const QString& name, bool value) m_reportVariables.variableByName(name)->setMandatory(value); } -QStringList DataSourceManager::variableNames() -{ - return m_reportVariables.variableNames(); -} +QStringList DataSourceManager::variableNames() { return m_reportVariables.variableNames(); } QStringList DataSourceManager::variableNamesByRenderPass(RenderPass pass) { QStringList result; - foreach(QString variableName, m_reportVariables.variableNames()){ - if (m_reportVariables.variablePass(variableName) == pass){ + foreach (QString variableName, m_reportVariables.variableNames()) { + if (m_reportVariables.variablePass(variableName) == pass) { result.append(variableName); } } return result; } -QStringList DataSourceManager::userVariableNames(){ - return m_userVariables.variableNames(); -} +QStringList DataSourceManager::userVariableNames() { return m_userVariables.variableNames(); } -VarDesc::VarType DataSourceManager::variableType(const QString &name) +VarDesc::VarType DataSourceManager::variableType(const QString& name) { if (m_reportVariables.containsVariable(name)) return m_reportVariables.variableType(name); @@ -1835,9 +1913,10 @@ void DataSourceManager::setVariableDataType(const QString& name, VariableDataTyp void DataSourceManager::setAllDatasourcesToFirst() { - foreach(IDataSourceHolder* ds,m_datasources.values()) { - if (ds->dataSource()) ds->dataSource()->first(); + foreach (IDataSourceHolder* ds, m_datasources.values()) { + if (ds->dataSource()) + ds->dataSource()->first(); } } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrdatasourcemanager.h b/limereport/lrdatasourcemanager.h index 7e94be9..e57fd8e 100644 --- a/limereport/lrdatasourcemanager.h +++ b/limereport/lrdatasourcemanager.h @@ -30,70 +30,93 @@ #ifndef LRDATASOURCEMANAGER_H #define LRDATASOURCEMANAGER_H -#include -#include -#include "lrdatadesignintf.h" #include "lrcollection.h" -#include "lrglobal.h" -#include "lrvariablesholder.h" -#include "lrgroupfunctions.h" -#include "lrdatasourcemanagerintf.h" +#include "lrdatadesignintf.h" #include "lrdatasourceintf.h" +#include "lrdatasourcemanagerintf.h" +#include "lrglobal.h" +#include "lrgroupfunctions.h" +#include "lrvariablesholder.h" -namespace LimeReport{ +#include +#include +namespace LimeReport { class DataSourceManager; class DataNode { public: - enum NodeType{Root,Connection,DataSources,Query,SubQuery,Model,Field,Variables,Variable}; - DataNode(const QString& name="", NodeType type=Root, DataNode* parent=0, const QIcon& icon=QIcon()) - :m_name(name), m_icon(icon), m_type(type), m_parent(parent){} + enum NodeType { + Root, + Connection, + DataSources, + Query, + SubQuery, + Model, + Field, + Variables, + Variable + }; + DataNode(const QString& name = "", NodeType type = Root, DataNode* parent = 0, + const QIcon& icon = QIcon()): + m_name(name), + m_icon(icon), + m_type(type), + m_parent(parent) + { + } virtual ~DataNode(); - int childCount(){return m_childs.count();} - DataNode* child(int index){return m_childs[index];} - DataNode* parent(){return m_parent;} - DataNode* addChild(const QString& name="", NodeType type=Root, const QIcon& icon=QIcon()); - int row(); - QString name(){return m_name;} - QIcon icon(){return m_icon;} - void clear(); - NodeType type(){return m_type;} + int childCount() { return m_childs.count(); } + DataNode* child(int index) { return m_childs[index]; } + DataNode* parent() { return m_parent; } + DataNode* addChild(const QString& name = "", NodeType type = Root, const QIcon& icon = QIcon()); + int row(); + QString name() { return m_name; } + QIcon icon() { return m_icon; } + void clear(); + NodeType type() { return m_type; } + private: - QString m_name; - QIcon m_icon; - NodeType m_type; - DataNode* m_parent; + QString m_name; + QIcon m_icon; + NodeType m_type; + DataNode* m_parent; QVector m_childs; }; -class DataSourceModel : public QAbstractItemModel{ +class DataSourceModel: public QAbstractItemModel { Q_OBJECT friend class DataSourceManager; + public: - DataSourceModel():m_dataManager(NULL),m_rootNode(new DataNode()){} + DataSourceModel(): m_dataManager(NULL), m_rootNode(new DataNode()) { } DataSourceModel(DataSourceManager* dataManager); ~DataSourceModel(); - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; + QModelIndex index(int row, int column, const QModelIndex& parent) const; + QModelIndex parent(const QModelIndex& child) const; + int rowCount(const QModelIndex& parent) const; + int columnCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& index, int role) const; void setDataSourceManager(DataSourceManager* dataManager); private slots: void slotDatasourcesChanged(); + private: - DataNode* nodeFromIndex(const QModelIndex &index) const; + DataNode* nodeFromIndex(const QModelIndex& index) const; void fillFields(DataNode* parent); void updateModel(); + private: DataSourceManager* m_dataManager; DataNode* m_rootNode; }; -class DataSourceManager : public QObject, public ICollectionContainer, public IVariablesContainer, public IDataSourceManager -{ +class DataSourceManager: + public QObject, + public ICollectionContainer, + public IVariablesContainer, + public IDataSourceManager { Q_OBJECT Q_PROPERTY(ACollectionProperty connections READ fakeCollectionReader) Q_PROPERTY(ACollectionProperty queries READ fakeCollectionReader) @@ -103,40 +126,48 @@ class DataSourceManager : public QObject, public ICollectionContainer, public IV Q_PROPERTY(ACollectionProperty csvs READ fakeCollectionReader) friend class ReportEnginePrivate; friend class ReportRender; + public: - typedef QHash DataSourcesMap; - enum ClearMethod {All,Owned}; + typedef QHash DataSourcesMap; + enum ClearMethod { + All, + Owned + }; ~DataSourceManager(); void connectAllDatabases(); void addConnection(const QString& connectionName); - void addConnectionDesc(ConnectionDesc *); - bool checkConnectionDesc(ConnectionDesc *connection); - void addQuery(const QString& name, const QString& sqlText, const QString& connectionName=""); - void addSubQuery(const QString& name, const QString& sqlText, const QString& connectionName, const QString& masterDatasource); - void addProxy(const QString& name, const QString& master, const QString& detail, QList fields); - void addCSV(const QString& name, const QString& csvText, const QString& separator, bool firstRowIsHeader); - bool addModel(const QString& name, QAbstractItemModel *model, bool owned); + void addConnectionDesc(ConnectionDesc*); + bool checkConnectionDesc(ConnectionDesc* connection); + void addQuery(const QString& name, const QString& sqlText, const QString& connectionName = ""); + void addSubQuery(const QString& name, const QString& sqlText, const QString& connectionName, + const QString& masterDatasource); + void addProxy(const QString& name, const QString& master, const QString& detail, + QList fields); + void addCSV(const QString& name, const QString& csvText, const QString& separator, + bool firstRowIsHeader); + bool addModel(const QString& name, QAbstractItemModel* model, bool owned); void removeModel(const QString& name); - ICallbackDatasource* createCallbackDatasource(const QString &name); - void registerDbCredentialsProvider(IDbCredentialsProvider *provider); - void addCallbackDatasource(ICallbackDatasource *datasource, const QString &name); + ICallbackDatasource* createCallbackDatasource(const QString& name); + void registerDbCredentialsProvider(IDbCredentialsProvider* provider); + void addCallbackDatasource(ICallbackDatasource* datasource, const QString& name); void setReportVariable(const QString& name, const QVariant& value); void deleteVariable(const QString& name); bool containsVariable(const QString& variableName); void clearUserVariables(); - void addVariable(const QString& name, const QVariant& value, VarDesc::VarType type=VarDesc::User, RenderPass pass=FirstPass); - void changeVariable(const QString& name,const QVariant& value); - QVariant variable(const QString& variableName); - RenderPass variablePass(const QString& name); + void addVariable(const QString& name, const QVariant& value, + VarDesc::VarType type = VarDesc::User, RenderPass pass = FirstPass); + void changeVariable(const QString& name, const QVariant& value); + QVariant variable(const QString& variableName); + RenderPass variablePass(const QString& name); QStringList variableNames(); QStringList variableNamesByRenderPass(RenderPass pass); QStringList userVariableNames(); - VarDesc::VarType variableType(const QString& name); - VariableDataType variableDataType(const QString& name); - void setVariableDataType(const QString &name, VariableDataType value); + VarDesc::VarType variableType(const QString& name); + VariableDataType variableDataType(const QString& name); + void setVariableDataType(const QString& name, VariableDataType value); bool variableIsSystem(const QString& name); bool variableIsMandatory(const QString& name); - void setVarableMandatory(const QString &name, bool value); + void setVarableMandatory(const QString& name, bool value); QString queryText(const QString& dataSourceName); QString connectionName(const QString& dataSourceName); void removeDatasource(const QString& name); @@ -148,21 +179,21 @@ public: bool isCSV(const QString& datasourceName); bool isConnection(const QString& connectionName); bool isConnectionConnected(const QString& connectionName); - bool connectConnection(const QString &connectionName); + bool connectConnection(const QString& connectionName); void connectAutoConnections(); - void disconnectConnection(const QString &connectionName); + void disconnectConnection(const QString& connectionName); QueryDesc* queryByName(const QString& datasourceName); SubQueryDesc* subQueryByName(const QString& datasourceName); ProxyDesc* proxyByName(const QString& datasourceName); CSVDesc* csvByName(const QString& datasourceName); - ConnectionDesc *connectionByName(const QString& connectionName); + ConnectionDesc* connectionByName(const QString& connectionName); int queryIndexByName(const QString& dataSourceName); int subQueryIndexByName(const QString& dataSourceName); int proxyIndexByName(const QString& dataSourceName); int csvIndexByName(const QString& dataSourceName); int connectionIndexByName(const QString& connectionName); - QList &conections(); + QList& conections(); bool dataSourceIsValid(const QString& name); IDataSource* dataSource(const QString& name); IDataSourceHolder* dataSourceHolder(const QString& name); @@ -170,81 +201,91 @@ public: QStringList dataSourceNames(const QString& connectionName); QStringList connectionNames(); QStringList fieldNames(const QString& datasourceName); - bool containsField(const QString& fieldName); - QVariant fieldData(const QString& fieldName); - QVariant fieldDataByRowIndex(const QString& fieldName, int rowIndex); - QVariant fieldDataByRowIndex(const QString &fieldName, int rowIndex, int role); - QVariant fieldDataByRowIndex(const QString &fieldName, int rowIndex, const QString &roleName); - QVariant fieldDataByKey( - const QString& datasourceName, - const QString& valueFieldName, - const QString& keyFieldName, - QVariant keyValue - ); - QVariant headerData(const QString &fieldName, const QString &roleName); - QString columnName(const QString &datasourceName, int index); - int columnCount(const QString &datasourceName); - void reopenDatasource(const QString& datasourceName); + bool containsField(const QString& fieldName); + QVariant fieldData(const QString& fieldName); + QVariant fieldDataByRowIndex(const QString& fieldName, int rowIndex); + QVariant fieldDataByRowIndex(const QString& fieldName, int rowIndex, int role); + QVariant fieldDataByRowIndex(const QString& fieldName, int rowIndex, const QString& roleName); + QVariant fieldDataByKey(const QString& datasourceName, const QString& valueFieldName, + const QString& keyFieldName, QVariant keyValue); + QVariant headerData(const QString& fieldName, const QString& roleName); + QString columnName(const QString& datasourceName, int index); + int columnCount(const QString& datasourceName); + void reopenDatasource(const QString& datasourceName); QString extractDataSource(const QString& fieldName); QString extractFieldName(const QString& fieldName); void setAllDatasourcesToFirst(); void clear(ClearMethod method); void clearGroupFunction(); - void clearGroupFunctionValues(const QString &bandObjectName); + void clearGroupFunctionValues(const QString& bandObjectName); - QList groupFunctionNames(){return m_groupFunctionFactory.functionNames();} - GroupFunction* addGroupFunction(const QString& name, const QString& expression, const QString& band, const QString &dataBand); - GroupFunction* groupFunction(const QString& name, const QString &expression, const QString& band); + QList groupFunctionNames() { return m_groupFunctionFactory.functionNames(); } + GroupFunction* addGroupFunction(const QString& name, const QString& expression, + const QString& band, const QString& dataBand); + GroupFunction* groupFunction(const QString& name, const QString& expression, + const QString& band); QList groupFunctionsByBand(const QString& band); void updateChildrenData(const QString& datasourceName); - DataSourceModel* datasourcesModel(){return &m_datasourcesModel;} - QString lastError() const { return m_lastError;} + DataSourceModel* datasourcesModel() { return &m_datasourcesModel; } + QString lastError() const { return m_lastError; } - void putError(QString error){ if (!m_errorsList.contains(error)) m_errorsList.append(error);} - void clearErrors(){ m_errorsList.clear(); m_lastError = "";} - QStringList errorsList(){ return m_errorsList;} + void putError(QString error) + { + if (!m_errorsList.contains(error)) + m_errorsList.append(error); + } + void clearErrors() + { + m_errorsList.clear(); + m_lastError = ""; + } + QStringList errorsList() { return m_errorsList; } bool designTime() const; void setDesignTime(bool designTime); QString extractField(QString source); - QString replaceVariables(QString query, QMap &aliasesToParam); + QString replaceVariables(QString query, QMap& aliasesToParam); QString replaceVariables(QString value); - QString replaceFields(QString query, QMap &aliasesToParam, QString masterDatasource = ""); - QSharedPointer previewSQL(const QString& connectionName, const QString& sqlText, QString masterDatasource=""); + QString replaceFields(QString query, QMap& aliasesToParam, + QString masterDatasource = ""); + QSharedPointer previewSQL(const QString& connectionName, + const QString& sqlText, + QString masterDatasource = ""); void updateDatasourceModel(); - bool isNeedUpdateDatasourceModel(){ return m_needUpdate;} + bool isNeedUpdateDatasourceModel() { return m_needUpdate; } QString defaultDatabasePath() const; - void setDefaultDatabasePath(const QString &defaultDatabasePath); + void setDefaultDatabasePath(const QString& defaultDatabasePath); QString putGroupFunctionsExpressions(QString expression); - void clearGroupFuntionsExpressions(); + void clearGroupFuntionsExpressions(); QString getExpression(QString index); - ReportSettings *reportSettings() const; - void setReportSettings(ReportSettings *reportSettings); + ReportSettings* reportSettings() const; + void setReportSettings(ReportSettings* reportSettings); - bool hasChanges(){ return m_hasChanges; } - void dropChanges(){ m_hasChanges = false; } + bool hasChanges() { return m_hasChanges; } + void dropChanges() { m_hasChanges = false; } signals: void loadCollectionFinished(const QString& collectionName); void cleared(); void datasourcesChanged(); + protected: void putHolder(const QString& name, LimeReport::IDataSourceHolder* dataSource); - void putQueryDesc(QueryDesc *queryDesc); - void putSubQueryDesc(SubQueryDesc *subQueryDesc); - void putProxyDesc(ProxyDesc *proxyDesc); + void putQueryDesc(QueryDesc* queryDesc); + void putSubQueryDesc(SubQueryDesc* subQueryDesc); + void putProxyDesc(ProxyDesc* proxyDesc); void putCSVDesc(CSVDesc* csvDesc); bool connectConnection(ConnectionDesc* connectionDesc); void clearReportVariables(); QList childDatasources(const QString& datasourceName); void invalidateChildren(const QString& parentDatasourceName); - //ICollectionContainer - virtual QObject* createElement(const QString& collectionName,const QString&); + // ICollectionContainer + virtual QObject* createElement(const QString& collectionName, const QString&); virtual int elementsCount(const QString& collectionName); - virtual QObject *elementAt(const QString& collectionName,int index); + virtual QObject* elementAt(const QString& collectionName, int index); virtual void collectionLoadFinished(const QString& collectionName); void setSystemVariable(const QString& name, const QVariant& value, RenderPass pass); @@ -253,14 +294,15 @@ protected: bool checkConnection(QSqlDatabase db); void invalidateQueriesContainsVariable(const QString& variableName); private slots: - void slotConnectionRenamed(const QString& oldName,const QString& newName); + void slotConnectionRenamed(const QString& oldName, const QString& newName); void slotQueryTextChanged(const QString& queryName, const QString& queryText); void slotVariableHasBeenAdded(const QString& variableName); void slotVariableHasBeenChanged(const QString& variableName); void slotCSVTextChanged(const QString& csvName, const QString& csvText); + private: - explicit DataSourceManager(QObject *parent = 0); - bool initAndOpenDB(QSqlDatabase &db, ConnectionDesc &connectionDesc); + explicit DataSourceManager(QObject* parent = 0); + bool initAndOpenDB(QSqlDatabase& db, ConnectionDesc& connectionDesc); Q_DISABLE_COPY(DataSourceManager) private: QList m_connections; @@ -270,7 +312,7 @@ private: QList m_tempVars; QList m_csvs; - QMultiMap m_groupFunctions; + QMultiMap m_groupFunctions; GroupFunctionFactory m_groupFunctionFactory; VariablesHolder m_reportVariables; VariablesHolder m_userVariables; @@ -282,15 +324,14 @@ private: bool m_needUpdate; QString m_defaultDatabasePath; ReportSettings* m_reportSettings; - QHash m_groupFunctionsExpressionsMap; + QHash m_groupFunctionsExpressionsMap; QVector m_groupFunctionsExpressions; IDbCredentialsProvider* m_dbCredentialsProvider; - QMap< QString, QVector > m_varToDataSource; + QMap> m_varToDataSource; bool m_hasChanges; }; -} +} // namespace LimeReport #endif // LRDATASOURCEMANAGER_H - diff --git a/limereport/lrdatasourcemanagerintf.h b/limereport/lrdatasourcemanagerintf.h index 0ff4a55..056555b 100644 --- a/limereport/lrdatasourcemanagerintf.h +++ b/limereport/lrdatasourcemanagerintf.h @@ -31,34 +31,36 @@ #define LRDATASOURCEMANAGERINTF_H #include "lrcallbackdatasourceintf.h" -#include "lrglobal.h" #include "lrdatasourceintf.h" +#include "lrglobal.h" class QVariant; class QString; class QAbstractItemModel; -namespace LimeReport{ +namespace LimeReport { -class IDbCredentialsProvider{ +class IDbCredentialsProvider { public: - virtual ~IDbCredentialsProvider(){} + virtual ~IDbCredentialsProvider() { } virtual QString getUserName(const QString& connectionName) = 0; virtual QString getPassword(const QString& connectionName) = 0; }; -class IDataSourceManager{ +class IDataSourceManager { public: - virtual ~IDataSourceManager(){} + virtual ~IDataSourceManager() { } virtual void setReportVariable(const QString& name, const QVariant& value) = 0; - virtual void setDefaultDatabasePath(const QString &defaultDatabasePath) = 0; + virtual void setDefaultDatabasePath(const QString& defaultDatabasePath) = 0; virtual void deleteVariable(const QString& name) = 0; virtual bool containsVariable(const QString& variableName) = 0; virtual QVariant variable(const QString& variableName) = 0; - virtual bool addModel(const QString& name, QAbstractItemModel *model, bool owned) = 0; - virtual void addCSV(const QString& name, const QString& csvText, const QString& separator, bool firstRowIsHeader) = 0; + virtual bool addModel(const QString& name, QAbstractItemModel* model, bool owned) = 0; + virtual void addCSV(const QString& name, const QString& csvText, const QString& separator, + bool firstRowIsHeader) + = 0; virtual void removeModel(const QString& name) = 0; virtual bool containsDatasource(const QString& dataSourceName) = 0; - virtual void clearUserVariables()=0; + virtual void clearUserVariables() = 0; virtual ICallbackDatasource* createCallbackDatasource(const QString& name) = 0; virtual void registerDbCredentialsProvider(IDbCredentialsProvider* provider) = 0; virtual QStringList variableNames() = 0; @@ -69,6 +71,5 @@ public: virtual IDataSourceHolder* dataSourceHolder(const QString& name) = 0; }; -} +} // namespace LimeReport #endif // LRDATASOURCEMANAGERINTF_H - diff --git a/limereport/lrdesignelementsfactory.h b/limereport/lrdesignelementsfactory.h index e28cfac..527aeb7 100644 --- a/limereport/lrdesignelementsfactory.h +++ b/limereport/lrdesignelementsfactory.h @@ -30,35 +30,37 @@ #ifndef LRDESIGNELEMENTSFACTORY_H #define LRDESIGNELEMENTSFACTORY_H -#include "lrbanddesignintf.h" #include "lrattribsabstractfactory.h" +#include "lrbanddesignintf.h" #include "lrsimpleabstractfactory.h" #include "lrsingleton.h" -namespace LimeReport{ +namespace LimeReport { -typedef BaseDesignIntf* (*CreateBand)(QObject* owner, BaseDesignIntf* parent); +typedef BaseDesignIntf* (*CreateBand)(QObject* owner, BaseDesignIntf* parent); -struct ItemAttribs{ +struct ItemAttribs { QString m_alias; QString m_tag; - ItemAttribs(){} - ItemAttribs(const QString& alias, const QString& tag):m_alias(alias),m_tag(tag){} - bool operator==( const ItemAttribs &right) const { - return (m_alias==right.m_alias) && (m_tag==right.m_tag); + ItemAttribs() { } + ItemAttribs(const QString& alias, const QString& tag): m_alias(alias), m_tag(tag) { } + bool operator==(const ItemAttribs& right) const + { + return (m_alias == right.m_alias) && (m_tag == right.m_tag); } }; -class DesignElementsFactory : public AttribsAbstractFactory -{ +class DesignElementsFactory: + public AttribsAbstractFactory { private: friend class Singleton; + private: - DesignElementsFactory(){} - ~DesignElementsFactory(){} - DesignElementsFactory(const DesignElementsFactory&){} - DesignElementsFactory& operator = (const DesignElementsFactory&){return *this;} + DesignElementsFactory() { } + ~DesignElementsFactory() { } + DesignElementsFactory(const DesignElementsFactory&) { } + DesignElementsFactory& operator=(const DesignElementsFactory&) { return *this; } }; -} +} // namespace LimeReport #endif // LRDESIGNELEMENTSFACTORY_H diff --git a/limereport/lrdesignerplugininterface.h b/limereport/lrdesignerplugininterface.h index f9cab7e..695682a 100644 --- a/limereport/lrdesignerplugininterface.h +++ b/limereport/lrdesignerplugininterface.h @@ -1,11 +1,11 @@ #ifndef LRDESIGNERPLUGININTERFACE_H #define LRDESIGNERPLUGININTERFACE_H +#include "lrreportdesignwindowintrerface.h" + #include #include - #include -#include "lrreportdesignwindowintrerface.h" QT_BEGIN_NAMESPACE class QSettings; @@ -13,16 +13,20 @@ class QMainWindow; QT_END_NAMESPACE namespace LimeReport { - class ReportDesignWindow; - class ReportEnginePrivateInterface; -} +class ReportDesignWindow; +class ReportEnginePrivateInterface; +} // namespace LimeReport class LimeReportDesignerPluginInterface { public: virtual ~LimeReportDesignerPluginInterface() { } - virtual LimeReport::ReportDesignWindowInterface* getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, QWidget *parent = 0, QSettings* settings=0) = 0; + virtual LimeReport::ReportDesignWindowInterface* + getDesignerWindow(LimeReport::ReportEnginePrivateInterface* report, QWidget* parent = 0, + QSettings* settings = 0) + = 0; }; -Q_DECLARE_INTERFACE( LimeReportDesignerPluginInterface, "ru.limereport.LimeReport.DesignerPluginInterface/1.0" ) +Q_DECLARE_INTERFACE(LimeReportDesignerPluginInterface, + "ru.limereport.LimeReport.DesignerPluginInterface/1.0") #endif // LRDESIGNERPLUGININTERFACE_H diff --git a/limereport/lrexporterintf.h b/limereport/lrexporterintf.h index bbeb043..cce6236 100644 --- a/limereport/lrexporterintf.h +++ b/limereport/lrexporterintf.h @@ -1,17 +1,20 @@ #ifndef LREXPORTERINTF_H #define LREXPORTERINTF_H -#include -#include -#include #include "lrpageitemdesignintf.h" +#include +#include +#include + namespace LimeReport { class ReportExporterInterface { public: - virtual ~ReportExporterInterface(){} - virtual bool exportPages(LimeReport::ReportPages pages, const QString& fileName, const QMap& params = QMap()) = 0; + virtual ~ReportExporterInterface() { } + virtual bool exportPages(LimeReport::ReportPages pages, const QString& fileName, + const QMap& params = QMap()) + = 0; virtual QString exporterName() = 0; virtual QString exporterFileExt() = 0; virtual QString hint() = 0; diff --git a/limereport/lrexportersfactory.h b/limereport/lrexportersfactory.h index bbb5e56..0156722 100644 --- a/limereport/lrexportersfactory.h +++ b/limereport/lrexportersfactory.h @@ -4,29 +4,32 @@ #include "lrattribsabstractfactory.h" #include "lrexporterintf.h" -namespace LimeReport{ +namespace LimeReport { typedef ReportExporterInterface* (*CreateExporter)(ReportEnginePrivate* parent); -struct ExporterAttribs{ +struct ExporterAttribs { QString m_alias; QString m_tag; - ExporterAttribs(){} - ExporterAttribs(const QString& alias, const QString& tag):m_alias(alias),m_tag(tag){} - bool operator==( const ExporterAttribs &right) const { - return (m_alias==right.m_alias) && (m_tag==right.m_tag); + ExporterAttribs() { } + ExporterAttribs(const QString& alias, const QString& tag): m_alias(alias), m_tag(tag) { } + bool operator==(const ExporterAttribs& right) const + { + return (m_alias == right.m_alias) && (m_tag == right.m_tag); } }; -class ExportersFactory : public AttribsAbstractFactory -{ +class ExportersFactory: + public AttribsAbstractFactory { private: friend class Singleton; + private: - ExportersFactory(){} - ~ExportersFactory(){} - ExportersFactory(const ExportersFactory&){} - ExportersFactory& operator = (const ExportersFactory&){return *this;} + ExportersFactory() { } + ~ExportersFactory() { } + ExportersFactory(const ExportersFactory&) { } + ExportersFactory& operator=(const ExportersFactory&) { return *this; } }; } // namespace LimeReport diff --git a/limereport/lrfactoryinitializer.cpp b/limereport/lrfactoryinitializer.cpp index 2a7225e..cae5eee 100644 --- a/limereport/lrfactoryinitializer.cpp +++ b/limereport/lrfactoryinitializer.cpp @@ -2,28 +2,27 @@ #include "bands/lrgroupbands.h" #include "bands/lrpagefooter.h" #include "bands/lrpageheader.h" -#include "bands/lrreportheader.h" #include "bands/lrreportfooter.h" +#include "bands/lrreportheader.h" #include "bands/lrsubdetailband.h" #include "bands/lrtearoffband.h" - - #include "items/lrtextitem.h" #ifdef HAVE_ZINT #include "items/lrbarcodeitem.h" #endif +#include "items/lrchartitem.h" #include "items/lrhorizontallayout.h" #include "items/lrimageitem.h" #include "items/lrshapeitem.h" -#include "items/lrchartitem.h" #include "lrdesignelementsfactory.h" #ifdef HAVE_SVG #include "items/lrsvgitem.h" #include "objectinspector/propertyItems/lrsvgpropitem.h" #endif - #ifdef HAVE_REPORT_DESIGNER +#include "items/lralignpropitem.h" +#include "items/lrsubitemparentpropitem.h" #include "objectinspector/lrobjectpropitem.h" #include "objectinspector/propertyItems/lrboolpropitem.h" #include "objectinspector/propertyItems/lrcolorpropitem.h" @@ -38,19 +37,17 @@ #include "objectinspector/propertyItems/lrqrealpropitem.h" #include "objectinspector/propertyItems/lrrectproptem.h" #include "objectinspector/propertyItems/lrstringpropitem.h" -#include "items/lralignpropitem.h" -#include "items/lrsubitemparentpropitem.h" #endif +#include "exporters/lrpdfexporter.h" +#include "lrexporterintf.h" +#include "lrexportersfactory.h" #include "serializators/lrxmlbasetypesserializators.h" #include "serializators/lrxmlqrectserializator.h" #include "serializators/lrxmlserializatorsfactory.h" -#include "lrexportersfactory.h" -#include "lrexporterintf.h" -#include "exporters/lrpdfexporter.h" - -void initResources(){ +void initResources() +{ Q_INIT_RESOURCE(report); #ifdef HAVE_REPORT_DESIGNER Q_INIT_RESOURCE(lobjectinspector); @@ -62,417 +59,472 @@ void initResources(){ #endif } -namespace LimeReport{ +namespace LimeReport { -BaseDesignIntf * createDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataBand(owner,parent); +BaseDesignIntf* createDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataBand(owner, parent); } -BaseDesignIntf * createHeaderDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataHeaderBand(owner,parent); +BaseDesignIntf* createHeaderDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataHeaderBand(owner, parent); } -BaseDesignIntf * createFooterDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::DataFooterBand(owner,parent); +BaseDesignIntf* createFooterDataBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::DataFooterBand(owner, parent); } -BaseDesignIntf* createGroupHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::GroupBandHeader(owner,parent); +BaseDesignIntf* createGroupHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::GroupBandHeader(owner, parent); } -BaseDesignIntf * createGroupFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::GroupBandFooter(owner,parent); +BaseDesignIntf* createGroupFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::GroupBandFooter(owner, parent); } -BaseDesignIntf * createPageHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::PageHeader(owner,parent); +BaseDesignIntf* createPageHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::PageHeader(owner, parent); } -BaseDesignIntf * createPageFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::PageFooter(owner,parent); +BaseDesignIntf* createPageFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::PageFooter(owner, parent); } -BaseDesignIntf * createSubDetailBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailBand(owner,parent); +BaseDesignIntf* createSubDetailBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailBand(owner, parent); } -BaseDesignIntf * createSubDetailHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailHeaderBand(owner,parent); +BaseDesignIntf* createSubDetailHeaderBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailHeaderBand(owner, parent); } -BaseDesignIntf * createSubDetailFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::SubDetailFooterBand(owner,parent); +BaseDesignIntf* createSubDetailFooterBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::SubDetailFooterBand(owner, parent); } -BaseDesignIntf * createTearOffBand(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::TearOffBand(owner,parent); +BaseDesignIntf* createTearOffBand(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::TearOffBand(owner, parent); } -BaseDesignIntf * createTextItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new LimeReport::TextItem(owner,parent); +BaseDesignIntf* createTextItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new LimeReport::TextItem(owner, parent); } #ifdef HAVE_ZINT -BaseDesignIntf * createBarcodeItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new BarcodeItem(owner,parent); +BaseDesignIntf* createBarcodeItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new BarcodeItem(owner, parent); } #endif #ifdef HAVE_SVG -BaseDesignIntf* createSVGItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new SVGItem(owner,parent); +BaseDesignIntf* createSVGItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new SVGItem(owner, parent); } #endif -BaseDesignIntf* createHLayout(QObject *owner, LimeReport::BaseDesignIntf *parent) +BaseDesignIntf* createHLayout(QObject* owner, LimeReport::BaseDesignIntf* parent) { return new HorizontalLayout(owner, parent); } -BaseDesignIntf* createImageItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new ImageItem(owner,parent); +BaseDesignIntf* createImageItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new ImageItem(owner, parent); } -BaseDesignIntf* createShapeItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new ShapeItem(owner,parent); +BaseDesignIntf* createShapeItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new ShapeItem(owner, parent); } -BaseDesignIntf* createChartItem(QObject* owner, LimeReport::BaseDesignIntf* parent){ - return new ChartItem(owner,parent); +BaseDesignIntf* createChartItem(QObject* owner, LimeReport::BaseDesignIntf* parent) +{ + return new ChartItem(owner, parent); } -void initReportItems(){ +void initReportItems() +{ initResources(); DesignElementsFactory::instance().registerCreator( - "TextItem", - LimeReport::ItemAttribs(QObject::tr("Text Item"),"TextItem"), - createTextItem - ); + "TextItem", LimeReport::ItemAttribs(QObject::tr("Text Item"), "TextItem"), createTextItem); #ifdef HAVE_ZINT DesignElementsFactory::instance().registerCreator( - "BarcodeItem", - LimeReport::ItemAttribs(QObject::tr("Barcode Item"),"Item"), - createBarcodeItem - ); + "BarcodeItem", LimeReport::ItemAttribs(QObject::tr("Barcode Item"), "Item"), + createBarcodeItem); #endif DesignElementsFactory::instance().registerCreator( - "HLayout", - LimeReport::ItemAttribs(QObject::tr("HLayout"), LimeReport::Const::bandTAG), - createHLayout - ); + "HLayout", LimeReport::ItemAttribs(QObject::tr("HLayout"), LimeReport::Const::bandTAG), + createHLayout); DesignElementsFactory::instance().registerCreator( - "ImageItem", LimeReport::ItemAttribs(QObject::tr("Image Item"),"Item"), createImageItem - ); + "ImageItem", LimeReport::ItemAttribs(QObject::tr("Image Item"), "Item"), createImageItem); #ifdef HAVE_SVG DesignElementsFactory::instance().registerCreator( - "SVGItem", - LimeReport::ItemAttribs(QObject::tr("SVG Item"),"Item"), - createSVGItem - ); + "SVGItem", LimeReport::ItemAttribs(QObject::tr("SVG Item"), "Item"), createSVGItem); #endif DesignElementsFactory::instance().registerCreator( - "ShapeItem", LimeReport::ItemAttribs(QObject::tr("Shape Item"),"Item"), createShapeItem - ); + "ShapeItem", LimeReport::ItemAttribs(QObject::tr("Shape Item"), "Item"), createShapeItem); DesignElementsFactory::instance().registerCreator( - "ChartItem", LimeReport::ItemAttribs(QObject::tr("Chart Item"),"Item"), createChartItem - ); + "ChartItem", LimeReport::ItemAttribs(QObject::tr("Chart Item"), "Item"), createChartItem); DesignElementsFactory::instance().registerCreator( - "Data", - LimeReport::ItemAttribs(QObject::tr("Data"),LimeReport::Const::bandTAG), - createDataBand - ); + "Data", LimeReport::ItemAttribs(QObject::tr("Data"), LimeReport::Const::bandTAG), + createDataBand); DesignElementsFactory::instance().registerCreator( - "DataHeader", - LimeReport::ItemAttribs(QObject::tr("DataHeader"),LimeReport::Const::bandTAG), - createHeaderDataBand - ); + "DataHeader", + LimeReport::ItemAttribs(QObject::tr("DataHeader"), LimeReport::Const::bandTAG), + createHeaderDataBand); DesignElementsFactory::instance().registerCreator( - "DataFooter", - LimeReport::ItemAttribs(QObject::tr("DataFooter"),LimeReport::Const::bandTAG), - createFooterDataBand - ); + "DataFooter", + LimeReport::ItemAttribs(QObject::tr("DataFooter"), LimeReport::Const::bandTAG), + createFooterDataBand); DesignElementsFactory::instance().registerCreator( - "GroupHeader", - LimeReport::ItemAttribs(QObject::tr("GroupHeader"),LimeReport::Const::bandTAG), - createGroupHeaderBand - ); + "GroupHeader", + LimeReport::ItemAttribs(QObject::tr("GroupHeader"), LimeReport::Const::bandTAG), + createGroupHeaderBand); DesignElementsFactory::instance().registerCreator( - "GroupFooter", - LimeReport::ItemAttribs(QObject::tr("GroupFooter"),LimeReport::Const::bandTAG), - createGroupFooterBand - ); + "GroupFooter", + LimeReport::ItemAttribs(QObject::tr("GroupFooter"), LimeReport::Const::bandTAG), + createGroupFooterBand); DesignElementsFactory::instance().registerCreator( - "PageFooter", - LimeReport::ItemAttribs(QObject::tr("Page Footer"),LimeReport::Const::bandTAG), - createPageFooterBand - ); + "PageFooter", + LimeReport::ItemAttribs(QObject::tr("Page Footer"), LimeReport::Const::bandTAG), + createPageFooterBand); DesignElementsFactory::instance().registerCreator( - "PageHeader", - LimeReport::ItemAttribs(QObject::tr("Page Header"),LimeReport::Const::bandTAG), - createPageHeaderBand - ); + "PageHeader", + LimeReport::ItemAttribs(QObject::tr("Page Header"), LimeReport::Const::bandTAG), + createPageHeaderBand); DesignElementsFactory::instance().registerCreator( - "SubDetail", - LimeReport::ItemAttribs(QObject::tr("SubDetail"),LimeReport::Const::bandTAG), - createSubDetailBand - ); + "SubDetail", LimeReport::ItemAttribs(QObject::tr("SubDetail"), LimeReport::Const::bandTAG), + createSubDetailBand); DesignElementsFactory::instance().registerCreator( - "SubDetailHeader", - LimeReport::ItemAttribs(QObject::tr("SubDetailHeader"),LimeReport::Const::bandTAG), - createSubDetailHeaderBand - ); + "SubDetailHeader", + LimeReport::ItemAttribs(QObject::tr("SubDetailHeader"), LimeReport::Const::bandTAG), + createSubDetailHeaderBand); DesignElementsFactory::instance().registerCreator( - "SubDetailFooter", - LimeReport::ItemAttribs(QObject::tr("SubDetailFooter"),LimeReport::Const::bandTAG), - createSubDetailFooterBand - ); + "SubDetailFooter", + LimeReport::ItemAttribs(QObject::tr("SubDetailFooter"), LimeReport::Const::bandTAG), + createSubDetailFooterBand); DesignElementsFactory::instance().registerCreator( - "TearOffBand", - LimeReport::ItemAttribs(QObject::tr("Tear-off Band"),LimeReport::Const::bandTAG), - createTearOffBand - ); - + "TearOffBand", + LimeReport::ItemAttribs(QObject::tr("Tear-off Band"), LimeReport::Const::bandTAG), + createTearOffBand); } #ifdef HAVE_REPORT_DESIGNER -ObjectPropItem * createBoolPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createBoolPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new LimeReport::BoolPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createColorPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createColorPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new ColorPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createContentPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createContentPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new ContentPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createDatasourcePropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createDatasourcePropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::DatasourcePropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::DatasourcePropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem* createFieldPropItem(QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly){ - return new LimeReport::FieldPropItem(object, objects, name, displayName, data, parent, readonly); +ObjectPropItem* createFieldPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) +{ + return new LimeReport::FieldPropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem * createEnumPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createEnumPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new LimeReport::EnumPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createFlagsPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createFlagsPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::FlagsPropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::FlagsPropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem * createFontPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createFontPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new LimeReport::FontPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem* createGroupFieldPropItem(QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly){ - return new LimeReport::GroupFieldPropItem(object, objects, name, displayName, data, parent, readonly); +ObjectPropItem* createGroupFieldPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) +{ + return new LimeReport::GroupFieldPropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem * createImagePropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createImagePropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::ImagePropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::ImagePropItem(object, objects, name, displayName, data, parent, + readonly); } #ifdef HAVE_SVG -ObjectPropItem * createSVGPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createSVGPropItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new LimeReport::SvgPropItem(object, objects, name, displayName, data, parent, readonly); } #endif -ObjectPropItem * createIntPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createIntPropItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { return new LimeReport::IntPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createQRealPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createQRealPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::QRealPropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::QRealPropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem * createReqtItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly -){ +ObjectPropItem* createReqtItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) +{ return new LimeReport::RectPropItem(object, objects, name, displayName, data, parent, readonly); } -ObjectPropItem * createReqtMMItem( - QObject*object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly -){ - return new LimeReport::RectUnitPropItem(object, objects, name, displayName, data, parent, readonly); -} - -ObjectPropItem * createStringPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createReqtMMItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::StringPropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::RectUnitPropItem(object, objects, name, displayName, data, parent, + readonly); } -ObjectPropItem * createAlignItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly -){ - return new LimeReport::AlignmentPropItem(object, objects, name, displayName, data, parent, readonly); -} - -ObjectPropItem * createLocationPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +ObjectPropItem* createStringPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return new LimeReport::ItemLocationPropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::StringPropItem(object, objects, name, displayName, data, parent, + readonly); +} + +ObjectPropItem* createAlignItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) +{ + return new LimeReport::AlignmentPropItem(object, objects, name, displayName, data, parent, + readonly); +} + +ObjectPropItem* createLocationPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) +{ + return new LimeReport::ItemLocationPropItem(object, objects, name, displayName, data, parent, + readonly); } void initObjectInspectorProperties() { + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("bool", ""), + QObject::tr("bool"), createBoolPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QColor", ""), + QObject::tr("QColor"), createColorPropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("bool",""),QObject::tr("bool"),createBoolPropItem - ); + LimeReport::APropIdent("content", "LimeReport::TextItem"), QObject::tr("content"), + createContentPropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QColor",""),QObject::tr("QColor"),createColorPropItem - ); + LimeReport::APropIdent("datasource", "LimeReport::DataBandDesignIntf"), + QObject::tr("datasource"), createDatasourcePropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("content","LimeReport::TextItem"),QObject::tr("content"),createContentPropItem - ); + LimeReport::APropIdent("datasource", "LimeReport::ImageItem"), QObject::tr("datasource"), + createDatasourcePropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::DataBandDesignIntf"),QObject::tr("datasource"),createDatasourcePropItem - ); + LimeReport::APropIdent("field", "LimeReport::ImageItem"), QObject::tr("field"), + createFieldPropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::ImageItem"),QObject::tr("datasource"),createDatasourcePropItem - ); + LimeReport::APropIdent("datasource", "LimeReport::SVGItem"), QObject::tr("datasource"), + createDatasourcePropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("field","LimeReport::ImageItem"),QObject::tr("field"),createFieldPropItem - ); + LimeReport::APropIdent("field", "LimeReport::SVGItem"), QObject::tr("field"), + createFieldPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("enum", ""), + QObject::tr("enum"), createEnumPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("flags", ""), + QObject::tr("flags"), createFlagsPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QFont", ""), + QObject::tr("QFont"), createFontPropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::SVGItem"),QObject::tr("datasource"),createDatasourcePropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("field","LimeReport::SVGItem"),QObject::tr("field"),createFieldPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("enum",""),QObject::tr("enum"),createEnumPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("flags",""),QObject::tr("flags"),createFlagsPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QFont",""),QObject::tr("QFont"),createFontPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("groupFieldName","LimeReport::GroupBandHeader"),QObject::tr("field"),createGroupFieldPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QImage",""),QObject::tr("QImage"),createImagePropItem - ); + LimeReport::APropIdent("groupFieldName", "LimeReport::GroupBandHeader"), + QObject::tr("field"), createGroupFieldPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QImage", ""), + QObject::tr("QImage"), createImagePropItem); #ifdef HAVE_SVG ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("image","LimeReport::SVGItem"),QObject::tr("image"),createSVGPropItem - ); + LimeReport::APropIdent("image", "LimeReport::SVGItem"), QObject::tr("image"), + createSVGPropItem); #endif + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("int", ""), + QObject::tr("int"), createIntPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("qreal", ""), + QObject::tr("qreal"), createQRealPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("double", ""), + QObject::tr("qreal"), createQRealPropItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QRect", ""), + QObject::tr("QRect"), createReqtItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QRectF", ""), + QObject::tr("QRectF"), createReqtItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("int",""),QObject::tr("int"),createIntPropItem - ); + LimeReport::APropIdent("geometry", "LimeReport::BaseDesignIntf"), QObject::tr("geometry"), + createReqtMMItem); + ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QString", ""), + QObject::tr("QString"), createStringPropItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("qreal",""),QObject::tr("qreal"),createQRealPropItem - ); + LimeReport::APropIdent("alignment", "LimeReport::TextItem"), QObject::tr("alignment"), + createAlignItem); ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("double",""),QObject::tr("qreal"),createQRealPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QRect",""),QObject::tr("QRect"),createReqtItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QRectF",""),QObject::tr("QRectF"),createReqtItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("geometry","LimeReport::BaseDesignIntf"),QObject::tr("geometry"),createReqtMMItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("QString",""),QObject::tr("QString"),createStringPropItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("alignment","LimeReport::TextItem"),QObject::tr("alignment"),createAlignItem - ); - ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("itemLocation","LimeReport::ItemDesignIntf"),QObject::tr("itemLocation"),createLocationPropItem - ); - + LimeReport::APropIdent("itemLocation", "LimeReport::ItemDesignIntf"), + QObject::tr("itemLocation"), createLocationPropItem); } #endif -SerializatorIntf * createIntSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlIntSerializator(doc,node); +SerializatorIntf* createIntSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlIntSerializator(doc, node); } -SerializatorIntf * createQRealSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQRealSerializator(doc,node); +SerializatorIntf* createQRealSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQRealSerializator(doc, node); } -SerializatorIntf * createQStringSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQStringSerializator(doc,node); +SerializatorIntf* createQStringSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQStringSerializator(doc, node); } -SerializatorIntf * createEnumAndFlagsSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlEnumAndFlagsSerializator(doc,node); +SerializatorIntf* createEnumAndFlagsSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlEnumAndFlagsSerializator(doc, node); } -SerializatorIntf * createBoolSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlBoolSerializator(doc,node); +SerializatorIntf* createBoolSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlBoolSerializator(doc, node); } -SerializatorIntf * createFontSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlFontSerializator(doc,node); +SerializatorIntf* createFontSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlFontSerializator(doc, node); } -SerializatorIntf * createQSizeFSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQSizeFSerializator(doc,node); +SerializatorIntf* createQSizeFSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQSizeFSerializator(doc, node); } -SerializatorIntf * createQImageSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQImageSerializator(doc,node); +SerializatorIntf* createQImageSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQImageSerializator(doc, node); } -SerializatorIntf * createQColorSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlColorSerializator(doc,node); +SerializatorIntf* createQColorSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlColorSerializator(doc, node); } -SerializatorIntf* createQByteArraySerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQByteArraySerializator(doc,node); +SerializatorIntf* createQByteArraySerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQByteArraySerializator(doc, node); } -SerializatorIntf* createQVariantSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQVariantSerializator(doc,node); +SerializatorIntf* createQVariantSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQVariantSerializator(doc, node); } -SerializatorIntf * createQRectSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XMLQRectSerializator(doc,node); +SerializatorIntf* createQRectSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XMLQRectSerializator(doc, node); } void initSerializators() { - XMLAbstractSerializatorFactory::instance().registerCreator("QString", createQStringSerializator); + XMLAbstractSerializatorFactory::instance().registerCreator("QString", + createQStringSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("int", createIntSerializator); - XMLAbstractSerializatorFactory::instance().registerCreator("enumAndFlags",createEnumAndFlagsSerializator); + XMLAbstractSerializatorFactory::instance().registerCreator("enumAndFlags", + createEnumAndFlagsSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("bool", createBoolSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("QFont", createFontSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("QSizeF", createQSizeFSerializator); @@ -480,23 +532,24 @@ void initSerializators() XMLAbstractSerializatorFactory::instance().registerCreator("qreal", createQRealSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("double", createQRealSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("QColor", createQColorSerializator); - XMLAbstractSerializatorFactory::instance().registerCreator("QByteArray", createQByteArraySerializator); - XMLAbstractSerializatorFactory::instance().registerCreator("QVariant", createQVariantSerializator); + XMLAbstractSerializatorFactory::instance().registerCreator("QByteArray", + createQByteArraySerializator); + XMLAbstractSerializatorFactory::instance().registerCreator("QVariant", + createQVariantSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("QRect", createQRectSerializator); XMLAbstractSerializatorFactory::instance().registerCreator("QRectF", createQRectSerializator); } -LimeReport::ReportExporterInterface* createPDFExporter(ReportEnginePrivate* parent){ +LimeReport::ReportExporterInterface* createPDFExporter(ReportEnginePrivate* parent) +{ return new LimeReport::PDFExporter(parent); } void initExporters() { ExportersFactory::instance().registerCreator( - "PDF", - LimeReport::ExporterAttribs(QObject::tr("Export to PDF"), "PDFExporter"), - createPDFExporter - ); + "PDF", LimeReport::ExporterAttribs(QObject::tr("Export to PDF"), "PDFExporter"), + createPDFExporter); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrfactoryinitializer.h b/limereport/lrfactoryinitializer.h index 8810e55..8b8e31c 100644 --- a/limereport/lrfactoryinitializer.h +++ b/limereport/lrfactoryinitializer.h @@ -1,7 +1,7 @@ void initResources(); -namespace LimeReport{ - void initReportItems(); - void initObjectInspectorProperties(); - void initSerializators(); - void initExporters(); +namespace LimeReport { +void initReportItems(); +void initObjectInspectorProperties(); +void initSerializators(); +void initExporters(); } // namespace LimeReport diff --git a/limereport/lrglobal.cpp b/limereport/lrglobal.cpp index b90f6bb..c2ea0ab 100644 --- a/limereport/lrglobal.cpp +++ b/limereport/lrglobal.cpp @@ -27,18 +27,21 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include #include "lrglobal.h" +#include +#include + namespace LimeReport { QString extractClassName(QString className) { - int startPos=className.lastIndexOf("::"); - if(startPos==-1) startPos=0; - else startPos+=2; - return className.right(className.length()-startPos); + int startPos = className.lastIndexOf("::"); + if (startPos == -1) + startPos = 0; + else + startPos += 2; + return className.right(className.length() - startPos); } bool ReportSettings::suppressAbsentFieldsAndVarsWarnings() const @@ -46,41 +49,41 @@ bool ReportSettings::suppressAbsentFieldsAndVarsWarnings() const return m_suppressAbsentFieldsAndVarsWarnings; } -void ReportSettings::setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings) +void ReportSettings::setSuppressAbsentFieldsAndVarsWarnings( + bool suppressAbsentFieldsAndVarsWarnings) { m_suppressAbsentFieldsAndVarsWarnings = suppressAbsentFieldsAndVarsWarnings; } -int ReportSettings::baseItemPadding() const -{ - return m_baseItemPadding; -} +int ReportSettings::baseItemPadding() const { return m_baseItemPadding; } void ReportSettings::setBaseItemPadding(int newBaseTextItemPadding) { m_baseItemPadding = newBaseTextItemPadding; } -QString escapeSimbols(const QString &value) +QString escapeSimbols(const QString& value) { QString result = value; - result.replace("\"","\\\""); - result.replace('\n',"\\n"); + result.replace("\"", "\\\""); + result.replace('\n', "\\n"); return result; } -QString replaceHTMLSymbols(const QString &value) +QString replaceHTMLSymbols(const QString& value) { QString result = value; - result.replace("<","<"); - result.replace(">",">"); + result.replace("<", "<"); + result.replace(">", ">"); return result; } #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) -QVector normalizeCaptures(const QRegularExpressionMatch& reg){ +QVector normalizeCaptures(const QRegularExpressionMatch& reg) +{ #else -QVector normalizeCaptures(const QRegExp& reg){ +QVector normalizeCaptures(const QRegExp& reg) +{ #endif QVector result; foreach (QString cap, reg.capturedTexts()) { @@ -90,66 +93,60 @@ QVector normalizeCaptures(const QRegExp& reg){ return result; } -bool isColorDark(QColor color){ - qreal darkness = 1-(0.299*color.red() + 0.587*color.green() + 0.114*color.blue())/255; - if(darkness<0.5){ +bool isColorDark(QColor color) +{ + qreal darkness = 1 - (0.299 * color.red() + 0.587 * color.green() + 0.114 * color.blue()) / 255; + if (darkness < 0.5) { return false; } else { return true; } } -ReportError::ReportError(const QString& message):std::runtime_error(message.toStdString()){} -IExternalPainter::~IExternalPainter(){} -IPainterProxy::~IPainterProxy(){} - +ReportError::ReportError(const QString& message): std::runtime_error(message.toStdString()) { } +IExternalPainter::~IExternalPainter() { } +IPainterProxy::~IPainterProxy() { } #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) -QRegularExpression getRegEx(QString expression){ +QRegularExpression getRegEx(QString expression) +{ return QRegularExpression(expression, QRegularExpression::DotMatchesEverythingOption); } -QRegularExpression getVariableRegEx(){ - return QRegularExpression( - Const::VARIABLE_RX, - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::CaseInsensitiveOption - ); +QRegularExpression getVariableRegEx() +{ + return QRegularExpression(Const::VARIABLE_RX, + QRegularExpression::DotMatchesEverythingOption + | QRegularExpression::CaseInsensitiveOption); } -QRegularExpression getFieldRegEx(){ - return QRegularExpression( - Const::FIELD_RX, - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::CaseInsensitiveOption - ); +QRegularExpression getFieldRegEx() +{ + return QRegularExpression(Const::FIELD_RX, + QRegularExpression::DotMatchesEverythingOption + | QRegularExpression::CaseInsensitiveOption); } -QRegularExpression getScriptRegEx(){ - return QRegularExpression( - Const::SCRIPT_RX, - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::CaseInsensitiveOption - ); +QRegularExpression getScriptRegEx() +{ + return QRegularExpression(Const::SCRIPT_RX, + QRegularExpression::DotMatchesEverythingOption + | QRegularExpression::CaseInsensitiveOption); } -QRegularExpression getGroupFunctionRegEx(QString functionName){ - return QRegularExpression( - QString(Const::GROUP_FUNCTION_RX).arg(functionName), - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::InvertedGreedinessOption - ); +QRegularExpression getGroupFunctionRegEx(QString functionName) +{ + return QRegularExpression(QString(Const::GROUP_FUNCTION_RX).arg(functionName), + QRegularExpression::DotMatchesEverythingOption + | QRegularExpression::InvertedGreedinessOption); } -QRegularExpression getGroupFunctionNameRegEx(QString functionName){ - return QRegularExpression( - QString(Const::GROUP_FUNCTION_NAME_RX).arg(functionName), - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::InvertedGreedinessOption - ); +QRegularExpression getGroupFunctionNameRegEx(QString functionName) +{ + return QRegularExpression(QString(Const::GROUP_FUNCTION_NAME_RX).arg(functionName), + QRegularExpression::DotMatchesEverythingOption + | QRegularExpression::InvertedGreedinessOption); } -QRegularExpression getNamedVariableRegEx(QString variableName){ - return QRegularExpression( - QString(Const::NAMED_VARIABLE_RX).arg(variableName), - QRegularExpression::DotMatchesEverythingOption - ); +QRegularExpression getNamedVariableRegEx(QString variableName) +{ + return QRegularExpression(QString(Const::NAMED_VARIABLE_RX).arg(variableName), + QRegularExpression::DotMatchesEverythingOption); } #endif - -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrglobal.h b/limereport/lrglobal.h index ed8b86a..c7ef2a2 100644 --- a/limereport/lrglobal.h +++ b/limereport/lrglobal.h @@ -30,23 +30,25 @@ #ifndef LRGLOBAL_H #define LRGLOBAL_H #include "qglobal.h" -#include + #include #include #include +#include + #if defined(LIMEREPORT_EXPORTS) -# define LIMEREPORT_EXPORT Q_DECL_EXPORT -#elif defined (LIMEREPORT_IMPORTS) -# define LIMEREPORT_EXPORT Q_DECL_IMPORT +#define LIMEREPORT_EXPORT Q_DECL_EXPORT +#elif defined(LIMEREPORT_IMPORTS) +#define LIMEREPORT_EXPORT Q_DECL_IMPORT #else -# define LIMEREPORT_EXPORT /**/ +#define LIMEREPORT_EXPORT /**/ #endif namespace LimeReport { #ifdef __GNUC__ -#define VARIABLE_IS_NOT_USED __attribute__ ((unused)) +#define VARIABLE_IS_NOT_USED __attribute__((unused)) #else #define VARIABLE_IS_NOT_USED #endif @@ -55,12 +57,12 @@ namespace LimeReport { Q_NAMESPACE #endif -namespace Const{ +namespace Const { int const DEFAULT_GRID_STEP = 1; int const RESIZE_HANDLE_SIZE = 5; int const SELECTION_PEN_SIZE = 1; - int const MINIMUM_ITEM_WIDTH = 2*RESIZE_HANDLE_SIZE; - int const MINIMUM_ITEM_HEIGHT = 2*RESIZE_HANDLE_SIZE; + int const MINIMUM_ITEM_WIDTH = 2 * RESIZE_HANDLE_SIZE; + int const MINIMUM_ITEM_HEIGHT = 2 * RESIZE_HANDLE_SIZE; double const RESIZE_ZONE_OPACITY = 0.5; double const SELECTED_RESIZE_ZONE_OPACITY = 0.6; Qt::GlobalColor const RESIZE_ZONE_COLOR = Qt::green; @@ -80,15 +82,21 @@ namespace Const{ const qreal BAND_NAME_TEXT_OPACITY = 0.6; const qreal SELECTION_OPACITY = 0.3; const QString FIELD_RX = "\\$D\\s*\\{\\s*([^{}]*)\\s*\\}"; - const QString VARIABLE_RX = "\\$V\\s*\\{\\s*(?:([^\\{\\},]*)|(?:([^\\{\\}]*)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; - const QString NAMED_VARIABLE_RX = "\\$V\\s*\\{\\s*(?:(%1)|(?:(%1)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; - const QString SCRIPT_RX = "\\$S\\s*\\{(.*)\\}"; - const QString GROUP_FUNCTION_PARAM_RX = "\\(\\s*((?:(?:\\\")|(?:))(?:(?:\\$(?:(?:D\\{\\s*\\w*..*\\})|(?:V\\{\\s*\\w*\\s*\\})|(?:S\\{.+\\})))|(?:\\w*))(?:(?:\\\")|(?:)))(?:(?:\\s*,\\s*(?:\\\"(\\w*)\\\"))|(?:))(?:(?:\\s*,\\s*(?:(\\w*)))|(?:))\\)"; + const QString VARIABLE_RX = "\\$V\\s*\\{\\s*(?:([^\\{\\},]*)|(?:([^\\{\\}]*)\\s*,\\s*([^\\{" + "\\}]*)))\\s*\\}"; + const QString NAMED_VARIABLE_RX + = "\\$V\\s*\\{\\s*(?:(%1)|(?:(%1)\\s*,\\s*([^\\{\\}]*)))\\s*\\}"; + const QString SCRIPT_RX = "\\$S\\s*\\{(.*)\\}"; + const QString GROUP_FUNCTION_PARAM_RX + = "\\(\\s*((?:(?:\\\")|(?:))(?:(?:\\$(?:(?:D\\{\\s*\\w*..*\\})|" + "(?:V\\{\\s*\\w*\\s*\\})|(?:S\\{.+\\})))|(?:\\w*))(?:(?:\\\")" + "|(?:)))(?:(?:\\s*,\\s*(?:\\\"(\\w*)\\\"))|(?:))(?:(?:\\s*," + "\\s*(?:(\\w*)))|(?:))\\)"; const int DATASOURCE_INDEX = 3; const int VALUE_INDEX = 2; const int EXPRESSION_ARGUMENT_INDEX = 1; - const QString GROUP_FUNCTION_RX = "(%1\\s*"+GROUP_FUNCTION_PARAM_RX+")"; + const QString GROUP_FUNCTION_RX = "(%1\\s*" + GROUP_FUNCTION_PARAM_RX + ")"; const QString GROUP_FUNCTION_NAME_RX = "%1\\s*\\((.*[^\\)])\\)"; const int SCENE_MARGIN = 50; const QString FUNCTION_MANAGER_NAME = "LimeReport"; @@ -100,104 +108,135 @@ namespace Const{ const char SCRIPT_SIGN = 'S'; const char FIELD_SIGN = 'D'; const char VARIABLE_SIGN = 'V'; -} - QString extractClassName(QString className); - QString escapeSimbols(const QString& value); - QString replaceHTMLSymbols(const QString &value); +} // namespace Const +QString extractClassName(QString className); +QString escapeSimbols(const QString& value); +QString replaceHTMLSymbols(const QString& value); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - QVector normalizeCaptures(const QRegularExpressionMatch ®); +QVector normalizeCaptures(const QRegularExpressionMatch& reg); #else - QVector normalizeCaptures(const QRegExp ®); +QVector normalizeCaptures(const QRegExp& reg); #endif - bool isColorDark(QColor color); +bool isColorDark(QColor color); - enum ExpandType {EscapeSymbols, NoEscapeSymbols, ReplaceHTMLSymbols}; - enum RenderPass {FirstPass = 1, SecondPass = 2}; - enum ArrangeType {AsNeeded, Force}; - enum ScaleType {FitWidth, FitPage, OneToOne, Percents}; - enum PreviewHint{ShowAllPreviewBars = 0, - HidePreviewToolBar = 1, - HidePreviewMenuBar = 2, - HidePreviewStatusBar = 4, - HideAllPreviewBar = 7, - PreviewBarsUserSetting = 8}; +enum ExpandType { + EscapeSymbols, + NoEscapeSymbols, + ReplaceHTMLSymbols +}; +enum RenderPass { + FirstPass = 1, + SecondPass = 2 +}; +enum ArrangeType { + AsNeeded, + Force +}; +enum ScaleType { + FitWidth, + FitPage, + OneToOne, + Percents +}; +enum PreviewHint { + ShowAllPreviewBars = 0, + HidePreviewToolBar = 1, + HidePreviewMenuBar = 2, + HidePreviewStatusBar = 4, + HideAllPreviewBar = 7, + PreviewBarsUserSetting = 8 +}; - Q_DECLARE_FLAGS(PreviewHints, PreviewHint) - Q_FLAGS(PreviewHints) +Q_DECLARE_FLAGS(PreviewHints, PreviewHint) +Q_FLAGS(PreviewHints) - class LIMEREPORT_EXPORT ReportError : public std::runtime_error{ - public: - ReportError(const QString& message); - }; +class LIMEREPORT_EXPORT ReportError: public std::runtime_error { +public: + ReportError(const QString& message); +}; - class LIMEREPORT_EXPORT ReportSettings{ - public: +class LIMEREPORT_EXPORT ReportSettings { +public: #ifdef DEFAULT_ITEM_PADDING - ReportSettings():m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(DEFAULT_ITEM_PADDING){} + ReportSettings(): + m_suppressAbsentFieldsAndVarsWarnings(false), + m_baseItemPadding(DEFAULT_ITEM_PADDING) + { + } #else - ReportSettings():m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(0){} + ReportSettings(): m_suppressAbsentFieldsAndVarsWarnings(false), m_baseItemPadding(0) { } #endif - void setDefaultValues(){ - m_suppressAbsentFieldsAndVarsWarnings = false; + void setDefaultValues() + { + m_suppressAbsentFieldsAndVarsWarnings = false; #ifdef DEFAULT_ITEM_PADDING - m_baseItemPadding = DEFAULT_ITEM_PADDING; + m_baseItemPadding = DEFAULT_ITEM_PADDING; #else - m_baseItemPadding = 0; + m_baseItemPadding = 0; #endif + } + bool suppressAbsentFieldsAndVarsWarnings() const; + void setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings); + int baseItemPadding() const; + void setBaseItemPadding(int newBaseTextItemPadding); - } - bool suppressAbsentFieldsAndVarsWarnings() const; - void setSuppressAbsentFieldsAndVarsWarnings(bool suppressAbsentFieldsAndVarsWarnings); - int baseItemPadding() const; - void setBaseItemPadding(int newBaseTextItemPadding); - private: - bool m_suppressAbsentFieldsAndVarsWarnings; - int m_baseItemPadding; - }; +private: + bool m_suppressAbsentFieldsAndVarsWarnings; + int m_baseItemPadding; +}; - class LIMEREPORT_EXPORT IExternalPainter{ - public: - virtual void paintByExternalPainter(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem* options) = 0; - virtual ~IExternalPainter(); - }; +class LIMEREPORT_EXPORT IExternalPainter { +public: + virtual void paintByExternalPainter(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem* options) + = 0; + virtual ~IExternalPainter(); +}; - class LIMEREPORT_EXPORT IPainterProxy{ - public: - virtual void setExternalPainter(IExternalPainter* externalPainter) = 0; - virtual ~IPainterProxy(); - }; +class LIMEREPORT_EXPORT IPainterProxy { +public: + virtual void setExternalPainter(IExternalPainter* externalPainter) = 0; + virtual ~IPainterProxy(); +}; #if QT_VERSION < 0x050000 - typedef QStyleOptionViewItemV4 StyleOptionViewItem; +typedef QStyleOptionViewItemV4 StyleOptionViewItem; #else - typedef QStyleOptionViewItem StyleOptionViewItem; +typedef QStyleOptionViewItem StyleOptionViewItem; #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - QRegularExpression getRegEx(QString expression); - QRegularExpression getVariableRegEx(); - QRegularExpression getFieldRegEx(); - QRegularExpression getScriptRegEx(); - QRegularExpression getGroupFunctionRegEx(QString functionName); - QRegularExpression getGroupFunctionNameRegEx(QString functionName); - QRegularExpression getNamedVariableRegEx(QString variableName); +QRegularExpression getRegEx(QString expression); +QRegularExpression getVariableRegEx(); +QRegularExpression getFieldRegEx(); +QRegularExpression getScriptRegEx(); +QRegularExpression getGroupFunctionRegEx(QString functionName); +QRegularExpression getGroupFunctionNameRegEx(QString functionName); +QRegularExpression getNamedVariableRegEx(QString variableName); #endif - - class LIMEREPORT_EXPORT Enums - { - public: - enum VariableDataType {Undefined, String, Bool, Int, Real, Date, Time, DateTime}; -#if QT_VERSION >= 0x050500 - Q_ENUM(VariableDataType) -#else - Q_ENUMS(VariableDataType) -#endif - private: - Enums(){} - Q_GADGET +class LIMEREPORT_EXPORT Enums { +public: + enum VariableDataType { + Undefined, + String, + Bool, + Int, + Real, + Date, + Time, + DateTime }; +#if QT_VERSION >= 0x050500 + Q_ENUM(VariableDataType) +#else + Q_ENUMS(VariableDataType) +#endif +private: + Enums() { } + Q_GADGET +}; - typedef Enums::VariableDataType VariableDataType; +typedef Enums::VariableDataType VariableDataType; } // namespace LimeReport diff --git a/limereport/lrgraphicsviewzoom.cpp b/limereport/lrgraphicsviewzoom.cpp index 54fac03..bc5ab37 100644 --- a/limereport/lrgraphicsviewzoom.cpp +++ b/limereport/lrgraphicsviewzoom.cpp @@ -1,40 +1,37 @@ #include "lrgraphicsviewzoom.h" -#include + #include +#include #include -namespace LimeReport{ +namespace LimeReport { -GraphicsViewZoomer::GraphicsViewZoomer(QGraphicsView* view) - : QObject(view), m_view(view) +GraphicsViewZoomer::GraphicsViewZoomer(QGraphicsView* view): QObject(view), m_view(view) { - m_view->viewport()->installEventFilter(this); - m_view->setMouseTracking(true); - m_modifiers = Qt::ControlModifier; - m_zoomFactorBase = 1.0009; + m_view->viewport()->installEventFilter(this); + m_view->setMouseTracking(true); + m_modifiers = Qt::ControlModifier; + m_zoomFactorBase = 1.0009; } -void GraphicsViewZoomer::gentleZoom(double factor) { - m_view->scale(factor, factor); - m_view->centerOn(m_targetScenePos); - QPointF delta_viewport_pos = m_targetViewportPos - QPointF(m_view->viewport()->width() / 2.0, - m_view->viewport()->height() / 2.0); - QPointF viewport_center = m_view->mapFromScene(m_targetScenePos) - delta_viewport_pos; - m_view->centerOn(m_view->mapToScene(viewport_center.toPoint())); - emit zoomed(factor); -} - -void GraphicsViewZoomer::setModifiers(Qt::KeyboardModifiers modifiers) { - m_modifiers = modifiers; -} - -void GraphicsViewZoomer::setZoomFactorBase(double value) { - m_zoomFactorBase = value; -} - -void GraphicsViewZoomer::setView(QGraphicsView *view) +void GraphicsViewZoomer::gentleZoom(double factor) { - if (m_view!=view){ + m_view->scale(factor, factor); + m_view->centerOn(m_targetScenePos); + QPointF delta_viewport_pos = m_targetViewportPos + - QPointF(m_view->viewport()->width() / 2.0, m_view->viewport()->height() / 2.0); + QPointF viewport_center = m_view->mapFromScene(m_targetScenePos) - delta_viewport_pos; + m_view->centerOn(m_view->mapToScene(viewport_center.toPoint())); + emit zoomed(factor); +} + +void GraphicsViewZoomer::setModifiers(Qt::KeyboardModifiers modifiers) { m_modifiers = modifiers; } + +void GraphicsViewZoomer::setZoomFactorBase(double value) { m_zoomFactorBase = value; } + +void GraphicsViewZoomer::setView(QGraphicsView* view) +{ + if (m_view != view) { m_view->viewport()->removeEventFilter(this); m_view = view; m_view->viewport()->installEventFilter(this); @@ -42,36 +39,37 @@ void GraphicsViewZoomer::setView(QGraphicsView *view) } } -bool GraphicsViewZoomer::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::MouseMove) { - QMouseEvent* mouse_event = static_cast(event); - QPointF delta = m_targetViewportPos - mouse_event->pos(); - if (qAbs(delta.x()) > 5 || qAbs(delta.y()) > 5) { - m_targetViewportPos = mouse_event->pos(); - m_targetScenePos = m_view->mapToScene(mouse_event->pos()); - } - } else if (event->type() == QEvent::Wheel) { - QWheelEvent* wheel_event = static_cast(event); - if (QApplication::keyboardModifiers() == m_modifiers) { +bool GraphicsViewZoomer::eventFilter(QObject* object, QEvent* event) +{ + if (event->type() == QEvent::MouseMove) { + QMouseEvent* mouse_event = static_cast(event); + QPointF delta = m_targetViewportPos - mouse_event->pos(); + if (qAbs(delta.x()) > 5 || qAbs(delta.y()) > 5) { + m_targetViewportPos = mouse_event->pos(); + m_targetScenePos = m_view->mapToScene(mouse_event->pos()); + } + } else if (event->type() == QEvent::Wheel) { + QWheelEvent* wheel_event = static_cast(event); + if (QApplication::keyboardModifiers() == m_modifiers) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (wheel_event->orientation() == Qt::Vertical) { - double angle = wheel_event->delta(); - double factor = qPow(m_zoomFactorBase, angle); - gentleZoom(factor); - return true; - } + if (wheel_event->orientation() == Qt::Vertical) { + double angle = wheel_event->delta(); + double factor = qPow(m_zoomFactorBase, angle); + gentleZoom(factor); + return true; + } #else - if (wheel_event->angleDelta().y() != 0) { - double angle = wheel_event->angleDelta().y(); - double factor = qPow(m_zoomFactorBase, angle); - gentleZoom(factor); - return true; - } + if (wheel_event->angleDelta().y() != 0) { + double angle = wheel_event->angleDelta().y(); + double factor = qPow(m_zoomFactorBase, angle); + gentleZoom(factor); + return true; + } #endif + } } - } - Q_UNUSED(object) - return false; + Q_UNUSED(object) + return false; } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrgraphicsviewzoom.h b/limereport/lrgraphicsviewzoom.h index 7c7f014..5c212cc 100644 --- a/limereport/lrgraphicsviewzoom.h +++ b/limereport/lrgraphicsviewzoom.h @@ -1,27 +1,28 @@ #ifndef LRGRAPHICSVIEWZOOM_H #define LRGRAPHICSVIEWZOOM_H -#include #include +#include namespace LimeReport { -class GraphicsViewZoomer : public QObject { - Q_OBJECT +class GraphicsViewZoomer: public QObject { + Q_OBJECT public: - GraphicsViewZoomer(QGraphicsView* view); - void gentleZoom(double factor); - void setModifiers(Qt::KeyboardModifiers modifiers); - void setZoomFactorBase(double value); - void setView(QGraphicsView* view); + GraphicsViewZoomer(QGraphicsView* view); + void gentleZoom(double factor); + void setModifiers(Qt::KeyboardModifiers modifiers); + void setZoomFactorBase(double value); + void setView(QGraphicsView* view); + private: - QGraphicsView* m_view; - Qt::KeyboardModifiers m_modifiers; - double m_zoomFactorBase; - QPointF m_targetScenePos, m_targetViewportPos; - bool eventFilter(QObject* object, QEvent* event); + QGraphicsView* m_view; + Qt::KeyboardModifiers m_modifiers; + double m_zoomFactorBase; + QPointF m_targetScenePos, m_targetViewportPos; + bool eventFilter(QObject* object, QEvent* event); signals: - void zoomed(double factor); + void zoomed(double factor); }; } // namespace LimeReport diff --git a/limereport/lrgroupfunctions.cpp b/limereport/lrgroupfunctions.cpp index f893d12..206f839 100644 --- a/limereport/lrgroupfunctions.cpp +++ b/limereport/lrgroupfunctions.cpp @@ -28,11 +28,12 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrgroupfunctions.h" -#include "lrdatasourcemanager.h" + #include "lrbanddesignintf.h" +#include "lrdatasourcemanager.h" #include "lritemdesignintf.h" -#include "lrscriptenginemanager.h" #include "lrpageitemdesignintf.h" +#include "lrscriptenginemanager.h" #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include @@ -40,7 +41,7 @@ namespace LimeReport { -void GroupFunction::slotBandRendered(BandDesignIntf *band) +void GroupFunction::slotBandRendered(BandDesignIntf* band) { ScriptEngineManager& sm = ScriptEngineManager::instance(); @@ -52,17 +53,17 @@ void GroupFunction::slotBandRendered(BandDesignIntf *band) QRegularExpression rxVar = getVariableRegEx(); #endif - switch (m_dataType){ - case Field:{ + switch (m_dataType) { + case Field: { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (rxField.indexIn(m_data) != -1){ + if (rxField.indexIn(m_data) != -1) { QString field = rxField.cap(1); #else QRegularExpressionMatch matchField = rxField.match(m_data); - if(matchField.hasMatch()){ + if (matchField.hasMatch()) { QString field = matchField.captured(1); #endif - if (m_dataManager->containsField(field)){ + if (m_dataManager->containsField(field)) { m_values.push_back(m_dataManager->fieldData(field)); m_valuesByBand.insert(band, m_dataManager->fieldData(field)); } else { @@ -71,16 +72,16 @@ void GroupFunction::slotBandRendered(BandDesignIntf *band) } break; } - case Variable:{ + case Variable: { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (rxVar.indexIn(m_data) != -1){ + if (rxVar.indexIn(m_data) != -1) { QString var = rxVar.cap(1); #else QRegularExpressionMatch matchVar = rxVar.match(m_data); - if(matchVar.hasMatch()){ + if (matchVar.hasMatch()) { QString var = matchVar.captured(1); #endif - if (m_dataManager->containsVariable(var)){ + if (m_dataManager->containsVariable(var)) { m_values.push_back(m_dataManager->variable(var)); m_valuesByBand.insert(band, m_dataManager->variable(var)); } else { @@ -89,10 +90,9 @@ void GroupFunction::slotBandRendered(BandDesignIntf *band) } break; } - case Script: - { + case Script: { QVariant value = sm.evaluateScript(m_data); - if (value.isValid()){ + if (value.isValid()) { m_values.push_back(value); m_valuesByBand.insert(band, value); } else { @@ -100,16 +100,18 @@ void GroupFunction::slotBandRendered(BandDesignIntf *band) } break; } - case ContentItem:{ + case ContentItem: { QString itemName = m_data; - ContentItemDesignIntf* item = dynamic_cast(band->childByName(itemName.remove('"'))); - if (item){ + ContentItemDesignIntf* item + = dynamic_cast(band->childByName(itemName.remove('"'))); + if (item) { m_values.push_back(item->content()); m_valuesByBand.insert(band, item->content()); - } else if (m_name.compare("COUNT",Qt::CaseInsensitive) == 0) { + } else if (m_name.compare("COUNT", Qt::CaseInsensitive) == 0) { m_values.push_back(1); m_valuesByBand.insert(band, 1); - } else setInvalid(tr("Item \"%1\" not found").arg(m_data)); + } else + setInvalid(tr("Item \"%1\" not found").arg(m_data)); break; } @@ -118,9 +120,9 @@ void GroupFunction::slotBandRendered(BandDesignIntf *band) } } -void GroupFunction::slotBandReRendered(BandDesignIntf *oldBand, BandDesignIntf *newBand) +void GroupFunction::slotBandReRendered(BandDesignIntf* oldBand, BandDesignIntf* newBand) { - if (m_valuesByBand.contains(oldBand)){ + if (m_valuesByBand.contains(oldBand)) { m_valuesByBand.insert(newBand, m_valuesByBand.value(oldBand)); m_valuesByBand.remove(oldBand); } @@ -128,12 +130,12 @@ void GroupFunction::slotBandReRendered(BandDesignIntf *oldBand, BandDesignIntf * QVariant GroupFunction::addition(QVariant value1, QVariant value2) { - return value1.toDouble()+value2.toDouble(); + return value1.toDouble() + value2.toDouble(); } QVariant GroupFunction::subtraction(QVariant value1, QVariant value2) { - return value1.toDouble()-value2.toDouble(); + return value1.toDouble() - value2.toDouble(); } QVariant GroupFunction::division(QVariant value1, QVariant value2) @@ -146,43 +148,48 @@ QVariant GroupFunction::multiplication(QVariant value1, QVariant value2) return value1.toDouble() * value2.toDouble(); } -GroupFunction::GroupFunction(const QString &expression, const QString &dataBandName, DataSourceManager* dataManager) - :m_data(expression), m_dataBandName(dataBandName), m_dataManager(dataManager), m_isValid(true), m_errorMessage("") +GroupFunction::GroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + m_data(expression), + m_dataBandName(dataBandName), + m_dataManager(dataManager), + m_isValid(true), + m_errorMessage("") { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - QRegExp rxField(Const::FIELD_RX,Qt::CaseInsensitive); - QRegExp rxVariable(Const::VARIABLE_RX,Qt::CaseInsensitive); - QRegExp rxScript(Const::SCRIPT_RX,Qt::CaseInsensitive); + QRegExp rxField(Const::FIELD_RX, Qt::CaseInsensitive); + QRegExp rxVariable(Const::VARIABLE_RX, Qt::CaseInsensitive); + QRegExp rxScript(Const::SCRIPT_RX, Qt::CaseInsensitive); #else QRegularExpression rxField = getFieldRegEx(); QRegularExpression rxVariable = getVariableRegEx(); QRegularExpression rxScript = getScriptRegEx(); #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (rxScript.indexIn(expression) != -1){ + if (rxScript.indexIn(expression) != -1) { #else QRegularExpressionMatch matchScript = rxScript.match(expression); - if(matchScript.hasMatch()){ + if (matchScript.hasMatch()) { #endif m_dataType = Script; return; } #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (rxField.indexIn(expression) != -1){ + if (rxField.indexIn(expression) != -1) { #else QRegularExpressionMatch matchField = rxField.match(expression); - if(matchField.hasMatch()){ + if (matchField.hasMatch()) { #endif - m_dataType=Field; + m_dataType = Field; return; } #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (rxVariable.indexIn(expression) != -1){ + if (rxVariable.indexIn(expression) != -1) { #else QRegularExpressionMatch matchVariable = rxVariable.match(expression); - if(matchVariable.hasMatch()){ + if (matchVariable.hasMatch()) { #endif m_dataType = Variable; return; @@ -191,28 +198,32 @@ GroupFunction::GroupFunction(const QString &expression, const QString &dataBandN m_dataType = ContentItem; } -GroupFunction *GroupFunctionFactory::createGroupFunction(const QString &functionName, const QString &expression, const QString& dataBandName, DataSourceManager *dataManager) +GroupFunction* GroupFunctionFactory::createGroupFunction(const QString& functionName, + const QString& expression, + const QString& dataBandName, + DataSourceManager* dataManager) { - if (m_creators.contains(functionName)){ - return m_creators.value(functionName)->createFunction(expression, dataBandName, dataManager); + if (m_creators.contains(functionName)) { + return m_creators.value(functionName) + ->createFunction(expression, dataBandName, dataManager); } return 0; } GroupFunctionFactory::~GroupFunctionFactory() { - foreach(GroupFunctionCreator* creator, m_creators.values()){ + foreach (GroupFunctionCreator* creator, m_creators.values()) { delete creator; } m_creators.clear(); } -QVariant SumGroupFunction::calculate(PageItemDesignIntf *page) +QVariant SumGroupFunction::calculate(PageItemDesignIntf* page) { QVariant res = 0; - if (!page){ - foreach(QVariant value,values()){ - res = addition(res,value); + if (!page) { + foreach (QVariant value, values()) { + res = addition(res, value); } } else { foreach (BandDesignIntf* band, page->bands()) { @@ -222,70 +233,79 @@ QVariant SumGroupFunction::calculate(PageItemDesignIntf *page) return res; } -QVariant AvgGroupFunction::calculate(PageItemDesignIntf *page) +QVariant AvgGroupFunction::calculate(PageItemDesignIntf* page) { QVariant res = QVariant(); - if (!page){ - foreach(QVariant value,values()){ - res=addition(res,value); + if (!page) { + foreach (QVariant value, values()) { + res = addition(res, value); } } else { foreach (BandDesignIntf* band, page->bands()) { res = addition(res, m_valuesByBand.value(band)); } } - if (!res.isNull()&&(values().count()>0)){ - res=division(res,values().count()); + if (!res.isNull() && (values().count() > 0)) { + res = division(res, values().count()); } return res; } -QVariant MinGroupFunction::calculate(PageItemDesignIntf *page) +QVariant MinGroupFunction::calculate(PageItemDesignIntf* page) { - //TODO: check variant type + // TODO: check variant type QVariant res = QVariant(); - if (!page){ - if (!values().empty()) res = values().at(0); - foreach(QVariant value, values()){ - if (res.toDouble() > value.toDouble()) res = value; + if (!page) { + if (!values().empty()) + res = values().at(0); + foreach (QVariant value, values()) { + if (res.toDouble() > value.toDouble()) + res = value; } } else { - if (!page->bands().empty()) res = m_valuesByBand.value(page->bands().at(0)); + if (!page->bands().empty()) + res = m_valuesByBand.value(page->bands().at(0)); foreach (BandDesignIntf* band, page->bands()) { - if (res.toDouble() > m_valuesByBand.value(band).toDouble()) res = m_valuesByBand.value(band); + if (res.toDouble() > m_valuesByBand.value(band).toDouble()) + res = m_valuesByBand.value(band); } } return res; } -QVariant MaxGroupFunction::calculate(PageItemDesignIntf *page) +QVariant MaxGroupFunction::calculate(PageItemDesignIntf* page) { - //TODO: check variant type + // TODO: check variant type QVariant res = QVariant(); - if (!page){ - if (!values().empty()) res = values().at(0); - foreach(QVariant value, values()){ - if (res.toDouble() < value.toDouble()) res = value; + if (!page) { + if (!values().empty()) + res = values().at(0); + foreach (QVariant value, values()) { + if (res.toDouble() < value.toDouble()) + res = value; } } else { - if (!page->bands().empty()) res = m_valuesByBand.value(page->bands().at(0)); + if (!page->bands().empty()) + res = m_valuesByBand.value(page->bands().at(0)); foreach (BandDesignIntf* band, page->bands()) { - if (res.toDouble() < m_valuesByBand.value(band).toDouble()) res = m_valuesByBand.value(band); + if (res.toDouble() < m_valuesByBand.value(band).toDouble()) + res = m_valuesByBand.value(band); } } return res; } -QVariant CountGroupFunction::calculate(PageItemDesignIntf *page){ - if (!page){ +QVariant CountGroupFunction::calculate(PageItemDesignIntf* page) +{ + if (!page) { return values().count(); } else { int res = 0; foreach (BandDesignIntf* band, page->bands()) { - if (!m_valuesByBand.value(band).isNull()){ + if (!m_valuesByBand.value(band).isNull()) { res++; } } @@ -293,5 +313,4 @@ QVariant CountGroupFunction::calculate(PageItemDesignIntf *page){ } } -} //namespace LimeReport - +} // namespace LimeReport diff --git a/limereport/lrgroupfunctions.h b/limereport/lrgroupfunctions.h index ed2ffec..f4c58c6 100644 --- a/limereport/lrgroupfunctions.h +++ b/limereport/lrgroupfunctions.h @@ -34,35 +34,43 @@ #include #include -namespace LimeReport{ +namespace LimeReport { class DataSourceManager; class BandDesignIntf; class PageItemDesignIntf; -class GroupFunction : public QObject{ +class GroupFunction: public QObject { Q_OBJECT public: - enum DataType{Variable, Field, Script, ContentItem}; - GroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager); - bool isValid(){return m_isValid;} - void setInvalid(QString message){m_isValid=false,m_errorMessage=message;} - const QString& name(){return m_name;} - const QString& data(){return m_data;} - const QString& error(){return m_errorMessage;} - QVector& values(){return m_values;} + enum DataType { + Variable, + Field, + Script, + ContentItem + }; + GroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager); + bool isValid() { return m_isValid; } + void setInvalid(QString message) { m_isValid = false, m_errorMessage = message; } + const QString& name() { return m_name; } + const QString& data() { return m_data; } + const QString& error() { return m_errorMessage; } + QVector& values() { return m_values; } QHash m_valuesByBand; - const QString& dataBandName(){return m_dataBandName;} - virtual QVariant calculate(PageItemDesignIntf* page = 0)=0; + const QString& dataBandName() { return m_dataBandName; } + virtual QVariant calculate(PageItemDesignIntf* page = 0) = 0; public slots: void slotBandRendered(BandDesignIntf* band); void slotBandReRendered(BandDesignIntf* oldBand, BandDesignIntf* newBand); + protected: - void setName(const QString& value){m_name=value;} + void setName(const QString& value) { m_name = value; } QVariant addition(QVariant value1, QVariant value2); QVariant subtraction(QVariant value1, QVariant value2); QVariant division(QVariant value1, QVariant value2); QVariant multiplication(QVariant value1, QVariant value2); + private: QString m_data; QString m_name; @@ -74,80 +82,110 @@ private: QString m_errorMessage; }; -class GroupFunctionCreator{ +class GroupFunctionCreator { public: - virtual GroupFunction* createFunction(const QString&, const QString&, DataSourceManager*)=0; - virtual ~GroupFunctionCreator(){} + virtual GroupFunction* createFunction(const QString&, const QString&, DataSourceManager*) = 0; + virtual ~GroupFunctionCreator() { } }; -class GroupFunctionFactory{ +class GroupFunctionFactory { public: - void registerFunctionCreator(const QString& functionName,GroupFunctionCreator* creator){ - m_creators.insert(functionName,creator); + void registerFunctionCreator(const QString& functionName, GroupFunctionCreator* creator) + { + m_creators.insert(functionName, creator); } - QList functionNames(){return m_creators.keys();} - GroupFunction* createGroupFunction(const QString& functionName, const QString& expression, const QString& dataBandName, DataSourceManager* dataManager); + QList functionNames() { return m_creators.keys(); } + GroupFunction* createGroupFunction(const QString& functionName, const QString& expression, + const QString& dataBandName, DataSourceManager* dataManager); ~GroupFunctionFactory(); + private: - QMap m_creators; + QMap m_creators; }; -class CountGroupFunction :public GroupFunction{ +class CountGroupFunction: public GroupFunction { Q_OBJECT public: - CountGroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager) - :GroupFunction(expression, dataBandName, dataManager){setName("COUNT");} + CountGroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + GroupFunction(expression, dataBandName, dataManager) + { + setName("COUNT"); + } + protected: virtual QVariant calculate(PageItemDesignIntf* page = 0); }; -class SumGroupFunction :public GroupFunction{ +class SumGroupFunction: public GroupFunction { Q_OBJECT public: - SumGroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager) - :GroupFunction(expression, dataBandName, dataManager){setName("SUM");} + SumGroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + GroupFunction(expression, dataBandName, dataManager) + { + setName("SUM"); + } + protected: virtual QVariant calculate(PageItemDesignIntf* page = 0); }; -class AvgGroupFunction :public GroupFunction{ +class AvgGroupFunction: public GroupFunction { Q_OBJECT public: - AvgGroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager) - :GroupFunction(expression, dataBandName, dataManager){setName("AVG");} + AvgGroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + GroupFunction(expression, dataBandName, dataManager) + { + setName("AVG"); + } + protected: virtual QVariant calculate(PageItemDesignIntf* page = 0); }; -class MinGroupFunction :public GroupFunction{ +class MinGroupFunction: public GroupFunction { Q_OBJECT public: - MinGroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager) - :GroupFunction(expression, dataBandName, dataManager){setName("MIN");} + MinGroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + GroupFunction(expression, dataBandName, dataManager) + { + setName("MIN"); + } + protected: virtual QVariant calculate(PageItemDesignIntf* page = 0); }; -class MaxGroupFunction :public GroupFunction{ +class MaxGroupFunction: public GroupFunction { Q_OBJECT public: - MaxGroupFunction(const QString& expression, const QString& dataBandName, DataSourceManager *dataManager) - :GroupFunction(expression, dataBandName, dataManager){setName("MAX");} + MaxGroupFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager): + GroupFunction(expression, dataBandName, dataManager) + { + setName("MAX"); + } + protected: virtual QVariant calculate(PageItemDesignIntf* page = 0); }; +template class ConstructorGroupFunctionCreator: public GroupFunctionCreator { + virtual GroupFunction* createFunction(const QString& expression, const QString& dataBandName, + DataSourceManager* dataManager); +}; + template -class ConstructorGroupFunctionCreator : public GroupFunctionCreator{ - virtual GroupFunction* createFunction(const QString& expression, const QString &dataBandName, DataSourceManager* dataManager); -}; - -template< typename T > -GroupFunction* ConstructorGroupFunctionCreator< T >::createFunction(const QString &expression, const QString &dataBandName, DataSourceManager *dataManager) +GroupFunction* ConstructorGroupFunctionCreator::createFunction(const QString& expression, + const QString& dataBandName, + DataSourceManager* dataManager) { return new T(expression, dataBandName, dataManager); } -} //namespace LimeReport +} // namespace LimeReport #endif // LRGROUPFUNCTIONS_H diff --git a/limereport/lritemdesignintf.cpp b/limereport/lritemdesignintf.cpp index b3f41a6..c1e0c5d 100644 --- a/limereport/lritemdesignintf.cpp +++ b/limereport/lritemdesignintf.cpp @@ -28,11 +28,12 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lritemdesignintf.h" + #include "lrbasedesignintf.h" -#include "lrpagedesignintf.h" #include "lrdatasourcemanager.h" -#include "lrscriptenginemanager.h" #include "lrglobal.h" +#include "lrpagedesignintf.h" +#include "lrscriptenginemanager.h" #include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) @@ -40,36 +41,39 @@ #endif #include -namespace LimeReport{ +namespace LimeReport { -ItemDesignIntf::ItemDesignIntf(const QString &xmlTypeName, QObject* owner, QGraphicsItem* parent) : - BaseDesignIntf(xmlTypeName,owner,parent), m_itemLocation(Band), m_stretchToMaxHeight(false){ +ItemDesignIntf::ItemDesignIntf(const QString& xmlTypeName, QObject* owner, QGraphicsItem* parent): + BaseDesignIntf(xmlTypeName, owner, parent), + m_itemLocation(Band), + m_stretchToMaxHeight(false) +{ initFlags(); } void ItemDesignIntf::setItemLocation(LocationType location) { - if (m_itemLocation!=location){ + if (m_itemLocation != location) { LocationType oldValue = m_itemLocation; - m_itemLocation=location; - if(!isLoading()){ - if (location==Band){ - QGraphicsItem *parentBand=bandByPos(); - if (parentBand){ - QPointF parentPos = parentBand->mapFromItem(parentItem(),x(),y()); + m_itemLocation = location; + if (!isLoading()) { + if (location == Band) { + QGraphicsItem* parentBand = bandByPos(); + if (parentBand) { + QPointF parentPos = parentBand->mapFromItem(parentItem(), x(), y()); setParentItem(parentBand); setParent(dynamic_cast(parentBand)); setPos(parentPos); emit itemLocationChanged(this, dynamic_cast(parentBand)); } else { - m_itemLocation=Page; + m_itemLocation = Page; } } else { - if (scene()){ + if (scene()) { PageItemDesignIntf* page = dynamic_cast(scene())->pageItem(); - if (page){ - QPointF parentPos = page->mapFromItem(parentItem(),x(),y()); + if (page) { + QPointF parentPos = page->mapFromItem(parentItem(), x(), y()); setParentItem(page); setParent(page); setPos(parentPos); @@ -77,32 +81,32 @@ void ItemDesignIntf::setItemLocation(LocationType location) } } } - notify("locationType",oldValue,location); + notify("locationType", oldValue, location); } } } void ItemDesignIntf::setStretchToMaxHeight(bool value) { - if (m_stretchToMaxHeight!=value){ + if (m_stretchToMaxHeight != value) { bool oldValue = m_stretchToMaxHeight; - m_stretchToMaxHeight=value; - notify("stretchToMaxHeight",oldValue,value); + m_stretchToMaxHeight = value; + notify("stretchToMaxHeight", oldValue, value); } } -BaseDesignIntf *ItemDesignIntf::cloneEmpty(int height, QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* ItemDesignIntf::cloneEmpty(int height, QObject* owner, QGraphicsItem* parent) { - BaseDesignIntf* spacer = new Spacer(owner,parent); + BaseDesignIntf* spacer = new Spacer(owner, parent); spacer->initFromItem(this); spacer->setHeight(height); return spacer; } -QGraphicsItem * ItemDesignIntf::bandByPos() +QGraphicsItem* ItemDesignIntf::bandByPos() { - foreach(QGraphicsItem *item, scene()->items()){ - if (dynamic_cast(item) && item->collidesWithItem(this)){ + foreach (QGraphicsItem* item, scene()->items()) { + if (dynamic_cast(item) && item->collidesWithItem(this)) { return item; } } @@ -112,30 +116,27 @@ QGraphicsItem * ItemDesignIntf::bandByPos() void ItemDesignIntf::initFlags() { BaseDesignIntf::initFlags(); - if ((itemMode()&DesignMode) || (itemMode()&EditMode)){ + if ((itemMode() & DesignMode) || (itemMode() & EditMode)) { setFlag(QGraphicsItem::ItemIsMovable); } else { - setFlag(QGraphicsItem::ItemIsMovable,false); + setFlag(QGraphicsItem::ItemIsMovable, false); } } -Spacer::Spacer(QObject *owner, QGraphicsItem *parent) - :ItemDesignIntf("Spacer",owner,parent){} +Spacer::Spacer(QObject* owner, QGraphicsItem* parent): ItemDesignIntf("Spacer", owner, parent) { } -QMap ContentItemDesignIntf::getStringForTranslation(){ - QMapmap; - map.insert("content",content()); +QMap ContentItemDesignIntf::getStringForTranslation() +{ + QMap map; + map.insert("content", content()); return map; } -bool ContentItemDesignIntf::isContentBackedUp() const -{ - return m_contentBackedUp; -} +bool ContentItemDesignIntf::isContentBackedUp() const { return m_contentBackedUp; } void ContentItemDesignIntf::setContentBackedUp(bool contentBackedUp) { m_contentBackedUp = contentBackedUp; } -}// namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lritemdesignintf.h b/limereport/lritemdesignintf.h index 55ebe5a..9a5bddf 100644 --- a/limereport/lritemdesignintf.h +++ b/limereport/lritemdesignintf.h @@ -30,78 +30,95 @@ #ifndef LRITEMDESIGNITTF_H #define LRITEMDESIGNITTF_H -#include #include "lrbasedesignintf.h" -namespace LimeReport{ +#include + +namespace LimeReport { class BaseDesignIntf; -class ItemDesignIntf : public BaseDesignIntf -{ +class ItemDesignIntf: public BaseDesignIntf { Q_OBJECT Q_PROPERTY(LocationType itemLocation READ itemLocation WRITE setItemLocation) Q_PROPERTY(bool stretchToMaxHeight READ stretchToMaxHeight WRITE setStretchToMaxHeight) Q_PROPERTY(ItemAlign itemAlign READ itemAlign WRITE setItemAlign) public: - enum LocationType{Band,Page}; + enum LocationType { + Band, + Page + }; #if QT_VERSION >= 0x050500 Q_ENUM(LocationType) #else Q_ENUMS(LocationType) #endif - ItemDesignIntf(const QString& xmlTypeName, QObject* owner = 0,QGraphicsItem* parent = 0); - LocationType itemLocation(){return m_itemLocation;} + ItemDesignIntf(const QString& xmlTypeName, QObject* owner = 0, QGraphicsItem* parent = 0); + LocationType itemLocation() { return m_itemLocation; } void setItemLocation(LocationType location); void setStretchToMaxHeight(bool value); - bool stretchToMaxHeight(){return m_stretchToMaxHeight;} - BaseDesignIntf* cloneEmpty(int height, QObject *owner, QGraphicsItem *parent); + bool stretchToMaxHeight() { return m_stretchToMaxHeight; } + BaseDesignIntf* cloneEmpty(int height, QObject* owner, QGraphicsItem* parent); signals: void itemLocationChanged(BaseDesignIntf* item, BaseDesignIntf* parent); + protected: QGraphicsItem* bandByPos(); virtual void initFlags(); + private: LocationType m_itemLocation; bool m_stretchToMaxHeight; }; -class Spacer :public ItemDesignIntf{ +class Spacer: public ItemDesignIntf { public: - Spacer(QObject* owner,QGraphicsItem* parent); - bool isEmpty() const {return true;} + Spacer(QObject* owner, QGraphicsItem* parent); + bool isEmpty() const { return true; } + protected: - BaseDesignIntf* createSameTypeItem(QObject *owner, QGraphicsItem *parent){ + BaseDesignIntf* createSameTypeItem(QObject* owner, QGraphicsItem* parent) + { return new Spacer(owner, parent); } }; -class ContentItemDesignIntf : public ItemDesignIntf -{ +class ContentItemDesignIntf: public ItemDesignIntf { Q_OBJECT public: - ContentItemDesignIntf(const QString& xmlTypeName, QObject* owner = 0,QGraphicsItem* parent = 0) - :ItemDesignIntf(xmlTypeName,owner,parent), m_contentBackedUp(false){} + ContentItemDesignIntf(const QString& xmlTypeName, QObject* owner = 0, + QGraphicsItem* parent = 0): + ItemDesignIntf(xmlTypeName, owner, parent), + m_contentBackedUp(false) + { + } virtual QString content() const = 0; virtual void setContent(const QString& value) = 0; QMap getStringForTranslation(); - void backupContent(){ m_contentBackUp = content(); m_contentBackedUp = true;} - void restoreContent() {setContent(m_contentBackUp);} + void backupContent() + { + m_contentBackUp = content(); + m_contentBackedUp = true; + } + void restoreContent() { setContent(m_contentBackUp); } bool isContentBackedUp() const; void setContentBackedUp(bool contentBackedUp); + private: QString m_contentBackUp; bool m_contentBackedUp; }; -class LayoutDesignIntf : public ItemDesignIntf{ +class LayoutDesignIntf: public ItemDesignIntf { public: - LayoutDesignIntf(const QString& xmlTypeName, QObject* owner = 0,QGraphicsItem* parent = 0): - ItemDesignIntf(xmlTypeName,owner,parent){} - virtual void addChild(BaseDesignIntf *item,bool updateSize=true) = 0; - virtual void removeChild(BaseDesignIntf *item) = 0; - virtual void restoreChild(BaseDesignIntf *item) = 0; + LayoutDesignIntf(const QString& xmlTypeName, QObject* owner = 0, QGraphicsItem* parent = 0): + ItemDesignIntf(xmlTypeName, owner, parent) + { + } + virtual void addChild(BaseDesignIntf* item, bool updateSize = true) = 0; + virtual void removeChild(BaseDesignIntf* item) = 0; + virtual void restoreChild(BaseDesignIntf* item) = 0; virtual int childrenCount() = 0; friend class BaseDesignIntf; }; -} +} // namespace LimeReport #endif // LRITEMDESIGNITTF_H diff --git a/limereport/lritemscontainerdesignitf.cpp b/limereport/lritemscontainerdesignitf.cpp index 365e7e3..206ce8a 100644 --- a/limereport/lritemscontainerdesignitf.cpp +++ b/limereport/lritemscontainerdesignitf.cpp @@ -1,6 +1,7 @@ #include "lritemscontainerdesignitf.h" -#include "lritemdesignintf.h" + #include "lrbanddesignintf.h" +#include "lritemdesignintf.h" namespace LimeReport { @@ -11,84 +12,95 @@ bool Segment::intersect(Segment value) qreal Segment::intersectValue(Segment value) { - if (!intersect(value)) return 0; - if ((value.m_end >= m_begin) && (value.m_end <= m_end)){ - return value.m_end-m_begin; + if (!intersect(value)) + return 0; + if ((value.m_end >= m_begin) && (value.m_end <= m_end)) { + return value.m_end - m_begin; } - if ((value.m_begin>=m_begin)&&(value.m_end>=m_end)){ - return m_end-value.m_begin; + if ((value.m_begin >= m_begin) && (value.m_end >= m_end)) { + return m_end - value.m_begin; } - if ((value.m_begin>=m_begin)&&(value.m_end<=m_end)){ - return value.m_end-value.m_begin; + if ((value.m_begin >= m_begin) && (value.m_end <= m_end)) { + return value.m_end - value.m_begin; } - if ((value.m_beginm_end)){ - return m_end-m_begin; + if ((value.m_begin < m_begin) && (value.m_end > m_end)) { + return m_end - m_begin; } return 0; } bool itemSortContainerLessThen(const PItemSortContainer c1, const PItemSortContainer c2) { - VSegment vS1(c1->m_rect),vS2(c2->m_rect); - HSegment hS1(c1->m_rect),hS2(c2->m_rect); - if (vS1.intersectValue(vS2)>hS1.intersectValue(hS2)) - return c1->m_rect.x()m_rect.x(); - else return c1->m_rect.y()m_rect.y(); + VSegment vS1(c1->m_rect), vS2(c2->m_rect); + HSegment hS1(c1->m_rect), hS2(c2->m_rect); + if (vS1.intersectValue(vS2) > hS1.intersectValue(hS2)) + return c1->m_rect.x() < c2->m_rect.x(); + else + return c1->m_rect.y() < c2->m_rect.y(); } void ItemsContainerDesignInft::snapshotItemsLayout(SnapshotType type) { m_containerItems.clear(); - foreach(BaseDesignIntf *childItem, childBaseItems()){ - if (type == IgnoreBands){ + foreach (BaseDesignIntf* childItem, childBaseItems()) { + if (type == IgnoreBands) { if (!dynamic_cast(childItem)) m_containerItems.append(PItemSortContainer(new ItemSortContainer(childItem))); } else m_containerItems.append(PItemSortContainer(new ItemSortContainer(childItem))); } - std::sort(m_containerItems.begin(),m_containerItems.end(),itemSortContainerLessThen); + std::sort(m_containerItems.begin(), m_containerItems.end(), itemSortContainerLessThen); } -void ItemsContainerDesignInft::arrangeSubItems(RenderPass pass, DataSourceManager *dataManager, ArrangeType type) +void ItemsContainerDesignInft::arrangeSubItems(RenderPass pass, DataSourceManager* dataManager, + ArrangeType type) { - bool needArrage=(type==Force); + bool needArrage = (type == Force); foreach (PItemSortContainer item, m_containerItems) { - if (item->m_item->isNeedUpdateSize(pass)){ + if (item->m_item->isNeedUpdateSize(pass)) { item->m_item->updateItemSize(dataManager, pass); - needArrage=true; + needArrage = true; } } - if (needArrage){ - for (int i=0;im_item->collidesWithItem(m_containerItems[j]->m_item))){ - HSegment hS1(m_containerItems[j]->m_rect),hS2(m_containerItems[i]->m_rect); - VSegment vS1(m_containerItems[j]->m_rect),vS2(m_containerItems[i]->m_rect); - if (m_containerItems[i]->m_rect.bottom()m_item->geometry().bottom()){ - if (hS1.intersectValue(hS2)>vS1.intersectValue(vS2)) - m_containerItems[j]->m_item->setY(m_containerItems[i]->m_item->y()+m_containerItems[i]->m_item->height() - +m_containerItems[j]->m_rect.top()-m_containerItems[i]->m_rect.bottom()); - + if (needArrage) { + for (int i = 0; i < m_containerItems.count(); i++) { + for (int j = i; j < m_containerItems.count(); j++) { + if ((i != j) + && (m_containerItems[i]->m_item->collidesWithItem( + m_containerItems[j]->m_item))) { + HSegment hS1(m_containerItems[j]->m_rect), hS2(m_containerItems[i]->m_rect); + VSegment vS1(m_containerItems[j]->m_rect), vS2(m_containerItems[i]->m_rect); + if (m_containerItems[i]->m_rect.bottom() + < m_containerItems[i]->m_item->geometry().bottom()) { + if (hS1.intersectValue(hS2) > vS1.intersectValue(vS2)) + m_containerItems[j]->m_item->setY( + m_containerItems[i]->m_item->y() + + m_containerItems[i]->m_item->height() + + m_containerItems[j]->m_rect.top() + - m_containerItems[i]->m_rect.bottom()); } - if (m_containerItems[i]->m_rect.right()m_item->geometry().right()){ - if (vS1.intersectValue(vS2)>hS1.intersectValue(hS2)) - m_containerItems[j]->m_item->setX(m_containerItems[i]->m_item->geometry().right()+ - (m_containerItems[j]->m_rect.x()-m_containerItems[i]->m_rect.right())); + if (m_containerItems[i]->m_rect.right() + < m_containerItems[i]->m_item->geometry().right()) { + if (vS1.intersectValue(vS2) > hS1.intersectValue(hS2)) + m_containerItems[j]->m_item->setX( + m_containerItems[i]->m_item->geometry().right() + + (m_containerItems[j]->m_rect.x() + - m_containerItems[i]->m_rect.right())); } } } } } - if (needArrage||pass==FirstPass){ + if (needArrage || pass == FirstPass) { int maxBottom = findMaxBottom(); - foreach(BaseDesignIntf* item,childBaseItems()){ - ItemDesignIntf* childItem=dynamic_cast(item); - if (childItem){ + foreach (BaseDesignIntf* item, childBaseItems()) { + ItemDesignIntf* childItem = dynamic_cast(item); + if (childItem) { if (childItem->stretchToMaxHeight()) - childItem->setHeight(maxBottom-childItem->geometry().top()); + childItem->setHeight(maxBottom - childItem->geometry().top()); } } } @@ -97,33 +109,35 @@ void ItemsContainerDesignInft::arrangeSubItems(RenderPass pass, DataSourceManage qreal ItemsContainerDesignInft::findMaxBottom() const { qreal maxBottom = 0; - foreach(QGraphicsItem* item,childItems()){ - BaseDesignIntf* subItem = dynamic_cast(item); - if(subItem) - if ( subItem->isVisible() && (subItem->geometry().bottom()>maxBottom) ) - maxBottom = subItem->geometry().bottom(); + foreach (QGraphicsItem* item, childItems()) { + BaseDesignIntf* subItem = dynamic_cast(item); + if (subItem) + if (subItem->isVisible() && (subItem->geometry().bottom() > maxBottom)) + maxBottom = subItem->geometry().bottom(); } return maxBottom; } -qreal ItemsContainerDesignInft::findMinTop() const{ +qreal ItemsContainerDesignInft::findMinTop() const +{ qreal minTop = height(); - foreach(QGraphicsItem* item,childItems()){ - BaseDesignIntf* subItem = dynamic_cast(item); - if(subItem) - if ( subItem->isVisible() && (subItem->geometry().top()geometry().top(); + foreach (QGraphicsItem* item, childItems()) { + BaseDesignIntf* subItem = dynamic_cast(item); + if (subItem) + if (subItem->isVisible() && (subItem->geometry().top() < minTop)) + minTop = subItem->geometry().top(); } return minTop > 0 ? minTop : 0; } qreal ItemsContainerDesignInft::findMaxHeight() const { - qreal maxHeight=0; - foreach(QGraphicsItem* item,childItems()){ - BaseDesignIntf* subItem = dynamic_cast(item); - if(subItem) - if (subItem->geometry().height()>maxHeight) maxHeight=subItem->geometry().height(); + qreal maxHeight = 0; + foreach (QGraphicsItem* item, childItems()) { + BaseDesignIntf* subItem = dynamic_cast(item); + if (subItem) + if (subItem->geometry().height() > maxHeight) + maxHeight = subItem->geometry().height(); } return maxHeight; } diff --git a/limereport/lritemscontainerdesignitf.h b/limereport/lritemscontainerdesignitf.h index 5a87532..0bc9a00 100644 --- a/limereport/lritemscontainerdesignitf.h +++ b/limereport/lritemscontainerdesignitf.h @@ -3,55 +3,66 @@ #include "lrbasedesignintf.h" -namespace LimeReport{ +namespace LimeReport { -class LIMEREPORT_EXPORT Segment{ +class LIMEREPORT_EXPORT Segment { public: - Segment(qreal segmentStart,qreal segmentEnd):m_begin(segmentStart),m_end(segmentEnd){} + Segment(qreal segmentStart, qreal segmentEnd): m_begin(segmentStart), m_end(segmentEnd) { } bool intersect(Segment value); qreal intersectValue(Segment value); + private: qreal m_begin; qreal m_end; }; -class LIMEREPORT_EXPORT VSegment : public Segment{ +class LIMEREPORT_EXPORT VSegment: public Segment { public: - VSegment(QRectF rect):Segment(rect.top(),rect.bottom()){} + VSegment(QRectF rect): Segment(rect.top(), rect.bottom()) { } }; -struct LIMEREPORT_EXPORT HSegment :public Segment{ +struct LIMEREPORT_EXPORT HSegment: public Segment { public: - HSegment(QRectF rect):Segment(rect.left(),rect.right()){} + HSegment(QRectF rect): Segment(rect.left(), rect.right()) { } }; struct LIMEREPORT_EXPORT ItemSortContainer { QRectF m_rect; - BaseDesignIntf * m_item; - ItemSortContainer(BaseDesignIntf *item){ - m_item=item; - m_rect=item->geometry(); + BaseDesignIntf* m_item; + ItemSortContainer(BaseDesignIntf* item) + { + m_item = item; + m_rect = item->geometry(); } }; -typedef QSharedPointer< ItemSortContainer > PItemSortContainer; -bool LIMEREPORT_EXPORT itemSortContainerLessThen(const PItemSortContainer c1, const PItemSortContainer c2); +typedef QSharedPointer PItemSortContainer; +bool LIMEREPORT_EXPORT itemSortContainerLessThen(const PItemSortContainer c1, + const PItemSortContainer c2); -class LIMEREPORT_EXPORT ItemsContainerDesignInft : public BookmarkContainerDesignIntf{ +class LIMEREPORT_EXPORT ItemsContainerDesignInft: public BookmarkContainerDesignIntf { Q_OBJECT public: - ItemsContainerDesignInft(const QString& xmlTypeName, QObject* owner = 0, QGraphicsItem* parent=0): - BookmarkContainerDesignIntf(xmlTypeName, owner, parent){} - enum SnapshotType{Full, IgnoreBands}; -protected: - void snapshotItemsLayout(SnapshotType type = Full); - void arrangeSubItems(RenderPass pass, DataSourceManager *dataManager, ArrangeType type = AsNeeded); - qreal findMaxBottom() const; - qreal findMaxHeight() const; - qreal findMinTop() const; -private: - QVector m_containerItems; + ItemsContainerDesignInft(const QString& xmlTypeName, QObject* owner = 0, + QGraphicsItem* parent = 0): + BookmarkContainerDesignIntf(xmlTypeName, owner, parent) + { + } + enum SnapshotType { + Full, + IgnoreBands + }; +protected: + void snapshotItemsLayout(SnapshotType type = Full); + void arrangeSubItems(RenderPass pass, DataSourceManager* dataManager, + ArrangeType type = AsNeeded); + qreal findMaxBottom() const; + qreal findMaxHeight() const; + qreal findMinTop() const; + +private: + QVector m_containerItems; }; } // namespace LimeReport diff --git a/limereport/lrpagedesignintf.cpp b/limereport/lrpagedesignintf.cpp index bde5df2..b48ebba 100644 --- a/limereport/lrpagedesignintf.cpp +++ b/limereport/lrpagedesignintf.cpp @@ -28,52 +28,48 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrpagedesignintf.h" + #include "lrbasedesignintf.h" -#include "lrtextitem.h" #include "lrhorizontallayout.h" +#include "lrtextitem.h" #include "lrverticallayout.h" //#include "lrbarcodeitem.h" #include "lrbanddesignintf.h" #include "lrbandsmanager.h" -#include "lrreportengine_p.h" - -#include "serializators/lrstorageintf.h" -#include "serializators/lrxmlwriter.h" -#include "serializators/lrxmlreader.h" #include "lrdesignelementsfactory.h" - -#include "lrpageheader.h" -#include "lrpagefooter.h" - #include "lrglobal.h" +#include "lrpagefooter.h" +#include "lrpageheader.h" +#include "lrreportengine_p.h" +#include "serializators/lrstorageintf.h" +#include "serializators/lrxmlreader.h" +#include "serializators/lrxmlwriter.h" -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include #include +#include +#include +#include +namespace LimeReport { -namespace LimeReport -{ - -bool bandSortBandLessThen(const BandDesignIntf *c1, const BandDesignIntf *c2) +bool bandSortBandLessThen(const BandDesignIntf* c1, const BandDesignIntf* c2) { return c1->geometry().top() < c2->geometry().top(); } -PageDesignIntf::PageDesignIntf(QObject *parent): +PageDesignIntf::PageDesignIntf(QObject* parent): QGraphicsScene(parent), m_pageItem(0), m_insertMode(false), m_itemInsertRect(0), m_itemMode(DesignMode), m_cutterBorder(0), -// m_infoPosRect(0), + // m_infoPosRect(0), m_currentCommand(-1), m_changeSizeMode(false), m_changePosMode(false), @@ -96,11 +92,10 @@ PageDesignIntf::PageDesignIntf(QObject *parent): m_currentPage(0) { - m_reportEditor = dynamic_cast(parent); + m_reportEditor = dynamic_cast(parent); updatePageRect(); connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); setBackgroundBrush(QBrush(Qt::white)); - } PageDesignIntf::~PageDesignIntf() @@ -110,7 +105,7 @@ PageDesignIntf::~PageDesignIntf() m_pageItem.clear(); } foreach (PageItemDesignIntf::Ptr pageItem, m_reportPages) { - removeItem(pageItem.data()); + removeItem(pageItem.data()); } m_commandsList.clear(); } @@ -118,86 +113,88 @@ PageDesignIntf::~PageDesignIntf() void PageDesignIntf::updatePageRect() { if (m_pageItem.isNull()) { - m_pageItem = PageItemDesignIntf::create(this); + m_pageItem = PageItemDesignIntf::create(this); addItem(m_pageItem.data()); m_pageItem->setTopMargin(5); m_pageItem->setBottomMargin(5); m_pageItem->setLeftMargin(5); m_pageItem->setRightMargin(5); m_pageItem->setObjectName("ReportPage1"); - connect(m_pageItem.data(), SIGNAL(itemSelected(LimeReport::BaseDesignIntf *)), this, SIGNAL(itemSelected(LimeReport::BaseDesignIntf *))); - connect(m_pageItem.data(), SIGNAL(geometryChanged(QObject *, QRectF, QRectF)), this, SLOT(slotPageGeometryChanged(QObject *, QRectF, QRectF))); - connect(m_pageItem.data(), SIGNAL(objectLoaded(QObject *)), this, SLOT(slotPageItemLoaded(QObject *))); + connect(m_pageItem.data(), SIGNAL(itemSelected(LimeReport::BaseDesignIntf*)), this, + SIGNAL(itemSelected(LimeReport::BaseDesignIntf*))); + connect(m_pageItem.data(), SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), this, + SLOT(slotPageGeometryChanged(QObject*, QRectF, QRectF))); + connect(m_pageItem.data(), SIGNAL(objectLoaded(QObject*)), this, + SLOT(slotPageItemLoaded(QObject*))); } this->setSceneRect(-Const::SCENE_MARGIN, -Const::SCENE_MARGIN, - pageItem()->geometry().width() + Const::SCENE_MARGIN*2, - pageItem()->boundingRect().height() + Const::SCENE_MARGIN*2); + pageItem()->geometry().width() + Const::SCENE_MARGIN * 2, + pageItem()->boundingRect().height() + Const::SCENE_MARGIN * 2); emit sceneRectChanged(sceneRect()); } -void PageDesignIntf::keyPressEvent(QKeyEvent *event) +void PageDesignIntf::keyPressEvent(QKeyEvent* event) { - if (event->modifiers() == Qt::NoModifier || - (event->key() != Qt::Key_Left && - event->key() != Qt::Key_Right && - event->key() != Qt::Key_Up && - event->key() != Qt::Key_Down && - !m_changePosMode && !m_changeSizeMode ) - ) { + if (event->modifiers() == Qt::NoModifier + || (event->key() != Qt::Key_Left && event->key() != Qt::Key_Right + && event->key() != Qt::Key_Up && event->key() != Qt::Key_Down && !m_changePosMode + && !m_changeSizeMode)) { QGraphicsScene::keyPressEvent(event); return; } - if ((event->modifiers()& Qt::ControlModifier) && (!m_changeSizeMode)) { + if ((event->modifiers() & Qt::ControlModifier) && (!m_changeSizeMode)) { if (!m_changePosMode) { saveSelectedItemsPos(); m_changePosMode = true; } } - if ((event->modifiers()& Qt::ShiftModifier) && (!m_changePosMode)) { + if ((event->modifiers() & Qt::ShiftModifier) && (!m_changePosMode)) { if (!m_changeSizeMode) { saveSelectedItemsGeometry(); m_changeSizeMode = true; } } - if ((event->modifiers()& Qt::ControlModifier) && m_changePosMode && (!(event->modifiers()& Qt::ShiftModifier))) { - foreach(QGraphicsItem * item, selectedItems()) { - if (dynamic_cast(item)) { + if ((event->modifiers() & Qt::ControlModifier) && m_changePosMode + && (!(event->modifiers() & Qt::ShiftModifier))) { + foreach (QGraphicsItem* item, selectedItems()) { + if (dynamic_cast(item)) { switch (event->key()) { case Qt::Key_Right: - dynamic_cast(item)->moveRight(); + dynamic_cast(item)->moveRight(); break; case Qt::Key_Left: - dynamic_cast(item)->moveLeft(); + dynamic_cast(item)->moveLeft(); break; case Qt::Key_Up: - dynamic_cast(item)->moveUp(); + dynamic_cast(item)->moveUp(); break; case Qt::Key_Down: - dynamic_cast(item)->moveDown(); + dynamic_cast(item)->moveDown(); break; } } } } - if ((event->modifiers()& Qt::ShiftModifier) && m_changeSizeMode && (!(event->modifiers()& Qt::ControlModifier))) { - foreach(QGraphicsItem * item, selectedItems()) { - if (dynamic_cast(item)) { + if ((event->modifiers() & Qt::ShiftModifier) && m_changeSizeMode + && (!(event->modifiers() & Qt::ControlModifier))) { + foreach (QGraphicsItem* item, selectedItems()) { + if (dynamic_cast(item)) { switch (event->key()) { case Qt::Key_Right: - dynamic_cast(item)->sizeRight(); + dynamic_cast(item)->sizeRight(); break; case Qt::Key_Left: - dynamic_cast(item)->sizeLeft(); + dynamic_cast(item)->sizeLeft(); break; case Qt::Key_Up: - dynamic_cast(item)->sizeUp(); + dynamic_cast(item)->sizeUp(); break; case Qt::Key_Down: - dynamic_cast(item)->sizeDown(); + dynamic_cast(item)->sizeDown(); break; } } @@ -205,22 +202,23 @@ void PageDesignIntf::keyPressEvent(QKeyEvent *event) } } -void PageDesignIntf::keyReleaseEvent(QKeyEvent *event) +void PageDesignIntf::keyReleaseEvent(QKeyEvent* event) { if ((event->key() == Qt::Key_Control) && m_changePosMode) { checkSizeOrPosChanges(); } - if ((event->key() == Qt::Key_Shift) && m_changeSizeMode ) { + if ((event->key() == Qt::Key_Shift) && m_changeSizeMode) { checkSizeOrPosChanges(); } QGraphicsScene::keyReleaseEvent(event); } -void PageDesignIntf::startInsertMode(const QString &ItemType) +void PageDesignIntf::startInsertMode(const QString& ItemType) { - if (m_insertMode) emit itemInsertCanceled(m_insertItemType); + if (m_insertMode) + emit itemInsertCanceled(m_insertItemType); emit insertModeStarted(); m_insertMode = true; @@ -234,30 +232,30 @@ void PageDesignIntf::startInsertMode(const QString &ItemType) void PageDesignIntf::startEditMode() { - if (m_insertMode) emit itemInsertCanceled(m_insertItemType); + if (m_insertMode) + emit itemInsertCanceled(m_insertItemType); finalizeInsertMode(); m_insertMode = false; } -PageItemDesignIntf *PageDesignIntf::pageItem() +PageItemDesignIntf* PageDesignIntf::pageItem() { return m_currentPage ? m_currentPage : m_pageItem.data(); } void PageDesignIntf::setPageItem(PageItemDesignIntf::Ptr pageItem) { - if (pageItem.isNull()) return; + if (pageItem.isNull()) + return; if (!m_pageItem.isNull()) { removeItem(m_pageItem.data()); m_pageItem->setParent(0); } m_pageItem = pageItem; m_pageItem->setItemMode(itemMode()); - setSceneRect(pageItem->rect().adjusted(-10 * Const::mmFACTOR, - -10 * Const::mmFACTOR, - 10 * Const::mmFACTOR, - 10 * Const::mmFACTOR)); + setSceneRect(pageItem->rect().adjusted(-10 * Const::mmFACTOR, -10 * Const::mmFACTOR, + 10 * Const::mmFACTOR, 10 * Const::mmFACTOR)); addItem(m_pageItem.data()); registerItem(m_pageItem.data()); } @@ -277,44 +275,43 @@ void PageDesignIntf::setPageItems(QList pages) pageItem->setItemMode(itemMode()); addItem(pageItem.data()); registerItem(pageItem.data()); - pageItem->setPos(0,curHeight); - curHeight+=pageItem->height()+20; - if (curWidthwidth()) curWidth=pageItem->width(); + pageItem->setPos(0, curHeight); + curHeight += pageItem->height() + 20; + if (curWidth < pageItem->width()) + curWidth = pageItem->width(); } - setSceneRect(QRectF( 0, 0, curWidth,curHeight).adjusted( -10 * Const::mmFACTOR, - -10 * Const::mmFACTOR, - 10 * Const::mmFACTOR, - 10 * Const::mmFACTOR)); - if (m_reportPages.count()>0) + setSceneRect(QRectF(0, 0, curWidth, curHeight) + .adjusted(-10 * Const::mmFACTOR, -10 * Const::mmFACTOR, 10 * Const::mmFACTOR, + 10 * Const::mmFACTOR)); + if (m_reportPages.count() > 0) m_currentPage = m_reportPages.at(0).data(); - } void PageDesignIntf::removePageItem(PageItemDesignIntf::Ptr pageItem) { - if (m_pageItem == pageItem){ + if (m_pageItem == pageItem) { removeItem(m_pageItem.data()); m_pageItem.clear(); } } -void PageDesignIntf::mousePressEvent(QGraphicsSceneMouseEvent *event) +void PageDesignIntf::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (m_insertMode) { finalizeInsertMode(); - CommandIf::Ptr command = InsertItemCommand::create(this, m_insertItemType, event->scenePos(), QSize(200, 50)); + CommandIf::Ptr command + = InsertItemCommand::create(this, m_insertItemType, event->scenePos(), QSize(200, 50)); saveCommand(command); emit itemInserted(this, event->scenePos(), m_insertItemType); } - if (event->buttons() & Qt::LeftButton && event->modifiers()==Qt::ShiftModifier){ + if (event->buttons() & Qt::LeftButton && event->modifiers() == Qt::ShiftModifier) { m_multiSelectStarted = true; } else { QGraphicsScene::mousePressEvent(event); } } - -void PageDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +void PageDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { PageItemDesignIntf* page = pageItem() ? pageItem() : getCurrentPage(); @@ -324,77 +321,84 @@ void PageDesignIntf::mouseMoveEvent(QGraphicsSceneMouseEvent *event) saveSelectedItemsGeometry(); m_changePosOrSizeMode = true; } -// qreal posY = div(page->mapFromScene(event->scenePos()).y(), verticalGridStep()).quot * verticalGridStep(); -// qreal posX = div(page->mapFromScene(event->scenePos()).x(), verticalGridStep()).quot * horizontalGridStep(); + // qreal posY = div(page->mapFromScene(event->scenePos()).y(), + // verticalGridStep()).quot * verticalGridStep(); qreal posX = + // div(page->mapFromScene(event->scenePos()).x(), verticalGridStep()).quot * + // horizontalGridStep(); -// if(!m_infoPosRect) -// { -// m_infoPosRect = new QGraphicsTextItem(); -// m_infoPosRect->setDefaultTextColor(QColor(100,150,50)); + // if(!m_infoPosRect) + // { + // m_infoPosRect = new QGraphicsTextItem(); + // m_infoPosRect->setDefaultTextColor(QColor(100,150,50)); -// QFont font("Arial"); -// font.setPointSize(16); -// font.setBold(true); -// m_infoPosRect->setFont(font); -// addItem(m_infoPosRect); -// } - -// m_infoPosRect->setPlainText("(x: "+QString::number(posX/100)+", y: "+QString::number(posY/100)+") cm"); -// m_infoPosRect->setPos(posX,posY+30); + // QFont font("Arial"); + // font.setPointSize(16); + // font.setBold(true); + // m_infoPosRect->setFont(font); + // addItem(m_infoPosRect); + // } + // m_infoPosRect->setPlainText("(x: "+QString::number(posX/100)+", y: + // "+QString::number(posY/100)+") cm"); m_infoPosRect->setPos(posX,posY+30); } - if (event->buttons() & Qt::LeftButton && m_multiSelectStarted){ - if (!m_selectionRect){ + if (event->buttons() & Qt::LeftButton && m_multiSelectStarted) { + if (!m_selectionRect) { m_selectionRect = new QGraphicsRectItem(); - QBrush brush(QColor(140,190,30,50)); + QBrush brush(QColor(140, 190, 30, 50)); m_selectionRect->setBrush(brush); m_selectionRect->setPen(Qt::DashLine); addItem(m_selectionRect); } QRectF selectionRect; - selectionRect.setX(qMin(event->buttonDownScenePos(Qt::LeftButton).x(),event->scenePos().x())); - selectionRect.setY(qMin(event->buttonDownScenePos(Qt::LeftButton).y(),event->scenePos().y())); - selectionRect.setRight(qMax(event->buttonDownScenePos(Qt::LeftButton).x(),event->scenePos().x())); - selectionRect.setBottom(qMax(event->buttonDownScenePos(Qt::LeftButton).y(),event->scenePos().y())); + selectionRect.setX( + qMin(event->buttonDownScenePos(Qt::LeftButton).x(), event->scenePos().x())); + selectionRect.setY( + qMin(event->buttonDownScenePos(Qt::LeftButton).y(), event->scenePos().y())); + selectionRect.setRight( + qMax(event->buttonDownScenePos(Qt::LeftButton).x(), event->scenePos().x())); + selectionRect.setBottom( + qMax(event->buttonDownScenePos(Qt::LeftButton).y(), event->scenePos().y())); m_selectionRect->setRect(selectionRect); } if ((m_insertMode) && (page && page->rect().contains(page->mapFromScene(event->scenePos())))) { - if (!m_itemInsertRect->isVisible()) m_itemInsertRect->setVisible(true); - qreal posY = div(page->mapFromScene(event->scenePos()).y(), verticalGridStep()).quot * verticalGridStep(); - qreal posX = div(page->mapFromScene(event->scenePos()).x(), verticalGridStep()).quot * horizontalGridStep(); - m_itemInsertRect->setPos(posX,posY); - if (magneticMovement()){ - rectMoved( - QRectF(m_itemInsertRect->pos().x(), - m_itemInsertRect->pos().y(), - m_itemInsertRect->boundingRect().width(), - m_itemInsertRect->boundingRect().height() - ) - ); + if (!m_itemInsertRect->isVisible()) + m_itemInsertRect->setVisible(true); + qreal posY = div(page->mapFromScene(event->scenePos()).y(), verticalGridStep()).quot + * verticalGridStep(); + qreal posX = div(page->mapFromScene(event->scenePos()).x(), verticalGridStep()).quot + * horizontalGridStep(); + m_itemInsertRect->setPos(posX, posY); + if (magneticMovement()) { + rectMoved(QRectF(m_itemInsertRect->pos().x(), m_itemInsertRect->pos().y(), + m_itemInsertRect->boundingRect().width(), + m_itemInsertRect->boundingRect().height())); } } else { - if (m_insertMode) m_itemInsertRect->setVisible(false); + if (m_insertMode) + m_itemInsertRect->setVisible(false); } QGraphicsScene::mouseMoveEvent(event); } -void PageDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +void PageDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { - if ( (event->button() == Qt::LeftButton)) { - if (m_joinItem && selectedItems().count()==1){ + if ((event->button() == Qt::LeftButton)) { + if (m_joinItem && selectedItems().count() == 1) { BaseDesignIntf* selectedItem = dynamic_cast(selectedItems().at(0)); - if (m_magneticMovement){ - if (m_joinType == Width){ + if (m_magneticMovement) { + if (m_joinType == Width) { QPointF tmpPos; - if (selectedItem->pos().y()>m_joinItem->pos().y()) - tmpPos = QPointF(m_joinItem->x(),m_joinItem->pos().y()+m_joinItem->height()); + if (selectedItem->pos().y() > m_joinItem->pos().y()) + tmpPos = QPointF(m_joinItem->x(), + m_joinItem->pos().y() + m_joinItem->height()); else - tmpPos = QPointF(m_joinItem->x(),m_joinItem->pos().y()-selectedItem->height()); + tmpPos = QPointF(m_joinItem->x(), + m_joinItem->pos().y() - selectedItem->height()); selectedItem->setPos(tmpPos); selectedItem->setWidth(m_joinItem->width()); @@ -402,10 +406,12 @@ void PageDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) } else { QPointF tmpPos; - if (selectedItem->pos().x()>m_joinItem->pos().x()) - tmpPos = QPointF(m_joinItem->x()+m_joinItem->width(),m_joinItem->pos().y()); + if (selectedItem->pos().x() > m_joinItem->pos().x()) + tmpPos + = QPointF(m_joinItem->x() + m_joinItem->width(), m_joinItem->pos().y()); else - tmpPos = QPointF(m_joinItem->x()-selectedItem->width(),m_joinItem->pos().y()); + tmpPos = QPointF(m_joinItem->x() - selectedItem->width(), + m_joinItem->pos().y()); selectedItem->setPos(tmpPos); selectedItem->setHeight(m_joinItem->height()); @@ -425,27 +431,27 @@ void PageDesignIntf::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) QGraphicsScene::mouseReleaseEvent(event); } -void PageDesignIntf::setSelectionRect(QRectF selectionRect){ +void PageDesignIntf::setSelectionRect(QRectF selectionRect) +{ clearSelection(); - foreach(QGraphicsItem* item, items()){ - if ( selectionRect.intersects(item->mapRectToScene(item->boundingRect()))) + foreach (QGraphicsItem* item, items()) { + if (selectionRect.intersects(item->mapRectToScene(item->boundingRect()))) if (dynamic_cast(item)) item->setSelected(true); } } -BaseDesignIntf *PageDesignIntf::addBand(const QString &bandType) +BaseDesignIntf* PageDesignIntf::addBand(const QString& bandType) { return internalAddBand(bandType); } -BaseDesignIntf *PageDesignIntf::addBand(BandDesignIntf::BandsType bandType) +BaseDesignIntf* PageDesignIntf::addBand(BandDesignIntf::BandsType bandType) { return internalAddBand(bandType); } -template -BaseDesignIntf *PageDesignIntf::internalAddBand(T bandType) +template BaseDesignIntf* PageDesignIntf::internalAddBand(T bandType) { if (m_insertMode) { @@ -454,16 +460,13 @@ BaseDesignIntf *PageDesignIntf::internalAddBand(T bandType) } QSet needParentBands; - needParentBands << BandDesignIntf::SubDetailBand - << BandDesignIntf::SubDetailHeader - << BandDesignIntf::SubDetailFooter - << BandDesignIntf::GroupHeader - << BandDesignIntf::GroupFooter - << BandDesignIntf::DataHeader + needParentBands << BandDesignIntf::SubDetailBand << BandDesignIntf::SubDetailHeader + << BandDesignIntf::SubDetailFooter << BandDesignIntf::GroupHeader + << BandDesignIntf::GroupFooter << BandDesignIntf::DataHeader << BandDesignIntf::DataFooter; BandsManager bandsManager; - BandDesignIntf *band = bandsManager.createBand(bandType, pageItem(), pageItem()); + BandDesignIntf* band = bandsManager.createBand(bandType, pageItem(), pageItem()); if (band->isUnique()) { if (pageItem()->isBandExists(bandType)) { @@ -477,47 +480,52 @@ BaseDesignIntf *PageDesignIntf::internalAddBand(T bandType) BandDesignIntf* pb = 0; if (selectedItems().count() > 0) { - pb = dynamic_cast(selectedItems().at(0)); + pb = dynamic_cast(selectedItems().at(0)); } bool increaseBandIndex = false; int bandIndex = pageItem()->calcBandIndex(band->bandType(), pb, increaseBandIndex); band->setBandIndex(bandIndex); - if (needParentBands.contains(band->bandType())){ + if (needParentBands.contains(band->bandType())) { band->setParentBand(pb); } - if (increaseBandIndex) pageItem()->increaseBandIndex(bandIndex); + if (increaseBandIndex) + pageItem()->increaseBandIndex(bandIndex); registerItem(band); - foreach(QGraphicsItem * item, selectedItems()) item->setSelected(false); + foreach (QGraphicsItem* item, selectedItems()) + item->setSelected(false); band->setSelected(true); CommandIf::Ptr command = InsertBandCommand::create(this, band->objectName()); saveCommand(command, false); return band; } -void PageDesignIntf::bandGeometryChanged(QObject* /*object*/, QRectF newGeometry, QRectF oldGeometry) +void PageDesignIntf::bandGeometryChanged(QObject* /*object*/, QRectF newGeometry, + QRectF oldGeometry) { Q_UNUSED(newGeometry); Q_UNUSED(oldGeometry); pageItem()->relocateBands(); } -QPointF PageDesignIntf::placePosOnGrid(QPointF point){ +QPointF PageDesignIntf::placePosOnGrid(QPointF point) +{ return QPointF(div(point.x(), horizontalGridStep()).quot * horizontalGridStep(), div(point.y(), verticalGridStep()).quot * verticalGridStep()); } -QSizeF PageDesignIntf::placeSizeOnGrid(QSizeF size){ +QSizeF PageDesignIntf::placeSizeOnGrid(QSizeF size) +{ return QSizeF(div(size.width(), horizontalGridStep()).quot * horizontalGridStep(), - div(size.height(), verticalGridStep()).quot * verticalGridStep()); + div(size.height(), verticalGridStep()).quot * verticalGridStep()); } -BaseDesignIntf *PageDesignIntf::addReportItem(const QString &itemType, QPointF pos, QSizeF size) +BaseDesignIntf* PageDesignIntf::addReportItem(const QString& itemType, QPointF pos, QSizeF size) { - BandDesignIntf *band = bandAt(pos); + BandDesignIntf* band = bandAt(pos); if (band) { - BaseDesignIntf *reportItem = addReportItem(itemType, band, band); + BaseDesignIntf* reportItem = addReportItem(itemType, band, band); reportItem->setPos(placePosOnGrid(band->mapFromScene(pos))); reportItem->setReportSettings(m_reportSettings); reportItem->setSize(placeSizeOnGrid(size)); @@ -525,8 +533,8 @@ BaseDesignIntf *PageDesignIntf::addReportItem(const QString &itemType, QPointF p return reportItem; } else { PageItemDesignIntf* page = pageItem() ? pageItem() : m_currentPage; - if (page){ - BaseDesignIntf *reportItem = addReportItem(itemType, page, page); + if (page) { + BaseDesignIntf* reportItem = addReportItem(itemType, page, page); reportItem->setReportSettings(m_reportSettings); reportItem->setPos(placePosOnGrid(page->mapFromScene(pos))); reportItem->setSize(placeSizeOnGrid(size)); @@ -541,9 +549,11 @@ BaseDesignIntf *PageDesignIntf::addReportItem(const QString &itemType, QPointF p return 0; } -BaseDesignIntf *PageDesignIntf::addReportItem(const QString &itemType, QObject *owner, LimeReport::BaseDesignIntf *parent) +BaseDesignIntf* PageDesignIntf::addReportItem(const QString& itemType, QObject* owner, + LimeReport::BaseDesignIntf* parent) { - BaseDesignIntf *item = LimeReport::DesignElementsFactory::instance().objectCreator(itemType)((owner) ? owner : pageItem(), (parent) ? parent : pageItem()); + BaseDesignIntf* item = LimeReport::DesignElementsFactory::instance().objectCreator(itemType)( + (owner) ? owner : pageItem(), (parent) ? parent : pageItem()); item->setObjectName(genObjectName(*item)); item->setItemTypeName(itemType); item->setUnitType(pageItem()->unitType()); @@ -551,30 +561,34 @@ BaseDesignIntf *PageDesignIntf::addReportItem(const QString &itemType, QObject * return item; } -BaseDesignIntf *PageDesignIntf::createReportItem(const QString &itemType, QObject* owner, BaseDesignIntf* parent) +BaseDesignIntf* PageDesignIntf::createReportItem(const QString& itemType, QObject* owner, + BaseDesignIntf* parent) { - return LimeReport::DesignElementsFactory::instance().objectCreator(itemType)((owner) ? owner : pageItem(), (parent) ? parent : pageItem()); + return LimeReport::DesignElementsFactory::instance().objectCreator(itemType)( + (owner) ? owner : pageItem(), (parent) ? parent : pageItem()); } -CommandIf::Ptr createBandDeleteCommand(PageDesignIntf* page, BandDesignIntf* band){ +CommandIf::Ptr createBandDeleteCommand(PageDesignIntf* page, BandDesignIntf* band) +{ - if (band->hasChildren()){ + if (band->hasChildren()) { CommandIf::Ptr command = CommandGroup::create(); - command->addCommand(DeleteItemCommand::create(page,band),false); - foreach(BandDesignIntf* curband, band->childBands()){ - command->addCommand(createBandDeleteCommand(page,curband),false); + command->addCommand(DeleteItemCommand::create(page, band), false); + foreach (BandDesignIntf* curband, band->childBands()) { + command->addCommand(createBandDeleteCommand(page, curband), false); } return command; } else { - CommandIf::Ptr command = DeleteItemCommand::create(page,band); + CommandIf::Ptr command = DeleteItemCommand::create(page, band); return command; } } -CommandIf::Ptr PageDesignIntf::removeReportItemCommand(BaseDesignIntf *item){ +CommandIf::Ptr PageDesignIntf::removeReportItemCommand(BaseDesignIntf* item) +{ BandDesignIntf* band = dynamic_cast(item); - if (band){ - CommandIf::Ptr command = createBandDeleteCommand(this,band); + if (band) { + CommandIf::Ptr command = createBandDeleteCommand(this, band); return command; } else { LayoutDesignIntf* parentLayout = dynamic_cast(item->parent()); @@ -582,54 +596,55 @@ CommandIf::Ptr PageDesignIntf::removeReportItemCommand(BaseDesignIntf *item){ // When removing layout child all his children will be assigned to parent if (!layout && parentLayout && (parentLayout->childrenCount() == 2)) { CommandGroup::Ptr commandGroup = CommandGroup::create(); - commandGroup->addCommand(DeleteLayoutCommand::create(this, parentLayout),false); - commandGroup->addCommand(DeleteItemCommand::create(this,item),false); + commandGroup->addCommand(DeleteLayoutCommand::create(this, parentLayout), false); + commandGroup->addCommand(DeleteItemCommand::create(this, item), false); return commandGroup; } else { - return layout ? DeleteLayoutCommand::create(this, layout) : DeleteItemCommand::create(this, item) ; + return layout ? DeleteLayoutCommand::create(this, layout) + : DeleteItemCommand::create(this, item); } } } -void PageDesignIntf::removeReportItem(BaseDesignIntf *item, bool createComand) +void PageDesignIntf::removeReportItem(BaseDesignIntf* item, bool createComand) { - if (!createComand){ + if (!createComand) { removeItem(item); BandDesignIntf* band = dynamic_cast(item); - if (band){ - emit bandRemoved(this,band); + if (band) { + emit bandRemoved(this, band); } else { - emit itemRemoved(this,item); + emit itemRemoved(this, item); } delete item; } else { BandDesignIntf* band = dynamic_cast(item); - if (band){ - CommandIf::Ptr command = createBandDeleteCommand(this,band); + if (band) { + CommandIf::Ptr command = createBandDeleteCommand(this, band); saveCommand(command); } else { LayoutDesignIntf* layout = dynamic_cast(item->parent()); - if (layout && (layout->childrenCount()==2)){ + if (layout && (layout->childrenCount() == 2)) { CommandGroup::Ptr commandGroup = CommandGroup::create(); - commandGroup->addCommand(DeleteLayoutCommand::create(this, layout),false); - commandGroup->addCommand(DeleteItemCommand::create(this,item),false); + commandGroup->addCommand(DeleteLayoutCommand::create(this, layout), false); + commandGroup->addCommand(DeleteItemCommand::create(this, item), false); saveCommand(commandGroup); } else { - CommandIf::Ptr command = (dynamic_cast(item))? - DeleteLayoutCommand::create(this, dynamic_cast(item)) : - DeleteItemCommand::create(this, item) ; + CommandIf::Ptr command = (dynamic_cast(item)) + ? DeleteLayoutCommand::create(this, dynamic_cast(item)) + : DeleteItemCommand::create(this, item); saveCommand(command); } } } - } bool PageDesignIntf::saveCommand(CommandIf::Ptr command, bool runCommand) { - if (m_executingCommand||m_isLoading) return false; + if (m_executingCommand || m_isLoading) + return false; if (runCommand) { m_executingCommand = true; if (!command->doIt()) { @@ -649,41 +664,29 @@ bool PageDesignIntf::saveCommand(CommandIf::Ptr command, bool runCommand) return true; } -bool PageDesignIntf::isCanRedo() +bool PageDesignIntf::isCanRedo() { return m_currentCommand < m_commandsList.count() - 1; } + +bool PageDesignIntf::isCanUndo() { return m_currentCommand >= 0; } + +bool PageDesignIntf::isHasChanges() { return (m_commandsList.count() > 0) && m_hasChanges; } + +bool PageDesignIntf::isItemInsertMode() { return m_insertMode; } + +void PageDesignIntf::bandPosChanged(QObject* /*object*/, QPointF /*newPos*/, QPointF /*oldPos*/) { - return m_currentCommand < m_commandsList.count() - 1; + // relocateBands(dynamic_cast(object)); } -bool PageDesignIntf::isCanUndo() +QString PageDesignIntf::genObjectName(const QObject& object) { - return m_currentCommand >= 0; -} - -bool PageDesignIntf::isHasChanges() -{ - return (m_commandsList.count() > 0) && m_hasChanges; -} - -bool PageDesignIntf::isItemInsertMode() -{ - return m_insertMode; -} - -void PageDesignIntf::bandPosChanged(QObject * /*object*/, QPointF /*newPos*/, QPointF /*oldPos*/) -{ - //relocateBands(dynamic_cast(object)); -} - -QString PageDesignIntf::genObjectName(const QObject &object) -{ - //int index = 1; + // int index = 1; QString className(object.metaObject()->className()); className = className.right(className.length() - (className.lastIndexOf("::") + 2)); QString tmpName = QString("%1%2").arg(className).arg(m_currentObjectIndex); QList itemsList = items(); - while (isExistsObjectName(tmpName,itemsList)) { + while (isExistsObjectName(tmpName, itemsList)) { ++m_currentObjectIndex; tmpName = QString("%1%2").arg(className).arg(m_currentObjectIndex); } @@ -691,20 +694,22 @@ QString PageDesignIntf::genObjectName(const QObject &object) return tmpName; } -bool PageDesignIntf::isExistsObjectName(const QString &objectName, QList& itemsList) const +bool PageDesignIntf::isExistsObjectName(const QString& objectName, + QList& itemsList) const { - QObject *item = 0; - //QList itemList = items(); + QObject* item = 0; + // QList itemList = items(); for (int i = 0; i < itemsList.count(); i++) { - item = dynamic_cast(itemsList[i]); + item = dynamic_cast(itemsList[i]); if (item) - if (item->objectName() == objectName) return true; + if (item->objectName() == objectName) + return true; } return false; } -//QRectF PageDesignIntf::getRectByPageSize(PageDesignIntf::PageSize pageSize) +// QRectF PageDesignIntf::getRectByPageSize(PageDesignIntf::PageSize pageSize) //{ // if (m_pageSize != PageSize::Custom) { // QPrinter printer; @@ -721,35 +726,23 @@ bool PageDesignIntf::isExistsObjectName(const QString &objectName, QListremoveBand(band); } -ReportEnginePrivate *PageDesignIntf::reportEditor() -{ - return m_reportEditor; -} +ReportEnginePrivate* PageDesignIntf::reportEditor() { return m_reportEditor; } -void PageDesignIntf::dragEnterEvent(QGraphicsSceneDragDropEvent *event) +void PageDesignIntf::dragEnterEvent(QGraphicsSceneDragDropEvent* event) { - if (!event->mimeData()->text().isEmpty()){ + if (!event->mimeData()->text().isEmpty()) { event->setDropAction(Qt::CopyAction); event->accept(); } else { @@ -760,38 +753,42 @@ void PageDesignIntf::dragEnterEvent(QGraphicsSceneDragDropEvent *event) void PageDesignIntf::dragMoveEvent(QGraphicsSceneDragDropEvent* /**event*/) { -// event->setDropAction(Qt::CopyAction); -// event->accept(); + // event->setDropAction(Qt::CopyAction); + // event->accept(); } void PageDesignIntf::dropEvent(QGraphicsSceneDragDropEvent* event) { - if (event->mimeData()->hasText() && - ((event->mimeData()->text().indexOf("field:")==0) || - (event->mimeData()->text().indexOf("variable:")==0)) - ){ - bool isVar = event->mimeData()->text().indexOf("variable:")==0; - BaseDesignIntf* item = addReportItem("TextItem",event->scenePos(),QSize(250, 50)); + if (event->mimeData()->hasText() + && ((event->mimeData()->text().indexOf("field:") == 0) + || (event->mimeData()->text().indexOf("variable:") == 0))) { + bool isVar = event->mimeData()->text().indexOf("variable:") == 0; + BaseDesignIntf* item = addReportItem("TextItem", event->scenePos(), QSize(250, 50)); TextItem* ti = dynamic_cast(item); - QString data = event->mimeData()->text().remove(0,event->mimeData()->text().indexOf(":")+1); + QString data + = event->mimeData()->text().remove(0, event->mimeData()->text().indexOf(":") + 1); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (isVar) data = data.remove(QRegExp(" \\[.*\\]")); + if (isVar) + data = data.remove(QRegExp(" \\[.*\\]")); #else - if (isVar) data = data.remove(QRegularExpression(" \\[.*\\]", QRegularExpression::DotMatchesEverythingOption)); + if (isVar) + data = data.remove( + QRegularExpression(" \\[.*\\]", QRegularExpression::DotMatchesEverythingOption)); #endif ti->setContent(data); - if (!isVar){ + if (!isVar) { BandDesignIntf* parentBand = dynamic_cast(ti->parentItem()); - if (parentBand && parentBand->datasourceName().isEmpty()){ + if (parentBand && parentBand->datasourceName().isEmpty()) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp dataSource("(?:\\$D\\{\\s*(.*)\\..*\\})"); - if (dataSource.indexIn(data) != -1){ - parentBand->setProperty("datasource",dataSource.cap(1)); + if (dataSource.indexIn(data) != -1) { + parentBand->setProperty("datasource", dataSource.cap(1)); } #else - QRegularExpression dataSource("(?:\\$D\\{\\s*(.*)\\..*\\})", QRegularExpression::DotMatchesEverythingOption); + QRegularExpression dataSource("(?:\\$D\\{\\s*(.*)\\..*\\})", + QRegularExpression::DotMatchesEverythingOption); QRegularExpressionMatch match = dataSource.match(data); - if(match.hasMatch()){ + if (match.hasMatch()) { parentBand->setProperty("datasource", match.captured(1)); } #endif @@ -800,18 +797,18 @@ void PageDesignIntf::dropEvent(QGraphicsSceneDragDropEvent* event) } } -void PageDesignIntf::dragLeaveEvent(QGraphicsSceneDragDropEvent *) +void PageDesignIntf::dragLeaveEvent(QGraphicsSceneDragDropEvent*) { - //removeItem(m_itemInsertRect); - //delete m_itemInsertRect; - //m_itemInsertRect = 0; + // removeItem(m_itemInsertRect); + // delete m_itemInsertRect; + // m_itemInsertRect = 0; } QStringList PageDesignIntf::possibleParentItems() { QStringList itemsList; - foreach(QGraphicsItem * item, items()) { - BandDesignIntf *band = dynamic_cast(item); + foreach (QGraphicsItem* item, items()) { + BandDesignIntf* band = dynamic_cast(item); if (band) { itemsList.append(band->objectName()); @@ -820,52 +817,51 @@ QStringList PageDesignIntf::possibleParentItems() return itemsList; } -void PageDesignIntf::slotPageGeometryChanged(QObject *, QRectF /*newGeometry*/, QRectF) +void PageDesignIntf::slotPageGeometryChanged(QObject*, QRectF /*newGeometry*/, QRectF) { - if (!m_isLoading){ + if (!m_isLoading) { pageItem()->relocateBands(); updatePageRect(); emit geometryChanged(sceneRect()); } } -void PageDesignIntf::slotItemPropertyChanged(QString propertyName, const QVariant &oldValue, const QVariant& newValue) +void PageDesignIntf::slotItemPropertyChanged(QString propertyName, const QVariant& oldValue, + const QVariant& newValue) { - if (!m_isLoading && m_animationList.isEmpty()){ - saveChangeProppertyCommand(sender()->objectName(),propertyName,oldValue,newValue); - emit itemPropertyChanged(sender()->objectName(),propertyName,oldValue,newValue); + if (!m_isLoading && m_animationList.isEmpty()) { + saveChangeProppertyCommand(sender()->objectName(), propertyName, oldValue, newValue); + emit itemPropertyChanged(sender()->objectName(), propertyName, oldValue, newValue); } } -void PageDesignIntf::slotItemPropertyObjectNameChanged(const QString &oldName, const QString &newName) +void PageDesignIntf::slotItemPropertyObjectNameChanged(const QString& oldName, + const QString& newName) { - if (oldName.compare(newName)!=0 && !m_executingCommand){ + if (oldName.compare(newName) != 0 && !m_executingCommand) { CommandIf::Ptr command = PropertyObjectNameChangedCommand::create(this, oldName, newName); saveCommand(command, false); emit itemPropertyObjectNameChanged(oldName, newName); } } -void PageDesignIntf::bandDeleted(QObject *band) +void PageDesignIntf::bandDeleted(QObject* band) { - pageItem()->removeBand(reinterpret_cast(band)); + pageItem()->removeBand(reinterpret_cast(band)); delete band; pageItem()->relocateBands(); } -void PageDesignIntf::slotPageItemLoaded(QObject *) -{ - setItemMode(m_itemMode); -} +void PageDesignIntf::slotPageItemLoaded(QObject*) { setItemMode(m_itemMode); } void PageDesignIntf::slotSelectionChanged() { if (selectedItems().count() == 1) { - m_firstSelectedItem = dynamic_cast(selectedItems().at(0)); + m_firstSelectedItem = dynamic_cast(selectedItems().at(0)); } } -void PageDesignIntf::slotAnimationStoped(QObject *animation) +void PageDesignIntf::slotAnimationStoped(QObject* animation) { m_animationList.removeOne(animation); } @@ -885,8 +881,8 @@ void PageDesignIntf::finalizeInsertMode() void PageDesignIntf::saveSelectedItemsPos() { m_positionStamp.clear(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *reportItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* reportItem = dynamic_cast(item); if (reportItem) { ReportItemPos rp; @@ -900,8 +896,8 @@ void PageDesignIntf::saveSelectedItemsPos() void PageDesignIntf::saveSelectedItemsGeometry() { m_geometryStamp.clear(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *reportItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* reportItem = dynamic_cast(item); if (reportItem) { ReportItemSize rs; @@ -917,9 +913,9 @@ void PageDesignIntf::checkSizeOrPosChanges() CommandIf::Ptr posCommand; if ((selectedItems().count() > 0) && (m_positionStamp.count() > 0)) { bool bandFound = false; - foreach(QGraphicsItem* item, selectedItems()){ + foreach (QGraphicsItem* item, selectedItems()) { BandDesignIntf* band = dynamic_cast(item); - if (band){ + if (band) { bandFound = true; break; } @@ -932,34 +928,35 @@ void PageDesignIntf::checkSizeOrPosChanges() CommandIf::Ptr sizeCommand; if ((selectedItems().count() > 0) && (m_geometryStamp.count() > 0)) { - BaseDesignIntf *reportItem = dynamic_cast(selectedItems()[0]); + BaseDesignIntf* reportItem = dynamic_cast(selectedItems()[0]); if (reportItem && (m_geometryStamp[0].size != reportItem->size())) { sizeCommand = createChangeSizeCommand(); } m_geometryStamp.clear(); } - if (sizeCommand && posCommand){ + if (sizeCommand && posCommand) { CommandGroup::Ptr cm = CommandGroup::create(); cm->addCommand(sizeCommand, false); cm->addCommand(posCommand, false); saveCommand(cm); } else { - if (sizeCommand) saveCommand(sizeCommand); - if (posCommand) saveCommand(posCommand); + if (sizeCommand) + saveCommand(sizeCommand); + if (posCommand) + saveCommand(posCommand); } m_changeSizeMode = false; m_changePosMode = false; m_changePosOrSizeMode = false; - } CommandIf::Ptr PageDesignIntf::createChangePosCommand() { QVector newPoses; - foreach(ReportItemPos itemPos, m_positionStamp) { - BaseDesignIntf *reportItem = reportItemByName(itemPos.objectName); + foreach (ReportItemPos itemPos, m_positionStamp) { + BaseDesignIntf* reportItem = reportItemByName(itemPos.objectName); if (reportItem) { ReportItemPos newPos; newPos.objectName = reportItem->objectName(); @@ -974,8 +971,8 @@ CommandIf::Ptr PageDesignIntf::createChangeSizeCommand() { QVector newSizes; - foreach(ReportItemSize itemPos, m_geometryStamp) { - BaseDesignIntf *reportItem = reportItemByName(itemPos.objectName); + foreach (ReportItemSize itemPos, m_geometryStamp) { + BaseDesignIntf* reportItem = reportItemByName(itemPos.objectName); if (reportItem) { ReportItemSize newSize; @@ -990,20 +987,21 @@ CommandIf::Ptr PageDesignIntf::createChangeSizeCommand() void PageDesignIntf::reactivatePageItem(PageItemDesignIntf::Ptr pageItem) { pageItem->setItemMode(itemMode()); - if (pageItem.data()->scene()!=this) + if (pageItem.data()->scene() != this) addItem(pageItem.data()); } -void PageDesignIntf::animateItem(BaseDesignIntf *item) +void PageDesignIntf::animateItem(BaseDesignIntf* item) { - if (item && (item->metaObject()->indexOfProperty("backgroundColor")>-1)){ + if (item && (item->metaObject()->indexOfProperty("backgroundColor") > -1)) { foreach (QObject* obj, m_animationList) { QPropertyAnimation* animation = dynamic_cast(obj); - if (animation->targetObject() == item) return; + if (animation->targetObject() == item) + return; } - QPropertyAnimation* ani1 = new QPropertyAnimation(item,"backgroundColor"); + QPropertyAnimation* ani1 = new QPropertyAnimation(item, "backgroundColor"); m_animationList.append(ani1); QColor startColor = QColor(Qt::red); @@ -1015,91 +1013,98 @@ void PageDesignIntf::animateItem(BaseDesignIntf *item) ani1->setEndValue(endColor); ani1->start(QAbstractAnimation::DeleteWhenStopped); - - connect(ani1,SIGNAL(destroyed(QObject*)), this, SLOT(slotAnimationStoped(QObject*))); + connect(ani1, SIGNAL(destroyed(QObject*)), this, SLOT(slotAnimationStoped(QObject*))); } } -void PageDesignIntf::registerItem(BaseDesignIntf *item) +void PageDesignIntf::registerItem(BaseDesignIntf* item) { item->setItemMode(itemMode()); - BandDesignIntf *band = dynamic_cast(item); - if (band){ + BandDesignIntf* band = dynamic_cast(item); + if (band) { registerBand(band); - connect(band, SIGNAL(propertyObjectNameChanged(QString,QString)), this, SLOT(slotItemPropertyObjectNameChanged(QString,QString))); - emit bandAdded(this,band); + connect(band, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotItemPropertyObjectNameChanged(QString, QString))); + emit bandAdded(this, band); } else { - connect(item, SIGNAL(propertyChanged(QString,QVariant,QVariant)), this, SLOT(slotItemPropertyChanged(QString,QVariant,QVariant))); - connect(item, SIGNAL(propertyObjectNameChanged(QString,QString)), this, SLOT(slotItemPropertyObjectNameChanged(QString,QString))); - emit itemAdded(this,item); + connect(item, SIGNAL(propertyChanged(QString, QVariant, QVariant)), this, + SLOT(slotItemPropertyChanged(QString, QVariant, QVariant))); + connect(item, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotItemPropertyObjectNameChanged(QString, QString))); + emit itemAdded(this, item); } } -void PageDesignIntf::emitRegisterdItem(BaseDesignIntf *item){ - emit itemAdded(this,item); -} +void PageDesignIntf::emitRegisterdItem(BaseDesignIntf* item) { emit itemAdded(this, item); } -void PageDesignIntf::emitItemRemoved(BaseDesignIntf *item) +void PageDesignIntf::emitItemRemoved(BaseDesignIntf* item) { BandDesignIntf* band = dynamic_cast(item); - if (band){ - emit bandRemoved(this,band); + if (band) { + emit bandRemoved(this, band); } else { - emit itemRemoved(this,item); + emit itemRemoved(this, item); } } -DataSourceManager *PageDesignIntf::datasourceManager() +DataSourceManager* PageDesignIntf::datasourceManager() { - if (m_reportEditor) return m_reportEditor->dataManager(); + if (m_reportEditor) + return m_reportEditor->dataManager(); return 0; } -void PageDesignIntf::registerBand(BandDesignIntf *band) +void PageDesignIntf::registerBand(BandDesignIntf* band) { - if (pageItem()&&!pageItem()->isBandRegistred(band)) { + if (pageItem() && !pageItem()->isBandRegistred(band)) { pageItem()->registerBand(band); - if (itemMode() == DesignMode) pageItem()->relocateBands(); + if (itemMode() == DesignMode) + pageItem()->relocateBands(); } } void PageDesignIntf::slotUpdateItemSize() { - foreach(QGraphicsItem * item, items()) { - BandDesignIntf *reportBand = dynamic_cast(item); + foreach (QGraphicsItem* item, items()) { + BandDesignIntf* reportBand = dynamic_cast(item); - if (reportBand) reportBand->updateItemSize(0); + if (reportBand) + reportBand->updateItemSize(0); } } -void PageDesignIntf::saveChangeProppertyCommand(const QString &objectName, const QString &propertyName, const QVariant &oldPropertyValue, const QVariant &newPropertyValue) +void PageDesignIntf::saveChangeProppertyCommand(const QString& objectName, + const QString& propertyName, + const QVariant& oldPropertyValue, + const QVariant& newPropertyValue) { if (!m_executingCommand) { CommandIf::Ptr command; - if (propertyName.compare("ItemAlign",Qt::CaseInsensitive)==0){ - command = PropertyItemAlignChangedCommand::create(this, objectName, - BaseDesignIntf::ItemAlign(oldPropertyValue.toInt()), - BaseDesignIntf::ItemAlign(newPropertyValue.toInt()) - ); + if (propertyName.compare("ItemAlign", Qt::CaseInsensitive) == 0) { + command = PropertyItemAlignChangedCommand::create( + this, objectName, BaseDesignIntf::ItemAlign(oldPropertyValue.toInt()), + BaseDesignIntf::ItemAlign(newPropertyValue.toInt())); } else { - command = PropertyChangedCommand::create(this, objectName, propertyName, oldPropertyValue, newPropertyValue); + command = PropertyChangedCommand::create(this, objectName, propertyName, + oldPropertyValue, newPropertyValue); } saveCommand(command, false); } } -void PageDesignIntf::changeSelectedGroupProperty(const QString &name, const QVariant &value) +void PageDesignIntf::changeSelectedGroupProperty(const QString& name, const QVariant& value) { if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); m_executingCommand = true; - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem) { QVariant oldValue = bdItem->property(name.toLatin1()); - if (oldValue.isValid()){ - bdItem->setProperty(name.toLatin1(),value); - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), name, oldValue, value); + if (oldValue.isValid()) { + bdItem->setProperty(name.toLatin1(), value); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), name, oldValue, value); cm->addCommand(command, false); } } @@ -1109,28 +1114,23 @@ void PageDesignIntf::changeSelectedGroupProperty(const QString &name, const QVar } } -PageItemDesignIntf* PageDesignIntf::getCurrentPage() const -{ - return m_currentPage; -} +PageItemDesignIntf* PageDesignIntf::getCurrentPage() const { return m_currentPage; } void PageDesignIntf::setCurrentPage(PageItemDesignIntf* currentPage) { - if (m_currentPage != currentPage ){ - if (m_currentPage) m_currentPage->setItemMode(PreviewMode); + if (m_currentPage != currentPage) { + if (m_currentPage) + m_currentPage->setItemMode(PreviewMode); m_currentPage = currentPage; - if (m_itemMode == DesignMode){ + if (m_itemMode == DesignMode) { m_currentPage->setItemMode(DesignMode); } } } -ReportSettings *PageDesignIntf::getReportSettings() const -{ - return m_reportSettings; -} +ReportSettings* PageDesignIntf::getReportSettings() const { return m_reportSettings; } -void PageDesignIntf::setReportSettings(ReportSettings *reportSettings) +void PageDesignIntf::setReportSettings(ReportSettings* reportSettings) { m_reportSettings = reportSettings; m_pageItem->setReportSettings(m_reportSettings); @@ -1138,26 +1138,21 @@ void PageDesignIntf::setReportSettings(ReportSettings *reportSettings) void PageDesignIntf::setPropertyToSelectedItems(const char* name, const QVariant& value) { - foreach(QGraphicsItem* gi, selectedItems()){ + foreach (QGraphicsItem* gi, selectedItems()) { BaseDesignIntf* item = dynamic_cast(gi); - if(item && item->metaObject()->indexOfProperty(name) != -1 ) item->setProperty(name,value); + if (item && item->metaObject()->indexOfProperty(name) != -1) + item->setProperty(name, value); } } -bool PageDesignIntf::magneticMovement() const -{ - return m_magneticMovement; -} +bool PageDesignIntf::magneticMovement() const { return m_magneticMovement; } void PageDesignIntf::setMagneticMovement(bool magneticMovement) { m_magneticMovement = magneticMovement; } -int PageDesignIntf::horizontalGridStep() const -{ - return m_horizontalGridStep; -} +int PageDesignIntf::horizontalGridStep() const { return m_horizontalGridStep; } void PageDesignIntf::setHorizontalGridStep(int horizontalGridStep) { @@ -1170,10 +1165,10 @@ void PageDesignIntf::endUpdate() emit pageUpdateFinished(this); } - -void PageDesignIntf::activateItemToJoin(QRectF itemRect, QList& items){ - QRectF r1(itemRect.x(), itemRect.y()-50, itemRect.width(), itemRect.height()+100); - QRectF r2(itemRect.x()-50, itemRect.y(), itemRect.width()+100, itemRect.height()); +void PageDesignIntf::activateItemToJoin(QRectF itemRect, QList& items) +{ + QRectF r1(itemRect.x(), itemRect.y() - 50, itemRect.width(), itemRect.height() + 100); + QRectF r2(itemRect.x() - 50, itemRect.y(), itemRect.width() + 100, itemRect.height()); qreal maxSquare = 0; if (m_joinItem) { @@ -1181,61 +1176,66 @@ void PageDesignIntf::activateItemToJoin(QRectF itemRect, QList& m_joinItem = 0; } - foreach(ItemProjections p, items){ - qreal tmpSquare = qMax(p.square(r1)/itemRect.width(),p.square(r2)/itemRect.height()); - if (tmpSquare>maxSquare) { + foreach (ItemProjections p, items) { + qreal tmpSquare = qMax(p.square(r1) / itemRect.width(), p.square(r2) / itemRect.height()); + if (tmpSquare > maxSquare) { maxSquare = tmpSquare; m_joinItem = p.item(); - if (p.square(r1)/itemRect.width() > p.square(r2) / itemRect.height()) + if (p.square(r1) / itemRect.width() > p.square(r2) / itemRect.height()) m_joinType = Width; else m_joinType = Height; } } - if (m_joinItem) m_joinItem->turnOnJoinMarker(true); + if (m_joinItem) + m_joinItem->turnOnJoinMarker(true); } -void PageDesignIntf::selectAllChildren(BaseDesignIntf *item) +void PageDesignIntf::selectAllChildren(BaseDesignIntf* item) { if (item) - foreach(BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { child->setSelected(true); } } -void PageDesignIntf::rectMoved(QRectF itemRect, BaseDesignIntf* container){ - if (!container){ +void PageDesignIntf::rectMoved(QRectF itemRect, BaseDesignIntf* container) +{ + if (!container) { container = bandAt(QPointF(itemRect.topLeft())); - if (!container) container = this->pageItem(); + if (!container) + container = this->pageItem(); } - if (container){ + if (container) { m_projections.clear(); - foreach(BaseDesignIntf* bi, container->childBaseItems()){ + foreach (BaseDesignIntf* bi, container->childBaseItems()) { m_projections.append(ItemProjections(bi)); } } activateItemToJoin(itemRect, m_projections); - } -void PageDesignIntf::itemMoved(BaseDesignIntf *item) +void PageDesignIntf::itemMoved(BaseDesignIntf* item) { - if (m_movedItem!=item){ + if (m_movedItem != item) { m_movedItem = item; - BaseDesignIntf* curItem = dynamic_cast(item->parentItem()); ; - while (curItem){ + BaseDesignIntf* curItem = dynamic_cast(item->parentItem()); + ; + while (curItem) { m_movedItemContainer = dynamic_cast(curItem); if (!m_movedItemContainer) m_movedItemContainer = dynamic_cast(curItem); - if (m_movedItemContainer) break; - else curItem = dynamic_cast(curItem->parentItem()); + if (m_movedItemContainer) + break; + else + curItem = dynamic_cast(curItem->parentItem()); } - if (m_movedItemContainer){ + if (m_movedItemContainer) { m_projections.clear(); - foreach(BaseDesignIntf* bi, m_movedItemContainer->childBaseItems()){ + foreach (BaseDesignIntf* bi, m_movedItemContainer->childBaseItems()) { if (bi != item) m_projections.append(ItemProjections(bi)); } @@ -1243,45 +1243,43 @@ void PageDesignIntf::itemMoved(BaseDesignIntf *item) } activateItemToJoin(item->geometry(), m_projections); -// QRectF r1(item->pos().x(),item->pos().y()-50,item->width(),item->height()+100); -// QRectF r2(item->pos().x()-50,item->pos().y(),item->width()+100,item->height()); -// qreal maxSquare = 0; + // QRectF r1(item->pos().x(),item->pos().y()-50,item->width(),item->height()+100); + // QRectF r2(item->pos().x()-50,item->pos().y(),item->width()+100,item->height()); + // qreal maxSquare = 0; -// if (m_joinItem) { -// m_joinItem->turnOnJoinMarker(false); -// m_joinItem = 0; -// } + // if (m_joinItem) { + // m_joinItem->turnOnJoinMarker(false); + // m_joinItem = 0; + // } -// foreach(ItemProjections p, m_projections){ -// qreal tmpSquare = qMax(p.square(r1)/item->width(),p.square(r2)/item->height()); -// if (tmpSquare>maxSquare) { -// maxSquare = tmpSquare; -// m_joinItem = p.item(); -// if (p.square(r1)/item->width()>p.square(r2)/item->height()) -// m_joinType = Width; -// else -// m_joinType = Height; -// } -// } - -// if (m_joinItem) m_joinItem->turnOnJoinMarker(true); + // foreach(ItemProjections p, m_projections){ + // qreal tmpSquare = qMax(p.square(r1)/item->width(),p.square(r2)/item->height()); + // if (tmpSquare>maxSquare) { + // maxSquare = tmpSquare; + // m_joinItem = p.item(); + // if (p.square(r1)/item->width()>p.square(r2)/item->height()) + // m_joinType = Width; + // else + // m_joinType = Height; + // } + // } + // if (m_joinItem) m_joinItem->turnOnJoinMarker(true); } -int PageDesignIntf::verticalGridStep() const -{ - return m_verticalGridStep; -} +int PageDesignIntf::verticalGridStep() const { return m_verticalGridStep; } void PageDesignIntf::setVerticalGridStep(int verticalGridStep) { m_verticalGridStep = verticalGridStep; } -Qt::AlignmentFlag transformFlags(bool horizontalAlign, Qt::AlignmentFlag value, Qt::AlignmentFlag flag){ +Qt::AlignmentFlag transformFlags(bool horizontalAlign, Qt::AlignmentFlag value, + Qt::AlignmentFlag flag) +{ int tmpValue = value; - if (horizontalAlign){ - tmpValue &= ~(Qt::AlignHCenter | Qt::AlignLeft | Qt::AlignRight | Qt::AlignJustify); + if (horizontalAlign) { + tmpValue &= ~(Qt::AlignHCenter | Qt::AlignLeft | Qt::AlignRight | Qt::AlignJustify); tmpValue |= flag; } else { tmpValue &= ~(Qt::AlignVCenter | Qt::AlignTop | Qt::AlignBottom); @@ -1290,19 +1288,22 @@ Qt::AlignmentFlag transformFlags(bool horizontalAlign, Qt::AlignmentFlag value, return Qt::AlignmentFlag(tmpValue); } -void PageDesignIntf::changeSelectedGrpoupTextAlignPropperty(const bool& horizontalAlign, Qt::AlignmentFlag flag) +void PageDesignIntf::changeSelectedGrpoupTextAlignPropperty(const bool& horizontalAlign, + Qt::AlignmentFlag flag) { if (selectedItems().count() > 0) { CommandGroup::Ptr cm = CommandGroup::create(); m_executingCommand = true; - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem) { QVariant oldValue = bdItem->property("alignment"); - if (oldValue.isValid()){ - QVariant value = transformFlags(horizontalAlign, Qt::AlignmentFlag(oldValue.toInt()), flag); - bdItem->setProperty("alignment",value); - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "alignment", oldValue, value); + if (oldValue.isValid()) { + QVariant value = transformFlags(horizontalAlign, + Qt::AlignmentFlag(oldValue.toInt()), flag); + bdItem->setProperty("alignment", value); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "alignment", oldValue, value); cm->addCommand(command, false); } } @@ -1337,11 +1338,11 @@ void PageDesignIntf::redo() void PageDesignIntf::copy() { if (!selectedItems().isEmpty()) { - QClipboard *clipboard = QApplication::clipboard(); - ItemsWriterIntf *writer = new XMLWriter; + QClipboard* clipboard = QApplication::clipboard(); + ItemsWriterIntf* writer = new XMLWriter; bool shouldWrite = false; - foreach(QGraphicsItem * item, selectedItems()) { - ItemDesignIntf *reportItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + ItemDesignIntf* reportItem = dynamic_cast(item); if (reportItem) { writer->putItem(reportItem); @@ -1357,10 +1358,12 @@ void PageDesignIntf::copy() } } -BaseDesignIntf* PageDesignIntf::findDestObject(BaseDesignIntf* item){ - if (item && item->canAcceptPaste()) return item; - BaseDesignIntf * curItem = item; - while (curItem && !curItem->canAcceptPaste()){ +BaseDesignIntf* PageDesignIntf::findDestObject(BaseDesignIntf* item) +{ + if (item && item->canAcceptPaste()) + return item; + BaseDesignIntf* curItem = item; + while (curItem && !curItem->canAcceptPaste()) { curItem = dynamic_cast(curItem->parentItem()); } return curItem; @@ -1368,15 +1371,15 @@ BaseDesignIntf* PageDesignIntf::findDestObject(BaseDesignIntf* item){ void PageDesignIntf::paste() { - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); ItemsReaderIntf::Ptr reader = StringXMLreader::create(clipboard->text()); - if (reader->first() && reader->itemType() == "Object"){ + if (reader->first() && reader->itemType() == "Object") { BaseDesignIntf* destItem = 0; if (!selectedItems().isEmpty()) destItem = findDestObject(dynamic_cast(selectedItems().at(0))); else destItem = this->pageItem(); - if (destItem){ + if (destItem) { CommandIf::Ptr command = PasteCommand::create(this, clipboard->text(), destItem); saveCommand(command); } @@ -1385,9 +1388,10 @@ void PageDesignIntf::paste() void PageDesignIntf::deleteSelected() { - if (selectedItems().count()==1){ + if (selectedItems().count() == 1) { if (!dynamic_cast(selectedItems().at(0))) - saveCommand(removeReportItemCommand(dynamic_cast(selectedItems().at(0)))); + saveCommand( + removeReportItemCommand(dynamic_cast(selectedItems().at(0)))); } else { QList itemsToDelete = selectedItems(); @@ -1397,7 +1401,7 @@ void PageDesignIntf::deleteSelected() QList bands; QList::iterator it; - for(it = itemsToDelete.begin(); it != itemsToDelete.end();){ + for (it = itemsToDelete.begin(); it != itemsToDelete.end();) { BandDesignIntf* band = dynamic_cast(*it); if (band) { bands.append(band); @@ -1407,28 +1411,28 @@ void PageDesignIntf::deleteSelected() } } - foreach (BandDesignIntf* band, bands){ + foreach (BandDesignIntf* band, bands) { foreach (QGraphicsItem* bandItem, band->childItems()) { itemsToDelete.removeOne(bandItem); } } - if (!itemsToDelete.isEmpty()){ - foreach(QGraphicsItem* item, itemsToDelete){ + if (!itemsToDelete.isEmpty()) { + foreach (QGraphicsItem* item, itemsToDelete) { if (!dynamic_cast(item)) - commandGroup->addCommand(removeReportItemCommand(dynamic_cast(item)),false); + commandGroup->addCommand( + removeReportItemCommand(dynamic_cast(item)), false); } } - if (!bands.isEmpty()){ + if (!bands.isEmpty()) { foreach (BandDesignIntf* band, bands) { - commandGroup->addCommand(removeReportItemCommand(band),false); + commandGroup->addCommand(removeReportItemCommand(band), false); } } saveCommand(commandGroup); } - } void PageDesignIntf::cut() @@ -1437,22 +1441,19 @@ void PageDesignIntf::cut() saveCommand(command); } -void PageDesignIntf::setToSaved() -{ - m_hasChanges = false; -} +void PageDesignIntf::setToSaved() { m_hasChanges = false; } void PageDesignIntf::bringToFront() { - foreach(QGraphicsItem * item, selectedItems()) { + foreach (QGraphicsItem* item, selectedItems()) { qreal zOrder = 0; - foreach(QGraphicsItem * colItem, collidingItems(item)) { + foreach (QGraphicsItem* colItem, collidingItems(item)) { if (zOrder <= colItem->zValue()) zOrder = colItem->zValue() + 0.1; } - BaseDesignIntf *bdItem = dynamic_cast(item); + BaseDesignIntf* bdItem = dynamic_cast(item); - if (bdItem){ + if (bdItem) { saveChangeProppertyCommand(bdItem->objectName(), "zOrder", bdItem->zValue(), zOrder); BandDesignIntf* band = dynamic_cast(item); PageItemDesignIntf* page = dynamic_cast(item); @@ -1466,14 +1467,14 @@ void PageDesignIntf::bringToFront() void PageDesignIntf::sendToBack() { - foreach(QGraphicsItem * item, selectedItems()) { + foreach (QGraphicsItem* item, selectedItems()) { qreal zOrder = 0; - foreach(QGraphicsItem * colItem, collidingItems(item)) { + foreach (QGraphicsItem* colItem, collidingItems(item)) { if (zOrder >= colItem->zValue()) zOrder = colItem->zValue() - 0.1; } - BaseDesignIntf *bdItem = dynamic_cast(item); - if (bdItem){ + BaseDesignIntf* bdItem = dynamic_cast(item); + if (bdItem) { saveChangeProppertyCommand(bdItem->objectName(), "zOrder", bdItem->zValue(), zOrder); BandDesignIntf* band = dynamic_cast(item); PageItemDesignIntf* page = dynamic_cast(item); @@ -1485,10 +1486,12 @@ void PageDesignIntf::sendToBack() } } -bool PageDesignIntf::selectionContainsBand(){ - foreach(QGraphicsItem * item,selectedItems()){ - BandDesignIntf *band = dynamic_cast(item); - if (band) return true; +bool PageDesignIntf::selectionContainsBand() +{ + foreach (QGraphicsItem* item, selectedItems()) { + BandDesignIntf* band = dynamic_cast(item); + if (band) + return true; } return false; } @@ -1498,12 +1501,14 @@ void PageDesignIntf::alignToLeft() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked()) { QRectF oldGeometry = bdItem->geometry(); - bdItem->setPos(QPointF(moveInBand ? 0 : m_firstSelectedItem->pos().x(), item->pos().y())); - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + bdItem->setPos( + QPointF(moveInBand ? 0 : m_firstSelectedItem->pos().x(), item->pos().y())); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1516,19 +1521,21 @@ void PageDesignIntf::alignToRigth() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked() && !bdItem->isBand()) { QRectF oldGeometry = bdItem->geometry(); - if (moveInBand && dynamic_cast(bdItem->parent())) - { - bdItem->setPos(QPointF(dynamic_cast(bdItem->parent())->geometry().width() - bdItem->width(), - bdItem->pos().y())); + if (moveInBand && dynamic_cast(bdItem->parent())) { + bdItem->setPos( + QPointF(dynamic_cast(bdItem->parent())->geometry().width() + - bdItem->width(), + bdItem->pos().y())); } else { qreal x = m_firstSelectedItem->geometry().right() - bdItem->width(); - bdItem->setPos(QPointF(x+1, bdItem->pos().y())); + bdItem->setPos(QPointF(x + 1, bdItem->pos().y())); } - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1541,18 +1548,23 @@ void PageDesignIntf::alignToVCenter() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked() && !bdItem->isBand()) { QRectF oldGeometry = bdItem->geometry(); - if (moveInBand && dynamic_cast(bdItem->parent())){ - bdItem->setPos(QPointF((dynamic_cast(bdItem->parent())->geometry().width() / 2) - bdItem->width() / 2, - bdItem->pos().y())); + if (moveInBand && dynamic_cast(bdItem->parent())) { + bdItem->setPos(QPointF( + (dynamic_cast(bdItem->parent())->geometry().width() / 2) + - bdItem->width() / 2, + bdItem->pos().y())); } else { - qreal x = (m_firstSelectedItem->geometry().right() - m_firstSelectedItem->width() / 2) - bdItem->width() / 2; - bdItem->setPos(QPointF(x+1, bdItem->pos().y())); + qreal x = (m_firstSelectedItem->geometry().right() + - m_firstSelectedItem->width() / 2) + - bdItem->width() / 2; + bdItem->setPos(QPointF(x + 1, bdItem->pos().y())); } - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1565,16 +1577,17 @@ void PageDesignIntf::alignToTop() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked() && !bdItem->isBand()) { QRectF oldGeometry = bdItem->geometry(); - if (moveInBand){ + if (moveInBand) { bdItem->setPos(QPointF(0, m_firstSelectedItem->pos().y())); } else { bdItem->setPos(QPointF(bdItem->pos().x(), m_firstSelectedItem->pos().y())); } - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1587,17 +1600,20 @@ void PageDesignIntf::alignToBottom() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked() && !bdItem->isBand()) { QRectF oldGeometry = bdItem->geometry(); - if (moveInBand && dynamic_cast(bdItem->parent())){ - bdItem->setPos(QPointF(bdItem->pos().x(), dynamic_cast(bdItem->parent())->height() - bdItem->height())); + if (moveInBand && dynamic_cast(bdItem->parent())) { + bdItem->setPos(QPointF(bdItem->pos().x(), + dynamic_cast(bdItem->parent())->height() + - bdItem->height())); } else { qreal y = m_firstSelectedItem->geometry().bottom() - bdItem->height(); - bdItem->setPos(QPointF(bdItem->pos().x(), y+1)); + bdItem->setPos(QPointF(bdItem->pos().x(), y + 1)); } - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1610,17 +1626,23 @@ void PageDesignIntf::alignToHCenter() if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); bool moveInBand = selectionContainsBand(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked() && !bdItem->isBand()) { QRectF oldGeometry = bdItem->geometry(); - if (moveInBand && dynamic_cast(bdItem->parent())){ - bdItem->setPos(QPointF(bdItem->pos().x(), (dynamic_cast(bdItem->parent())->height() / 2) - bdItem->height() / 2)); + if (moveInBand && dynamic_cast(bdItem->parent())) { + bdItem->setPos( + QPointF(bdItem->pos().x(), + (dynamic_cast(bdItem->parent())->height() / 2) + - bdItem->height() / 2)); } else { - qreal y = (m_firstSelectedItem->geometry().bottom() - m_firstSelectedItem->height() / 2) - bdItem->height() / 2; - bdItem->setPos(QPointF(bdItem->pos().x(), y+1)); + qreal y = (m_firstSelectedItem->geometry().bottom() + - m_firstSelectedItem->height() / 2) + - bdItem->height() / 2; + bdItem->setPos(QPointF(bdItem->pos().x(), y + 1)); } - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1632,12 +1654,13 @@ void PageDesignIntf::sameWidth() { if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked()) { QRectF oldGeometry = bdItem->geometry(); bdItem->setWidth(m_firstSelectedItem->width()); - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1649,12 +1672,13 @@ void PageDesignIntf::sameHeight() { if ((selectedItems().count() > 0) && m_firstSelectedItem) { CommandGroup::Ptr cm = CommandGroup::create(); - foreach(QGraphicsItem * item, selectedItems()) { - BaseDesignIntf *bdItem = dynamic_cast(item); + foreach (QGraphicsItem* item, selectedItems()) { + BaseDesignIntf* bdItem = dynamic_cast(item); if (bdItem && !bdItem->isGeometryLocked()) { QRectF oldGeometry = bdItem->geometry(); bdItem->setHeight(m_firstSelectedItem->height()); - CommandIf::Ptr command = PropertyChangedCommand::create(this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); + CommandIf::Ptr command = PropertyChangedCommand::create( + this, bdItem->objectName(), "geometry", oldGeometry, bdItem->geometry()); cm->addCommand(command, false); } } @@ -1665,117 +1689,121 @@ void PageDesignIntf::sameHeight() void PageDesignIntf::addHLayout() { - if (selectedItems().isEmpty()) return; + if (selectedItems().isEmpty()) + return; - QList si = selectedItems(); - QList::iterator it = si.begin(); + QList si = selectedItems(); + QList::iterator it = si.begin(); int itemsCount = 0; for (; it != si.end();) { - if (dynamic_cast(*it)){ + if (dynamic_cast(*it)) { itemsCount++; break; } ++it; }; - if (itemsCount == 0) return; + if (itemsCount == 0) + return; for (; it != si.end();) { - if (!dynamic_cast(*it)) { + if (!dynamic_cast(*it)) { (*it)->setSelected(false); it = si.erase(it); - } - else ++it; + } else + ++it; } - if (!si.isEmpty()){ + if (!si.isEmpty()) { it = si.begin(); QGraphicsItem* elementsParent = (*it)->parentItem(); - for (; it != si.end();++it) { - if ((*it)->parentItem()!=elementsParent){ - QMessageBox::information(0,QObject::tr("Attention!"),QObject::tr("Selected elements have different parent containers")); + for (; it != si.end(); ++it) { + if ((*it)->parentItem() != elementsParent) { + QMessageBox::information( + 0, QObject::tr("Attention!"), + QObject::tr("Selected elements have different parent containers")); return; } } CommandIf::Ptr cm = InsertHLayoutCommand::create(this); - saveCommand(cm,true); + saveCommand(cm, true); } - - } void PageDesignIntf::addVLayout() { - if (selectedItems().isEmpty()) return; + if (selectedItems().isEmpty()) + return; - QList si = selectedItems(); - QList::iterator it = si.begin(); + QList si = selectedItems(); + QList::iterator it = si.begin(); int itemsCount = 0; for (; it != si.end();) { - if (dynamic_cast(*it)){ + if (dynamic_cast(*it)) { itemsCount++; break; } ++it; }; - if (itemsCount == 0) return; + if (itemsCount == 0) + return; for (; it != si.end();) { - if (!dynamic_cast(*it)) { + if (!dynamic_cast(*it)) { (*it)->setSelected(false); it = si.erase(it); - } - else ++it; + } else + ++it; } - if (!si.isEmpty()){ + if (!si.isEmpty()) { it = si.begin(); QGraphicsItem* elementsParent = (*it)->parentItem(); - for (; it != si.end();++it) { - if ((*it)->parentItem()!=elementsParent){ - QMessageBox::information(0,QObject::tr("Attention!"),QObject::tr("Selected elements have different parent containers")); + for (; it != si.end(); ++it) { + if ((*it)->parentItem() != elementsParent) { + QMessageBox::information( + 0, QObject::tr("Attention!"), + QObject::tr("Selected elements have different parent containers")); return; } } CommandIf::Ptr cm = InsertVLayoutCommand::create(this); - saveCommand(cm,true); + saveCommand(cm, true); } } -bool hLayoutLessThen(QGraphicsItem *c1, QGraphicsItem *c2) -{ - return c1->pos().x() < c2->pos().x(); -} +bool hLayoutLessThen(QGraphicsItem* c1, QGraphicsItem* c2) { return c1->pos().x() < c2->pos().x(); } HorizontalLayout* PageDesignIntf::internalAddHLayout() { if (m_firstSelectedItem && (selectedItems().count() > 1)) { - QList si = selectedItems(); - QList::iterator it = si.begin(); + QList si = selectedItems(); + QList::iterator it = si.begin(); std::sort(si.begin(), si.end(), hLayoutLessThen); it = si.begin(); if (si.count() > 1) { it = si.begin(); - ItemDesignIntf *firstElement = dynamic_cast(*it); + ItemDesignIntf* firstElement = dynamic_cast(*it); - HorizontalLayout *layout = new HorizontalLayout(firstElement->parent(), firstElement->parentItem()); + HorizontalLayout* layout + = new HorizontalLayout(firstElement->parent(), firstElement->parentItem()); layout->setItemLocation(firstElement->itemLocation()); layout->setPos(firstElement->pos()); layout->setWidth(0); layout->setHeight(firstElement->height()); for (; it != si.end(); ++it) { - BaseDesignIntf *bdItem = dynamic_cast(*it); + BaseDesignIntf* bdItem = dynamic_cast(*it); layout->addChild(bdItem); } - foreach(QGraphicsItem * item, selectedItems()) { + foreach (QGraphicsItem* item, selectedItems()) { item->setSelected(false); } @@ -1789,37 +1817,35 @@ HorizontalLayout* PageDesignIntf::internalAddHLayout() return 0; } -bool vLayoutLessThen(QGraphicsItem *c1, QGraphicsItem *c2) -{ - return c1->pos().y() < c2->pos().y(); -} +bool vLayoutLessThen(QGraphicsItem* c1, QGraphicsItem* c2) { return c1->pos().y() < c2->pos().y(); } VerticalLayout* PageDesignIntf::internalAddVLayout() { if (m_firstSelectedItem && (selectedItems().count() > 1)) { - QList si = selectedItems(); - QList::iterator it = si.begin(); + QList si = selectedItems(); + QList::iterator it = si.begin(); std::sort(si.begin(), si.end(), vLayoutLessThen); it = si.begin(); if (si.count() > 1) { it = si.begin(); - ItemDesignIntf *firstElement = dynamic_cast(*it); + ItemDesignIntf* firstElement = dynamic_cast(*it); - VerticalLayout *layout = new VerticalLayout(firstElement->parent(), firstElement->parentItem()); + VerticalLayout* layout + = new VerticalLayout(firstElement->parent(), firstElement->parentItem()); layout->setItemLocation(firstElement->itemLocation()); layout->setPos(firstElement->pos()); layout->setWidth(firstElement->width()); layout->setHeight(0); for (; it != si.end(); ++it) { - BaseDesignIntf *bdItem = dynamic_cast(*it); + BaseDesignIntf* bdItem = dynamic_cast(*it); layout->addChild(bdItem); } - foreach(QGraphicsItem * item, selectedItems()) { + foreach (QGraphicsItem* item, selectedItems()) { item->setSelected(false); } @@ -1833,14 +1859,11 @@ VerticalLayout* PageDesignIntf::internalAddVLayout() return 0; } -void PageDesignIntf::setFont(const QFont& font) -{ - changeSelectedGroupProperty("font",font); -} +void PageDesignIntf::setFont(const QFont& font) { changeSelectedGroupProperty("font", font); } void PageDesignIntf::setTextAlign(const Qt::Alignment& alignment) { - changeSelectedGroupProperty("alignment",QVariant(alignment)); + changeSelectedGroupProperty("alignment", QVariant(alignment)); } void PageDesignIntf::setBorders(const BaseDesignIntf::BorderLines& border) @@ -1848,11 +1871,10 @@ void PageDesignIntf::setBorders(const BaseDesignIntf::BorderLines& border) changeSelectedGroupProperty("borders", (int)border); } -void PageDesignIntf::setBordersExt( - const BaseDesignIntf::BorderLines& border, - const double borderWidth, - const LimeReport::BaseDesignIntf::BorderStyle style, - const QString color +void PageDesignIntf::setBordersExt(const BaseDesignIntf::BorderLines& border, + const double borderWidth, + const LimeReport::BaseDesignIntf::BorderStyle style, + const QString color ) { @@ -1864,24 +1886,25 @@ void PageDesignIntf::setBordersExt( void PageDesignIntf::lockSelectedItems() { - foreach(QGraphicsItem* graphicItem, selectedItems()){ + foreach (QGraphicsItem* graphicItem, selectedItems()) { BaseDesignIntf* item = dynamic_cast(graphicItem); - if (item) item->setProperty("geometryLocked", true); + if (item) + item->setProperty("geometryLocked", true); } } void PageDesignIntf::unlockSelectedItems() { - foreach(QGraphicsItem* graphicItem, selectedItems()){ + foreach (QGraphicsItem* graphicItem, selectedItems()) { BaseDesignIntf* item = dynamic_cast(graphicItem); - if (item) item->setProperty("geometryLocked", false); + if (item) + item->setProperty("geometryLocked", false); } } - void PageDesignIntf::selectOneLevelItems() { - foreach(QGraphicsItem* graphicItem, selectedItems()){ + foreach (QGraphicsItem* graphicItem, selectedItems()) { BaseDesignIntf* item = dynamic_cast(graphicItem->parentItem()); if (item) selectAllChildren(item); @@ -1898,50 +1921,54 @@ void PageDesignIntf::removeAllItems() void PageDesignIntf::setItemMode(BaseDesignIntf::ItemMode mode) { - if (m_itemMode != mode){ + if (m_itemMode != mode) { m_itemMode = mode; if (m_currentPage) { m_currentPage->setItemMode(mode); } else { - foreach(QGraphicsItem * item, items()) { - BaseDesignIntf *reportItem = dynamic_cast(item); + foreach (QGraphicsItem* item, items()) { + BaseDesignIntf* reportItem = dynamic_cast(item); if (reportItem) { reportItem->setItemMode(itemMode()); } } } - foreach(PageItemDesignIntf::Ptr page, m_reportPages){ + foreach (PageItemDesignIntf::Ptr page, m_reportPages) { page->setItemMode(mode); } } } -BaseDesignIntf* PageDesignIntf::reportItemByName(const QString &name) +BaseDesignIntf* PageDesignIntf::reportItemByName(const QString& name) { - foreach(QGraphicsItem * item, items()) { - BaseDesignIntf *bd = dynamic_cast(item); - if (bd && (bd->objectName().compare(name, Qt::CaseInsensitive) == 0)) return bd; + foreach (QGraphicsItem* item, items()) { + BaseDesignIntf* bd = dynamic_cast(item); + if (bd && (bd->objectName().compare(name, Qt::CaseInsensitive) == 0)) + return bd; } return 0; } -QList PageDesignIntf::reportItemsByName(const QString &name){ +QList PageDesignIntf::reportItemsByName(const QString& name) +{ QList result; - foreach(QGraphicsItem * item, items()) { - BaseDesignIntf *bd = dynamic_cast(item); - if (bd && (bd->objectName().compare(name, Qt::CaseInsensitive) == 0)) result.append(bd); + foreach (QGraphicsItem* item, items()) { + BaseDesignIntf* bd = dynamic_cast(item); + if (bd && (bd->objectName().compare(name, Qt::CaseInsensitive) == 0)) + result.append(bd); } return result; } -BandDesignIntf *PageDesignIntf::bandAt(QPointF pos) +BandDesignIntf* PageDesignIntf::bandAt(QPointF pos) { - BandDesignIntf *band=0; - foreach(QGraphicsItem * item, items(pos)) { - band = dynamic_cast(item); - if (band) break; + BandDesignIntf* band = 0; + foreach (QGraphicsItem* item, items(pos)) { + band = dynamic_cast(item); + if (band) + break; } return band; } @@ -1952,9 +1979,10 @@ void CommandIf::addCommand(Ptr command, bool execute) Q_UNUSED(execute) } -CommandIf::Ptr InsertItemCommand::create(PageDesignIntf *page, const QString &itemType, QPointF pos, QSizeF size) +CommandIf::Ptr InsertItemCommand::create(PageDesignIntf* page, const QString& itemType, QPointF pos, + QSizeF size) { - InsertItemCommand *command = new InsertItemCommand(); + InsertItemCommand* command = new InsertItemCommand(); command->setPage(page); command->setType(itemType); command->setPos(pos); @@ -1964,38 +1992,39 @@ CommandIf::Ptr InsertItemCommand::create(PageDesignIntf *page, const QString &it bool InsertItemCommand::doIt() { - BaseDesignIntf *item = page()->addReportItem(m_itemType, m_pos, m_size); - if (item) m_itemName = item->objectName(); + BaseDesignIntf* item = page()->addReportItem(m_itemType, m_pos, m_size); + if (item) + m_itemName = item->objectName(); return item != 0; } void InsertItemCommand::undoIt() { - BaseDesignIntf *item = page()->reportItemByName(m_itemName); - if (item){ - page()->removeReportItem(item,false); + BaseDesignIntf* item = page()->reportItemByName(m_itemName); + if (item) { + page()->removeReportItem(item, false); } -// page()->removeItem(item); -// delete item; + // page()->removeItem(item); + // delete item; } -CommandIf::Ptr DeleteItemCommand::create(PageDesignIntf *page, BaseDesignIntf *item) +CommandIf::Ptr DeleteItemCommand::create(PageDesignIntf* page, BaseDesignIntf* item) { - DeleteItemCommand *command = new DeleteItemCommand(); - //QScopedPointer writer(new XMLWriter()); - //writer->putItem(item); + DeleteItemCommand* command = new DeleteItemCommand(); + // QScopedPointer writer(new XMLWriter()); + // writer->putItem(item); command->setPage(page); command->setItem(item); LayoutDesignIntf* layout = dynamic_cast(item->parent()); if (layout) command->m_layoutName = layout->objectName(); - //command->m_itemXML = writer->saveToString(); + // command->m_itemXML = writer->saveToString(); return CommandIf::Ptr(command); } bool DeleteItemCommand::doIt() { - BaseDesignIntf *item = page()->reportItemByName(m_itemName); + BaseDesignIntf* item = page()->reportItemByName(m_itemName); if (item) { item->beforeDelete(); page()->removeItem(item); @@ -2008,25 +2037,27 @@ bool DeleteItemCommand::doIt() void DeleteItemCommand::undoIt() { - BaseDesignIntf *item = page()->createReportItem(m_itemType); + BaseDesignIntf* item = page()->createReportItem(m_itemType); ItemsReaderIntf::Ptr reader = StringXMLreader::create(m_itemXML); - if (reader->first()) reader->readItem(item); + if (reader->first()) + reader->readItem(item); BandDesignIntf* band = dynamic_cast(item); - if (band){ + if (band) { page()->pageItem()->increaseBandIndex(band->bandIndex()); } page()->registerItem(item); if (!m_layoutName.isEmpty()) { - LayoutDesignIntf* layout = dynamic_cast(page()->reportItemByName(m_layoutName)); - if (layout){ + LayoutDesignIntf* layout + = dynamic_cast(page()->reportItemByName(m_layoutName)); + if (layout) { layout->restoreChild(item); } page()->emitRegisterdItem(item); } } -void DeleteItemCommand::setItem(BaseDesignIntf *value) +void DeleteItemCommand::setItem(BaseDesignIntf* value) { m_itemName = value->objectName(); m_itemType = value->storageTypeName(); @@ -2035,12 +2066,12 @@ void DeleteItemCommand::setItem(BaseDesignIntf *value) m_itemXML = writer->saveToString(); } -CommandIf::Ptr DeleteLayoutCommand::create(PageDesignIntf *page, LayoutDesignIntf *item) +CommandIf::Ptr DeleteLayoutCommand::create(PageDesignIntf* page, LayoutDesignIntf* item) { DeleteLayoutCommand* command = new DeleteLayoutCommand(); command->setPage(page); command->setItem(item); - foreach (BaseDesignIntf* childItem, item->childBaseItems()){ + foreach (BaseDesignIntf* childItem, item->childBaseItems()) { command->m_childItems.append(childItem->objectName()); } LayoutDesignIntf* layout = dynamic_cast(item->parent()); @@ -2051,7 +2082,7 @@ CommandIf::Ptr DeleteLayoutCommand::create(PageDesignIntf *page, LayoutDesignInt bool DeleteLayoutCommand::doIt() { - BaseDesignIntf *item = page()->reportItemByName(m_itemName); + BaseDesignIntf* item = page()->reportItemByName(m_itemName); if (item) { item->beforeDelete(); QScopedPointer writer(new XMLWriter()); @@ -2067,19 +2098,21 @@ bool DeleteLayoutCommand::doIt() void DeleteLayoutCommand::undoIt() { - BaseDesignIntf *item = page()->addReportItem(m_itemType); + BaseDesignIntf* item = page()->addReportItem(m_itemType); ItemsReaderIntf::Ptr reader = StringXMLreader::create(m_itemXML); - if (reader->first()) reader->readItem(item); + if (reader->first()) + reader->readItem(item); if (!m_layoutName.isEmpty()) { - LayoutDesignIntf* layout = dynamic_cast(page()->reportItemByName(m_layoutName)); - if (layout){ + LayoutDesignIntf* layout + = dynamic_cast(page()->reportItemByName(m_layoutName)); + if (layout) { layout->restoreChild(item); } page()->emitRegisterdItem(item); } - foreach(QString ci, m_childItems){ + foreach (QString ci, m_childItems) { BaseDesignIntf* ri = page()->reportItemByName(ci); - if (ri){ + if (ri) { LayoutDesignIntf* parentLayout = dynamic_cast(ri->parent()); if (parentLayout) { parentLayout->removeChild(ri); @@ -2090,15 +2123,16 @@ void DeleteLayoutCommand::undoIt() } } -void DeleteLayoutCommand::setItem(BaseDesignIntf *item) +void DeleteLayoutCommand::setItem(BaseDesignIntf* item) { m_itemName = item->objectName(); m_itemType = item->storageTypeName(); } -CommandIf::Ptr PasteCommand::create(PageDesignIntf *page, const QString &itemsXML, BaseDesignIntf *parent) +CommandIf::Ptr PasteCommand::create(PageDesignIntf* page, const QString& itemsXML, + BaseDesignIntf* parent) { - PasteCommand *command = new PasteCommand(); + PasteCommand* command = new PasteCommand(); command->setPage(page); command->setItemsXML(itemsXML); command->setParent(parent); @@ -2119,11 +2153,11 @@ bool PasteCommand::doIt() insertItem(reader); } page()->endUpdate(); - } - else return false; + } else + return false; page()->selectedItems().clear(); - foreach(QString name, m_itemNames) { + foreach (QString name, m_itemNames) { page()->reportItemByName(name)->setSelected(true); } return m_itemNames.count() > 0; @@ -2131,33 +2165,31 @@ bool PasteCommand::doIt() void PasteCommand::undoIt() { - foreach(QString name, m_itemNames) { - BaseDesignIntf *item = page()->reportItemByName(name); + foreach (QString name, m_itemNames) { + BaseDesignIntf* item = page()->reportItemByName(name); page()->emitItemRemoved(item); page()->removeItem(item); delete item; } } -void PasteCommand::setItemsXML(const QString &itemsXML) -{ - m_itemsXML = itemsXML; -} +void PasteCommand::setItemsXML(const QString& itemsXML) { m_itemsXML = itemsXML; } bool PasteCommand::insertItem(ItemsReaderIntf::Ptr reader) { BaseDesignIntf* parentItem = page()->reportItemByName(m_parentItemName); - if (parentItem){ - BaseDesignIntf *item = page()->addReportItem(reader->itemClassName(), parentItem, parentItem); + if (parentItem) { + BaseDesignIntf* item + = page()->addReportItem(reader->itemClassName(), parentItem, parentItem); if (item) { QString objectName = item->objectName(); reader->readItem(item); item->setParent(parentItem); item->setParentItem(parentItem); - if (page()->reportItemsByName(item->objectName()).size()>1){ + if (page()->reportItemsByName(item->objectName()).size() > 1) { item->setObjectName(objectName); } - foreach (BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { changeName(page(), child); }; m_itemNames.push_back(item->objectName()); @@ -2167,22 +2199,22 @@ bool PasteCommand::insertItem(ItemsReaderIntf::Ptr reader) return false; } -void PasteCommand::changeName(PageDesignIntf *page, BaseDesignIntf* item) +void PasteCommand::changeName(PageDesignIntf* page, BaseDesignIntf* item) { item->setObjectName(page->genObjectName(*item)); - foreach(BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { changeName(page, child); }; } -CommandIf::Ptr CutCommand::create(PageDesignIntf *page) +CommandIf::Ptr CutCommand::create(PageDesignIntf* page) { - CutCommand *command = new CutCommand(); + CutCommand* command = new CutCommand(); command->setPage(page); - ItemsWriterIntf *writer = new XMLWriter(); - foreach(QGraphicsItem * item, page->selectedItems()) { - if (!dynamic_cast(item)){ - ItemDesignIntf *reportItem = dynamic_cast(item); + ItemsWriterIntf* writer = new XMLWriter(); + foreach (QGraphicsItem* item, page->selectedItems()) { + if (!dynamic_cast(item)) { + ItemDesignIntf* reportItem = dynamic_cast(item); if (reportItem) { command->m_itemNames.push_back(reportItem->objectName()); @@ -2193,7 +2225,7 @@ CommandIf::Ptr CutCommand::create(PageDesignIntf *page) command->setXML(writer->saveToString()); if (command->m_itemNames.count() > 0) { - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); clipboard->setText(writer->saveToString()); } @@ -2202,8 +2234,8 @@ CommandIf::Ptr CutCommand::create(PageDesignIntf *page) bool CutCommand::doIt() { - foreach(QString name, m_itemNames) { - BaseDesignIntf *item = page()->reportItemByName(name); + foreach (QString name, m_itemNames) { + BaseDesignIntf* item = page()->reportItemByName(name); page()->removeItem(item); page()->emitItemRemoved(item); delete item; @@ -2216,21 +2248,24 @@ void CutCommand::undoIt() ItemsReaderIntf::Ptr reader = StringXMLreader::create(m_itemsXML); if (reader->first()) { - BaseDesignIntf *item = page()->addReportItem(reader->itemClassName()); + BaseDesignIntf* item = page()->addReportItem(reader->itemClassName()); - if (item) reader->readItem(item); + if (item) + reader->readItem(item); while (reader->next()) { item = page()->addReportItem(reader->itemClassName()); - if (item) reader->readItem(item); + if (item) + reader->readItem(item); } } } -CommandIf::Ptr PosChangedCommand::create(PageDesignIntf *page, QVector &oldPos, QVector &newPos) +CommandIf::Ptr PosChangedCommand::create(PageDesignIntf* page, QVector& oldPos, + QVector& newPos) { - PosChangedCommand *command = new PosChangedCommand(); + PosChangedCommand* command = new PosChangedCommand(); command->setPage(page); command->m_newPos = newPos; command->m_oldPos = oldPos; @@ -2240,9 +2275,9 @@ CommandIf::Ptr PosChangedCommand::create(PageDesignIntf *page, QVectorreportItemByName(m_newPos[i].objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_newPos[i].objectName); - if (reportItem && (reportItem->pos() != m_newPos[i].pos)){ + if (reportItem && (reportItem->pos() != m_newPos[i].pos)) { QPointF oldValue = reportItem->pos(); reportItem->setPos(m_newPos[i].pos); reportItem->emitPosChanged(oldValue, reportItem->pos()); @@ -2255,9 +2290,9 @@ bool PosChangedCommand::doIt() void PosChangedCommand::undoIt() { for (int i = 0; i < m_oldPos.count(); i++) { - BaseDesignIntf *reportItem = page()->reportItemByName(m_oldPos[i].objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_oldPos[i].objectName); - if (reportItem && (reportItem->pos() != m_oldPos[i].pos)){ + if (reportItem && (reportItem->pos() != m_oldPos[i].pos)) { QPointF oldValue = reportItem->pos(); reportItem->setPos(m_oldPos[i].pos); reportItem->emitPosChanged(oldValue, reportItem->pos()); @@ -2265,9 +2300,10 @@ void PosChangedCommand::undoIt() } } -CommandIf::Ptr SizeChangedCommand::create(PageDesignIntf *page, QVector &oldSize, QVector &newSize) +CommandIf::Ptr SizeChangedCommand::create(PageDesignIntf* page, QVector& oldSize, + QVector& newSize) { - SizeChangedCommand *command = new SizeChangedCommand(); + SizeChangedCommand* command = new SizeChangedCommand(); command->setPage(page); command->m_newSize = newSize; command->m_oldSize = oldSize; @@ -2277,9 +2313,10 @@ CommandIf::Ptr SizeChangedCommand::create(PageDesignIntf *page, QVectorreportItemByName(m_newSize[i].objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_newSize[i].objectName); - if (reportItem && (reportItem->size() != m_newSize[i].size)) reportItem->setSize(m_newSize[i].size); + if (reportItem && (reportItem->size() != m_newSize[i].size)) + reportItem->setSize(m_newSize[i].size); } return true; @@ -2288,16 +2325,18 @@ bool SizeChangedCommand::doIt() void SizeChangedCommand::undoIt() { for (int i = 0; i < m_oldSize.count(); i++) { - BaseDesignIntf *reportItem = page()->reportItemByName(m_oldSize[i].objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_oldSize[i].objectName); - if (reportItem && (reportItem->size() != m_oldSize[i].size)) reportItem->setSize(m_oldSize[i].size); + if (reportItem && (reportItem->size() != m_oldSize[i].size)) + reportItem->setSize(m_oldSize[i].size); } } -CommandIf::Ptr PropertyChangedCommand::create(PageDesignIntf *page, const QString &objectName, const QString &propertyName, - const QVariant &oldValue, const QVariant &newValue) +CommandIf::Ptr PropertyChangedCommand::create(PageDesignIntf* page, const QString& objectName, + const QString& propertyName, const QVariant& oldValue, + const QVariant& newValue) { - PropertyChangedCommand *command = new PropertyChangedCommand(); + PropertyChangedCommand* command = new PropertyChangedCommand(); command->setPage(page); command->m_objectName = objectName; command->m_propertyName = propertyName; @@ -2308,7 +2347,7 @@ CommandIf::Ptr PropertyChangedCommand::create(PageDesignIntf *page, const QStrin bool PropertyChangedCommand::doIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_objectName); if (reportItem && (reportItem->property(m_propertyName.toLatin1()) != m_newValue)) { reportItem->setProperty(m_propertyName.toLatin1(), m_newValue); @@ -2319,22 +2358,22 @@ bool PropertyChangedCommand::doIt() void PropertyChangedCommand::undoIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_objectName); if (reportItem && (reportItem->property(m_propertyName.toLatin1()) != m_oldValue)) { reportItem->setProperty(m_propertyName.toLatin1(), m_oldValue); } } -CommandIf::Ptr InsertBandCommand::create(PageDesignIntf *page, const QString &bandName) +CommandIf::Ptr InsertBandCommand::create(PageDesignIntf* page, const QString& bandName) { - InsertBandCommand *command = new InsertBandCommand(); + InsertBandCommand* command = new InsertBandCommand(); command->setPage(page); - BandDesignIntf *band = dynamic_cast(page->reportItemByName(bandName)); + BandDesignIntf* band = dynamic_cast(page->reportItemByName(bandName)); command->m_bandType = band->bandType(); command->m_bandName = band->objectName(); if (band->parentBand()) - command->m_parentBandName = band->parentBandName(); + command->m_parentBandName = band->parentBandName(); return CommandIf::Ptr(command); } @@ -2342,7 +2381,7 @@ bool InsertBandCommand::doIt() { if (!m_parentBandName.isEmpty() && page()->reportItemByName(m_parentBandName)) page()->reportItemByName(m_parentBandName)->setSelected(true); - BaseDesignIntf *item = page()->addBand(m_bandType); + BaseDesignIntf* item = page()->addBand(m_bandType); if (item) { m_bandName = item->objectName(); @@ -2354,21 +2393,18 @@ bool InsertBandCommand::doIt() void InsertBandCommand::undoIt() { - BaseDesignIntf *item = page()->reportItemByName(m_bandName); + BaseDesignIntf* item = page()->reportItemByName(m_bandName); if (item) { - page()->removeReportItem(item,false); + page()->removeReportItem(item, false); } } -CommandIf::Ptr CommandGroup::create() -{ - return CommandIf::Ptr(new CommandGroup); -} +CommandIf::Ptr CommandGroup::create() { return CommandIf::Ptr(new CommandGroup); } bool CommandGroup::doIt() { - foreach(CommandIf::Ptr command, m_commands) { + foreach (CommandIf::Ptr command, m_commands) { if (!command->doIt()) return false; } @@ -2377,39 +2413,42 @@ bool CommandGroup::doIt() void CommandGroup::undoIt() { - foreach(CommandIf::Ptr command, m_commands) { + foreach (CommandIf::Ptr command, m_commands) { command->undoIt(); } } void CommandGroup::addCommand(CommandIf::Ptr command, bool execute) { - if (execute){ + if (execute) { if (command->doIt()) m_commands.append(command); } else m_commands.append(command); } -PrintRange::PrintRange(QAbstractPrintDialog::PrintRange rangeType, int fromPage, int toPage) - :m_rangeType(rangeType), m_fromPage(fromPage), m_toPage(toPage) -{} - -CommandIf::Ptr InsertHLayoutCommand::create(PageDesignIntf *page) +PrintRange::PrintRange(QAbstractPrintDialog::PrintRange rangeType, int fromPage, int toPage): + m_rangeType(rangeType), + m_fromPage(fromPage), + m_toPage(toPage) { - InsertHLayoutCommand *command = new InsertHLayoutCommand(); +} + +CommandIf::Ptr InsertHLayoutCommand::create(PageDesignIntf* page) +{ + InsertHLayoutCommand* command = new InsertHLayoutCommand(); command->setPage(page); - QList si = page->selectedItems(); - QList::iterator it = si.begin(); + QList si = page->selectedItems(); + QList::iterator it = si.begin(); BaseDesignIntf* parentItem = dynamic_cast((*it)->parentItem()); - command->m_oldParentName = (parentItem)?(parentItem->objectName()):""; + command->m_oldParentName = (parentItem) ? (parentItem->objectName()) : ""; - for(it = si.begin();it!=si.end();++it){ + for (it = si.begin(); it != si.end(); ++it) { BaseDesignIntf* bi = dynamic_cast(*it); if (bi) - command->m_elements.insert(bi->objectName(),bi->pos()); + command->m_elements.insert(bi->objectName(), bi->pos()); } return CommandIf::Ptr(command); @@ -2420,7 +2459,7 @@ bool InsertHLayoutCommand::doIt() foreach (QString itemName, m_elements.keys()) { BaseDesignIntf* bi = page()->reportItemByName(itemName); if (bi) - bi->setSelected(true); + bi->setSelected(true); } LayoutDesignIntf* layout = page()->internalAddHLayout(); if (layout) @@ -2430,12 +2469,13 @@ bool InsertHLayoutCommand::doIt() void InsertHLayoutCommand::undoIt() { - HorizontalLayout* layout = dynamic_cast(page()->reportItemByName(m_layoutName)); - if (layout){ - foreach(QGraphicsItem* item, layout->childBaseItems()){ + HorizontalLayout* layout + = dynamic_cast(page()->reportItemByName(m_layoutName)); + if (layout) { + foreach (QGraphicsItem* item, layout->childBaseItems()) { BaseDesignIntf* bi = dynamic_cast(item); BaseDesignIntf* parent = page()->reportItemByName(m_oldParentName); - if (bi && parent){ + if (bi && parent) { bi->setParentItem(parent); bi->setParent(parent); bi->setPos(m_elements.value(bi->objectName())); @@ -2444,13 +2484,15 @@ void InsertHLayoutCommand::undoIt() bi->setVisible(true); } } - page()->removeReportItem(layout,false); + page()->removeReportItem(layout, false); } } -CommandIf::Ptr PropertyObjectNameChangedCommand::create(PageDesignIntf *page, const QString &oldValue, const QString &newValue) +CommandIf::Ptr PropertyObjectNameChangedCommand::create(PageDesignIntf* page, + const QString& oldValue, + const QString& newValue) { - PropertyObjectNameChangedCommand *command = new PropertyObjectNameChangedCommand(); + PropertyObjectNameChangedCommand* command = new PropertyObjectNameChangedCommand(); command->setPage(page); command->m_oldName = oldValue; command->m_newName = newValue; @@ -2459,11 +2501,11 @@ CommandIf::Ptr PropertyObjectNameChangedCommand::create(PageDesignIntf *page, co bool PropertyObjectNameChangedCommand::doIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_oldName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_oldName); - if (reportItem ) { + if (reportItem) { reportItem->setObjectName(m_newName); - reportItem->emitObjectNamePropertyChanged(m_oldName,m_newName); + reportItem->emitObjectNamePropertyChanged(m_oldName, m_newName); return true; } return false; @@ -2471,27 +2513,28 @@ bool PropertyObjectNameChangedCommand::doIt() void PropertyObjectNameChangedCommand::undoIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_newName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_newName); - if (reportItem ) { + if (reportItem) { reportItem->setObjectName(m_oldName); - reportItem->emitObjectNamePropertyChanged(m_newName,m_oldName); + reportItem->emitObjectNamePropertyChanged(m_newName, m_oldName); } - } -CommandIf::Ptr PropertyItemAlignChangedCommand::create(PageDesignIntf *page, const QString &objectName, - BaseDesignIntf::ItemAlign oldValue, BaseDesignIntf::ItemAlign newValue) +CommandIf::Ptr PropertyItemAlignChangedCommand::create(PageDesignIntf* page, + const QString& objectName, + BaseDesignIntf::ItemAlign oldValue, + BaseDesignIntf::ItemAlign newValue) { - PropertyItemAlignChangedCommand *command = new PropertyItemAlignChangedCommand(); + PropertyItemAlignChangedCommand* command = new PropertyItemAlignChangedCommand(); command->setPage(page); command->m_objectName = objectName; command->m_propertyName = "itemAlign"; command->m_oldValue = oldValue; command->m_newValue = newValue; - BaseDesignIntf *reportItem = page->reportItemByName(objectName); - if (oldValue == BaseDesignIntf::DesignedItemAlign){ + BaseDesignIntf* reportItem = page->reportItemByName(objectName); + if (oldValue == BaseDesignIntf::DesignedItemAlign) { command->m_savedPos = reportItem->pos(); } @@ -2500,7 +2543,7 @@ CommandIf::Ptr PropertyItemAlignChangedCommand::create(PageDesignIntf *page, con bool PropertyItemAlignChangedCommand::doIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_objectName); if (reportItem && (reportItem->property(m_propertyName.toLatin1()) != m_newValue)) { reportItem->setProperty(m_propertyName.toLatin1(), m_newValue); @@ -2511,90 +2554,84 @@ bool PropertyItemAlignChangedCommand::doIt() void PropertyItemAlignChangedCommand::undoIt() { - BaseDesignIntf *reportItem = page()->reportItemByName(m_objectName); + BaseDesignIntf* reportItem = page()->reportItemByName(m_objectName); if (reportItem && (reportItem->property(m_propertyName.toLatin1()) != m_oldValue)) { reportItem->setProperty(m_propertyName.toLatin1(), m_oldValue); } - if (reportItem && (m_oldValue == BaseDesignIntf::DesignedItemAlign)){ + if (reportItem && (m_oldValue == BaseDesignIntf::DesignedItemAlign)) { reportItem->setPos(m_savedPos); } } bool Projection::intersect(Projection projection) { - if ( - (projection.start()>=start() && projection.start()<=end()) || - (projection.end()>=start() && projection.end()<=end()) || - (projection.start()<=start() && projection.end()>=end()) - ) return true; + if ((projection.start() >= start() && projection.start() <= end()) + || (projection.end() >= start() && projection.end() <= end()) + || (projection.start() <= start() && projection.end() >= end())) + return true; return false; } -qreal Projection::start() const -{ - return m_start; -} +qreal Projection::start() const { return m_start; } -qreal Projection::end() const -{ - return m_end; -} +qreal Projection::end() const { return m_end; } bool ItemProjections::intersect(QRectF rect) { - Projection xProjection(rect.x(),rect.x()+rect.width()); - Projection yProjection(rect.y(),rect.y()+rect.height()); + Projection xProjection(rect.x(), rect.x() + rect.width()); + Projection yProjection(rect.y(), rect.y() + rect.height()); if (m_xProjection.intersect(xProjection) && m_yProjection.intersect(yProjection)) return true; return false; } -bool ItemProjections::intersect(BaseDesignIntf *item) +bool ItemProjections::intersect(BaseDesignIntf* item) { return intersect(QRectF(item->pos().x(), item->pos().y(), item->width(), item->height())); } -qreal lineLength(qreal start, qreal end, Projection p){ +qreal lineLength(qreal start, qreal end, Projection p) +{ qreal result = 0; - if (start>=p.start() && end<=p.end()) + if (start >= p.start() && end <= p.end()) result = end - start; - if (start>=p.start() && start<=p.end()) + if (start >= p.start() && start <= p.end()) result = p.end() - start; - else if (end>=p.start() && end<=p.end()) - result = end-p.start(); - else if (start<=p.start() && end>=p.end()) + else if (end >= p.start() && end <= p.end()) + result = end - p.start(); + else if (start <= p.start() && end >= p.end()) result = p.end() - p.start(); return result; } qreal ItemProjections::square(QRectF rect) { - qreal a = lineLength(rect.left(),rect.right(),m_xProjection); - qreal b = lineLength(rect.top(),rect.bottom(),m_yProjection); - return a*b; + qreal a = lineLength(rect.left(), rect.right(), m_xProjection); + qreal b = lineLength(rect.top(), rect.bottom(), m_yProjection); + return a * b; } -qreal ItemProjections::square(BaseDesignIntf *item) +qreal ItemProjections::square(BaseDesignIntf* item) { - return square(QRectF(item->pos().x(),item->pos().y(),item->width(),item->height())); + return square(QRectF(item->pos().x(), item->pos().y(), item->width(), item->height())); } CommandIf::Ptr InsertVLayoutCommand::create(PageDesignIntf* page) { - InsertVLayoutCommand *command = new InsertVLayoutCommand(); + InsertVLayoutCommand* command = new InsertVLayoutCommand(); command->setPage(page); - QList si = page->selectedItems(); - QList::iterator it = si.begin(); + QList si = page->selectedItems(); + QList::iterator it = si.begin(); BaseDesignIntf* parentItem = dynamic_cast((*it)->parentItem()); - command->m_oldParentName = (parentItem)?(parentItem->objectName()):""; + command->m_oldParentName = (parentItem) ? (parentItem->objectName()) : ""; - for(it = si.begin();it!=si.end();++it){ + for (it = si.begin(); it != si.end(); ++it) { BaseDesignIntf* bi = dynamic_cast(*it); if (bi) - command->m_elements.insert(bi->objectName(),bi->pos()); + command->m_elements.insert(bi->objectName(), bi->pos()); } return CommandIf::Ptr(command); @@ -2605,7 +2642,7 @@ bool InsertVLayoutCommand::doIt() foreach (QString itemName, m_elements.keys()) { BaseDesignIntf* bi = page()->reportItemByName(itemName); if (bi) - bi->setSelected(true); + bi->setSelected(true); } LayoutDesignIntf* layout = page()->internalAddVLayout(); if (layout) @@ -2616,11 +2653,11 @@ bool InsertVLayoutCommand::doIt() void InsertVLayoutCommand::undoIt() { VerticalLayout* layout = dynamic_cast(page()->reportItemByName(m_layoutName)); - if (layout){ - foreach(QGraphicsItem* item, layout->childBaseItems()){ + if (layout) { + foreach (QGraphicsItem* item, layout->childBaseItems()) { BaseDesignIntf* bi = dynamic_cast(item); BaseDesignIntf* parent = page()->reportItemByName(m_oldParentName); - if (bi && parent){ + if (bi && parent) { bi->setParentItem(parent); bi->setParent(parent); bi->setPos(m_elements.value(bi->objectName())); @@ -2629,13 +2666,14 @@ void InsertVLayoutCommand::undoIt() bi->setVisible(true); } } - page()->removeReportItem(layout,false); + page()->removeReportItem(layout, false); } } -CommandIf::Ptr BandSwapCommand::create(PageDesignIntf *page, const QString &bandName, const QString &bandToSwapName) +CommandIf::Ptr BandSwapCommand::create(PageDesignIntf* page, const QString& bandName, + const QString& bandToSwapName) { - BandSwapCommand *command = new BandSwapCommand(); + BandSwapCommand* command = new BandSwapCommand(); command->setPage(page); command->bandName = bandName; command->bandToSwapName = bandToSwapName; @@ -2645,8 +2683,9 @@ CommandIf::Ptr BandSwapCommand::create(PageDesignIntf *page, const QString &band bool BandSwapCommand::doIt() { BandDesignIntf* band = dynamic_cast(page()->reportItemByName(bandName)); - BandDesignIntf* bandToSwap = dynamic_cast(page()->reportItemByName(bandToSwapName)); - if (page() && band && bandToSwap){ + BandDesignIntf* bandToSwap + = dynamic_cast(page()->reportItemByName(bandToSwapName)); + if (page() && band && bandToSwap) { page()->pageItem()->swapBands(band, bandToSwap); return true; } @@ -2656,7 +2695,8 @@ bool BandSwapCommand::doIt() void BandSwapCommand::undoIt() { BandDesignIntf* band = dynamic_cast(page()->reportItemByName(bandName)); - BandDesignIntf* bandToSwap = dynamic_cast(page()->reportItemByName(bandToSwapName)); + BandDesignIntf* bandToSwap + = dynamic_cast(page()->reportItemByName(bandToSwapName)); if (page() && band && bandToSwap) page()->pageItem()->swapBands(bandToSwap, band); } @@ -2675,7 +2715,7 @@ bool BandMoveFromToCommand::doIt() if (page() && page()->pageItem() && from != to) { BandDesignIntf* fromBand = page()->pageItem()->bandByIndex(from); reverceTo = fromBand->minChildIndex(); - if (fromBand){ + if (fromBand) { page()->pageItem()->moveBandFromTo(from, to); reverceFrom = fromBand->bandIndex(); return true; @@ -2690,5 +2730,4 @@ void BandMoveFromToCommand::undoIt() page()->pageItem()->moveBandFromTo(reverceFrom, reverceTo); } -} - +} // namespace LimeReport diff --git a/limereport/lrpagedesignintf.h b/limereport/lrpagedesignintf.h index fe3209d..35675e6 100644 --- a/limereport/lrpagedesignintf.h +++ b/limereport/lrpagedesignintf.h @@ -30,518 +30,549 @@ #ifndef LRPAGEDEDIGNITF_H #define LRPAGEDEDIGNITF_H +#include "lrbanddesignintf.h" +#include "lrpageitemdesignintf.h" +#include "serializators/lrstorageintf.h" + #include #include -#include "lrpageitemdesignintf.h" -#include "serializators/lrstorageintf.h" -#include "lrbanddesignintf.h" - namespace LimeReport { - class BaseDesignIntf; - class ReportEnginePrivate; - class PropertyChangedCommand; - class HorizontalLayout; - class VerticalLayout; - class LayoutDesignIntf; +class BaseDesignIntf; +class ReportEnginePrivate; +class PropertyChangedCommand; +class HorizontalLayout; +class VerticalLayout; +class LayoutDesignIntf; - class CommandIf { - public: - virtual ~CommandIf(){} - typedef QSharedPointer Ptr; - virtual bool doIt() = 0; - virtual void undoIt() = 0; - virtual void addCommand(CommandIf::Ptr command,bool execute); - }; +class CommandIf { +public: + virtual ~CommandIf() { } + typedef QSharedPointer Ptr; + virtual bool doIt() = 0; + virtual void undoIt() = 0; + virtual void addCommand(CommandIf::Ptr command, bool execute); +}; - typedef QList::const_iterator BandsIterator; +typedef QList::const_iterator BandsIterator; - struct ReportItemPos{ - QString objectName; - QPointF pos; - }; +struct ReportItemPos { + QString objectName; + QPointF pos; +}; - struct ReportItemSize{ - QString objectName; - QSizeF size; - }; +struct ReportItemSize { + QString objectName; + QSizeF size; +}; - class Projection{ - public: - Projection(qreal start, qreal end) - :m_start(start),m_end(end){} - bool intersect(Projection projection); - qreal start() const; - qreal end() const; - private: - qreal m_start; - qreal m_end; - }; +class Projection { +public: + Projection(qreal start, qreal end): m_start(start), m_end(end) { } + bool intersect(Projection projection); + qreal start() const; + qreal end() const; - class ItemProjections{ - public: - ItemProjections(BaseDesignIntf* item) - :m_xProjection(item->pos().x(), item->pos().x()+item->width()), - m_yProjection(item->pos().y(), item->pos().y()+item->height()), - m_item(item) - {} - bool intersect(QRectF rect); - bool intersect(BaseDesignIntf* item); - qreal square(QRectF rect); - qreal square(BaseDesignIntf* item); - BaseDesignIntf* item(){return m_item;} - private: - Projection m_xProjection; - Projection m_yProjection; - BaseDesignIntf* m_item; - }; +private: + qreal m_start; + qreal m_end; +}; - class PageDesignIntf : public QGraphicsScene, public ObjectLoadingStateIntf{ - Q_OBJECT - Q_PROPERTY(QObject* pageItem READ pageItem) - public: - friend class PropertyChangedCommand; - friend class InsertHLayoutCommand; - friend class InsertVLayoutCommand; - explicit PageDesignIntf(QObject* parent = 0); - ~PageDesignIntf(); - void updatePageRect(); - void startInsertMode(const QString& ItemType); - void startEditMode(); +class ItemProjections { +public: + ItemProjections(BaseDesignIntf* item): + m_xProjection(item->pos().x(), item->pos().x() + item->width()), + m_yProjection(item->pos().y(), item->pos().y() + item->height()), + m_item(item) + { + } + bool intersect(QRectF rect); + bool intersect(BaseDesignIntf* item); + qreal square(QRectF rect); + qreal square(BaseDesignIntf* item); + BaseDesignIntf* item() { return m_item; } - PageItemDesignIntf *pageItem(); - void setPageItem(PageItemDesignIntf::Ptr pageItem); - void setPageItems(QList pages); - void removePageItem(PageItemDesignIntf::Ptr pageItem); - QList pageItems(){return m_reportPages;} +private: + Projection m_xProjection; + Projection m_yProjection; + BaseDesignIntf* m_item; +}; - bool isItemInsertMode(); - ReportEnginePrivate* reportEditor(); - void setReportEditor(ReportEnginePrivate* value){m_reportEditor=value;} +class PageDesignIntf: public QGraphicsScene, public ObjectLoadingStateIntf { + Q_OBJECT + Q_PROPERTY(QObject* pageItem READ pageItem) +public: + friend class PropertyChangedCommand; + friend class InsertHLayoutCommand; + friend class InsertVLayoutCommand; + explicit PageDesignIntf(QObject* parent = 0); + ~PageDesignIntf(); + void updatePageRect(); + void startInsertMode(const QString& ItemType); + void startEditMode(); - QStringList possibleParentItems(); - void registerItem(BaseDesignIntf* item); - void registerBand(BandDesignIntf* band); - void removeAllItems(); + PageItemDesignIntf* pageItem(); + void setPageItem(PageItemDesignIntf::Ptr pageItem); + void setPageItems(QList pages); + void removePageItem(PageItemDesignIntf::Ptr pageItem); + QList pageItems() { return m_reportPages; } - void setItemMode(BaseDesignIntf::ItemMode state); - BaseDesignIntf::ItemMode itemMode(){return m_itemMode;} - BaseDesignIntf* reportItemByName(const QString& name); - QList reportItemsByName(const QString &name); - BandDesignIntf* bandAt(QPointF pos); - BaseDesignIntf* addReportItem(const QString& itemType, QPointF pos, QSizeF size); - BaseDesignIntf* addReportItem(const QString& itemType, QObject *owner=0, BaseDesignIntf *parent=0); - BaseDesignIntf* createReportItem(const QString& itemType, QObject *owner=0, BaseDesignIntf *parent=0); - void removeReportItem(BaseDesignIntf* item, bool createComand = true); - CommandIf::Ptr removeReportItemCommand(BaseDesignIntf *item); - bool saveCommand(CommandIf::Ptr command, bool runCommand = true); + bool isItemInsertMode(); + ReportEnginePrivate* reportEditor(); + void setReportEditor(ReportEnginePrivate* value) { m_reportEditor = value; } - bool isCanRedo(); - bool isCanUndo(); - bool isHasChanges(); + QStringList possibleParentItems(); + void registerItem(BaseDesignIntf* item); + void registerBand(BandDesignIntf* band); + void removeAllItems(); - void reactivatePageItem(PageItemDesignIntf::Ptr pageItem); + void setItemMode(BaseDesignIntf::ItemMode state); + BaseDesignIntf::ItemMode itemMode() { return m_itemMode; } + BaseDesignIntf* reportItemByName(const QString& name); + QList reportItemsByName(const QString& name); + BandDesignIntf* bandAt(QPointF pos); + BaseDesignIntf* addReportItem(const QString& itemType, QPointF pos, QSizeF size); + BaseDesignIntf* addReportItem(const QString& itemType, QObject* owner = 0, + BaseDesignIntf* parent = 0); + BaseDesignIntf* createReportItem(const QString& itemType, QObject* owner = 0, + BaseDesignIntf* parent = 0); + void removeReportItem(BaseDesignIntf* item, bool createComand = true); + CommandIf::Ptr removeReportItemCommand(BaseDesignIntf* item); + bool saveCommand(CommandIf::Ptr command, bool runCommand = true); - void setSettings(QSettings* settings){ m_settings = settings;} - QSettings* settings(){ return m_settings;} + bool isCanRedo(); + bool isCanUndo(); + bool isHasChanges(); - QString genObjectName(const QObject& object); + void reactivatePageItem(PageItemDesignIntf::Ptr pageItem); - void animateItem(BaseDesignIntf* item); - void setSelectionRect(QRectF selectionRect); - void emitRegisterdItem(BaseDesignIntf *item); - void emitItemRemoved(BaseDesignIntf* item); + void setSettings(QSettings* settings) { m_settings = settings; } + QSettings* settings() { return m_settings; } - DataSourceManager* datasourceManager(); - bool isSaved(){ return !m_hasChanges;} - void changeSelectedGrpoupTextAlignPropperty(const bool& horizontalAlign, Qt::AlignmentFlag flag); + QString genObjectName(const QObject& object); - int verticalGridStep() const; - void setVerticalGridStep(int verticalGridStep); + void animateItem(BaseDesignIntf* item); + void setSelectionRect(QRectF selectionRect); + void emitRegisterdItem(BaseDesignIntf* item); + void emitItemRemoved(BaseDesignIntf* item); - int horizontalGridStep() const; - void setHorizontalGridStep(int horizontalGridStep); + DataSourceManager* datasourceManager(); + bool isSaved() { return !m_hasChanges; } + void changeSelectedGrpoupTextAlignPropperty(const bool& horizontalAlign, + Qt::AlignmentFlag flag); - void beginUpdate(){m_updating = true;} - bool isUpdating(){return m_updating;} - void endUpdate(); + int verticalGridStep() const; + void setVerticalGridStep(int verticalGridStep); - void rectMoved(QRectF itemRect, BaseDesignIntf* container = 0); - void itemMoved(BaseDesignIntf* item); - bool magneticMovement() const; - void setMagneticMovement(bool magneticMovement); + int horizontalGridStep() const; + void setHorizontalGridStep(int horizontalGridStep); - ReportSettings *getReportSettings() const; - void setReportSettings(ReportSettings *reportSettings); + void beginUpdate() { m_updating = true; } + bool isUpdating() { return m_updating; } + void endUpdate(); - void setPropertyToSelectedItems(const char *name, const QVariant &value); + void rectMoved(QRectF itemRect, BaseDesignIntf* container = 0); + void itemMoved(BaseDesignIntf* item); + bool magneticMovement() const; + void setMagneticMovement(bool magneticMovement); - PageItemDesignIntf* getCurrentPage() const; - void setCurrentPage(PageItemDesignIntf* currentPage); + ReportSettings* getReportSettings() const; + void setReportSettings(ReportSettings* reportSettings); - protected: + void setPropertyToSelectedItems(const char* name, const QVariant& value); - virtual void keyPressEvent(QKeyEvent *event); - virtual void keyReleaseEvent(QKeyEvent *event); - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + PageItemDesignIntf* getCurrentPage() const; + void setCurrentPage(PageItemDesignIntf* currentPage); - virtual void dragEnterEvent(QGraphicsSceneDragDropEvent *event); - virtual void dragMoveEvent(QGraphicsSceneDragDropEvent *); - virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); - virtual void dropEvent(QGraphicsSceneDragDropEvent *event); +protected: + virtual void keyPressEvent(QKeyEvent* event); + virtual void keyReleaseEvent(QKeyEvent* event); + virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event); + virtual void mousePressEvent(QGraphicsSceneMouseEvent* event); + virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); - LimeReport::BandDesignIntf::BandsType findPriorType(LimeReport::BandDesignIntf::BandsType bandType); - BaseDesignIntf *findDestObject(BaseDesignIntf *item); + virtual void dragEnterEvent(QGraphicsSceneDragDropEvent* event); + virtual void dragMoveEvent(QGraphicsSceneDragDropEvent*); + virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent* event); + virtual void dropEvent(QGraphicsSceneDragDropEvent* event); - bool isExistsObjectName (const QString& objectName, QList &itemsList) const; + LimeReport::BandDesignIntf::BandsType + findPriorType(LimeReport::BandDesignIntf::BandsType bandType); + BaseDesignIntf* findDestObject(BaseDesignIntf* item); - bool isLoading(); - void objectLoadStarted(); - void objectLoadFinished(); + bool isExistsObjectName(const QString& objectName, QList& itemsList) const; - HorizontalLayout* internalAddHLayout(); - VerticalLayout* internalAddVLayout(); - QPointF placePosOnGrid(QPointF point); - QSizeF placeSizeOnGrid(QSizeF size); - signals: - void geometryChanged(QRectF newGeometry); - void insertModeStarted(); - void itemInserted(LimeReport::PageDesignIntf* report, QPointF pos, const QString& ItemType); - void itemInsertCanceled(const QString& ItemType); - void itemSelected(LimeReport::BaseDesignIntf *item); - void multiItemsSelected(QList* objectsList); - void miltiItemsSelectionFinished(); - void commandHistoryChanged(); - void itemPropertyChanged(const QString& objectName, - const QString& propertyName, - const QVariant& oldValue, + bool isLoading(); + void objectLoadStarted(); + void objectLoadFinished(); + + HorizontalLayout* internalAddHLayout(); + VerticalLayout* internalAddVLayout(); + QPointF placePosOnGrid(QPointF point); + QSizeF placeSizeOnGrid(QSizeF size); +signals: + void geometryChanged(QRectF newGeometry); + void insertModeStarted(); + void itemInserted(LimeReport::PageDesignIntf* report, QPointF pos, const QString& ItemType); + void itemInsertCanceled(const QString& ItemType); + void itemSelected(LimeReport::BaseDesignIntf* item); + void multiItemsSelected(QList* objectsList); + void miltiItemsSelectionFinished(); + void commandHistoryChanged(); + void itemPropertyChanged(const QString& objectName, const QString& propertyName, + const QVariant& oldValue, const QVariant& newValue); + void itemPropertyObjectNameChanged(const QString& oldName, const QString& newName); + void itemAdded(LimeReport::PageDesignIntf* page, LimeReport::BaseDesignIntf* item); + void itemRemoved(LimeReport::PageDesignIntf* page, LimeReport::BaseDesignIntf* item); + void bandAdded(LimeReport::PageDesignIntf* page, LimeReport::BandDesignIntf* band); + void bandRemoved(LimeReport::PageDesignIntf* page, LimeReport::BandDesignIntf* band); + void pageUpdateFinished(LimeReport::PageDesignIntf* page); +public slots: + BaseDesignIntf* addBand(const QString& bandType); + BaseDesignIntf* addBand(BandDesignIntf::BandsType bandType); + void removeBand(LimeReport::BandDesignIntf* band); + void bandGeometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry); + void bandPosChanged(QObject* object, QPointF newPos, QPointF oldPos); + void slotUpdateItemSize(); + void undo(); + void redo(); + void copy(); + void paste(); + void deleteSelected(); + void cut(); + void setToSaved(); + void bringToFront(); + void sendToBack(); + void alignToLeft(); + void alignToRigth(); + void alignToVCenter(); + void alignToTop(); + void alignToBottom(); + void alignToHCenter(); + void sameWidth(); + void sameHeight(); + void addHLayout(); + void addVLayout(); + void setFont(const QFont& font); + void setTextAlign(const Qt::Alignment& alignment); + void setBorders(const BaseDesignIntf::BorderLines& border); + void setBordersExt(const BaseDesignIntf::BorderLines& border, const double borderWidth, + const BaseDesignIntf::BorderStyle style, const QString color); + void lockSelectedItems(); + void unlockSelectedItems(); + void selectOneLevelItems(); +private slots: + void slotPageGeometryChanged(QObject*, QRectF, QRectF); + void slotItemPropertyChanged(QString propertyName, const QVariant& oldValue, const QVariant& newValue); - void itemPropertyObjectNameChanged(const QString& oldName, const QString& newName); - void itemAdded(LimeReport::PageDesignIntf* page, LimeReport::BaseDesignIntf* item); - void itemRemoved(LimeReport::PageDesignIntf* page, LimeReport::BaseDesignIntf* item); - void bandAdded(LimeReport::PageDesignIntf* page, LimeReport::BandDesignIntf* band); - void bandRemoved(LimeReport::PageDesignIntf* page, LimeReport::BandDesignIntf* band); - void pageUpdateFinished(LimeReport::PageDesignIntf* page); - public slots: - BaseDesignIntf* addBand(const QString& bandType); - BaseDesignIntf* addBand(BandDesignIntf::BandsType bandType); - void removeBand(LimeReport::BandDesignIntf* band); - void bandGeometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry); - void bandPosChanged(QObject* object, QPointF newPos, QPointF oldPos); - void slotUpdateItemSize(); - void undo(); - void redo(); - void copy(); - void paste(); - void deleteSelected(); - void cut(); - void setToSaved(); - void bringToFront(); - void sendToBack(); - void alignToLeft(); - void alignToRigth(); - void alignToVCenter(); - void alignToTop(); - void alignToBottom(); - void alignToHCenter(); - void sameWidth(); - void sameHeight(); - void addHLayout(); - void addVLayout(); - void setFont(const QFont &font); - void setTextAlign(const Qt::Alignment& alignment); - void setBorders(const BaseDesignIntf::BorderLines& border); - void setBordersExt(const BaseDesignIntf::BorderLines &border, - const double borderWidth, - const BaseDesignIntf::BorderStyle style, - const QString color - ); - void lockSelectedItems(); - void unlockSelectedItems(); - void selectOneLevelItems(); - private slots: - void slotPageGeometryChanged(QObject*, QRectF, QRectF ); - void slotItemPropertyChanged(QString propertyName, - const QVariant &oldValue, - const QVariant &newValue); - void slotItemPropertyObjectNameChanged(const QString& oldName, const QString& newName); - void bandDeleted(QObject* band); - void slotPageItemLoaded(QObject *); - void slotSelectionChanged(); - void slotAnimationStoped(QObject *animation); - private: - template - BaseDesignIntf* internalAddBand(T bandType); - void finalizeInsertMode(); - void saveSelectedItemsPos(); - void saveSelectedItemsGeometry(); - void checkSizeOrPosChanges(); - CommandIf::Ptr createChangePosCommand(); - CommandIf::Ptr createChangeSizeCommand(); - void saveChangeProppertyCommand(const QString& objectName, - const QString& propertyName, - const QVariant& oldPropertyValue, - const QVariant& newPropertyValue); - void changeSelectedGroupProperty(const QString& name,const QVariant& value); - void activateItemToJoin(QRectF itemRect, QList& items); - void selectAllChildren(BaseDesignIntf* item); - bool selectionContainsBand(); - private: - enum JoinType{Width, Height}; - LimeReport::PageItemDesignIntf::Ptr m_pageItem; - QList m_reportPages; - ReportEnginePrivate* m_reportEditor; - bool m_insertMode; - QGraphicsItem * m_itemInsertRect; - QString m_insertItemType; - BaseDesignIntf::ItemMode m_itemMode; - QGraphicsRectItem* m_cutterBorder; - QGraphicsRectItem* m_pageRect; -// QGraphicsTextItem* m_infoPosRect; - QVector m_commandsList; - QVector m_positionStamp; - QVector m_geometryStamp; - BaseDesignIntf* m_firstSelectedItem; - int m_currentCommand; - bool m_changeSizeMode; - bool m_changePosMode; - bool m_changePosOrSizeMode; - bool m_executingCommand; - bool m_hasChanges; - bool m_isLoading; - bool m_executingGroupCommand; - QSettings* m_settings; - QList m_animationList; - QPointF m_startSelectionPoint; - QGraphicsRectItem* m_selectionRect; - int m_verticalGridStep; - int m_horizontalGridStep; - bool m_updating; - int m_currentObjectIndex; - bool m_multiSelectStarted; - QList m_projections; - BaseDesignIntf* m_movedItem; - BaseDesignIntf* m_movedItemContainer; - BaseDesignIntf* m_joinItem; - JoinType m_joinType; - bool m_magneticMovement; - ReportSettings* m_reportSettings; - PageItemDesignIntf* m_currentPage; + void slotItemPropertyObjectNameChanged(const QString& oldName, const QString& newName); + void bandDeleted(QObject* band); + void slotPageItemLoaded(QObject*); + void slotSelectionChanged(); + void slotAnimationStoped(QObject* animation); +private: + template BaseDesignIntf* internalAddBand(T bandType); + void finalizeInsertMode(); + void saveSelectedItemsPos(); + void saveSelectedItemsGeometry(); + void checkSizeOrPosChanges(); + CommandIf::Ptr createChangePosCommand(); + CommandIf::Ptr createChangeSizeCommand(); + void saveChangeProppertyCommand(const QString& objectName, const QString& propertyName, + const QVariant& oldPropertyValue, + const QVariant& newPropertyValue); + void changeSelectedGroupProperty(const QString& name, const QVariant& value); + void activateItemToJoin(QRectF itemRect, QList& items); + void selectAllChildren(BaseDesignIntf* item); + bool selectionContainsBand(); + +private: + enum JoinType { + Width, + Height }; + LimeReport::PageItemDesignIntf::Ptr m_pageItem; + QList m_reportPages; + ReportEnginePrivate* m_reportEditor; + bool m_insertMode; + QGraphicsItem* m_itemInsertRect; + QString m_insertItemType; + BaseDesignIntf::ItemMode m_itemMode; + QGraphicsRectItem* m_cutterBorder; + QGraphicsRectItem* m_pageRect; + // QGraphicsTextItem* m_infoPosRect; + QVector m_commandsList; + QVector m_positionStamp; + QVector m_geometryStamp; + BaseDesignIntf* m_firstSelectedItem; + int m_currentCommand; + bool m_changeSizeMode; + bool m_changePosMode; + bool m_changePosOrSizeMode; + bool m_executingCommand; + bool m_hasChanges; + bool m_isLoading; + bool m_executingGroupCommand; + QSettings* m_settings; + QList m_animationList; + QPointF m_startSelectionPoint; + QGraphicsRectItem* m_selectionRect; + int m_verticalGridStep; + int m_horizontalGridStep; + bool m_updating; + int m_currentObjectIndex; + bool m_multiSelectStarted; + QList m_projections; + BaseDesignIntf* m_movedItem; + BaseDesignIntf* m_movedItemContainer; + BaseDesignIntf* m_joinItem; + JoinType m_joinType; + bool m_magneticMovement; + ReportSettings* m_reportSettings; + PageItemDesignIntf* m_currentPage; +}; - class AbstractPageCommand : public CommandIf{ - public: - void setPage(PageDesignIntf* value){m_page = value;} - PageDesignIntf* page(){return m_page;} - private: - PageDesignIntf* m_page; - }; +class AbstractPageCommand: public CommandIf { +public: + void setPage(PageDesignIntf* value) { m_page = value; } + PageDesignIntf* page() { return m_page; } - class InsertHLayoutCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page); - bool doIt(); - void undoIt(); - private: - InsertHLayoutCommand(){} - private: - QString m_layoutName; - QString m_oldParentName; - QMap m_elements; - }; +private: + PageDesignIntf* m_page; +}; - class InsertVLayoutCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page); - bool doIt(); - void undoIt(); - private: - InsertVLayoutCommand(){} - private: - QString m_layoutName; - QString m_oldParentName; - QMap m_elements; - }; +class InsertHLayoutCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page); + bool doIt(); + void undoIt(); - class InsertItemCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString& itemType, QPointF pos, QSizeF size); - bool doIt(); - void undoIt(); - void setPos(QPointF& value){m_pos = value;} - QPointF pos(){return m_pos;} - void setSize(QSizeF& value){m_size=value;} - QSizeF size(){return m_size;} - void setType(const QString& value){m_itemType=value;} - private: - InsertItemCommand(){} - private: - QPointF m_pos; - QSizeF m_size; - QString m_itemType; - QString m_itemName; - }; +private: + InsertHLayoutCommand() { } - class InsertBandCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page,const QString& bandName); - bool doIt(); - void undoIt(); - private: - BandDesignIntf::BandsType m_bandType; - QString m_bandName; - QString m_parentBandName; - }; +private: + QString m_layoutName; + QString m_oldParentName; + QMap m_elements; +}; - class DeleteItemCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, BaseDesignIntf* item); - bool doIt(); - void undoIt(); - void setType(const QString& value){m_itemType=value;} - void setXml(const QString& value){m_itemXML=value;} - void setItem(BaseDesignIntf* value); - private: - QString m_itemXML; - QString m_itemType; - QString m_itemName; - QString m_layoutName; - }; +class InsertVLayoutCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page); + bool doIt(); + void undoIt(); - class DeleteLayoutCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, LayoutDesignIntf* item); - bool doIt(); - void undoIt(); - protected: - void setItem(BaseDesignIntf* item); - private: - QStringList m_childItems; - QString m_layoutName; - QString m_itemXML; - QString m_itemType; - QString m_itemName; - }; +private: + InsertVLayoutCommand() { } +private: + QString m_layoutName; + QString m_oldParentName; + QMap m_elements; +}; - class PasteCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString& itemsXML, BaseDesignIntf *parent); - bool doIt(); - void undoIt(); - protected: - void setItemsXML(const QString& itemsXML); - void setParent(BaseDesignIntf* parent){m_parentItemName = parent->objectName();} - bool insertItem(ItemsReaderIntf::Ptr reader); - void changeName(PageDesignIntf* page, BaseDesignIntf *item); - private: - QString m_itemsXML; - QString m_parentItemName; - QVector m_itemNames; - }; +class InsertItemCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& itemType, QPointF pos, + QSizeF size); + bool doIt(); + void undoIt(); + void setPos(QPointF& value) { m_pos = value; } + QPointF pos() { return m_pos; } + void setSize(QSizeF& value) { m_size = value; } + QSizeF size() { return m_size; } + void setType(const QString& value) { m_itemType = value; } - class CutCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page); - bool doIt(); - void undoIt(); - void setXML(const QString& value){m_itemsXML=value;} - private: - QString m_itemsXML; - QVector m_itemNames; - }; +private: + InsertItemCommand() { } - class PosChangedCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, QVector& oldPos, QVector& newPos); - bool doIt(); - void undoIt(); - private: - QVector m_oldPos; - QVector m_newPos; - }; +private: + QPointF m_pos; + QSizeF m_size; + QString m_itemType; + QString m_itemName; +}; - class BandSwapCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString& bandName, const QString& bandToSwapName); - bool doIt(); - void undoIt(); - private: - QString bandName; - QString bandToSwapName; - }; +class InsertBandCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& bandName); + bool doIt(); + void undoIt(); - class BandMoveFromToCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, int from, int to); - bool doIt(); - void undoIt(); - private: - int from; - int to; - int reverceFrom; - int reverceTo; - }; +private: + BandDesignIntf::BandsType m_bandType; + QString m_bandName; + QString m_parentBandName; +}; +class DeleteItemCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, BaseDesignIntf* item); + bool doIt(); + void undoIt(); + void setType(const QString& value) { m_itemType = value; } + void setXml(const QString& value) { m_itemXML = value; } + void setItem(BaseDesignIntf* value); - class SizeChangedCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, QVector& oldSize, QVector& newSize); - bool doIt(); - void undoIt(); - private: - QVector m_oldSize; - QVector m_newSize; - }; +private: + QString m_itemXML; + QString m_itemType; + QString m_itemName; + QString m_layoutName; +}; - class PropertyChangedCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString& objectName, const QString& propertyName, const QVariant& oldValue, const QVariant& newValue); - bool doIt(); - void undoIt(); - private: - QString m_objectName; - QString m_propertyName; - QVariant m_oldValue; - QVariant m_newValue; - }; +class DeleteLayoutCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, LayoutDesignIntf* item); + bool doIt(); + void undoIt(); - class PropertyObjectNameChangedCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString &oldValue, const QString &newValue); - bool doIt(); - void undoIt(); - private: - QString m_oldName; - QString m_newName; - }; +protected: + void setItem(BaseDesignIntf* item); - class PropertyItemAlignChangedCommand : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(PageDesignIntf* page, const QString& objectName, BaseDesignIntf::ItemAlign oldValue, BaseDesignIntf::ItemAlign newValue); - bool doIt(); - void undoIt(); - private: - QString m_objectName; - QString m_propertyName; - BaseDesignIntf::ItemAlign m_oldValue; - BaseDesignIntf::ItemAlign m_newValue; - QPointF m_savedPos; - }; +private: + QStringList m_childItems; + QString m_layoutName; + QString m_itemXML; + QString m_itemType; + QString m_itemName; +}; - class CommandGroup : public AbstractPageCommand{ - public: - static CommandIf::Ptr create(); - bool doIt(); - void undoIt(); - void addCommand(CommandIf::Ptr command,bool execute); - private: - QList m_commands; - }; +class PasteCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& itemsXML, + BaseDesignIntf* parent); + bool doIt(); + void undoIt(); -} -#endif //LRPAGEDEDIGNITF_H +protected: + void setItemsXML(const QString& itemsXML); + void setParent(BaseDesignIntf* parent) { m_parentItemName = parent->objectName(); } + bool insertItem(ItemsReaderIntf::Ptr reader); + void changeName(PageDesignIntf* page, BaseDesignIntf* item); + +private: + QString m_itemsXML; + QString m_parentItemName; + QVector m_itemNames; +}; + +class CutCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page); + bool doIt(); + void undoIt(); + void setXML(const QString& value) { m_itemsXML = value; } + +private: + QString m_itemsXML; + QVector m_itemNames; +}; + +class PosChangedCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, QVector& oldPos, + QVector& newPos); + bool doIt(); + void undoIt(); + +private: + QVector m_oldPos; + QVector m_newPos; +}; + +class BandSwapCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& bandName, + const QString& bandToSwapName); + bool doIt(); + void undoIt(); + +private: + QString bandName; + QString bandToSwapName; +}; + +class BandMoveFromToCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, int from, int to); + bool doIt(); + void undoIt(); + +private: + int from; + int to; + int reverceFrom; + int reverceTo; +}; + +class SizeChangedCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, QVector& oldSize, + QVector& newSize); + bool doIt(); + void undoIt(); + +private: + QVector m_oldSize; + QVector m_newSize; +}; + +class PropertyChangedCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& objectName, + const QString& propertyName, const QVariant& oldValue, + const QVariant& newValue); + bool doIt(); + void undoIt(); + +private: + QString m_objectName; + QString m_propertyName; + QVariant m_oldValue; + QVariant m_newValue; +}; + +class PropertyObjectNameChangedCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& oldValue, + const QString& newValue); + bool doIt(); + void undoIt(); + +private: + QString m_oldName; + QString m_newName; +}; + +class PropertyItemAlignChangedCommand: public AbstractPageCommand { +public: + static CommandIf::Ptr create(PageDesignIntf* page, const QString& objectName, + BaseDesignIntf::ItemAlign oldValue, + BaseDesignIntf::ItemAlign newValue); + bool doIt(); + void undoIt(); + +private: + QString m_objectName; + QString m_propertyName; + BaseDesignIntf::ItemAlign m_oldValue; + BaseDesignIntf::ItemAlign m_newValue; + QPointF m_savedPos; +}; + +class CommandGroup: public AbstractPageCommand { +public: + static CommandIf::Ptr create(); + bool doIt(); + void undoIt(); + void addCommand(CommandIf::Ptr command, bool execute); + +private: + QList m_commands; +}; + +} // namespace LimeReport +#endif // LRPAGEDEDIGNITF_H diff --git a/limereport/lrpageinitintf.h b/limereport/lrpageinitintf.h index 346138b..6574a32 100644 --- a/limereport/lrpageinitintf.h +++ b/limereport/lrpageinitintf.h @@ -1,7 +1,7 @@ #ifndef LRPAGEINITINTF_H #define LRPAGEINITINTF_H -class IPageInit{ +class IPageInit { public: virtual void pageObjectHasBeenLoaded() = 0; }; diff --git a/limereport/lrpageitemdesignintf.cpp b/limereport/lrpageitemdesignintf.cpp index 57f05ae..33be5e8 100644 --- a/limereport/lrpageitemdesignintf.cpp +++ b/limereport/lrpageitemdesignintf.cpp @@ -28,32 +28,49 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrpageitemdesignintf.h" + #include "lrbanddesignintf.h" #include "lrpagedesignintf.h" #include -#include #include +#include + #include namespace LimeReport { -bool bandSortBandLessThenByIndex(const BandDesignIntf *c1, const BandDesignIntf *c2){ - if (c1->bandIndex()!=c2->bandIndex()){ - return c1->bandIndex()bandIndex(); +bool bandSortBandLessThenByIndex(const BandDesignIntf* c1, const BandDesignIntf* c2) +{ + if (c1->bandIndex() != c2->bandIndex()) { + return c1->bandIndex() < c2->bandIndex(); } else { - return c1->bandType()bandType(); + return c1->bandType() < c2->bandType(); } } -PageItemDesignIntf::PageItemDesignIntf(QObject *owner, QGraphicsItem *parent) : - ItemsContainerDesignInft("PageItem",owner,parent), - m_topMargin(0), m_bottomMargin(0), m_leftMargin(0), m_rightMargin(0), - m_pageOrientaion(Portrait), m_pageSize(A4), m_sizeChainging(false), - m_fullPage(false), m_oldPrintMode(false), m_resetPageNumber(false), - m_isExtendedInDesignMode(false), m_extendedHeight(1000), m_isTOC(false), - m_setPageSizeToPrinter(false), m_endlessHeight(false), m_printable(true), - m_pageFooter(0), m_printBehavior(Split), m_dropPrinterMargins(false), - m_notPrintIfEmpty(false), m_mixWithPriorPage(false) +PageItemDesignIntf::PageItemDesignIntf(QObject* owner, QGraphicsItem* parent): + ItemsContainerDesignInft("PageItem", owner, parent), + m_topMargin(0), + m_bottomMargin(0), + m_leftMargin(0), + m_rightMargin(0), + m_pageOrientaion(Portrait), + m_pageSize(A4), + m_sizeChainging(false), + m_fullPage(false), + m_oldPrintMode(false), + m_resetPageNumber(false), + m_isExtendedInDesignMode(false), + m_extendedHeight(1000), + m_isTOC(false), + m_setPageSizeToPrinter(false), + m_endlessHeight(false), + m_printable(true), + m_pageFooter(0), + m_printBehavior(Split), + m_dropPrinterMargins(false), + m_notPrintIfEmpty(false), + m_mixWithPriorPage(false) { setFixedPos(true); setPossibleResizeDirectionFlags(Fixed); @@ -61,15 +78,30 @@ PageItemDesignIntf::PageItemDesignIntf(QObject *owner, QGraphicsItem *parent) : initPageSize(m_pageSize); } -PageItemDesignIntf::PageItemDesignIntf(const PageSize pageSize, const QRectF &rect, QObject *owner, QGraphicsItem *parent) : - ItemsContainerDesignInft("PageItem",owner,parent), - m_topMargin(0), m_bottomMargin(0), m_leftMargin(0), m_rightMargin(0), - m_pageOrientaion(Portrait), m_pageSize(pageSize), m_sizeChainging(false), - m_fullPage(false), m_oldPrintMode(false), m_resetPageNumber(false), - m_isExtendedInDesignMode(false), m_extendedHeight(1000), m_isTOC(false), - m_setPageSizeToPrinter(false), m_endlessHeight(false), m_printable(true), - m_pageFooter(0), m_printBehavior(Split), m_dropPrinterMargins(false), - m_notPrintIfEmpty(false), m_mixWithPriorPage(false) +PageItemDesignIntf::PageItemDesignIntf(const PageSize pageSize, const QRectF& rect, QObject* owner, + QGraphicsItem* parent): + ItemsContainerDesignInft("PageItem", owner, parent), + m_topMargin(0), + m_bottomMargin(0), + m_leftMargin(0), + m_rightMargin(0), + m_pageOrientaion(Portrait), + m_pageSize(pageSize), + m_sizeChainging(false), + m_fullPage(false), + m_oldPrintMode(false), + m_resetPageNumber(false), + m_isExtendedInDesignMode(false), + m_extendedHeight(1000), + m_isTOC(false), + m_setPageSizeToPrinter(false), + m_endlessHeight(false), + m_printable(true), + m_pageFooter(0), + m_printBehavior(Split), + m_dropPrinterMargins(false), + m_notPrintIfEmpty(false), + m_mixWithPriorPage(false) { setFixedPos(true); setPossibleResizeDirectionFlags(Fixed); @@ -79,17 +111,19 @@ PageItemDesignIntf::PageItemDesignIntf(const PageSize pageSize, const QRectF &re PageItemDesignIntf::~PageItemDesignIntf() { - foreach(BandDesignIntf* band, m_bands) + foreach (BandDesignIntf* band, m_bands) band->disconnect(this); m_bands.clear(); } -void PageItemDesignIntf::paint(QPainter *ppainter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void PageItemDesignIntf::paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { - if (itemMode() & DesignMode){ + if (itemMode() & DesignMode) { QRectF rect = pageRect(); - if (isExtendedInDesignMode()) rect.adjust(0,0,0,m_extendedHeight); + if (isExtendedInDesignMode()) + rect.adjust(0, 0, 0, m_extendedHeight); ppainter->save(); ppainter->setOpacity(0.8); ppainter->fillRect(boundingRect(), pageBorderColor()); @@ -111,17 +145,16 @@ void PageItemDesignIntf::paint(QPainter *ppainter, const QStyleOptionGraphicsIte pen.setStyle(Qt::SolidLine); ppainter->setPen(pen); QRectF tmpRect = rect(); - tmpRect.adjust(-4,-4,4,4); + tmpRect.adjust(-4, -4, 4, 4); ppainter->drawRect(tmpRect); ppainter->restore(); - BaseDesignIntf::paint(ppainter,option,widget); + BaseDesignIntf::paint(ppainter, option, widget); } - } -BaseDesignIntf *PageItemDesignIntf::createSameTypeItem(QObject *owner, QGraphicsItem *parent) +BaseDesignIntf* PageItemDesignIntf::createSameTypeItem(QObject* owner, QGraphicsItem* parent) { - return new PageItemDesignIntf(owner,parent); + return new PageItemDesignIntf(owner, parent); } void PageItemDesignIntf::geometryChangedEvent(QRectF newRect, QRectF) @@ -132,23 +165,14 @@ void PageItemDesignIntf::geometryChangedEvent(QRectF newRect, QRectF) PageSize oldSize = m_pageSize; if (!m_sizeChainging && !isLoading()) m_pageSize = Custom; - notify("pageSize",oldSize,m_pageSize); + notify("pageSize", oldSize, m_pageSize); } -QColor PageItemDesignIntf::selectionColor() const -{ - return Qt::gray; -} +QColor PageItemDesignIntf::selectionColor() const { return Qt::gray; } -QColor PageItemDesignIntf::pageBorderColor() const -{ - return QColor(100,150,50); -} +QColor PageItemDesignIntf::pageBorderColor() const { return QColor(100, 150, 50); } -QColor PageItemDesignIntf::gridColor() const -{ - return QColor(170,200,150); -} +QColor PageItemDesignIntf::gridColor() const { return QColor(170, 200, 150); } QRectF PageItemDesignIntf::boundingRect() const { @@ -156,7 +180,7 @@ QRectF PageItemDesignIntf::boundingRect() const return BaseDesignIntf::boundingRect(); else { QRectF result = BaseDesignIntf::boundingRect(); - return result.adjusted(0,0,0,m_extendedHeight); + return result.adjusted(0, 0, 0, m_extendedHeight); } } @@ -168,57 +192,62 @@ void PageItemDesignIntf::setItemMode(BaseDesignIntf::ItemMode mode) void PageItemDesignIntf::clear() { - foreach(QGraphicsItem* item, childItems()){ + foreach (QGraphicsItem* item, childItems()) { delete item; } childItems().clear(); m_bands.clear(); } -BandDesignIntf *PageItemDesignIntf::bandByType(BandDesignIntf::BandsType bandType) const +BandDesignIntf* PageItemDesignIntf::bandByType(BandDesignIntf::BandsType bandType) const { QList::const_iterator it = childBands().constBegin(); - for(;it!=childBands().constEnd();++it){ - if ( (*it)->bandType()==bandType) return (*it); + for (; it != childBands().constEnd(); ++it) { + if ((*it)->bandType() == bandType) + return (*it); } return 0; } bool PageItemDesignIntf::isBandExists(BandDesignIntf::BandsType bandType) { - foreach(BandDesignIntf* band, childBands()){ - if (band->bandType()==bandType) return true; + foreach (BandDesignIntf* band, childBands()) { + if (band->bandType() == bandType) + return true; } return false; } -bool PageItemDesignIntf::isBandExists(const QString &bandType) +bool PageItemDesignIntf::isBandExists(const QString& bandType) { - foreach(BandDesignIntf* band, childBands()){ - if (band->bandTitle()==bandType) return true; + foreach (BandDesignIntf* band, childBands()) { + if (band->bandTitle() == bandType) + return true; } return false; } BandDesignIntf* PageItemDesignIntf::bandByIndex(int index) { - foreach(BandDesignIntf* band, childBands()){ - if (band->bandIndex()==index) return band; + foreach (BandDesignIntf* band, childBands()) { + if (band->bandIndex() == index) + return band; } return 0; } -BandDesignIntf *PageItemDesignIntf::bandByName(QString bandObjectName) +BandDesignIntf* PageItemDesignIntf::bandByName(QString bandObjectName) { - foreach(BandDesignIntf* band, childBands()){ - if (band->objectName().compare(bandObjectName,Qt::CaseInsensitive)==0){ + foreach (BandDesignIntf* band, childBands()) { + if (band->objectName().compare(bandObjectName, Qt::CaseInsensitive) == 0) { return band; } } return 0; } -int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDesignIntf *parentBand, bool& increaseBandIndex) +int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, + BandDesignIntf* parentBand, bool& increaseBandIndex) { increaseBandIndex = false; @@ -228,18 +257,22 @@ int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDe int bandIndex = -1; std::sort(m_bands.begin(), m_bands.end(), bandSortBandLessThenByIndex); - if (bandType != BandDesignIntf::Data){ - foreach(BandDesignIntf* band,m_bands){ - if ((band->bandType() == BandDesignIntf::GroupHeader) && ( band->bandType() > bandType)) break; - if ((band->bandType() <= bandType)){ + if (bandType != BandDesignIntf::Data) { + foreach (BandDesignIntf* band, m_bands) { + if ((band->bandType() == BandDesignIntf::GroupHeader) && (band->bandType() > bandType)) + break; + if ((band->bandType() <= bandType)) { if (bandIndex <= band->bandIndex()) { - bandIndex=band->maxChildIndex(bandType) + 1; + bandIndex = band->maxChildIndex(bandType) + 1; } - } else { increaseBandIndex = true; break;} + } else { + increaseBandIndex = true; + break; + } } } else { int maxChildIndex = 0; - foreach(BandDesignIntf* band, m_bands){ + foreach (BandDesignIntf* band, m_bands) { maxChildIndex = std::max(maxChildIndex, band->maxChildIndex()); } bandIndex = std::max(bandIndex, maxChildIndex + 1); @@ -253,7 +286,7 @@ int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDe if (parentBand) { BandDesignIntf* dataBand = parentBand; - while (dataBand->parentBand() && dataBand->bandType()==BandDesignIntf::GroupHeader){ + while (dataBand->parentBand() && dataBand->bandType() == BandDesignIntf::GroupHeader) { dataBand = dataBand->parentBand(); } @@ -271,7 +304,7 @@ int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDe increaseBandIndex = true; break; case BandDesignIntf::GroupHeader: - if (parentBand->bandType()==BandDesignIntf::GroupHeader) + if (parentBand->bandType() == BandDesignIntf::GroupHeader) bandIndex = parentBand->bandIndex() + 1; else bandIndex = parentBand->minChildIndex(BandDesignIntf::GroupHeader); @@ -279,7 +312,8 @@ int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDe break; case BandDesignIntf::GroupFooter: bandIndex = std::max(parentBand->maxChildIndex(), - dataBand->maxChildIndex(groupFooterIgnoredBands)) + 1; + dataBand->maxChildIndex(groupFooterIgnoredBands)) + + 1; increaseBandIndex = true; break; case BandDesignIntf::DataHeader: @@ -290,36 +324,35 @@ int PageItemDesignIntf::calcBandIndex(BandDesignIntf::BandsType bandType, BandDe bandIndex = parentBand->maxChildIndex() + 1; increaseBandIndex = true; break; - default : - ; + default:; } - } return bandIndex; } void PageItemDesignIntf::increaseBandIndex(int startIndex) { - if (bandByIndex(startIndex)){ - foreach(BandDesignIntf* band, m_bands){ - if (band->bandIndex() >= startIndex){ + if (bandByIndex(startIndex)) { + foreach (BandDesignIntf* band, m_bands) { + if (band->bandIndex() >= startIndex) { band->setBandIndex(band->bandIndex() + 1); } } } } -bool PageItemDesignIntf::isBandRegistred(BandDesignIntf *band) +bool PageItemDesignIntf::isBandRegistred(BandDesignIntf* band) { - foreach(BandDesignIntf* cBand,childBands()){ - if (band==cBand) return true; + foreach (BandDesignIntf* cBand, childBands()) { + if (band == cBand) + return true; } return false; } -void PageItemDesignIntf::registerBand(BandDesignIntf *band) +void PageItemDesignIntf::registerBand(BandDesignIntf* band) { - if (!isBandRegistred(band)){ + if (!isBandRegistred(band)) { if (band->bandIndex() > childBands().count() - 1) m_bands.append(band); else @@ -327,48 +360,39 @@ void PageItemDesignIntf::registerBand(BandDesignIntf *band) band->setParent(this); band->setParentItem(this); band->setWidth(pageRect().width() / band->columnsCount()); - connect(band, SIGNAL(destroyed(QObject*)),this,SLOT(bandDeleted(QObject*))); - connect(band, SIGNAL(posChanged(QObject*, QPointF, QPointF)), - this, SLOT(bandPositionChanged(QObject*, QPointF, QPointF))); - connect(band, SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), - this, SLOT(bandGeometryChanged(QObject*, QRectF, QRectF))); - + connect(band, SIGNAL(destroyed(QObject*)), this, SLOT(bandDeleted(QObject*))); + connect(band, SIGNAL(posChanged(QObject*, QPointF, QPointF)), this, + SLOT(bandPositionChanged(QObject*, QPointF, QPointF))); + connect(band, SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), this, + SLOT(bandGeometryChanged(QObject*, QRectF, QRectF))); } } -void PageItemDesignIntf::initColumnsPos(QVector &posByColumns, qreal pos, int columnCount){ +void PageItemDesignIntf::initColumnsPos(QVector& posByColumns, qreal pos, int columnCount) +{ posByColumns.clear(); - for(int i=0;i(scene()); - if (page) page->updatePageRect(); + if (page) + page->updatePageRect(); update(); } -bool PageItemDesignIntf::isExtendedInDesignMode() const -{ - return m_isExtendedInDesignMode; -} +bool PageItemDesignIntf::isExtendedInDesignMode() const { return m_isExtendedInDesignMode; } void PageItemDesignIntf::setExtendedInDesignMode(bool pageIsExtended) { m_isExtendedInDesignMode = pageIsExtended; PageDesignIntf* page = dynamic_cast(scene()); - if (page) page->updatePageRect(); + if (page) + page->updatePageRect(); update(); } -BandDesignIntf *PageItemDesignIntf::pageFooter() const -{ - return m_pageFooter; -} +BandDesignIntf* PageItemDesignIntf::pageFooter() const { return m_pageFooter; } -void PageItemDesignIntf::setPageFooter(BandDesignIntf *pageFooter) -{ - m_pageFooter = pageFooter; -} +void PageItemDesignIntf::setPageFooter(BandDesignIntf* pageFooter) { m_pageFooter = pageFooter; } void PageItemDesignIntf::placeTearOffBand() { BandDesignIntf* tearOffBand = bandByType(BandDesignIntf::TearOffBand); - if (tearOffBand){ + if (tearOffBand) { BandDesignIntf* pf = pageFooter(); - if (pf){ - qreal bottomSpace = pageRect().bottom() - (tearOffBand->height() + pf->height() + bottomMargin()); - tearOffBand->setItemPos(pageRect().x(), - bottomSpace); + if (pf) { + qreal bottomSpace + = pageRect().bottom() - (tearOffBand->height() + pf->height() + bottomMargin()); + tearOffBand->setItemPos(pageRect().x(), bottomSpace); } else { qreal bottomSpace = pageRect().bottom() - (tearOffBand->height() + bottomMargin()); tearOffBand->setItemPos(pageRect().x(), bottomSpace); @@ -486,47 +476,35 @@ void PageItemDesignIntf::placeTearOffBand() } } -bool PageItemDesignIntf::resetPageNumber() const -{ - return m_resetPageNumber; -} +bool PageItemDesignIntf::resetPageNumber() const { return m_resetPageNumber; } void PageItemDesignIntf::setResetPageNumber(bool resetPageNumber) { - if (m_resetPageNumber!=resetPageNumber){ + if (m_resetPageNumber != resetPageNumber) { m_resetPageNumber = resetPageNumber; - notify("resetPageNumber",!m_resetPageNumber,m_resetPageNumber); + notify("resetPageNumber", !m_resetPageNumber, m_resetPageNumber); } } -void PageItemDesignIntf::updateSubItemsSize(RenderPass pass, DataSourceManager *dataManager) +void PageItemDesignIntf::updateSubItemsSize(RenderPass pass, DataSourceManager* dataManager) { - if (!endlessHeight()){ + if (!endlessHeight()) { snapshotItemsLayout(IgnoreBands); arrangeSubItems(pass, dataManager); } } -bool PageItemDesignIntf::oldPrintMode() const -{ - return m_oldPrintMode; -} +bool PageItemDesignIntf::oldPrintMode() const { return m_oldPrintMode; } -void PageItemDesignIntf::setOldPrintMode(bool oldPrintMode) -{ - m_oldPrintMode = oldPrintMode; -} +void PageItemDesignIntf::setOldPrintMode(bool oldPrintMode) { m_oldPrintMode = oldPrintMode; } -bool PageItemDesignIntf::fullPage() const -{ - return m_fullPage; -} +bool PageItemDesignIntf::fullPage() const { return m_fullPage; } void PageItemDesignIntf::setFullPage(bool fullPage) { - if (m_fullPage != fullPage){ + if (m_fullPage != fullPage) { m_fullPage = fullPage; - if (!isLoading()){ + if (!isLoading()) { updateMarginRect(); notify("fullPage", !m_fullPage, m_fullPage); } @@ -535,7 +513,8 @@ void PageItemDesignIntf::setFullPage(bool fullPage) void PageItemDesignIntf::relocateBands() { - if (isLoading()) return; + if (isLoading()) + return; int bandSpace = 0; @@ -544,53 +523,53 @@ void PageItemDesignIntf::relocateBands() std::sort(m_bands.begin(), m_bands.end(), bandSortBandLessThenByIndex); int bandIndex = 0; - if (!(itemMode() & DesignMode)){ - while ( (bandIndex < m_bands.count()) && - ((m_bands[bandIndex]->bandType() == BandDesignIntf::TearOffBand) || - (m_bands[bandIndex]->bandType() == BandDesignIntf::PageFooter) || - m_bands[bandIndex]->bandType() == BandDesignIntf::ReportFooter ) - ){ + if (!(itemMode() & DesignMode)) { + while ((bandIndex < m_bands.count()) + && ((m_bands[bandIndex]->bandType() == BandDesignIntf::TearOffBand) + || (m_bands[bandIndex]->bandType() == BandDesignIntf::PageFooter) + || m_bands[bandIndex]->bandType() == BandDesignIntf::ReportFooter)) { bandIndex++; } } - if ( (m_bands.count()>0) && (bandIndexcolumnsCount()); - m_bands[bandIndex]->setPos(pageRect().x(),pageRect().y()); - posByColumn[0]+=m_bands[bandIndex]->height()+bandSpace; + if ((m_bands.count() > 0) && (bandIndex < m_bands.count())) { + initColumnsPos(posByColumn, pageRect().y(), m_bands[bandIndex]->columnsCount()); + m_bands[bandIndex]->setPos(pageRect().x(), pageRect().y()); + posByColumn[0] += m_bands[bandIndex]->height() + bandSpace; } - if(m_bands.count()>1){ - for(int i=0;i<(m_bands.count()-1);i++){ - if (((m_bands[i+1]->bandType()!=BandDesignIntf::PageFooter) && - (m_bands[i+1]->bandType()!=BandDesignIntf::TearOffBand)) || (itemMode() & DesignMode)){ - if (m_bands[i+1]->columnsCount()>1 && - m_bands[i]->columnsCount() != m_bands[i+1]->columnsCount()) - { + if (m_bands.count() > 1) { + for (int i = 0; i < (m_bands.count() - 1); i++) { + if (((m_bands[i + 1]->bandType() != BandDesignIntf::PageFooter) + && (m_bands[i + 1]->bandType() != BandDesignIntf::TearOffBand)) + || (itemMode() & DesignMode)) { + if (m_bands[i + 1]->columnsCount() > 1 + && m_bands[i]->columnsCount() != m_bands[i + 1]->columnsCount()) { qreal curPos = posByColumn[0]; - initColumnsPos(posByColumn, - curPos, - m_bands[i+1]->columnsCount()); + initColumnsPos(posByColumn, curPos, m_bands[i + 1]->columnsCount()); } - if (m_bands[i+1]->columnIndex()==0){ - if ( ((m_bands[i]->borderLines() & BandDesignIntf::BottomLine) && - (m_bands[i+1]->borderLines() & BandDesignIntf::TopLine)) || - (!(m_bands[i]->borderLines() & BandDesignIntf::BottomLine) && - !(m_bands[i+1]->borderLines() & BandDesignIntf::TopLine)) ){ - m_bands[i+1]->setPos(pageRect().x(),posByColumn[0]); - posByColumn[0] += m_bands[i+1]->height()+bandSpace; + if (m_bands[i + 1]->columnIndex() == 0) { + if (((m_bands[i]->borderLines() & BandDesignIntf::BottomLine) + && (m_bands[i + 1]->borderLines() & BandDesignIntf::TopLine)) + || (!(m_bands[i]->borderLines() & BandDesignIntf::BottomLine) + && !(m_bands[i + 1]->borderLines() & BandDesignIntf::TopLine))) { + m_bands[i + 1]->setPos(pageRect().x(), posByColumn[0]); + posByColumn[0] += m_bands[i + 1]->height() + bandSpace; } else { - m_bands[i+1]->setPos(pageRect().x(),posByColumn[0]); - posByColumn[0] += m_bands[i+1]->height()+bandSpace; + m_bands[i + 1]->setPos(pageRect().x(), posByColumn[0]); + posByColumn[0] += m_bands[i + 1]->height() + bandSpace; } } else { - m_bands[i+1]->setPos(m_bands[i+1]->pos().x(),posByColumn[m_bands[i+1]->columnIndex()]); - posByColumn[m_bands[i+1]->columnIndex()] += m_bands[i+1]->height()+bandSpace; + m_bands[i + 1]->setPos(m_bands[i + 1]->pos().x(), + posByColumn[m_bands[i + 1]->columnIndex()]); + posByColumn[m_bands[i + 1]->columnIndex()] + += m_bands[i + 1]->height() + bandSpace; } } } - foreach(BandDesignIntf* band, m_bands){ - if (band->isSelected()) band->updateBandNameLabel(); + foreach (BandDesignIntf* band, m_bands) { + if (band->isSelected()) + band->updateBandNameLabel(); } } @@ -598,29 +577,31 @@ void PageItemDesignIntf::relocateBands() placeTearOffBand(); } -void PageItemDesignIntf::removeBand(BandDesignIntf *band) +void PageItemDesignIntf::removeBand(BandDesignIntf* band) { - if (!m_bands.isEmpty()){ + if (!m_bands.isEmpty()) { m_bands.removeOne(band); } } int PageItemDesignIntf::dataBandCount() { - int count=0; - foreach(BandDesignIntf* band,m_bands){ - if (band->bandType()==BandDesignIntf::Data) count++; + int count = 0; + foreach (BandDesignIntf* band, m_bands) { + if (band->bandType() == BandDesignIntf::Data) + count++; } return count; } -BandDesignIntf *PageItemDesignIntf::dataBandAt(int index) +BandDesignIntf* PageItemDesignIntf::dataBandAt(int index) { - int count=0; - std::sort(m_bands.begin(),m_bands.end(),bandSortBandLessThenByIndex); - foreach(BandDesignIntf* band,m_bands){ - if (band->bandType()==BandDesignIntf::Data){ - if(count==index) return band; + int count = 0; + std::sort(m_bands.begin(), m_bands.end(), bandSortBandLessThenByIndex); + foreach (BandDesignIntf* band, m_bands) { + if (band->bandType() == BandDesignIntf::Data) { + if (count == index) + return band; count++; } } @@ -629,27 +610,28 @@ BandDesignIntf *PageItemDesignIntf::dataBandAt(int index) void PageItemDesignIntf::setTopMargin(int value) { - if (m_topMargin!=value){ + if (m_topMargin != value) { m_sizeChainging = true; int oldValue = m_topMargin; - m_topMargin=value; - if (!isLoading()){ + m_topMargin = value; + if (!isLoading()) { updateMarginRect(); - notify("topMargin",oldValue,value);; + notify("topMargin", oldValue, value); + ; } - m_sizeChainging = false; + m_sizeChainging = false; } } void PageItemDesignIntf::setBottomMargin(int value) { - if (m_bottomMargin!=value){ + if (m_bottomMargin != value) { m_sizeChainging = true; int oldValue = m_bottomMargin; - m_bottomMargin=value; - if (!isLoading()){ + m_bottomMargin = value; + if (!isLoading()) { updateMarginRect(); - notify("bottomMargin",oldValue,value); + notify("bottomMargin", oldValue, value); } m_sizeChainging = false; } @@ -657,13 +639,13 @@ void PageItemDesignIntf::setBottomMargin(int value) void PageItemDesignIntf::setLeftMargin(int value) { - if (m_leftMargin!=value){ + if (m_leftMargin != value) { m_sizeChainging = true; int oldValue = m_leftMargin; - m_leftMargin=value; - if (!isLoading()){ + m_leftMargin = value; + if (!isLoading()) { updateMarginRect(); - notify("leftMargin",oldValue,value); + notify("leftMargin", oldValue, value); } m_sizeChainging = false; } @@ -671,13 +653,13 @@ void PageItemDesignIntf::setLeftMargin(int value) void PageItemDesignIntf::setRightMargin(int value) { - if (m_rightMargin!=value){ + if (m_rightMargin != value) { m_sizeChainging = true; int oldValue = m_rightMargin; - m_rightMargin=value; - if (!isLoading()){ + m_rightMargin = value; + if (!isLoading()) { updateMarginRect(); - notify("rightMargin",oldValue,value); + notify("rightMargin", oldValue, value); } m_sizeChainging = false; } @@ -685,18 +667,18 @@ void PageItemDesignIntf::setRightMargin(int value) void PageItemDesignIntf::setPageOrientation(PageItemDesignIntf::Orientation value) { - if (!m_sizeChainging && m_pageOrientaion!=value){ + if (!m_sizeChainging && m_pageOrientaion != value) { m_sizeChainging = true; PageItemDesignIntf::Orientation oldValue = m_pageOrientaion; m_pageOrientaion = value; - if (!isLoading()){ + if (!isLoading()) { qreal tmpWidth = width(); setWidth(height()); setHeight(tmpWidth); updateMarginRect(); - notify("pageOrientation",oldValue,value); + notify("pageOrientation", oldValue, value); } - m_sizeChainging = false; + m_sizeChainging = false; } } @@ -726,7 +708,7 @@ QSizeF PageItemDesignIntf::getRectByPageSize(const PageSize& size) } else { - return QSizeF(width(),height()); + return QSizeF(width(), height()); } } @@ -735,13 +717,12 @@ void PageItemDesignIntf::initPageSize(const QSizeF& size) m_sizeChainging = true; setWidth(size.width()); setHeight(size.height()); - m_sizeChainging=false; + m_sizeChainging = false; } -void PageItemDesignIntf::preparePopUpMenu(QMenu &menu) +void PageItemDesignIntf::preparePopUpMenu(QMenu& menu) { - foreach (QAction* action, menu.actions()) { if (action->text().compare(tr("Paste")) != 0) action->setVisible(false); @@ -749,7 +730,6 @@ void PageItemDesignIntf::preparePopUpMenu(QMenu &menu) menu.addSeparator(); menu.addAction(tr("Edit")); - menu.addSeparator(); QAction* action = menu.addAction(tr("Page is TOC")); @@ -772,102 +752,98 @@ void PageItemDesignIntf::preparePopUpMenu(QMenu &menu) action->setCheckable(true); action->setChecked(mixWithPriorPage()); -// action = menu.addAction(tr("Transparent")); -// action->setCheckable(true); -// action->setChecked(backgroundMode() == TransparentMode); - + // action = menu.addAction(tr("Transparent")); + // action->setCheckable(true); + // action->setChecked(backgroundMode() == TransparentMode); } -void PageItemDesignIntf::processPopUpAction(QAction *action) +void PageItemDesignIntf::processPopUpAction(QAction* action) { - if (action->text().compare(tr("Page is TOC")) == 0){ - page()->setPropertyToSelectedItems("pageIsTOC",action->isChecked()); + if (action->text().compare(tr("Page is TOC")) == 0) { + page()->setPropertyToSelectedItems("pageIsTOC", action->isChecked()); } - if (action->text().compare(tr("Reset page number")) == 0){ - page()->setPropertyToSelectedItems("resetPageNumber",action->isChecked()); + if (action->text().compare(tr("Reset page number")) == 0) { + page()->setPropertyToSelectedItems("resetPageNumber", action->isChecked()); } - if (action->text().compare(tr("Full page")) == 0){ - page()->setPropertyToSelectedItems("fullPage",action->isChecked()); + if (action->text().compare(tr("Full page")) == 0) { + page()->setPropertyToSelectedItems("fullPage", action->isChecked()); } - if (action->text().compare(tr("Set page size to printer")) == 0){ - page()->setPropertyToSelectedItems("setPageSizeToPrinter",action->isChecked()); + if (action->text().compare(tr("Set page size to printer")) == 0) { + page()->setPropertyToSelectedItems("setPageSizeToPrinter", action->isChecked()); } - if (action->text().compare(tr("Mix with prior page")) == 0){ - page()->setPropertyToSelectedItems("mixWithPriorPage",action->isChecked()); + if (action->text().compare(tr("Mix with prior page")) == 0) { + page()->setPropertyToSelectedItems("mixWithPriorPage", action->isChecked()); } - if(action->text() == tr("Edit")) - { - PageEditor pageEdit(NULL,this); + if (action->text() == tr("Edit")) { + PageEditor pageEdit(NULL, this); pageEdit.exec(); } - } -void PageItemDesignIntf::initPageSize(const PageItemDesignIntf::PageSize &size) +void PageItemDesignIntf::initPageSize(const PageItemDesignIntf::PageSize& size) { m_sizeChainging = true; - if (m_pageSize != Custom){ + if (m_pageSize != Custom) { QSizeF pageSize = getRectByPageSize(size); setWidth(pageSize.width()); setHeight(pageSize.height()); } - m_sizeChainging=false; + m_sizeChainging = false; } -void PageItemDesignIntf::setPageSize(const PageSize &size) +void PageItemDesignIntf::setPageSize(const PageSize& size) { - if(m_pageSize!=size){ - m_pageSize=size; + if (m_pageSize != size) { + m_pageSize = size; initPageSize(m_pageSize); } } -void PageItemDesignIntf::bandDeleted(QObject *band) +void PageItemDesignIntf::bandDeleted(QObject* band) { removeBand(reinterpret_cast(band)); relocateBands(); } -void PageItemDesignIntf::swapBands(BandDesignIntf* band, BandDesignIntf* bandToSwap){ +void PageItemDesignIntf::swapBands(BandDesignIntf* band, BandDesignIntf* bandToSwap) +{ int firstIndex = std::min(band->minChildIndex(), bandToSwap->minChildIndex()); int secondIndex = std::max(band->minChildIndex(), bandToSwap->minChildIndex()); int moveIndex = std::min(band->maxChildIndex(), bandToSwap->maxChildIndex()); QList bandToMove; - foreach(BandDesignIntf* curBand, m_bands){ - if ( curBand->bandIndex() > moveIndex && curBand->bandIndex() < secondIndex && - curBand->bandType() == band->bandType() && - curBand != band && curBand != bandToSwap - ) + foreach (BandDesignIntf* curBand, m_bands) { + if (curBand->bandIndex() > moveIndex && curBand->bandIndex() < secondIndex + && curBand->bandType() == band->bandType() && curBand != band && curBand != bandToSwap) bandToMove.append(curBand); } - BandDesignIntf* firstMoveBand = (bandToSwap->bandIndex() > band->bandIndex()) ? bandToSwap: band; + BandDesignIntf* firstMoveBand + = (bandToSwap->bandIndex() > band->bandIndex()) ? bandToSwap : band; firstMoveBand->changeBandIndex(firstIndex, true); moveIndex = firstIndex; std::sort(bandToMove.begin(), bandToMove.end(), bandIndexLessThen); - foreach(BandDesignIntf* curBand, bandToMove){ - curBand->changeBandIndex(moveIndex,true); - moveIndex = curBand->maxChildIndex() + 1; + foreach (BandDesignIntf* curBand, bandToMove) { + curBand->changeBandIndex(moveIndex, true); + moveIndex = curBand->maxChildIndex() + 1; } - if (firstMoveBand == band){ - bandToSwap->changeBandIndex(moveIndex,true); + if (firstMoveBand == band) { + bandToSwap->changeBandIndex(moveIndex, true); } else { band->changeBandIndex(moveIndex, true); } relocateBands(); - } QList PageItemDesignIntf::createBandGroup(int beginIndex, int endIndex) { QList result; - foreach(BandDesignIntf* curBand, m_bands){ - if ( curBand->bandIndex() >= beginIndex && curBand->bandIndex() <= endIndex) + foreach (BandDesignIntf* curBand, m_bands) { + if (curBand->bandIndex() >= beginIndex && curBand->bandIndex() <= endIndex) result.append(curBand); } std::sort(result.begin(), result.end(), bandIndexLessThen); @@ -880,118 +856,119 @@ void PageItemDesignIntf::moveBandFromTo(int from, int to) BandDesignIntf* fromBand = 0; BandDesignIntf* toBand = 0; - foreach(BandDesignIntf* band, bands()){ - if (band->bandIndex() == from){ + foreach (BandDesignIntf* band, bands()) { + if (band->bandIndex() == from) { fromBand = band->rootBand(band->parentBand()); } - if (band->bandIndex() == to){ + if (band->bandIndex() == to) { toBand = band->rootBand(band->parentBand()); } - if (fromBand && toBand) break; + if (fromBand && toBand) + break; } - if (!fromBand || !toBand) return; + if (!fromBand || !toBand) + return; int beginIndex = 0; int endIndex = 0; - if (from < to){ - beginIndex = fromBand->maxChildIndex()+1; + if (from < to) { + beginIndex = fromBand->maxChildIndex() + 1; endIndex = toBand->maxChildIndex(); } else { beginIndex = toBand->minChildIndex(); - endIndex = fromBand->minChildIndex()-1; + endIndex = fromBand->minChildIndex() - 1; } - QList firstGroup = createBandGroup(fromBand->minChildIndex(), fromBand->maxChildIndex()); + QList firstGroup + = createBandGroup(fromBand->minChildIndex(), fromBand->maxChildIndex()); QList secondGroup = createBandGroup(beginIndex, endIndex); - if (from < to){ + if (from < to) { int currentIndex = fromBand->minChildIndex(); - foreach(BandDesignIntf* band, secondGroup){ + foreach (BandDesignIntf* band, secondGroup) { band->setBandIndex(currentIndex); currentIndex++; } - foreach(BandDesignIntf* band, firstGroup){ + foreach (BandDesignIntf* band, firstGroup) { band->setBandIndex(currentIndex); currentIndex++; } } else { int currentIndex = toBand->minChildIndex(); - foreach(BandDesignIntf* band, firstGroup){ + foreach (BandDesignIntf* band, firstGroup) { band->setBandIndex(currentIndex); currentIndex++; } - foreach(BandDesignIntf* band, secondGroup){ + foreach (BandDesignIntf* band, secondGroup) { band->setBandIndex(currentIndex); currentIndex++; } } relocateBands(); - } void PageItemDesignIntf::bandPositionChanged(QObject* object, QPointF newPos, QPointF oldPos) { BandDesignIntf* band = dynamic_cast(object); - if (band && !band->isChangingPos() && (itemMode() == DesignMode)){ + if (band && !band->isChangingPos() && (itemMode() == DesignMode)) { int curIndex = band->bandIndex(); BandDesignIntf* bandToSwap = 0; - foreach(BandDesignIntf* curBand, bands()){ + foreach (BandDesignIntf* curBand, bands()) { if (newPos.y() > oldPos.y()) { - if (curBand->bandType() == band->bandType() - && curIndex < curBand->bandIndex() - && (curBand->pos().y() + (curBand->height()/2)) < newPos.y() - && curBand->parentBand() == band->parentBand()) - { + if (curBand->bandType() == band->bandType() && curIndex < curBand->bandIndex() + && (curBand->pos().y() + (curBand->height() / 2)) < newPos.y() + && curBand->parentBand() == band->parentBand()) { curIndex = curBand->bandIndex(); - bandToSwap = curBand; + bandToSwap = curBand; } } else { - if (curBand->bandType() == band->bandType() - && curIndex>curBand->bandIndex() - && (curBand->pos().y() + (curBand->height()/2)) > newPos.y() - && curBand->parentBand() == band->parentBand()) - { + if (curBand->bandType() == band->bandType() && curIndex > curBand->bandIndex() + && (curBand->pos().y() + (curBand->height() / 2)) > newPos.y() + && curBand->parentBand() == band->parentBand()) { curIndex = curBand->bandIndex(); - bandToSwap = curBand; + bandToSwap = curBand; } } } - if (curIndex != band->bandIndex() && itemMode() == DesignMode){ + if (curIndex != band->bandIndex() && itemMode() == DesignMode) { if (page()) - page()->saveCommand(BandMoveFromToCommand::create(page(), band->bandIndex(), bandToSwap->bandIndex()), true); + page()->saveCommand(BandMoveFromToCommand::create(page(), band->bandIndex(), + bandToSwap->bandIndex()), + true); } } if (band && !band->isChangingPos()) relocateBands(); } -void PageItemDesignIntf::bandGeometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry) +void PageItemDesignIntf::bandGeometryChanged(QObject* object, QRectF newGeometry, + QRectF oldGeometry) { bandPositionChanged(object, newGeometry.topLeft(), oldGeometry.topLeft()); } void PageItemDesignIntf::setUnitTypeProperty(BaseDesignIntf::UnitType value) { - if (unitType() != value){ + if (unitType() != value) { UnitType oldValue = unitType(); setUnitType(value); - if (!isLoading()){ + if (!isLoading()) { update(); notify("units", oldValue, value); } } } -void PageItemDesignIntf::collectionLoadFinished(const QString &collectionName) +void PageItemDesignIntf::collectionLoadFinished(const QString& collectionName) { - if (collectionName.compare("children",Qt::CaseInsensitive)==0){ + if (collectionName.compare("children", Qt::CaseInsensitive) == 0) { m_bands.clear(); #ifdef HAVE_QT5 - foreach(QObject* obj,children()){ + foreach (QObject* obj, children()) { #else - foreach(QObject* obj,QObject::children()){ + foreach (QObject* obj, QObject::children()) { #endif BandDesignIntf* item = dynamic_cast(obj); if (item) { @@ -1005,59 +982,66 @@ void PageItemDesignIntf::collectionLoadFinished(const QString &collectionName) void PageItemDesignIntf::updateMarginRect() { m_pageRect = rect(); - m_pageRect.adjust( leftMargin() * Const::mmFACTOR, - topMargin() * Const::mmFACTOR, - -rightMargin() * Const::mmFACTOR, - -bottomMargin() * Const::mmFACTOR - ); + m_pageRect.adjust(leftMargin() * Const::mmFACTOR, topMargin() * Const::mmFACTOR, + -rightMargin() * Const::mmFACTOR, -bottomMargin() * Const::mmFACTOR); - foreach(BandDesignIntf* band,m_bands){ - band->setWidth(pageRect().width()/band->columnsCount()); + foreach (BandDesignIntf* band, m_bands) { + band->setWidth(pageRect().width() / band->columnsCount()); relocateBands(); } foreach (BaseDesignIntf* item, childBaseItems()) { - if (item->itemAlign()!=DesignedItemAlign){ + if (item->itemAlign() != DesignedItemAlign) { item->updateItemAlign(); } } update(); } -void PageItemDesignIntf::paintGrid(QPainter *ppainter, QRectF rect) +void PageItemDesignIntf::paintGrid(QPainter* ppainter, QRectF rect) { ppainter->save(); ppainter->setPen(QPen(gridColor())); ppainter->setOpacity(0.5); - for (int i = 0; i <= (rect.height() - 5 * unitFactor()) / (10 * unitFactor()); ++i){ + for (int i = 0; i <= (rect.height() - 5 * unitFactor()) / (10 * unitFactor()); ++i) { if (i * 10 * unitFactor() + 5 * unitFactor() >= topMargin() * Const::mmFACTOR) - ppainter->drawLine(rect.x(), (i * 10 * unitFactor()) + ( (rect.y() + 5 * unitFactor()) - (topMargin() * Const::mmFACTOR)), - rect.right(), i * 10 * unitFactor() +( (rect.y() + 5 * unitFactor()) - (topMargin() * Const::mmFACTOR))); + ppainter->drawLine( + rect.x(), + (i * 10 * unitFactor()) + + ((rect.y() + 5 * unitFactor()) - (topMargin() * Const::mmFACTOR)), + rect.right(), + i * 10 * unitFactor() + + ((rect.y() + 5 * unitFactor()) - (topMargin() * Const::mmFACTOR))); }; - for (int i=0; i<=((rect.width() - 5 * unitFactor()) / (10 * unitFactor())); ++i){ + for (int i = 0; i <= ((rect.width() - 5 * unitFactor()) / (10 * unitFactor())); ++i) { if (i * 10 * unitFactor() + 5 * unitFactor() >= leftMargin() * Const::mmFACTOR) - ppainter->drawLine(i * 10 * unitFactor() + ((rect.x() + 5 * unitFactor()) - (leftMargin() * Const::mmFACTOR)), rect.y(), - i * 10 * unitFactor() + ((rect.x() + 5 * unitFactor()) - (leftMargin() * Const::mmFACTOR)), rect.bottom()); + ppainter->drawLine( + i * 10 * unitFactor() + + ((rect.x() + 5 * unitFactor()) - (leftMargin() * Const::mmFACTOR)), + rect.y(), + i * 10 * unitFactor() + + ((rect.x() + 5 * unitFactor()) - (leftMargin() * Const::mmFACTOR)), + rect.bottom()); }; ppainter->setPen(QPen(gridColor())); ppainter->setOpacity(1); - for (int i = 0; i <= (rect.width() / (10 * unitFactor())); ++i){ + for (int i = 0; i <= (rect.width() / (10 * unitFactor())); ++i) { if (i * 10 * unitFactor() >= leftMargin() * Const::mmFACTOR) - ppainter->drawLine(i * 10 * unitFactor() + (rect.x() - (leftMargin() * Const::mmFACTOR)), rect.y(), - i * 10 * unitFactor() + (rect.x() - (leftMargin() * Const::mmFACTOR)), rect.bottom()); + ppainter->drawLine( + i * 10 * unitFactor() + (rect.x() - (leftMargin() * Const::mmFACTOR)), rect.y(), + i * 10 * unitFactor() + (rect.x() - (leftMargin() * Const::mmFACTOR)), + rect.bottom()); }; - for (int i = 0; i <= rect.height() / (10 * unitFactor()); ++i){ + for (int i = 0; i <= rect.height() / (10 * unitFactor()); ++i) { if (i * 10 * unitFactor() >= topMargin() * Const::mmFACTOR) - ppainter->drawLine(rect.x(), i * 10 * unitFactor() + (rect.y() - (topMargin() * Const::mmFACTOR)), - rect.right(), i * 10 * unitFactor() + (rect.y() - (topMargin() * Const::mmFACTOR))); + ppainter->drawLine( + rect.x(), i * 10 * unitFactor() + (rect.y() - (topMargin() * Const::mmFACTOR)), + rect.right(), i * 10 * unitFactor() + (rect.y() - (topMargin() * Const::mmFACTOR))); }; ppainter->drawRect(rect); ppainter->restore(); } -QList& PageItemDesignIntf::bands() -{ - return m_bands; -} +QList& PageItemDesignIntf::bands() { return m_bands; } void PageItemDesignIntf::setGridStep(int value) { @@ -1069,8 +1053,10 @@ void PageItemDesignIntf::setGridStep(int value) int PageItemDesignIntf::gridStep() { - if (page()) return page()->horizontalGridStep(); - else return Const::DEFAULT_GRID_STEP; + if (page()) + return page()->horizontalGridStep(); + else + return Const::DEFAULT_GRID_STEP; } void PageItemDesignIntf::objectLoadFinished() @@ -1079,26 +1065,22 @@ void PageItemDesignIntf::objectLoadFinished() updateMarginRect(); } -PageItemDesignIntf::Ptr PageItemDesignIntf::create(QObject *owner) +PageItemDesignIntf::Ptr PageItemDesignIntf::create(QObject* owner) { return PageItemDesignIntf::Ptr(new PageItemDesignIntf(owner)); } -bool PageItemDesignIntf::mixWithPriorPage() const -{ - return m_mixWithPriorPage; -} +bool PageItemDesignIntf::mixWithPriorPage() const { return m_mixWithPriorPage; } void PageItemDesignIntf::setMixWithPriorPage(bool value) { - if (m_mixWithPriorPage != value){ + if (m_mixWithPriorPage != value) { m_mixWithPriorPage = value; - if (!isLoading()){ + if (!isLoading()) { update(); notify("mixWithPriorPage", !value, value); } } - } -} +} // namespace LimeReport diff --git a/limereport/lrpageitemdesignintf.h b/limereport/lrpageitemdesignintf.h index 1170a8f..70a2eae 100644 --- a/limereport/lrpageitemdesignintf.h +++ b/limereport/lrpageitemdesignintf.h @@ -29,33 +29,34 @@ ****************************************************************************/ #ifndef LRPAGEITEM_H #define LRPAGEITEM_H -#include "lrbasedesignintf.h" #include "lrbanddesignintf.h" +#include "lrbasedesignintf.h" #include "lritemscontainerdesignitf.h" -#include + #include +#include #include -namespace LimeReport{ +namespace LimeReport { class ReportRender; -class LIMEREPORT_EXPORT PageItemDesignIntf : public ItemsContainerDesignInft -{ +class LIMEREPORT_EXPORT PageItemDesignIntf: public ItemsContainerDesignInft { Q_OBJECT Q_PROPERTY(int topMargin READ topMargin WRITE setTopMargin) Q_PROPERTY(int bottomMargin READ bottomMargin WRITE setBottomMargin) Q_PROPERTY(int rightMargin READ rightMargin WRITE setRightMargin) Q_PROPERTY(int leftMargin READ leftMargin WRITE setLeftMargin) Q_PROPERTY(Orientation pageOrientation READ pageOrientation WRITE setPageOrientation) - Q_PROPERTY(PageSize pageSize READ pageSize WRITE setPageSize ) + Q_PROPERTY(PageSize pageSize READ pageSize WRITE setPageSize) Q_PROPERTY(int gridStep READ gridStep WRITE setGridStep) Q_PROPERTY(bool fullPage READ fullPage WRITE setFullPage) Q_PROPERTY(bool oldPrintMode READ oldPrintMode WRITE setOldPrintMode) Q_PROPERTY(bool resetPageNumber READ resetPageNumber WRITE setResetPageNumber) - Q_PROPERTY(bool isExtendedInDesignMode READ isExtendedInDesignMode WRITE setExtendedInDesignMode) - Q_PROPERTY(int extendedHeight READ extendedHeight WRITE setExtendedHeight) + Q_PROPERTY( + bool isExtendedInDesignMode READ isExtendedInDesignMode WRITE setExtendedInDesignMode) + Q_PROPERTY(int extendedHeight READ extendedHeight WRITE setExtendedHeight) Q_PROPERTY(bool pageIsTOC READ isTOC WRITE setIsTOC) - Q_PROPERTY(bool setPageSizeToPrinter READ getSetPageSizeToPrinter WRITE setSetPageSizeToPrinter ) + Q_PROPERTY(bool setPageSizeToPrinter READ getSetPageSizeToPrinter WRITE setSetPageSizeToPrinter) Q_PROPERTY(bool endlessHeight READ endlessHeight WRITE setEndlessHeight) Q_PROPERTY(bool printable READ isPrintable WRITE setPrintable) Q_PROPERTY(QString printerName READ printerName WRITE setPrinterName) @@ -65,39 +66,96 @@ class LIMEREPORT_EXPORT PageItemDesignIntf : public ItemsContainerDesignInft Q_PROPERTY(bool notPrintIfEmpty READ notPrintIfEmpty WRITE setNotPrintIfEmpty) Q_PROPERTY(bool mixWithPriorPage READ mixWithPriorPage WRITE setMixWithPriorPage) friend class ReportRender; + public: #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - enum Orientation { Portrait = QPrinter::Portrait, Landscape = QPrinter::Landscape }; + enum Orientation { + Portrait = QPrinter::Portrait, + Landscape = QPrinter::Landscape + }; - enum PrintBehavior {Scale, Split}; + enum PrintBehavior { + Scale, + Split + }; enum PageSize { - A4 = QPrinter::A4, B5 = QPrinter::B5, Letter = QPrinter::Letter, - Legal = QPrinter::Legal, Executive = QPrinter::Executive, - A0 = QPrinter::A0, A1 = QPrinter::A1, A2 = QPrinter::A2, A3 = QPrinter::A3, - A5 = QPrinter::A5, A6 = QPrinter::A6, A7 = QPrinter::A7, A8 = QPrinter::A8, - A9 = QPrinter::A9, B0 = QPrinter::B0, B1 = QPrinter::B1, B10 = QPrinter::B10, - B2 = QPrinter::B2, B3 = QPrinter::B3, B4 = QPrinter::B4, B6 = QPrinter::B6, - B7 = QPrinter::B7, B8 = QPrinter::B8, B9 = QPrinter::B9, C5E = QPrinter::C5E, - Comm10E = QPrinter::Comm10E, DLE = QPrinter::DLE, Folio = QPrinter::Folio, - Ledger = QPrinter::Ledger, Tabloid = QPrinter::Tabloid, Custom = QPrinter::Custom, + A4 = QPrinter::A4, + B5 = QPrinter::B5, + Letter = QPrinter::Letter, + Legal = QPrinter::Legal, + Executive = QPrinter::Executive, + A0 = QPrinter::A0, + A1 = QPrinter::A1, + A2 = QPrinter::A2, + A3 = QPrinter::A3, + A5 = QPrinter::A5, + A6 = QPrinter::A6, + A7 = QPrinter::A7, + A8 = QPrinter::A8, + A9 = QPrinter::A9, + B0 = QPrinter::B0, + B1 = QPrinter::B1, + B10 = QPrinter::B10, + B2 = QPrinter::B2, + B3 = QPrinter::B3, + B4 = QPrinter::B4, + B6 = QPrinter::B6, + B7 = QPrinter::B7, + B8 = QPrinter::B8, + B9 = QPrinter::B9, + C5E = QPrinter::C5E, + Comm10E = QPrinter::Comm10E, + DLE = QPrinter::DLE, + Folio = QPrinter::Folio, + Ledger = QPrinter::Ledger, + Tabloid = QPrinter::Tabloid, + Custom = QPrinter::Custom, NPageSize = Custom }; #else - enum Orientation { Portrait = QPageLayout::Portrait, Landscape = QPageLayout::Landscape }; + enum Orientation { + Portrait = QPageLayout::Portrait, + Landscape = QPageLayout::Landscape + }; - enum PrintBehavior {Scale, Split}; + enum PrintBehavior { + Scale, + Split + }; enum PageSize { - A4 = QPageSize::A4, B5 = QPageSize::B5, Letter = QPageSize::Letter, - Legal = QPageSize::Legal, Executive = QPageSize::Executive, - A0 = QPageSize::A0, A1 = QPageSize::A1, A2 = QPageSize::A2, A3 = QPageSize::A3, - A5 = QPageSize::A5, A6 = QPageSize::A6, A7 = QPageSize::A7, A8 = QPageSize::A8, - A9 = QPageSize::A9, B0 = QPageSize::B0, B1 = QPageSize::B1, B10 = QPageSize::B10, - B2 = QPageSize::B2, B3 = QPageSize::B3, B4 = QPageSize::B4, B6 = QPageSize::B6, - B7 = QPageSize::B7, B8 = QPageSize::B8, B9 = QPageSize::B9, C5E = QPageSize::C5E, - Comm10E = QPageSize::Comm10E, DLE = QPageSize::DLE, Folio = QPageSize::Folio, - Ledger = QPageSize::Ledger, Tabloid = QPageSize::Tabloid, Custom = QPageSize::Custom, + A4 = QPageSize::A4, + B5 = QPageSize::B5, + Letter = QPageSize::Letter, + Legal = QPageSize::Legal, + Executive = QPageSize::Executive, + A0 = QPageSize::A0, + A1 = QPageSize::A1, + A2 = QPageSize::A2, + A3 = QPageSize::A3, + A5 = QPageSize::A5, + A6 = QPageSize::A6, + A7 = QPageSize::A7, + A8 = QPageSize::A8, + A9 = QPageSize::A9, + B0 = QPageSize::B0, + B1 = QPageSize::B1, + B10 = QPageSize::B10, + B2 = QPageSize::B2, + B3 = QPageSize::B3, + B4 = QPageSize::B4, + B6 = QPageSize::B6, + B7 = QPageSize::B7, + B8 = QPageSize::B8, + B9 = QPageSize::B9, + C5E = QPageSize::C5E, + Comm10E = QPageSize::Comm10E, + DLE = QPageSize::DLE, + Folio = QPageSize::Folio, + Ledger = QPageSize::Ledger, + Tabloid = QPageSize::Tabloid, + Custom = QPageSize::Custom, NPageSize = Custom }; #endif @@ -115,11 +173,12 @@ public: typedef QList::const_iterator BandsIterator; typedef QSharedPointer Ptr; static PageItemDesignIntf::Ptr create(QObject* owner); - explicit PageItemDesignIntf(QObject *owner = 0, QGraphicsItem* parent=0); - explicit PageItemDesignIntf(const PageSize pageSize, const QRectF& rect,QObject *owner = 0, QGraphicsItem* parent=0); + explicit PageItemDesignIntf(QObject* owner = 0, QGraphicsItem* parent = 0); + explicit PageItemDesignIntf(const PageSize pageSize, const QRectF& rect, QObject* owner = 0, + QGraphicsItem* parent = 0); ~PageItemDesignIntf(); - virtual void paint(QPainter *ppainter, const QStyleOptionGraphicsItem *option, QWidget *widget); - virtual BaseDesignIntf* createSameTypeItem(QObject* owner=0, QGraphicsItem* parent=0); + virtual void paint(QPainter* ppainter, const QStyleOptionGraphicsItem* option, QWidget* widget); + virtual BaseDesignIntf* createSameTypeItem(QObject* owner = 0, QGraphicsItem* parent = 0); virtual void geometryChangedEvent(QRectF newRect, QRectF); virtual QColor selectionColor() const; virtual QColor pageBorderColor() const; @@ -127,13 +186,14 @@ public: virtual QRectF boundingRect() const; void setItemMode(LimeReport::BaseDesignIntf::ItemMode mode); void clear(); - const BandsList& childBands() const {return m_bands;} - BandDesignIntf * bandByType(BandDesignIntf::BandsType bandType) const; + const BandsList& childBands() const { return m_bands; } + BandDesignIntf* bandByType(BandDesignIntf::BandsType bandType) const; bool isBandExists(BandDesignIntf::BandsType bandType); bool isBandExists(const QString& bandType); BandDesignIntf* bandByIndex(int index); BandDesignIntf* bandByName(QString bandObjectName); - int calcBandIndex(BandDesignIntf::BandsType bandType, BandDesignIntf* parentBand, bool &increaseBandIndex); + int calcBandIndex(BandDesignIntf::BandsType bandType, BandDesignIntf* parentBand, + bool& increaseBandIndex); void increaseBandIndex(int startIndex); bool isBandRegistred(BandDesignIntf* band); void registerBand(BandDesignIntf* band); @@ -144,19 +204,19 @@ public: BandDesignIntf* dataBandAt(int index); void setTopMargin(int value); - int topMargin() const {return m_topMargin;} + int topMargin() const { return m_topMargin; } void setBottomMargin(int value); - int bottomMargin() const {return m_bottomMargin;} + int bottomMargin() const { return m_bottomMargin; } void setLeftMargin(int value); - int leftMargin() const {return m_leftMargin;} + int leftMargin() const { return m_leftMargin; } void setRightMargin(int value); - int rightMargin() const{return m_rightMargin;} + int rightMargin() const { return m_rightMargin; } void setPageOrientation(Orientation value); - Orientation pageOrientation() const {return m_pageOrientaion;} - PageSize pageSize() const {return m_pageSize;} - void setPageSize(const PageSize &size); - QList& bands(); + Orientation pageOrientation() const { return m_pageOrientaion; } + PageSize pageSize() const { return m_pageSize; } + void setPageSize(const PageSize& size); + QList& bands(); void setGridStep(int value); int gridStep(); void objectLoadFinished(); @@ -165,19 +225,19 @@ public: bool oldPrintMode() const; void setOldPrintMode(bool oldPrintMode); - bool canContainChildren() const{ return true;} - bool canAcceptPaste() const{ return true;} + bool canContainChildren() const { return true; } + bool canAcceptPaste() const { return true; } bool resetPageNumber() const; void setResetPageNumber(bool resetPageNumber); - void updateSubItemsSize(RenderPass pass, DataSourceManager *dataManager); - void swapBands(BandDesignIntf *band, BandDesignIntf *bandToSwap); + void updateSubItemsSize(RenderPass pass, DataSourceManager* dataManager); + void swapBands(BandDesignIntf* band, BandDesignIntf* bandToSwap); void moveBandFromTo(int from, int to); - QList createBandGroup(int beginIndex, int endIndex); - + QList createBandGroup(int beginIndex, int endIndex); + bool isExtendedInDesignMode() const; void setExtendedInDesignMode(bool isExtendedInDesignMode); - int extendedHeight() const; + int extendedHeight() const; void setExtendedHeight(int extendedHeight); bool isTOC() const; @@ -195,11 +255,11 @@ public: void setPrinterName(const QString& printerName); void placeTearOffBand(); - BandDesignIntf *pageFooter() const; - void setPageFooter(BandDesignIntf *pageFooter); - + BandDesignIntf* pageFooter() const; + void setPageFooter(BandDesignIntf* pageFooter); + PrintBehavior printBehavior() const; - void setPrintBehavior(const PrintBehavior &printBehavior); + void setPrintBehavior(const PrintBehavior& printBehavior); bool dropPrinterMargins() const; void setDropPrinterMargins(bool dropPrinterMargins); @@ -220,19 +280,22 @@ protected slots: void bandPositionChanged(QObject* object, QPointF newPos, QPointF oldPos); void bandGeometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry); void setUnitTypeProperty(BaseDesignIntf::UnitType value); + protected: - void collectionLoadFinished(const QString& collectionName); - QRectF& pageRect(){return m_pageRect;} - void updateMarginRect(); - QSizeF getRectByPageSize(const PageSize &size); - void initPageSize(const PageSize &size); - void initPageSize(const QSizeF &size); - QColor selectionMarkerColor(){return Qt::transparent;} - void preparePopUpMenu(QMenu &menu); - void processPopUpAction(QAction *action); + void collectionLoadFinished(const QString& collectionName); + QRectF& pageRect() { return m_pageRect; } + void updateMarginRect(); + QSizeF getRectByPageSize(const PageSize& size); + void initPageSize(const PageSize& size); + void initPageSize(const QSizeF& size); + QColor selectionMarkerColor() { return Qt::transparent; } + void preparePopUpMenu(QMenu& menu); + void processPopUpAction(QAction* action); + private: - void paintGrid(QPainter *ppainter, QRectF rect); - void initColumnsPos(QVector&posByColumns, qreal pos, int columnCount); + void paintGrid(QPainter* ppainter, QRectF rect); + void initColumnsPos(QVector& posByColumns, qreal pos, int columnCount); + private: int m_topMargin; int m_bottomMargin; @@ -247,7 +310,7 @@ private: bool m_oldPrintMode; bool m_resetPageNumber; bool m_isExtendedInDesignMode; - int m_extendedHeight; + int m_extendedHeight; bool m_isTOC; bool m_setPageSizeToPrinter; bool m_endlessHeight; @@ -258,11 +321,9 @@ private: bool m_dropPrinterMargins; bool m_notPrintIfEmpty; bool m_mixWithPriorPage; - - }; typedef QList ReportPages; -} +} // namespace LimeReport #endif // LRPAGEITEM_H diff --git a/limereport/lrpreparedpages.cpp b/limereport/lrpreparedpages.cpp index 5408d70..56e5177 100644 --- a/limereport/lrpreparedpages.cpp +++ b/limereport/lrpreparedpages.cpp @@ -5,7 +5,7 @@ namespace LimeReport { -bool PreparedPages::loadFromFile(const QString &fileName) +bool PreparedPages::loadFromFile(const QString& fileName) { ItemsReaderIntf::Ptr reader = FileXMLReader::create(fileName); return readPages(reader); @@ -17,17 +17,17 @@ bool PreparedPages::loadFromString(const QString data) return readPages(reader); } -bool PreparedPages::loadFromByteArray(QByteArray *data) +bool PreparedPages::loadFromByteArray(QByteArray* data) { ItemsReaderIntf::Ptr reader = ByteArrayXMLReader::create(data); return readPages(reader); } -bool PreparedPages::saveToFile(const QString &fileName) +bool PreparedPages::saveToFile(const QString& fileName) { - if (!fileName.isEmpty()){ - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); - foreach (PageItemDesignIntf::Ptr page, *m_pages){ + if (!fileName.isEmpty()) { + QScopedPointer writer(new XMLWriter()); + foreach (PageItemDesignIntf::Ptr page, *m_pages) { writer->putItem(page.data()); } return writer->saveToFile(fileName); @@ -37,8 +37,8 @@ bool PreparedPages::saveToFile(const QString &fileName) QString PreparedPages::saveToString() { - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); - foreach (PageItemDesignIntf::Ptr page, *m_pages){ + QScopedPointer writer(new XMLWriter()); + foreach (PageItemDesignIntf::Ptr page, *m_pages) { writer->putItem(page.data()); } return writer->saveToString(); @@ -46,30 +46,27 @@ QString PreparedPages::saveToString() QByteArray PreparedPages::saveToByteArray() { - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); - foreach (PageItemDesignIntf::Ptr page, *m_pages){ + QScopedPointer writer(new XMLWriter()); + foreach (PageItemDesignIntf::Ptr page, *m_pages) { writer->putItem(page.data()); } return writer->saveToByteArray(); } -void PreparedPages::clear() -{ - m_pages->clear(); -} +void PreparedPages::clear() { m_pages->clear(); } bool PreparedPages::readPages(ItemsReaderIntf::Ptr reader) { clear(); - if (reader->first()){ + if (reader->first()) { PageItemDesignIntf::Ptr page = PageItemDesignIntf::create(0); if (!reader->readItem(page.data())) return false; else { m_pages->append(page); - while (reader->next()){ + while (reader->next()) { page = PageItemDesignIntf::create(0); - if (!reader->readItem(page.data())){ + if (!reader->readItem(page.data())) { m_pages->clear(); return false; } else { @@ -83,4 +80,4 @@ bool PreparedPages::readPages(ItemsReaderIntf::Ptr reader) return false; } -} +} // namespace LimeReport diff --git a/limereport/lrpreparedpages.h b/limereport/lrpreparedpages.h index 8a03679..125029b 100644 --- a/limereport/lrpreparedpages.h +++ b/limereport/lrpreparedpages.h @@ -6,19 +6,20 @@ namespace LimeReport { -class PreparedPages: public IPreparedPages{ +class PreparedPages: public IPreparedPages { public: - PreparedPages(ReportPages* pages):m_pages(pages){} - ~PreparedPages(){} -// IPreviewPages interface + PreparedPages(ReportPages* pages): m_pages(pages) { } + ~PreparedPages() { } + // IPreviewPages interface private: - bool loadFromFile(const QString &fileName); + bool loadFromFile(const QString& fileName); bool loadFromString(const QString data); - bool loadFromByteArray(QByteArray *data); - bool saveToFile(const QString &fileName); + bool loadFromByteArray(QByteArray* data); + bool saveToFile(const QString& fileName); QString saveToString(); QByteArray saveToByteArray(); void clear(); + private: bool readPages(ItemsReaderIntf::Ptr reader); ReportPages* m_pages; diff --git a/limereport/lrpreparedpagesintf.h b/limereport/lrpreparedpagesintf.h index a079a9a..1c96ede 100644 --- a/limereport/lrpreparedpagesintf.h +++ b/limereport/lrpreparedpagesintf.h @@ -2,16 +2,16 @@ #define LRPREPAREDPAGESINTF_H #include "lrglobal.h" namespace LimeReport { -class LIMEREPORT_EXPORT IPreparedPages{ +class LIMEREPORT_EXPORT IPreparedPages { public: - virtual ~IPreparedPages(){}; + virtual ~IPreparedPages() {}; virtual bool loadFromFile(const QString& fileName) = 0; virtual bool loadFromString(const QString data) = 0; virtual bool loadFromByteArray(QByteArray* data) = 0; virtual bool saveToFile(const QString& fileName) = 0; - virtual QString saveToString() = 0; - virtual QByteArray saveToByteArray() = 0; + virtual QString saveToString() = 0; + virtual QByteArray saveToByteArray() = 0; virtual void clear() = 0; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRPREPAREDPAGESINTF_H diff --git a/limereport/lrpreviewreportwidget.cpp b/limereport/lrpreviewreportwidget.cpp index 41fb6a6..25fee54 100644 --- a/limereport/lrpreviewreportwidget.cpp +++ b/limereport/lrpreviewreportwidget.cpp @@ -1,56 +1,55 @@ #include "lrpreviewreportwidget.h" #include "ui_lrpreviewreportwidget.h" -#include +#include "lrexportersfactory.h" +#include "lrpagedesignintf.h" +#include "lrpreparedpages.h" +#include "lrpreviewreportwidget_p.h" +#include "lrreportengine_p.h" +#include "lrreportrender.h" +#include "serializators/lrxmlwriter.h" + +#include #include +#include #include #include -#include - -#include "lrpagedesignintf.h" -#include "lrreportrender.h" -#include "lrreportengine_p.h" -#include "lrpreviewreportwidget_p.h" -#include "serializators/lrxmlwriter.h" -#include "lrpreparedpages.h" - -#include "lrexportersfactory.h" - namespace LimeReport { -bool PreviewReportWidgetPrivate::pageIsVisible(){ +bool PreviewReportWidgetPrivate::pageIsVisible() +{ QGraphicsView* view = q_ptr->ui->graphicsView; - if ( m_currentPage-1 >= m_reportPages.size() || m_currentPage <= 0 ) + if (m_currentPage - 1 >= m_reportPages.size() || m_currentPage <= 0) return false; - PageItemDesignIntf::Ptr page = m_reportPages.at(m_currentPage-1); - return page->mapToScene(page->rect()).boundingRect().intersects( - view->mapToScene(view->viewport()->geometry()).boundingRect() - ); + PageItemDesignIntf::Ptr page = m_reportPages.at(m_currentPage - 1); + return page->mapToScene(page->rect()) + .boundingRect() + .intersects(view->mapToScene(view->viewport()->geometry()).boundingRect()); } -QRectF PreviewReportWidgetPrivate::calcPageShift(){ - QGraphicsView *view = q_ptr->ui->graphicsView; - PageItemDesignIntf::Ptr page = m_reportPages.at(m_currentPage-1); +QRectF PreviewReportWidgetPrivate::calcPageShift() +{ + QGraphicsView* view = q_ptr->ui->graphicsView; + PageItemDesignIntf::Ptr page = m_reportPages.at(m_currentPage - 1); qreal pageHeight = page->mapToScene(page->boundingRect()).boundingRect().height(); - qreal viewHeight = view->mapToScene( - 0, view->viewport()->height() - ).y() - view->mapToScene(0,0).y(); - viewHeight = (pageHeightmapRectToScene( - m_reportPages.at(m_currentPage-1)->rect() - ); - return QRectF(0,pageStartPos.y(),0,viewHeight); + qreal viewHeight + = view->mapToScene(0, view->viewport()->height()).y() - view->mapToScene(0, 0).y(); + viewHeight = (pageHeight < viewHeight) ? pageHeight : viewHeight; + QRectF pageStartPos = m_reportPages.at(m_currentPage - 1) + ->mapRectToScene(m_reportPages.at(m_currentPage - 1)->rect()); + return QRectF(0, pageStartPos.y(), 0, viewHeight); } void PreviewReportWidgetPrivate::setPages(ReportPages pages) { m_reportPages = pages; - if (!m_reportPages.isEmpty()){ + if (!m_reportPages.isEmpty()) { m_previewPage->setPageItems(m_reportPages); m_changingPage = true; m_currentPage = 1; - if (pages.at(0)) pages.at(0)->setSelected(true); + if (pages.at(0)) + pages.at(0)->setSelected(true); m_changingPage = false; q_ptr->initPreview(); q_ptr->emitPageSet(); @@ -60,9 +59,10 @@ void PreviewReportWidgetPrivate::setPages(ReportPages pages) PageItemDesignIntf::Ptr PreviewReportWidgetPrivate::currentPage() { - if (m_reportPages.count()>0 && m_reportPages.count() >= m_currentPage && m_currentPage > 0) - return m_reportPages.at(m_currentPage-1); - else return PageItemDesignIntf::Ptr(0); + if (m_reportPages.count() > 0 && m_reportPages.count() >= m_currentPage && m_currentPage > 0) + return m_reportPages.at(m_currentPage - 1); + else + return PageItemDesignIntf::Ptr(0); } QList PreviewReportWidgetPrivate::aviableExporters() @@ -75,35 +75,34 @@ void PreviewReportWidgetPrivate::startInsertTextItem() m_previewPage->startInsertMode("TextItem"); } -void PreviewReportWidgetPrivate::activateItemSelectionMode() -{ - m_previewPage->startEditMode(); -} +void PreviewReportWidgetPrivate::activateItemSelectionMode() { m_previewPage->startEditMode(); } -void PreviewReportWidgetPrivate::deleteSelectedItems() -{ - m_previewPage->deleteSelected(); -} +void PreviewReportWidgetPrivate::deleteSelectedItems() { m_previewPage->deleteSelected(); } -PreviewReportWidget::PreviewReportWidget(ReportEngine *report, QWidget *parent) : +PreviewReportWidget::PreviewReportWidget(ReportEngine* report, QWidget* parent): QWidget(parent), - ui(new Ui::PreviewReportWidget), d_ptr(new PreviewReportWidgetPrivate(this)), - m_scaleType(FitWidth), m_scalePercent(0), m_previewPageBackgroundColor(Qt::white), - m_defaultPrinter(0), m_scaleChanging(false) + ui(new Ui::PreviewReportWidget), + d_ptr(new PreviewReportWidgetPrivate(this)), + m_scaleType(FitWidth), + m_scalePercent(0), + m_previewPageBackgroundColor(Qt::white), + m_defaultPrinter(0), + m_scaleChanging(false) { ui->setupUi(this); d_ptr->m_report = report->d_ptr; d_ptr->m_previewPage = d_ptr->m_report->createPreviewPage(); - d_ptr->m_previewPage->setItemMode( LimeReport::PreviewMode ); + d_ptr->m_previewPage->setItemMode(LimeReport::PreviewMode); m_resizeTimer.setSingleShot(true); ui->errorsView->setVisible(false); - connect(ui->graphicsView->verticalScrollBar(),SIGNAL(valueChanged(int)), this, SLOT(slotSliderMoved(int))); - connect(d_ptr->m_report, SIGNAL(destroyed(QObject*)), this, SLOT(reportEngineDestroyed(QObject*))); + connect(ui->graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, + SLOT(slotSliderMoved(int))); + connect(d_ptr->m_report, SIGNAL(destroyed(QObject*)), this, + SLOT(reportEngineDestroyed(QObject*))); d_ptr->m_zoomer = new GraphicsViewZoomer(ui->graphicsView); connect(d_ptr->m_zoomer, SIGNAL(zoomed(double)), this, SLOT(slotZoomed(double))); connect(&m_resizeTimer, SIGNAL(timeout()), this, SLOT(resizeDone())); - } PreviewReportWidget::~PreviewReportWidget() @@ -115,20 +114,20 @@ PreviewReportWidget::~PreviewReportWidget() delete ui; } -QList PreviewReportWidget::aviableExporters() -{ - return d_ptr->aviableExporters(); -} +QList PreviewReportWidget::aviableExporters() { return d_ptr->aviableExporters(); } -bool PreviewReportWidget::exportReport(QString exporterName, const QMap ¶ms) +bool PreviewReportWidget::exportReport(QString exporterName, const QMap& params) { - if (ExportersFactory::instance().map().contains(exporterName)){ + if (ExportersFactory::instance().map().contains(exporterName)) { - ReportExporterInterface* e = ExportersFactory::instance().objectCreator(exporterName)(d_ptr->m_report); - QString defaultFileName = d_ptr->m_report->defaultExportDir() + d_ptr->m_report->reportName().split(".")[0]; + ReportExporterInterface* e + = ExportersFactory::instance().objectCreator(exporterName)(d_ptr->m_report); + QString defaultFileName + = d_ptr->m_report->defaultExportDir() + d_ptr->m_report->reportName().split(".")[0]; QString filter = QString("%1 (*.%2)").arg(e->exporterName()).arg(e->exporterFileExt()); - QString fileName = QFileDialog::getSaveFileName(this,tr("%1 file name").arg(e->exporterName()), defaultFileName, filter); - if (!fileName.isEmpty()){ + QString fileName = QFileDialog::getSaveFileName( + this, tr("%1 file name").arg(e->exporterName()), defaultFileName, filter); + if (!fileName.isEmpty()) { QFileInfo fi(fileName); if (fi.suffix().isEmpty()) fileName += QString(".%1").arg(e->exporterFileExt()); @@ -142,7 +141,7 @@ bool PreviewReportWidget::exportReport(QString exporterName, const QMapgraphicsView->scene()!=d_ptr->m_previewPage) + if (ui->graphicsView->scene() != d_ptr->m_previewPage) ui->graphicsView->setScene(d_ptr->m_previewPage); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) ui->graphicsView->resetMatrix(); @@ -154,8 +153,8 @@ void PreviewReportWidget::initPreview() setScalePercent(d_ptr->m_scalePercent); PageDesignIntf* page = dynamic_cast(ui->graphicsView->scene()); if (page) - connect(page, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), - this, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); + connect(page, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), this, + SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); } void PreviewReportWidget::setErrorsMesagesVisible(bool visible) @@ -165,73 +164,72 @@ void PreviewReportWidget::setErrorsMesagesVisible(bool visible) void PreviewReportWidget::zoomIn() { - d_ptr->m_scalePercent = (d_ptr->m_scalePercent / 10) * 10 + 10; + d_ptr->m_scalePercent = (d_ptr->m_scalePercent / 10) * 10 + 10; setScalePercent(d_ptr->m_scalePercent); } void PreviewReportWidget::zoomOut() { - if (d_ptr->m_scalePercent>0) + if (d_ptr->m_scalePercent > 0) d_ptr->m_scalePercent = (d_ptr->m_scalePercent / 10) * 10 - 10; setScalePercent(d_ptr->m_scalePercent); } void PreviewReportWidget::firstPage() { - d_ptr->m_changingPage=true; - if ((!d_ptr->m_reportPages.isEmpty())&&(d_ptr->m_currentPage>1)){ - d_ptr->m_currentPage=1; + d_ptr->m_changingPage = true; + if ((!d_ptr->m_reportPages.isEmpty()) && (d_ptr->m_currentPage > 1)) { + d_ptr->m_currentPage = 1; ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); emit pageChanged(d_ptr->m_currentPage); activateCurrentPage(); } - d_ptr->m_changingPage=false; + d_ptr->m_changingPage = false; } void PreviewReportWidget::priorPage() { - d_ptr->m_changingPage=true; - if ((!d_ptr->m_reportPages.isEmpty())&&(d_ptr->m_currentPage>1)){ - d_ptr->m_currentPage--; - ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); - emit pageChanged(d_ptr->m_currentPage); - activateCurrentPage(); + d_ptr->m_changingPage = true; + if ((!d_ptr->m_reportPages.isEmpty()) && (d_ptr->m_currentPage > 1)) { + d_ptr->m_currentPage--; + ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); + emit pageChanged(d_ptr->m_currentPage); + activateCurrentPage(); } - d_ptr->m_changingPage=false; + d_ptr->m_changingPage = false; } void PreviewReportWidget::nextPage() { - d_ptr->m_changingPage=true; - if ((!d_ptr->m_reportPages.isEmpty())&&(d_ptr->m_reportPages.count()>(d_ptr->m_currentPage))){ + d_ptr->m_changingPage = true; + if ((!d_ptr->m_reportPages.isEmpty()) + && (d_ptr->m_reportPages.count() > (d_ptr->m_currentPage))) { d_ptr->m_currentPage++; ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); emit pageChanged(d_ptr->m_currentPage); activateCurrentPage(); } - d_ptr->m_changingPage=false; + d_ptr->m_changingPage = false; } void PreviewReportWidget::lastPage() { - d_ptr->m_changingPage=true; - if ((!d_ptr->m_reportPages.isEmpty())&&(d_ptr->m_reportPages.count()>(d_ptr->m_currentPage))){ - d_ptr->m_currentPage=d_ptr->m_reportPages.count(); + d_ptr->m_changingPage = true; + if ((!d_ptr->m_reportPages.isEmpty()) + && (d_ptr->m_reportPages.count() > (d_ptr->m_currentPage))) { + d_ptr->m_currentPage = d_ptr->m_reportPages.count(); ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); emit pageChanged(d_ptr->m_currentPage); activateCurrentPage(); } - d_ptr->m_changingPage=false; + d_ptr->m_changingPage = false; } void PreviewReportWidget::printPages(QPrinter* printer) { if (!d_ptr->m_reportPages.isEmpty()) - d_ptr->m_report->printPages( - d_ptr->m_reportPages, - printer - ); - foreach(PageItemDesignIntf::Ptr pageItem, d_ptr->m_reportPages){ + d_ptr->m_report->printPages(d_ptr->m_reportPages, printer); + foreach (PageItemDesignIntf::Ptr pageItem, d_ptr->m_reportPages) { d_ptr->m_previewPage->reactivatePageItem(pageItem); } } @@ -241,28 +239,27 @@ void PreviewReportWidget::print() QPrinterInfo pi; QPrinter lp(QPrinter::HighResolution); - if (!pi.defaultPrinter().isNull()){ + if (!pi.defaultPrinter().isNull()) { #if QT_VERSION >= 0x050300 - lp.setPrinterName(pi.defaultPrinterName()); + lp.setPrinterName(pi.defaultPrinterName()); #else - lp.setPrinterName(pi.defaultPrinter().printerName()); + lp.setPrinterName(pi.defaultPrinter().printerName()); #endif } QPrinter* printer = m_defaultPrinter ? m_defaultPrinter : &lp; - QPrintDialog dialog(printer,QApplication::activeWindow()); - if (dialog.exec()==QDialog::Accepted){ + QPrintDialog dialog(printer, QApplication::activeWindow()); + if (dialog.exec() == QDialog::Accepted) { printPages(printer); } - } void PreviewReportWidget::printToPDF() { - if (!d_ptr->m_reportPages.isEmpty()){ + if (!d_ptr->m_reportPages.isEmpty()) { exportReport("PDF"); - foreach(PageItemDesignIntf::Ptr pageItem, d_ptr->m_reportPages){ + foreach (PageItemDesignIntf::Ptr pageItem, d_ptr->m_reportPages) { d_ptr->m_previewPage->reactivatePageItem(pageItem); } } @@ -270,14 +267,15 @@ void PreviewReportWidget::printToPDF() void PreviewReportWidget::pageNavigatorChanged(int value) { - if (d_ptr->m_changingPage) return; + if (d_ptr->m_changingPage) + return; d_ptr->m_changingPage = true; - if ((!d_ptr->m_reportPages.isEmpty())&&(d_ptr->m_reportPages.count() >= value) && value>0){ + if ((!d_ptr->m_reportPages.isEmpty()) && (d_ptr->m_reportPages.count() >= value) && value > 0) { d_ptr->m_currentPage = value; activateCurrentPage(); ui->graphicsView->ensureVisible(d_ptr->calcPageShift(), 0, 0); } - d_ptr->m_changingPage=false; + d_ptr->m_changingPage = false; } void PreviewReportWidget::saveToFile() @@ -285,11 +283,12 @@ void PreviewReportWidget::saveToFile() bool saved = false; PreparedPages pagesManager = PreparedPages(&d_ptr->m_reportPages); emit onSave(saved, &pagesManager); - if (!saved){ - QString fileName = QFileDialog::getSaveFileName(this,tr("Report file name"), d_ptr->m_report->defaultExportDir()); - if (!fileName.isEmpty()){ - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); - foreach (PageItemDesignIntf::Ptr page, d_ptr->m_reportPages){ + if (!saved) { + QString fileName = QFileDialog::getSaveFileName(this, tr("Report file name"), + d_ptr->m_report->defaultExportDir()); + if (!fileName.isEmpty()) { + QScopedPointer writer(new XMLWriter()); + foreach (PageItemDesignIntf::Ptr page, d_ptr->m_reportPages) { writer->putItem(page.data()); } writer->saveToFile(fileName); @@ -306,10 +305,10 @@ void PreviewReportWidget::setScalePercent(int percent) ui->graphicsView->resetTransform(); #endif d_ptr->m_scalePercent = percent; - qreal scaleSize = percent/100.0; + qreal scaleSize = percent / 100.0; ui->graphicsView->scale(scaleSize, scaleSize); emit scalePercentChanged(percent); - if (percent == 100){ + if (percent == 100) { m_scaleType = OneToOne; } else { m_scaleType = Percents; @@ -320,71 +319,47 @@ void PreviewReportWidget::setScalePercent(int percent) void PreviewReportWidget::fitWidth() { - if (d_ptr->currentPage()){ + if (d_ptr->currentPage()) { resize(m_scaleType = FitWidth); } } void PreviewReportWidget::fitPage() { - if (d_ptr->currentPage()){ + if (d_ptr->currentPage()) { resize(m_scaleType = FitPage); } } -void PreviewReportWidget::resizeEvent(QResizeEvent *) -{ - m_resizeTimer.start(100); -} +void PreviewReportWidget::resizeEvent(QResizeEvent*) { m_resizeTimer.start(100); } -void PreviewReportWidget::setErrorMessages(const QStringList &value) +void PreviewReportWidget::setErrorMessages(const QStringList& value) { foreach (QString line, value) { ui->errorsView->append(line); } } -void PreviewReportWidget::emitPageSet() -{ - emit pagesSet(d_ptr->m_reportPages.count()); -} +void PreviewReportWidget::emitPageSet() { emit pagesSet(d_ptr->m_reportPages.count()); } -QPrinter *PreviewReportWidget::defaultPrinter() const -{ - return m_defaultPrinter; -} +QPrinter* PreviewReportWidget::defaultPrinter() const { return m_defaultPrinter; } -void PreviewReportWidget::setDefaultPrinter(QPrinter *defaultPrinter) +void PreviewReportWidget::setDefaultPrinter(QPrinter* defaultPrinter) { m_defaultPrinter = defaultPrinter; } -ScaleType PreviewReportWidget::scaleType() const -{ - return m_scaleType; -} +ScaleType PreviewReportWidget::scaleType() const { return m_scaleType; } -void PreviewReportWidget::startInsertTextItem() -{ - d_ptr->startInsertTextItem(); -} +void PreviewReportWidget::startInsertTextItem() { d_ptr->startInsertTextItem(); } -void PreviewReportWidget::activateItemSelectionMode() -{ - d_ptr->activateItemSelectionMode(); -} +void PreviewReportWidget::activateItemSelectionMode() { d_ptr->activateItemSelectionMode(); } -void PreviewReportWidget::deleteSelectedItems() -{ - d_ptr->deleteSelectedItems(); -} +void PreviewReportWidget::deleteSelectedItems() { d_ptr->deleteSelectedItems(); } -int PreviewReportWidget::scalePercent() const -{ - return m_scalePercent; -} +int PreviewReportWidget::scalePercent() const { return m_scalePercent; } -void PreviewReportWidget::setScaleType(const ScaleType &scaleType, int percent) +void PreviewReportWidget::setScaleType(const ScaleType& scaleType, int percent) { m_scaleType = scaleType; m_scalePercent = percent; @@ -395,25 +370,22 @@ void PreviewReportWidget::setPreviewPageBackgroundColor(QColor color) m_previewPageBackgroundColor = color; } -QColor PreviewReportWidget::previewPageBackgroundColor() -{ - return m_previewPageBackgroundColor; -} +QColor PreviewReportWidget::previewPageBackgroundColor() { return m_previewPageBackgroundColor; } void PreviewReportWidget::refreshPages() { - if (d_ptr->m_report){ - try{ + if (d_ptr->m_report) { + try { d_ptr->m_report->dataManager()->setDesignTime(false); ReportPages pages = d_ptr->m_report->renderToPages(); d_ptr->m_report->dataManager()->setDesignTime(true); - if (pages.count()>0){ + if (pages.count() > 0) { d_ptr->setPages(pages); } - } catch (ReportError &exception){ + } catch (ReportError& exception) { d_ptr->m_report->saveError(exception.what()); d_ptr->m_report->showError(exception.what()); - } + } } } @@ -428,13 +400,14 @@ void PreviewReportWidget::resize(ScaleType scaleType, int percent) { switch (scaleType) { case FitWidth: - setScalePercent(ui->graphicsView->viewport()->width() / ui->graphicsView->scene()->width()*100); + setScalePercent(ui->graphicsView->viewport()->width() / ui->graphicsView->scene()->width() + * 100); break; case FitPage: - setScalePercent(qMin( - ui->graphicsView->viewport()->width() / ui->graphicsView->scene()->width(), - ui->graphicsView->viewport()->height() / d_ptr->currentPage()->height() - ) * 100); + setScalePercent( + qMin(ui->graphicsView->viewport()->width() / ui->graphicsView->scene()->width(), + ui->graphicsView->viewport()->height() / d_ptr->currentPage()->height()) + * 100); break; case OneToOne: setScalePercent(100); @@ -443,28 +416,28 @@ void PreviewReportWidget::resize(ScaleType scaleType, int percent) setScalePercent(percent); break; } - } void PreviewReportWidget::slotSliderMoved(int value) { - if (m_scaleChanging) return; + if (m_scaleChanging) + return; int curPage = d_ptr->m_currentPage; - if (ui->graphicsView->verticalScrollBar()->minimum()==value){ + if (ui->graphicsView->verticalScrollBar()->minimum() == value) { d_ptr->m_currentPage = 1; - } else if (ui->graphicsView->verticalScrollBar()->maximum()==value){ + } else if (ui->graphicsView->verticalScrollBar()->maximum() == value) { d_ptr->m_currentPage = d_ptr->m_reportPages.count(); } - if (!d_ptr->pageIsVisible()){ - if (value>d_ptr->m_priorScrolValue){ + if (!d_ptr->pageIsVisible()) { + if (value > d_ptr->m_priorScrolValue) { d_ptr->m_currentPage++; } else { d_ptr->m_currentPage--; } } - if (curPage != d_ptr->m_currentPage){ + if (curPage != d_ptr->m_currentPage) { d_ptr->m_changingPage = true; emit pageChanged(d_ptr->m_currentPage); activateCurrentPage(); @@ -474,19 +447,19 @@ void PreviewReportWidget::slotSliderMoved(int value) d_ptr->m_priorScrolValue = value; } -void PreviewReportWidget::reportEngineDestroyed(QObject *object) +void PreviewReportWidget::reportEngineDestroyed(QObject* object) { - if (object == d_ptr->m_report){ + if (object == d_ptr->m_report) { d_ptr->m_report = 0; } } -void PreviewReportWidget::slotZoomed(double ) +void PreviewReportWidget::slotZoomed(double) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) - d_ptr->m_scalePercent = ui->graphicsView->matrix().m11()*100; + d_ptr->m_scalePercent = ui->graphicsView->matrix().m11() * 100; #else - d_ptr->m_scalePercent = ui->graphicsView->transform().m11()*100; + d_ptr->m_scalePercent = ui->graphicsView->transform().m11() * 100; #endif emit scalePercentChanged(d_ptr->m_scalePercent); } @@ -509,5 +482,4 @@ void PreviewReportWidget::resizeDone() } } - -} +} // namespace LimeReport diff --git a/limereport/lrpreviewreportwidget.h b/limereport/lrpreviewreportwidget.h index 9a9eab7..c9b4377 100644 --- a/limereport/lrpreviewreportwidget.h +++ b/limereport/lrpreviewreportwidget.h @@ -1,16 +1,17 @@ #ifndef LRPREVIEWREPORTWIDGET_H #define LRPREVIEWREPORTWIDGET_H -#include -#include -#include #include "lrglobal.h" #include "lrpreparedpagesintf.h" +#include +#include +#include + namespace LimeReport { namespace Ui { -class PreviewReportWidget; + class PreviewReportWidget; } class PreviewReportWidgetPrivate; @@ -18,29 +19,30 @@ class ReportEnginePrivate; class ReportEngine; class PageDesignIntf; -class LIMEREPORT_EXPORT PreviewReportWidget : public QWidget -{ +class LIMEREPORT_EXPORT PreviewReportWidget: public QWidget { Q_OBJECT friend class ReportEnginePrivate; friend class PreviewReportWindow; friend class PreviewReportWidgetPrivate; + public: - explicit PreviewReportWidget(ReportEngine *report, QWidget *parent = 0); + explicit PreviewReportWidget(ReportEngine* report, QWidget* parent = 0); ~PreviewReportWidget(); QList aviableExporters(); - bool exportReport(QString exporterName, const QMap& params = QMap()); + bool exportReport(QString exporterName, + const QMap& params = QMap()); ScaleType scaleType() const; - int scalePercent() const; - void setScaleType(const ScaleType &scaleType, int percent = 0); + int scalePercent() const; + void setScaleType(const ScaleType& scaleType, int percent = 0); void setPreviewPageBackgroundColor(QColor color); QColor previewPageBackgroundColor(); - QPrinter *defaultPrinter() const; - void setDefaultPrinter(QPrinter *defaultPrinter); + QPrinter* defaultPrinter() const; + void setDefaultPrinter(QPrinter* defaultPrinter); void startInsertTextItem(); void activateItemSelectionMode(); void deleteSelectedItems(); void activateCurrentPage(); - void resize(ScaleType scaleType, int percent=0); + void resize(ScaleType scaleType, int percent = 0); public slots: void refreshPages(); @@ -59,8 +61,9 @@ public slots: void setScalePercent(int percent); void fitWidth(); void fitPage(); + protected: - void resizeEvent(QResizeEvent *); + void resizeEvent(QResizeEvent*); signals: void pageChanged(int page); void scalePercentChanged(int percent); @@ -72,20 +75,22 @@ private slots: void reportEngineDestroyed(QObject* object); void slotZoomed(double); void resizeDone(); + private: void initPreview(); void setErrorsMesagesVisible(bool visible); - void setErrorMessages(const QStringList &value); + void setErrorMessages(const QStringList& value); void emitPageSet(); + private: - Ui::PreviewReportWidget *ui; + Ui::PreviewReportWidget* ui; PreviewReportWidgetPrivate* d_ptr; ScaleType m_scaleType; - int m_scalePercent; - QTimer m_resizeTimer; - QColor m_previewPageBackgroundColor; + int m_scalePercent; + QTimer m_resizeTimer; + QColor m_previewPageBackgroundColor; QPrinter* m_defaultPrinter; - void printPages(QPrinter *printer); + void printPages(QPrinter* printer); bool m_scaleChanging; }; diff --git a/limereport/lrpreviewreportwidget_p.h b/limereport/lrpreviewreportwidget_p.h index d7dc719..07aba42 100644 --- a/limereport/lrpreviewreportwidget_p.h +++ b/limereport/lrpreviewreportwidget_p.h @@ -1,32 +1,40 @@ #ifndef LRPREVIEWREPORTWIDGET_P_H #define LRPREVIEWREPORTWIDGET_P_H +#include "lrgraphicsviewzoom.h" #include "lrpagedesignintf.h" #include "lrreportrender.h" -#include "lrgraphicsviewzoom.h" -namespace LimeReport{ +namespace LimeReport { class PreviewReportWidget; -class PreviewReportWidgetPrivate -{ +class PreviewReportWidgetPrivate { public: PreviewReportWidgetPrivate(PreviewReportWidget* previewReportWidget): - m_previewPage(NULL), m_report(NULL), m_zoomer(NULL), - m_currentPage(1), m_changingPage(false), m_priorScrolValue(0), m_scalePercent(50), - q_ptr(previewReportWidget), m_previePageColor(Qt::white) {} + m_previewPage(NULL), + m_report(NULL), + m_zoomer(NULL), + m_currentPage(1), + m_changingPage(false), + m_priorScrolValue(0), + m_scalePercent(50), + q_ptr(previewReportWidget), + m_previePageColor(Qt::white) + { + } bool pageIsVisible(); QRectF calcPageShift(); - void setPages( ReportPages pages); + void setPages(ReportPages pages); PageItemDesignIntf::Ptr currentPage(); QList aviableExporters(); void startInsertTextItem(); void activateItemSelectionMode(); void deleteSelectedItems(); + public: PageDesignIntf* m_previewPage; - ReportPages m_reportPages; + ReportPages m_reportPages; ReportEnginePrivate* m_report; GraphicsViewZoomer* m_zoomer; int m_currentPage; @@ -37,5 +45,5 @@ public: QColor m_previePageColor; }; -} +} // namespace LimeReport #endif // LRPREVIEWREPORTWIDGET_P_H diff --git a/limereport/lrpreviewreportwindow.cpp b/limereport/lrpreviewreportwindow.cpp index 7659288..94687d8 100644 --- a/limereport/lrpreviewreportwindow.cpp +++ b/limereport/lrpreviewreportwindow.cpp @@ -29,15 +29,16 @@ ****************************************************************************/ #include "lrpreviewreportwindow.h" #include "ui_lrpreviewreportwindow.h" -#include "lrreportengine_p.h" -#include "lrpreviewreportwidget.h" -#include "lrpreviewreportwidget_p.h" + #include "items/editors/lrfonteditorwidget.h" #include "items/editors/lrtextalignmenteditorwidget.h" +#include "lrpreviewreportwidget.h" +#include "lrpreviewreportwidget_p.h" +#include "lrreportengine_p.h" -#include -#include #include +#include +#include #include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include @@ -48,11 +49,14 @@ #include #include -namespace LimeReport{ +namespace LimeReport { -PreviewReportWindow::PreviewReportWindow(ReportEngine *report, QWidget *parent, QSettings *settings, Qt::WindowFlags flags) : - QMainWindow(parent,flags), - ui(new Ui::PreviewReportWindow), m_settings(settings), m_ownedSettings(false), +PreviewReportWindow::PreviewReportWindow(ReportEngine* report, QWidget* parent, QSettings* settings, + Qt::WindowFlags flags): + QMainWindow(parent, flags), + ui(new Ui::PreviewReportWindow), + m_settings(settings), + m_ownedSettings(false), m_scalePercentChanging(false) { ui->setupUi(this); @@ -80,51 +84,59 @@ PreviewReportWindow::PreviewReportWindow(ReportEngine *report, QWidget *parent, m_pagesNavigator->setMaximum(10000000); m_pagesNavigator->setPrefix(tr("Page: ")); m_pagesNavigator->setMinimumWidth(120); - ui->toolBar->insertWidget(ui->actionNextPage,m_pagesNavigator); + ui->toolBar->insertWidget(ui->actionNextPage, m_pagesNavigator); ui->editModeTools->hide(); ui->actionShowMessages->setVisible(false); - connect(m_pagesNavigator,SIGNAL(valueChanged(int)),this,SLOT(slotPageNavigatorChanged(int))); - m_previewReportWidget = new PreviewReportWidget(report,this); + connect(m_pagesNavigator, SIGNAL(valueChanged(int)), this, SLOT(slotPageNavigatorChanged(int))); + m_previewReportWidget = new PreviewReportWidget(report, this); setCentralWidget(m_previewReportWidget); - layout()->setContentsMargins(1,1,1,1); - connect(m_previewReportWidget, SIGNAL(pageChanged(int)), - this, SLOT(slotPageChanged(int)) ); - connect(m_previewReportWidget->d_ptr->m_previewPage, SIGNAL(selectionChanged()), - this, SLOT(slotSelectionChanged())); - connect(m_pagesNavigator, SIGNAL(valueChanged(int)), - this, SLOT(slotPageNavigatorChanged(int))); - connect(m_previewReportWidget, SIGNAL(onSave(bool&, LimeReport::IPreparedPages*)), - this, SIGNAL(onSave(bool&, LimeReport::IPreparedPages*))); + layout()->setContentsMargins(1, 1, 1, 1); + connect(m_previewReportWidget, SIGNAL(pageChanged(int)), this, SLOT(slotPageChanged(int))); + connect(m_previewReportWidget->d_ptr->m_previewPage, SIGNAL(selectionChanged()), this, + SLOT(slotSelectionChanged())); + connect(m_pagesNavigator, SIGNAL(valueChanged(int)), this, SLOT(slotPageNavigatorChanged(int))); + connect(m_previewReportWidget, SIGNAL(onSave(bool&, LimeReport::IPreparedPages*)), this, + SIGNAL(onSave(bool&, LimeReport::IPreparedPages*))); - connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(printingStarted(int)), this, SLOT(slotPrintingStarted(int))); - connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(pagePrintingFinished(int)), this, SLOT(slotPagePrintingFinished(int))); - connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(printingFinished()), this, SLOT(slotPrintingFinished())); + connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(printingStarted(int)), this, + SLOT(slotPrintingStarted(int))); + connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(pagePrintingFinished(int)), this, + SLOT(slotPagePrintingFinished(int))); + connect(m_previewReportWidget->d_ptr->m_report, SIGNAL(printingFinished()), this, + SLOT(slotPrintingFinished())); - m_fontEditor = new FontEditorWidgetForPage(m_previewReportWidget->d_ptr->m_previewPage,tr("Font"),this); + m_fontEditor = new FontEditorWidgetForPage(m_previewReportWidget->d_ptr->m_previewPage, + tr("Font"), this); m_fontEditor->setObjectName("fontTools"); m_fontEditor->setIconSize(ui->toolBar->iconSize()); - m_textAlignmentEditor = new TextAlignmentEditorWidgetForPage(m_previewReportWidget->d_ptr->m_previewPage,tr("Text align"),this); + m_textAlignmentEditor = new TextAlignmentEditorWidgetForPage( + m_previewReportWidget->d_ptr->m_previewPage, tr("Text align"), this); m_textAlignmentEditor->setObjectName("textAlignmentTools"); m_textAlignmentEditor->setIconSize(ui->toolBar->iconSize()); - addToolBar(Qt::TopToolBarArea,m_fontEditor); - addToolBar(Qt::TopToolBarArea,m_textAlignmentEditor); + addToolBar(Qt::TopToolBarArea, m_fontEditor); + addToolBar(Qt::TopToolBarArea, m_textAlignmentEditor); m_scalePercent = new QComboBox(this); m_scalePercent->setEditable(true); ui->toolBar->insertWidget(ui->actionZoomOut, m_scalePercent); initPercentCombobox(); - + connect(ui->actionShowMessages, SIGNAL(triggered()), this, SLOT(slotShowErrors())); - connect(m_previewReportWidget, SIGNAL(scalePercentChanged(int)), this, SLOT(slotScalePercentChanged(int))); + connect(m_previewReportWidget, SIGNAL(scalePercentChanged(int)), this, + SLOT(slotScalePercentChanged(int))); #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 3) - connect(m_scalePercent, SIGNAL(currentTextChanged(QString)), this, SLOT(scaleComboboxChanged(QString))); + connect(m_scalePercent, SIGNAL(currentTextChanged(QString)), this, + SLOT(scaleComboboxChanged(QString))); #else - connect(m_scalePercent, SIGNAL(currentIndexChanged(QString)), this, SLOT(scaleComboboxChanged(QString))); + connect(m_scalePercent, SIGNAL(currentIndexChanged(QString)), this, + SLOT(scaleComboboxChanged(QString))); #endif - connect(m_previewReportWidget, SIGNAL(pageChanged(int)), this, SLOT(slotCurrentPageChanged(int))); - connect(m_previewReportWidget, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), - this, SLOT(slotItemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); + connect(m_previewReportWidget, SIGNAL(pageChanged(int)), this, + SLOT(slotCurrentPageChanged(int))); + connect(m_previewReportWidget, + SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), this, + SLOT(slotItemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); restoreSetting(); selectStateIcon(); @@ -133,8 +145,8 @@ PreviewReportWindow::PreviewReportWindow(ReportEngine *report, QWidget *parent, void PreviewReportWindow::writeSetting() { settings()->beginGroup("PreviewWindow"); - settings()->setValue("Geometry",saveGeometry()); - settings()->setValue("State",saveState()); + settings()->setValue("Geometry", saveGeometry()); + settings()->setValue("State", saveState()); settings()->endGroup(); } @@ -142,37 +154,33 @@ void PreviewReportWindow::restoreSetting() { settings()->beginGroup("PreviewWindow"); QVariant v = settings()->value("Geometry"); - if (v.isValid()){ + if (v.isValid()) { restoreGeometry(v.toByteArray()); } else { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - QDesktopWidget *desktop = QApplication::desktop(); + QDesktopWidget* desktop = QApplication::desktop(); int screenWidth = desktop->screenGeometry().width(); int screenHeight = desktop->screenGeometry().height(); #else - QScreen *screen = QGuiApplication::primaryScreen(); + QScreen* screen = QGuiApplication::primaryScreen(); int screenWidth = screen->geometry().width(); int screenHeight = screen->geometry().height(); #endif - int x = static_cast(screenWidth*0.1); - int y = static_cast(screenHeight*0.1); + int x = static_cast(screenWidth * 0.1); + int y = static_cast(screenHeight * 0.1); - resize( - static_cast(screenWidth*0.8), - static_cast(screenHeight*0.8) - ); + resize(static_cast(screenWidth * 0.8), static_cast(screenHeight * 0.8)); move(x, y); } v = settings()->value("State"); - if (v.isValid()){ + if (v.isValid()) { restoreState(v.toByteArray()); } settings()->endGroup(); } - PreviewReportWindow::~PreviewReportWindow() { if (m_ownedSettings) @@ -188,21 +196,19 @@ void PreviewReportWindow::initPreview(int pagesCount) m_pagesNavigator->setValue(1); } -void PreviewReportWindow::reloadPreview() -{ - m_previewReportWidget->refreshPages(); -} +void PreviewReportWindow::reloadPreview() { m_previewReportWidget->refreshPages(); } void PreviewReportWindow::setSettings(QSettings* value) { if (m_ownedSettings) delete m_settings; - m_settings=value; - m_ownedSettings=false; + m_settings = value; + m_ownedSettings = false; restoreSetting(); } -void PreviewReportWindow::setErrorMessages(const QStringList &value){ +void PreviewReportWindow::setErrorMessages(const QStringList& value) +{ ui->actionShowMessages->setVisible(true); m_previewReportWidget->setErrorMessages(value); } @@ -213,15 +219,9 @@ void PreviewReportWindow::setToolBarVisible(bool value) selectStateIcon(); } -void PreviewReportWindow::setStatusBarVisible(bool value) -{ - ui->statusbar->setVisible(value); -} +void PreviewReportWindow::setStatusBarVisible(bool value) { ui->statusbar->setVisible(value); } -void PreviewReportWindow::setMenuVisible(bool value) -{ - ui->menubar->setVisible(value); -} +void PreviewReportWindow::setMenuVisible(bool value) { ui->menubar->setVisible(value); } void PreviewReportWindow::setHideResultEditButton(bool value) { @@ -232,10 +232,7 @@ void PreviewReportWindow::setHideResultEditButton(bool value) } } -void PreviewReportWindow::setHidePrintButton(bool value) -{ - ui->actionPrint->setVisible(value); -} +void PreviewReportWindow::setHidePrintButton(bool value) { ui->actionPrint->setVisible(value); } void PreviewReportWindow::setHideSaveToFileButton(bool value) { @@ -247,17 +244,14 @@ void PreviewReportWindow::setHidePrintToPdfButton(bool value) ui->actionPrint_To_PDF->setVisible(value); } -void PreviewReportWindow::setEnablePrintMenu(bool value) -{ - ui->menuReport->setEnabled(value); -} +void PreviewReportWindow::setEnablePrintMenu(bool value) { ui->menuReport->setEnabled(value); } -QSettings*PreviewReportWindow::settings() +QSettings* PreviewReportWindow::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QCoreApplication::applicationName()); + m_settings = new QSettings("LimeReport", QCoreApplication::applicationName()); m_ownedSettings = true; return m_settings; } @@ -266,12 +260,12 @@ QSettings*PreviewReportWindow::settings() void PreviewReportWindow::setPages(ReportPages pages) { m_previewReportWidget->d_ptr->setPages(pages); - if (!pages.isEmpty()){ + if (!pages.isEmpty()) { initPreview(pages.count()); } } -void PreviewReportWindow::setDefaultPrinter(QPrinter *printer) +void PreviewReportWindow::setDefaultPrinter(QPrinter* printer) { m_previewReportWidget->setDefaultPrinter(printer); } @@ -279,16 +273,17 @@ void PreviewReportWindow::setDefaultPrinter(QPrinter *printer) void PreviewReportWindow::exec() { bool deleteOnClose = testAttribute(Qt::WA_DeleteOnClose); - setAttribute(Qt::WA_DeleteOnClose,false); - setAttribute(Qt::WA_ShowModal,true); + setAttribute(Qt::WA_DeleteOnClose, false); + setAttribute(Qt::WA_ShowModal, true); show(); m_eventLoop.exec(); - if (deleteOnClose) delete this; + if (deleteOnClose) + delete this; } void PreviewReportWindow::closeEvent(QCloseEvent* e) { - if (m_progressBar->isVisible()){ + if (m_progressBar->isVisible()) { QMessageBox::critical(this, tr("Attention"), tr("The printing is in process")); e->setAccepted(false); } @@ -304,7 +299,7 @@ void PreviewReportWindow::closeEvent(QCloseEvent* e) void PreviewReportWindow::resizeEvent(QResizeEvent* e) { #ifdef Q_OS_UNIX - if (e->oldSize()!=e->size()){ + if (e->oldSize() != e->size()) { writeSetting(); } #else @@ -315,7 +310,7 @@ void PreviewReportWindow::resizeEvent(QResizeEvent* e) void PreviewReportWindow::moveEvent(QMoveEvent* e) { #ifdef Q_OS_UNIX - if (e->oldPos()!=e->pos()){ + if (e->oldPos() != e->pos()) { writeSetting(); } #else @@ -323,7 +318,7 @@ void PreviewReportWindow::moveEvent(QMoveEvent* e) #endif } -void PreviewReportWindow::showEvent(QShowEvent *) +void PreviewReportWindow::showEvent(QShowEvent*) { m_fontEditor->setVisible(ui->actionEdit_Mode->isChecked()); if (ui->editModeTools) @@ -341,43 +336,27 @@ void PreviewReportWindow::showEvent(QShowEvent *) break; case Percents: m_previewReportWidget->setScalePercent(m_previewScalePercent); - } } void PreviewReportWindow::selectStateIcon() { - if (ui->toolBar->isHidden()){ + if (ui->toolBar->isHidden()) { ui->actionShow_Toolbar->setIcon(QIcon(":/report/images/not_checked.png")); } else { ui->actionShow_Toolbar->setIcon(QIcon(":/report/images/checked.png")); } } -void PreviewReportWindow::slotPrint() -{ - m_previewReportWidget->print(); -} +void PreviewReportWindow::slotPrint() { m_previewReportWidget->print(); } -void PreviewReportWindow::slotPriorPage() -{ - m_previewReportWidget->priorPage(); -} +void PreviewReportWindow::slotPriorPage() { m_previewReportWidget->priorPage(); } -void PreviewReportWindow::slotNextPage() -{ - m_previewReportWidget->nextPage(); -} +void PreviewReportWindow::slotNextPage() { m_previewReportWidget->nextPage(); } -void PreviewReportWindow::slotZoomIn() -{ - m_previewReportWidget->zoomIn(); -} +void PreviewReportWindow::slotZoomIn() { m_previewReportWidget->zoomIn(); } -void PreviewReportWindow::slotZoomOut() -{ - m_previewReportWidget->zoomOut(); -} +void PreviewReportWindow::slotZoomOut() { m_previewReportWidget->zoomOut(); } void PreviewReportWindow::slotPageNavigatorChanged(int value) { @@ -391,19 +370,21 @@ void PreviewReportWindow::slotShowErrors() void PreviewReportWindow::on_actionEdit_Mode_triggered(bool checked) { - m_previewReportWidget->d_ptr->m_previewPage->setItemMode((checked)?ItemModes(DesignMode):PreviewMode); + m_previewReportWidget->d_ptr->m_previewPage->setItemMode((checked) ? ItemModes(DesignMode) + : PreviewMode); m_textAlignmentEditor->setVisible(checked); m_fontEditor->setVisible(checked); if (checked) ui->editModeTools->show(); - else ui->editModeTools->hide(); + else + ui->editModeTools->hide(); } void PreviewReportWindow::slotSelectionChanged() { - QGraphicsScene* page=dynamic_cast(sender()); - if (page){ - if (page->selectedItems().count()==1){ + QGraphicsScene* page = dynamic_cast(sender()); + if (page) { + if (page->selectedItems().count() == 1) { BaseDesignIntf* item = dynamic_cast(page->selectedItems().at(0)); if (item) { m_fontEditor->setItem(item); @@ -413,25 +394,19 @@ void PreviewReportWindow::slotSelectionChanged() } } -ItemsReaderIntf *PreviewReportWindow::reader() -{ - return m_reader.data(); -} +ItemsReaderIntf* PreviewReportWindow::reader() { return m_reader.data(); } void PreviewReportWindow::initPercentCombobox() { - for (int i = 10; i<310; i+=10){ + for (int i = 10; i < 310; i += 10) { m_scalePercent->addItem(QString("%1%").arg(i)); } m_scalePercent->setCurrentIndex(4); } -ScaleType PreviewReportWindow::previewScaleType() const -{ - return m_previewScaleType; -} +ScaleType PreviewReportWindow::previewScaleType() const { return m_previewScaleType; } -void PreviewReportWindow::setPreviewScaleType(const ScaleType &previewScaleType, int percent) +void PreviewReportWindow::setPreviewScaleType(const ScaleType& previewScaleType, int percent) { m_previewScaleType = previewScaleType; m_previewScalePercent = percent; @@ -448,30 +423,15 @@ void PreviewReportWindow::setPreviewPageBackgroundColor(QColor color) m_previewReportWidget->setPreviewPageBackgroundColor(color); } -void PreviewReportWindow::on_actionSaveToFile_triggered() -{ - m_previewReportWidget->saveToFile(); -} +void PreviewReportWindow::on_actionSaveToFile_triggered() { m_previewReportWidget->saveToFile(); } -void PreviewReportWindow::slotFirstPage() -{ - m_previewReportWidget->firstPage(); -} +void PreviewReportWindow::slotFirstPage() { m_previewReportWidget->firstPage(); } -void PreviewReportWindow::slotLastPage() -{ - m_previewReportWidget->lastPage(); -} +void PreviewReportWindow::slotLastPage() { m_previewReportWidget->lastPage(); } -void PreviewReportWindow::slotPrintToPDF() -{ - m_previewReportWidget->printToPDF(); -} +void PreviewReportWindow::slotPrintToPDF() { m_previewReportWidget->printToPDF(); } -void PreviewReportWindow::slotPageChanged(int pageIndex) -{ - m_pagesNavigator->setValue(pageIndex); -} +void PreviewReportWindow::slotPageChanged(int pageIndex) { m_pagesNavigator->setValue(pageIndex); } void PreviewReportWindow::slotInsertNewTextItem() { @@ -491,15 +451,9 @@ void PreviewReportWindow::slotDeleteSelectedItems() m_previewReportWidget->deleteSelectedItems(); } -void PreviewReportWindow::on_actionFit_page_width_triggered() -{ - m_previewReportWidget->fitWidth(); -} +void PreviewReportWindow::on_actionFit_page_width_triggered() { m_previewReportWidget->fitWidth(); } -void PreviewReportWindow::on_actionFit_page_triggered() -{ - m_previewReportWidget->fitPage(); -} +void PreviewReportWindow::on_actionFit_page_triggered() { m_previewReportWidget->fitPage(); } void PreviewReportWindow::on_actionOne_to_one_triggered() { @@ -508,15 +462,17 @@ void PreviewReportWindow::on_actionOne_to_one_triggered() void PreviewReportWindow::scaleComboboxChanged(QString text) { - if (m_scalePercentChanging) return; + if (m_scalePercentChanging) + return; m_scalePercentChanging = true; - m_previewReportWidget->setScalePercent(text.remove(text.count()-1,1).toInt()); + m_previewReportWidget->setScalePercent(text.remove(text.count() - 1, 1).toInt()); m_scalePercentChanging = false; } void PreviewReportWindow::slotScalePercentChanged(int percent) { - if (m_scalePercentChanging) return; + if (m_scalePercentChanging) + return; m_scalePercentChanging = true; if (m_scalePercent->findText(QString("%1%").arg(percent)) == -1) m_scalePercent->setCurrentIndex(-1); @@ -526,7 +482,7 @@ void PreviewReportWindow::slotScalePercentChanged(int percent) void PreviewReportWindow::on_actionShowMessages_toggled(bool value) { - m_previewReportWidget->setErrorsMesagesVisible(value); + m_previewReportWidget->setErrorsMesagesVisible(value); } void PreviewReportWindow::on_actionShow_Toolbar_triggered() @@ -535,12 +491,9 @@ void PreviewReportWindow::on_actionShow_Toolbar_triggered() writeSetting(); } -void PreviewReportWindow::slotCurrentPageChanged(int /*page*/) -{ - slotActivateItemSelectionMode(); -} +void PreviewReportWindow::slotCurrentPageChanged(int /*page*/) { slotActivateItemSelectionMode(); } -void PreviewReportWindow::slotItemInserted(PageDesignIntf *, QPointF, const QString&) +void PreviewReportWindow::slotItemInserted(PageDesignIntf*, QPointF, const QString&) { slotActivateItemSelectionMode(); } @@ -557,15 +510,11 @@ void PreviewReportWindow::slotPagePrintingFinished(int pageIndex) m_progressBar->setValue(pageIndex); } -void PreviewReportWindow::slotPrintingFinished() -{ - m_progressWidget->setVisible(false); -} +void PreviewReportWindow::slotPrintingFinished() { m_progressWidget->setVisible(false); } void PreviewReportWindow::slotCancelPrinting(bool) { m_previewReportWidget->d_ptr->m_report->cancelPrinting(); } -}// namespace LimeReport - +} // namespace LimeReport diff --git a/limereport/lrpreviewreportwindow.h b/limereport/lrpreviewreportwindow.h index be84775..9568244 100644 --- a/limereport/lrpreviewreportwindow.h +++ b/limereport/lrpreviewreportwindow.h @@ -30,22 +30,22 @@ #ifndef LRPREVIEWREPORTWINDOW_H #define LRPREVIEWREPORTWINDOW_H -#include -#include -#include +#include "lrpreparedpagesintf.h" +#include "serializators/lrxmlreader.h" + #include -#include +#include #include +#include #include #include - -#include "serializators/lrxmlreader.h" -#include "lrpreparedpagesintf.h" +#include +#include namespace LimeReport { namespace Ui { -class PreviewReportWindow; + class PreviewReportWindow; } class PreviewReportWidget; @@ -53,14 +53,13 @@ class FontEditorWidget; class TextAlignmentEditorWidget; class ReportEngine; class PageItemDesignIntf; -typedef QList< QSharedPointer > ReportPages; +typedef QList> ReportPages; - -class PreviewReportWindow : public QMainWindow -{ - Q_OBJECT +class PreviewReportWindow: public QMainWindow { + Q_OBJECT public: - explicit PreviewReportWindow(ReportEngine *report, QWidget *parent = 0, QSettings* settings=0, Qt::WindowFlags flags=Qt::WindowFlags()); + explicit PreviewReportWindow(ReportEngine* report, QWidget* parent = 0, QSettings* settings = 0, + Qt::WindowFlags flags = Qt::WindowFlags()); ~PreviewReportWindow(); void setPages(ReportPages pages); void setDefaultPrinter(QPrinter* printer); @@ -79,16 +78,17 @@ public: void setEnablePrintMenu(bool value); QSettings* settings(); ScaleType previewScaleType() const; - void setPreviewScaleType(const ScaleType &previewScaleType, int percent = 0); + void setPreviewScaleType(const ScaleType& previewScaleType, int percent = 0); QColor previewPageBackgroundColor(); void setPreviewPageBackgroundColor(QColor color); + protected: void writeSetting(); void restoreSetting(); - void closeEvent(QCloseEvent *); - void resizeEvent(QResizeEvent *e); - void moveEvent(QMoveEvent *e); - void showEvent(QShowEvent *); + void closeEvent(QCloseEvent*); + void resizeEvent(QResizeEvent* e); + void moveEvent(QMoveEvent* e); + void showEvent(QShowEvent*); void selectStateIcon(); public slots: void slotPrint(); @@ -113,7 +113,7 @@ private slots: void on_actionFit_page_triggered(); void on_actionOne_to_one_triggered(); void scaleComboboxChanged(QString text); - void slotScalePercentChanged(int percent); + void slotScalePercentChanged(int percent); void on_actionShowMessages_toggled(bool value); void on_actionShow_Toolbar_triggered(); void slotCurrentPageChanged(int page); @@ -124,11 +124,13 @@ private slots: void slotCancelPrinting(bool); signals: void onSave(bool& saved, LimeReport::IPreparedPages* pages); + private: ItemsReaderIntf* reader(); void initPercentCombobox(); + private: - Ui::PreviewReportWindow *ui; + Ui::PreviewReportWindow* ui; QSpinBox* m_pagesNavigator; QSharedPointer m_reader; QEventLoop m_eventLoop; @@ -146,5 +148,5 @@ private: QProgressBar* m_progressBar; QWidget* m_progressWidget; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRPREVIEWREPORTWINDOW_H diff --git a/limereport/lrreportdesignwidget.cpp b/limereport/lrreportdesignwidget.cpp index 929a76d..63a17c6 100644 --- a/limereport/lrreportdesignwidget.cpp +++ b/limereport/lrreportdesignwidget.cpp @@ -28,36 +28,44 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrreportdesignwidget.h" + +#include "dialogdesigner/lrdialogdesigner.h" +#include "lrbasedesignintf.h" +#include "lrreportengine_p.h" +#include "lrsettingdialog.h" +#include "scripteditor/lrscripteditor.h" #include "serializators/lrxmlreader.h" #include "serializators/lrxmlwriter.h" -#include "lrreportengine_p.h" -#include "lrbasedesignintf.h" -#include "lrsettingdialog.h" -#include "dialogdesigner/lrdialogdesigner.h" #include "translationeditor/translationeditor.h" -#include "scripteditor/lrscripteditor.h" -#include -#include -#include -#include -#include -#include #include -#include +#include +#include +#include #include +#include +#include +#include +#include namespace LimeReport { // ReportDesignIntf -ReportDesignWidget::ReportDesignWidget(ReportEnginePrivateInterface* report, QSettings* settings, QMainWindow *mainWindow, QWidget *parent) : +ReportDesignWidget::ReportDesignWidget(ReportEnginePrivateInterface* report, QSettings* settings, + QMainWindow* mainWindow, QWidget* parent): QWidget(parent), #ifdef HAVE_QTDESIGNER_INTEGRATION m_dialogDesignerManager(new DialogDesignerManager(this)), #endif - m_mainWindow(mainWindow), m_verticalGridStep(10), m_horizontalGridStep(10), m_useGrid(false), - m_dialogChanged(false), m_theme("Default"), m_settings(settings), m_defaultUnits(BaseDesignIntf::Millimeters) + m_mainWindow(mainWindow), + m_verticalGridStep(10), + m_horizontalGridStep(10), + m_useGrid(false), + m_dialogChanged(false), + m_theme("Default"), + m_settings(settings), + m_defaultUnits(BaseDesignIntf::Millimeters) { #if QT_VERSION < 0x050000 m_tabWidget = new LimeReportTabWidget(this); @@ -66,50 +74,53 @@ ReportDesignWidget::ReportDesignWidget(ReportEnginePrivateInterface* report, QSe #endif m_tabWidget->setTabPosition(QTabWidget::South); m_tabWidget->setMovable(true); - connect(m_tabWidget->tabBar(), SIGNAL(tabMoved(int,int)), this, SLOT(slotTabMoved(int,int))); + connect(m_tabWidget->tabBar(), SIGNAL(tabMoved(int, int)), this, SLOT(slotTabMoved(int, int))); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->addWidget(m_tabWidget); setLayout(mainLayout); - m_report=report; + m_report = report; m_settings->beginGroup("DesignerWidget"); QVariant v = m_settings->value("DefaultUnits"); - if (v.isValid()){ + if (v.isValid()) { m_defaultUnits = static_cast(v.toInt()); } m_settings->endGroup(); - if (!m_report->pageCount()){ + if (!m_report->pageCount()) { createStartPage(); } createTabs(); - connect(dynamic_cast(m_report), SIGNAL(pagesLoadFinished()),this,SLOT(slotPagesLoadFinished())); + connect(dynamic_cast(m_report), SIGNAL(pagesLoadFinished()), this, + SLOT(slotPagesLoadFinished())); connect(dynamic_cast(m_report), SIGNAL(cleared()), this, SIGNAL(cleared())); - connect(dynamic_cast(m_report), SIGNAL(loadFinished()), this, SLOT(slotReportLoaded())); + connect(dynamic_cast(m_report), SIGNAL(loadFinished()), this, + SLOT(slotReportLoaded())); connect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotCurrentTabChanged(int))); #ifdef HAVE_UI_LOADER - connect(m_report->scriptContext(), SIGNAL(dialogDeleted(QString)), this, SLOT(slotDialogDeleted(QString))); + connect(m_report->scriptContext(), SIGNAL(dialogDeleted(QString)), this, + SLOT(slotDialogDeleted(QString))); #endif - //m_instance=this; + // m_instance=this; m_scriptEditor->setPlainText(m_report->scriptContext()->initScript()); m_zoomer = new GraphicsViewZoomer(activeView()); #ifdef Q_OS_WIN - m_defaultFont = QFont("Arial",10); + m_defaultFont = QFont("Arial", 10); #endif #ifdef HAVE_QTDESIGNER_INTEGRATION - connect(m_dialogDesignerManager, SIGNAL(dialogChanged(QString)), - this, SLOT(slotDialogChanged(QString))); - connect(m_dialogDesignerManager, SIGNAL(dialogNameChanged(QString,QString)), - this, SLOT(slotDialogNameChanged(QString,QString))); + connect(m_dialogDesignerManager, SIGNAL(dialogChanged(QString)), this, + SLOT(slotDialogChanged(QString))); + connect(m_dialogDesignerManager, SIGNAL(dialogNameChanged(QString, QString)), this, + SLOT(slotDialogNameChanged(QString, QString))); #endif - m_themes.insert("Default",""); + m_themes.insert("Default", ""); m_localToEng.insert(QObject::tr("Dark"), "Dark"); m_localToEng.insert(QObject::tr("Light"), "Light"); initThemeIfExist("Dark", ":/qdarkstyle/style.qss"); @@ -117,7 +128,7 @@ ReportDesignWidget::ReportDesignWidget(ReportEnginePrivateInterface* report, QSe } #ifdef HAVE_QTDESIGNER_INTEGRATION -DialogDesignerManager *ReportDesignWidget::dialogDesignerManager() const +DialogDesignerManager* ReportDesignWidget::dialogDesignerManager() const { return m_dialogDesignerManager; } @@ -125,12 +136,11 @@ DialogDesignerManager *ReportDesignWidget::dialogDesignerManager() const QString ReportDesignWidget::activeDialogName() { if (activeDialogPage()) - return activeDialogPage()->dialogName(); + return activeDialogPage()->dialogName(); return ""; } - -QWidget *ReportDesignWidget::toolWindow(ReportDesignWidget::ToolWindowType windowType) +QWidget* ReportDesignWidget::toolWindow(ReportDesignWidget::ToolWindowType windowType) { switch (windowType) { case WidgetBox: @@ -154,39 +164,41 @@ QWidget *ReportDesignWidget::toolWindow(ReportDesignWidget::ToolWindowType windo ReportDesignWidget::EditorTabType ReportDesignWidget::activeTabType() { QString tabType = m_tabWidget->tabWhatsThis(m_tabWidget->currentIndex()); - if ( tabType.compare("dialog") == 0) return Dialog; - if ( tabType.compare("script") == 0) return Script; - if ( tabType.compare("translations") == 0) return Translations; + if (tabType.compare("dialog") == 0) + return Dialog; + if (tabType.compare("script") == 0) + return Script; + if (tabType.compare("translations") == 0) + return Translations; return Page; } #ifdef HAVE_QTDESIGNER_INTEGRATION -void ReportDesignWidget::initDialogDesignerToolBar(QToolBar *toolBar) +void ReportDesignWidget::initDialogDesignerToolBar(QToolBar* toolBar) { m_dialogDesignerManager->initToolBar(toolBar); } void ReportDesignWidget::updateDialogs() { - for ( int i = 0; icount(); ++i ){ - if (m_tabWidget->tabWhatsThis(i).compare("dialog") == 0){ - m_report->scriptContext()->changeDialog(m_tabWidget->tabText(i), m_dialogDesignerManager->getDialogDescription(m_tabWidget->widget(i))); + for (int i = 0; i < m_tabWidget->count(); ++i) { + if (m_tabWidget->tabWhatsThis(i).compare("dialog") == 0) { + m_report->scriptContext()->changeDialog( + m_tabWidget->tabText(i), + m_dialogDesignerManager->getDialogDescription(m_tabWidget->widget(i))); } } } #endif -bool ReportDesignWidget::useMagnet() const -{ - return m_useMagnet; -} +bool ReportDesignWidget::useMagnet() const { return m_useMagnet; } void ReportDesignWidget::setUseMagnet(bool useMagnet) { m_useMagnet = useMagnet; - for (int i=0;ipageCount();++i){ + for (int i = 0; i < m_report->pageCount(); ++i) { m_report->pageAt(i)->setMagneticMovement(useMagnet); } } @@ -194,11 +206,11 @@ void ReportDesignWidget::setUseMagnet(bool useMagnet) void ReportDesignWidget::saveState() { m_settings->beginGroup("DesignerWidget"); - m_settings->setValue("hGridStep",m_horizontalGridStep); - m_settings->setValue("vGridStep",m_verticalGridStep); - m_settings->setValue("defaultFont",m_defaultFont); - m_settings->setValue("useGrid",m_useGrid); - m_settings->setValue("theme",m_theme); + m_settings->setValue("hGridStep", m_horizontalGridStep); + m_settings->setValue("vGridStep", m_verticalGridStep); + m_settings->setValue("defaultFont", m_defaultFont); + m_settings->setValue("useGrid", m_useGrid); + m_settings->setValue("theme", m_theme); m_settings->setValue("ScriptEditorState", m_scriptEditor->saveState()); m_settings->setValue("DefaultUnits", m_defaultUnits); m_settings->endGroup(); @@ -206,12 +218,12 @@ void ReportDesignWidget::saveState() void ReportDesignWidget::applySettings() { - for (int i=0;ipageCount();++i){ + for (int i = 0; i < m_report->pageCount(); ++i) { m_report->pageAt(i)->pageItem()->setFont(m_defaultFont); } applyUseGrid(); - if (m_themes.contains(m_theme)){ + if (m_themes.contains(m_theme)) { parentWidget()->setStyleSheet(m_themes.value(m_theme)); m_report->setStyleSheet(m_themes.value(m_theme)); } else { @@ -220,26 +232,26 @@ void ReportDesignWidget::applySettings() m_report->setStyleSheet(""); } -// if (m_theme.compare("Dark") == 0) { -// QFile theme(":/qdarkstyle/style.qss"); -// theme.open(QIODevice::ReadOnly); -// QString styleSheet = theme.readAll(); -// parentWidget()->setStyleSheet(styleSheet); -// m_report->setStyleSheet(styleSheet); -// } else { -// parentWidget()->setStyleSheet(""); -// m_report->setStyleSheet(""); -// } + // if (m_theme.compare("Dark") == 0) { + // QFile theme(":/qdarkstyle/style.qss"); + // theme.open(QIODevice::ReadOnly); + // QString styleSheet = theme.readAll(); + // parentWidget()->setStyleSheet(styleSheet); + // m_report->setStyleSheet(styleSheet); + // } else { + // parentWidget()->setStyleSheet(""); + // m_report->setStyleSheet(""); + // } - if (m_settings){ + if (m_settings) { m_settings->beginGroup("ScriptEditor"); QVariant v = m_settings->value("DefaultFontName"); - if (v.isValid()){ + if (v.isValid()) { QVariant fontSize = m_settings->value("DefaultFontSize"); - m_scriptEditor->setEditorFont(QFont(v.toString(),fontSize.toInt())); + m_scriptEditor->setEditorFont(QFont(v.toString(), fontSize.toInt())); } - v = m_settings->value("TabIndention"); - if (v.isValid()){ + v = m_settings->value("TabIndention"); + if (v.isValid()) { m_scriptEditor->setTabIndention(v.toInt()); } m_settings->endGroup(); @@ -250,36 +262,36 @@ void ReportDesignWidget::loadState() { m_settings->beginGroup("DesignerWidget"); QVariant v = m_settings->value("hGridStep"); - if (v.isValid()){ + if (v.isValid()) { m_horizontalGridStep = v.toInt(); } v = m_settings->value("vGridStep"); - if (v.isValid()){ + if (v.isValid()) { m_verticalGridStep = v.toInt(); } v = m_settings->value("defaultFont"); - if (v.isValid()){ + if (v.isValid()) { m_defaultFont = v.value(); } v = m_settings->value("useGrid"); - if (v.isValid()){ + if (v.isValid()) { m_useGrid = v.toBool(); } v = m_settings->value("theme"); - if (v.isValid()){ + if (v.isValid()) { m_theme = v.toString(); } v = m_settings->value("ScriptEditorState"); - if (v.isValid() && m_scriptEditor){ + if (v.isValid() && m_scriptEditor) { m_scriptEditor->restoreState(v.toByteArray()); } v = m_settings->value("DefaultUnits"); - if (v.isValid()){ + if (v.isValid()) { m_defaultUnits = static_cast(v.toInt()); } @@ -287,7 +299,8 @@ void ReportDesignWidget::loadState() applySettings(); } -PageView* ReportDesignWidget::createPageView(PageDesignIntf* page){ +PageView* ReportDesignWidget::createPageView(PageDesignIntf* page) +{ PageView* view = new PageView(this); view->setBackgroundBrush(QBrush(Qt::gray)); view->setFrameShape(QFrame::NoFrame); @@ -298,11 +311,12 @@ PageView* ReportDesignWidget::createPageView(PageDesignIntf* page){ return view; } -void ReportDesignWidget::createTabs(){ +void ReportDesignWidget::createTabs() +{ m_tabWidget->clear(); - int pageIndex = -1; + int pageIndex = -1; - for (int i = 0; i < m_report->pageCount(); ++i){ + for (int i = 0; i < m_report->pageCount(); ++i) { PageDesignIntf* page = m_report->pageAt(i); page->clearSelection(); connectPage(page); @@ -314,75 +328,73 @@ void ReportDesignWidget::createTabs(){ m_scriptEditor = new ScriptEditor(this); connect(m_scriptEditor, SIGNAL(textChanged()), this, SLOT(slotScriptTextChanged())); m_scriptEditor->setReportEngine(m_report); - pageIndex = m_tabWidget->addTab(m_scriptEditor,QIcon(),tr("Script")); - m_tabWidget->setTabWhatsThis(pageIndex,"script"); + pageIndex = m_tabWidget->addTab(m_scriptEditor, QIcon(), tr("Script")); + m_tabWidget->setTabWhatsThis(pageIndex, "script"); m_tabWidget->setCurrentIndex(0); #ifdef HAVE_QTDESIGNER_INTEGRATION QWidget* dialogDesigner; - foreach(DialogDescriber::Ptr dialogDesc, m_report->scriptContext()->dialogDescribers()){ + foreach (DialogDescriber::Ptr dialogDesc, m_report->scriptContext()->dialogDescribers()) { dialogDesigner = m_dialogDesignerManager->createFormEditor(dialogDesc->description()); - pageIndex = m_tabWidget->addTab(dialogDesigner,QIcon(),dialogDesc->name()); - m_tabWidget->setTabWhatsThis(pageIndex,"dialog"); + pageIndex = m_tabWidget->addTab(dialogDesigner, QIcon(), dialogDesc->name()); + m_tabWidget->setTabWhatsThis(pageIndex, "dialog"); } #endif m_traslationEditor = new TranslationEditor(this); - pageIndex = m_tabWidget->addTab(m_traslationEditor,QIcon(),tr("Translations")); - m_tabWidget->setTabWhatsThis(pageIndex,"translations"); - + pageIndex = m_tabWidget->addTab(m_traslationEditor, QIcon(), tr("Translations")); + m_tabWidget->setTabWhatsThis(pageIndex, "translations"); } #ifdef HAVE_QTDESIGNER_INTEGRATION -void ReportDesignWidget::createNewDialogTab(const QString& dialogName, const QByteArray& description) +void ReportDesignWidget::createNewDialogTab(const QString& dialogName, + const QByteArray& description) { QWidget* dialogDesigner = m_dialogDesignerManager->createFormEditor(description); - int pageIndex = m_tabWidget->addTab(dialogDesigner,QIcon(),dialogName); - m_tabWidget->setTabWhatsThis(pageIndex,"dialog"); + int pageIndex = m_tabWidget->addTab(dialogDesigner, QIcon(), dialogName); + m_tabWidget->setTabWhatsThis(pageIndex, "dialog"); m_tabWidget->setCurrentIndex(pageIndex); m_dialogDesignerManager->setActiveEditor(dialogDesigner); } -DialogDesigner*ReportDesignWidget::activeDialogPage() +DialogDesigner* ReportDesignWidget::activeDialogPage() { return dynamic_cast(m_tabWidget->currentWidget()); } #endif -ReportDesignWidget::~ReportDesignWidget() -{ - delete m_zoomer; -} +ReportDesignWidget::~ReportDesignWidget() { delete m_zoomer; } -QGraphicsView* ReportDesignWidget::activeView(){ +QGraphicsView* ReportDesignWidget::activeView() +{ return dynamic_cast(m_tabWidget->currentWidget()); } -void ReportDesignWidget::connectPage(PageDesignIntf *page) +void ReportDesignWidget::connectPage(PageDesignIntf* page) { - connect(page, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), - this, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); - connect(page, SIGNAL(itemInsertCanceled(QString)),this,SIGNAL(itemInsertCanceled(QString))); - connect(page, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), - this, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant))); - connect(page, SIGNAL(itemPropertyObjectNameChanged(QString, QString)), - this, SLOT(slotItemPropertyObjectNameChanged(QString, QString))); + connect(page, SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), this, + SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); + connect(page, SIGNAL(itemInsertCanceled(QString)), this, SIGNAL(itemInsertCanceled(QString))); + connect(page, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), this, + SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant))); + connect(page, SIGNAL(itemPropertyObjectNameChanged(QString, QString)), this, + SLOT(slotItemPropertyObjectNameChanged(QString, QString))); connect(page, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); connect(page, SIGNAL(insertModeStarted()), this, SIGNAL(insertModeStarted())); connect(page, SIGNAL(commandHistoryChanged()), this, SIGNAL(commandHistoryChanged())); connect(page, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(slotSceneRectChanged(QRectF))); - connect(page, SIGNAL(itemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*)), - this, SIGNAL(itemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*))); + connect(page, SIGNAL(itemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*)), this, + SIGNAL(itemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*))); connect(page, SIGNAL(itemRemoved(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*)), this, SIGNAL(itemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*))); - connect(page, SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), - this, SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); + connect(page, SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, + SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); connect(page, SIGNAL(bandRemoved(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, SIGNAL(bandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); - connect(page, SIGNAL(pageUpdateFinished(LimeReport::PageDesignIntf*)), - this, SIGNAL(activePageUpdated(LimeReport::PageDesignIntf*))); - connect(page->pageItem(), SIGNAL(propertyObjectNameChanged(QString, QString)), - this, SLOT(slotPagePropertyObjectNameChanged(QString, QString))); + connect(page, SIGNAL(pageUpdateFinished(LimeReport::PageDesignIntf*)), this, + SIGNAL(activePageUpdated(LimeReport::PageDesignIntf*))); + connect(page->pageItem(), SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPagePropertyObjectNameChanged(QString, QString))); emit activePageChanged(); } @@ -390,17 +402,17 @@ PageDesignIntf* ReportDesignWidget::createStartPage() { PageDesignIntf* page = m_report->appendPage("page1"); page->pageItem()->setUnitType(m_defaultUnits); -// createTabs(); + // createTabs(); return page; } -void ReportDesignWidget::removeDatasource(const QString &datasourceName) +void ReportDesignWidget::removeDatasource(const QString& datasourceName) { if (m_report->dataManager()) m_report->dataManager()->removeDatasource(datasourceName); } -void ReportDesignWidget::addBand(const QString &bandType) +void ReportDesignWidget::addBand(const QString& bandType) { if (activePage()) activePage()->addBand(bandType); @@ -412,7 +424,7 @@ void ReportDesignWidget::addBand(BandDesignIntf::BandsType bandType) activePage()->addBand(bandType); } -void ReportDesignWidget::startInsertMode(const QString &itemType) +void ReportDesignWidget::startInsertMode(const QString& itemType) { if (activePage()) activePage()->startInsertMode(itemType); @@ -424,34 +436,31 @@ void ReportDesignWidget::startEditMode() activePage()->startEditMode(); } -PageDesignIntf * ReportDesignWidget::activePage() +PageDesignIntf* ReportDesignWidget::activePage() { if (activeView()) return dynamic_cast(activeView()->scene()); return 0; } -QList ReportDesignWidget::selectedItems(){ - return activePage()->selectedItems(); -} +QList ReportDesignWidget::selectedItems() { return activePage()->selectedItems(); } -void ReportDesignWidget::deleteItem(QGraphicsItem *item){ +void ReportDesignWidget::deleteItem(QGraphicsItem* item) +{ activePage()->removeReportItem(dynamic_cast(item)); } -void ReportDesignWidget::deleteSelectedItems(){ - activePage()->deleteSelected(); -} +void ReportDesignWidget::deleteSelectedItems() { activePage()->deleteSelected(); } -QStringList ReportDesignWidget::datasourcesNames(){ +QStringList ReportDesignWidget::datasourcesNames() +{ return m_report->dataManager()->dataSourceNames(); } -void ReportDesignWidget::slotItemSelected(BaseDesignIntf *item){ - emit itemSelected(item); -} +void ReportDesignWidget::slotItemSelected(BaseDesignIntf* item) { emit itemSelected(item); } -bool ReportDesignWidget::saveToFile(const QString &fileName){ +bool ReportDesignWidget::saveToFile(const QString& fileName) +{ bool result = false; prepareReport(); @@ -465,7 +474,7 @@ bool ReportDesignWidget::saveToFile(const QString &fileName){ } #ifdef HAVE_QTDESIGNER_INTEGRATION - if (result){ + if (result) { m_dialogChanged = false; m_dialogDesignerManager->setDirty(false); } @@ -485,7 +494,7 @@ bool ReportDesignWidget::save() if (emitSaveReport()) { result = true; } else if (!m_report->reportFileName().isEmpty()) { - if (m_report->saveToFile()){ + if (m_report->saveToFile()) { m_report->emitSaveFinished(); result = true; } @@ -493,23 +502,16 @@ bool ReportDesignWidget::save() if (m_report->isSaved()) { m_report->emitSaveFinished(); result = true; - } - else if ( - m_report->saveToFile( - QFileDialog::getSaveFileName( - this, tr("Report file name"), - m_report->currentReportsDir(), - "Report files (*.lrxml);; All files (*)" - ) - ) - ){ + } else if (m_report->saveToFile(QFileDialog::getSaveFileName( + this, tr("Report file name"), m_report->currentReportsDir(), + "Report files (*.lrxml);; All files (*)"))) { m_report->emitSaveFinished(); result = true; }; } #ifdef HAVE_QTDESIGNER_INTEGRATION - if (result){ + if (result) { m_dialogChanged = false; m_dialogDesignerManager->setDirty(false); } @@ -517,26 +519,27 @@ bool ReportDesignWidget::save() return result; } -bool ReportDesignWidget::loadFromFile(const QString &fileName) +bool ReportDesignWidget::loadFromFile(const QString& fileName) { - if (m_report->loadFromFile(fileName,false)){ -// QByteArray editorState = m_scriptEditor->saveState(); -// createTabs(); -// m_scriptEditor->setPlainText(m_report->scriptContext()->initScript()); -// m_scriptEditor->restoreState(editorState); -// emit loaded(); -// m_dialogChanged = false; + if (m_report->loadFromFile(fileName, false)) { + // QByteArray editorState = m_scriptEditor->saveState(); + // createTabs(); + // m_scriptEditor->setPlainText(m_report->scriptContext()->initScript()); + // m_scriptEditor->restoreState(editorState); + // emit loaded(); + // m_dialogChanged = false; return true; } else { - QMessageBox::critical(this,tr("Error"),tr("Wrong file format")); + QMessageBox::critical(this, tr("Error"), tr("Wrong file format")); return false; } } void ReportDesignWidget::scale(qreal sx, qreal sy) { - //m_view->scale(sx,sy); - if (activeView()) activeView()->scale(sx,sy); + // m_view->scale(sx,sy); + if (activeView()) + activeView()->scale(sx, sy); } QString ReportDesignWidget::reportFileName() @@ -548,25 +551,16 @@ QString ReportDesignWidget::reportFileName() bool ReportDesignWidget::isNeedToSave() { - if(m_report) + if (m_report) return (m_report->isNeedToSave() || m_dialogChanged); return false; } -bool ReportDesignWidget::emitSaveReport() -{ - return m_report->emitSaveReport(); -} +bool ReportDesignWidget::emitSaveReport() { return m_report->emitSaveReport(); } -bool ReportDesignWidget::emitSaveReportAs() -{ - return m_report->emitSaveReportAs(); -} +bool ReportDesignWidget::emitSaveReportAs() { return m_report->emitSaveReportAs(); } -bool ReportDesignWidget::emitLoadReport() -{ - return m_report->emitLoadReport(); -} +bool ReportDesignWidget::emitLoadReport() { return m_report->emitLoadReport(); } void ReportDesignWidget::updateSize() { @@ -674,10 +668,12 @@ void ReportDesignWidget::sameWidth() void ReportDesignWidget::editLayoutMode(bool value) { - if (value ){ - activePage()->pageItem()->setItemMode(activePage()->pageItem()->itemMode() | LayoutEditMode); - } else if (activePage()->pageItem()->itemMode() & LayoutEditMode){ - activePage()->pageItem()->setItemMode(activePage()->pageItem()->itemMode() ^ LayoutEditMode); + if (value) { + activePage()->pageItem()->setItemMode(activePage()->pageItem()->itemMode() + | LayoutEditMode); + } else if (activePage()->pageItem()->itemMode() & LayoutEditMode) { + activePage()->pageItem()->setItemMode(activePage()->pageItem()->itemMode() + ^ LayoutEditMode); } } @@ -699,7 +695,8 @@ void ReportDesignWidget::setFont(const QFont& font) activePage()->setFont(font); } -void ReportDesignWidget::setTextAlign(const bool& horizontalAlign, const Qt::AlignmentFlag& alignment) +void ReportDesignWidget::setTextAlign(const bool& horizontalAlign, + const Qt::AlignmentFlag& alignment) { if (activePage()) activePage()->changeSelectedGrpoupTextAlignPropperty(horizontalAlign, alignment); @@ -711,12 +708,11 @@ void ReportDesignWidget::setBorders(const BaseDesignIntf::BorderLines& borders) activePage()->setBorders(borders); } -void ReportDesignWidget::setBordersExt( - const BaseDesignIntf::BorderLines& border, - const double borderWidth, - const LimeReport::BaseDesignIntf::BorderStyle style, - const QString color -){ +void ReportDesignWidget::setBordersExt(const BaseDesignIntf::BorderLines& border, + const double borderWidth, + const LimeReport::BaseDesignIntf::BorderStyle style, + const QString color) +{ if (activePage()) activePage()->setBordersExt(border, borderWidth, style, color); } @@ -727,10 +723,10 @@ void ReportDesignWidget::prepareReport() report()->clearSelection(); } -void ReportDesignWidget::initThemeIfExist(const QString &themeName, const QString &path) +void ReportDesignWidget::initThemeIfExist(const QString& themeName, const QString& path) { QFile theme(path); - if (theme.exists()){ + if (theme.exists()) { theme.open(QIODevice::ReadOnly); QString styleSheet = theme.readAll(); m_themes.insert(themeName, styleSheet); @@ -739,7 +735,8 @@ void ReportDesignWidget::initThemeIfExist(const QString &themeName, const QStrin void ReportDesignWidget::previewReport() { - if (report()->isBusy()) return; + if (report()->isBusy()) + return; prepareReport(); #ifdef HAVE_QTDESIGNER_INTEGRATION updateDialogs(); @@ -752,7 +749,8 @@ void ReportDesignWidget::previewReport() void ReportDesignWidget::printReport() { - if (report()->isBusy()) return; + if (report()->isBusy()) + return; prepareReport(); #ifdef HAVE_QTDESIGNER_INTEGRATION updateDialogs(); @@ -764,10 +762,11 @@ void ReportDesignWidget::printReport() void ReportDesignWidget::addPage() { - PageDesignIntf* page = m_report->appendPage("page"+QString::number(m_report->pageCount()+1)); + PageDesignIntf* page + = m_report->appendPage("page" + QString::number(m_report->pageCount() + 1)); connectPage(page); PageView* view = createPageView(page); - int index = m_report->pageCount()-1; + int index = m_report->pageCount() - 1; m_tabWidget->insertTab(index, view, QIcon(), page->pageItem()->objectName()); m_tabWidget->setTabWhatsThis(index, "page"); m_tabWidget->setCurrentIndex(index); @@ -777,15 +776,16 @@ void ReportDesignWidget::addPage() void ReportDesignWidget::deleteCurrentPage() { - if (m_report->pageCount()>1){ + if (m_report->pageCount() > 1) { QGraphicsView* view = dynamic_cast(m_tabWidget->currentWidget()); - if (view){ + if (view) { PageDesignIntf* page = dynamic_cast(view->scene()); - if (page){ - if (m_report->deletePage(page)){ + if (page) { + if (m_report->deletePage(page)) { int index = m_tabWidget->currentIndex(); m_tabWidget->removeTab(m_tabWidget->currentIndex()); - if (index>0) m_tabWidget->setCurrentIndex(index-1); + if (index > 0) + m_tabWidget->setCurrentIndex(index - 1); emit pageDeleted(); } } @@ -805,21 +805,22 @@ void ReportDesignWidget::editSetting() QStringList themes; themes.append(QObject::tr("Default")); - foreach(QString theme, m_themes.keys()) + foreach (QString theme, m_themes.keys()) if (!themes.contains(QObject::tr(theme.toLatin1()))) themes.append(QObject::tr(theme.toLatin1())); setting.setDesignerThemes(themes, QObject::tr(m_theme.toLatin1())); - setting.setDesignerLanguages(m_report->designerLanguages(), m_report->currentDesignerLanguage()); + setting.setDesignerLanguages(m_report->designerLanguages(), + m_report->currentDesignerLanguage()); QList unitTypes; unitTypes << QObject::tr("Millimeters") << QObject::tr("Inches"); setting.setDesignerUnites(unitTypes, - m_defaultUnits == BaseDesignIntf::Millimeters ? - QObject::tr("Millimeters") : - QObject::tr("Inches")); + m_defaultUnits == BaseDesignIntf::Millimeters + ? QObject::tr("Millimeters") + : QObject::tr("Inches")); - if (setting.exec()){ + if (setting.exec()) { m_horizontalGridStep = setting.horizontalGridStep(); m_verticalGridStep = setting.verticalGridStep(); m_defaultFont = setting.defaultFont(); @@ -828,14 +829,14 @@ void ReportDesignWidget::editSetting() else { m_defaultUnits = BaseDesignIntf::Inches; } - if (m_localToEng.contains(setting.theme())){ - m_theme = m_localToEng.value(setting.theme()); + if (m_localToEng.contains(setting.theme())) { + m_theme = m_localToEng.value(setting.theme()); } else { m_theme = "Default"; } m_report->setSuppressFieldAndVarError(setting.suppressAbsentFieldsAndVarsWarnings()); m_report->setBaseItemPadding(setting.baseItemPadding()); - if (m_report->currentDesignerLanguage() != setting.designerLanguage() ){ + if (m_report->currentDesignerLanguage() != setting.designerLanguage()) { m_report->setCurrentDesignerLanguage(setting.designerLanguage()); } applySettings(); @@ -846,9 +847,9 @@ void ReportDesignWidget::applyUseGrid() { int hGridStep = m_useGrid ? m_horizontalGridStep : Const::DEFAULT_GRID_STEP; int vGridStep = m_useGrid ? m_verticalGridStep : Const::DEFAULT_GRID_STEP; - for(int i = 0; i < m_report->pageCount(); ++i){ - m_report->pageAt(i)->setVerticalGridStep(hGridStep); - m_report->pageAt(i)->setHorizontalGridStep(vGridStep); + for (int i = 0; i < m_report->pageCount(); ++i) { + m_report->pageAt(i)->setVerticalGridStep(hGridStep); + m_report->pageAt(i)->setHorizontalGridStep(vGridStep); } } @@ -874,45 +875,35 @@ bool ReportDesignWidget::isCanRedo() void ReportDesignWidget::slotSelectionChanged() { - QGraphicsScene* page=dynamic_cast(sender()); - if (page){ - if (page->selectedItems().count()==1){ + QGraphicsScene* page = dynamic_cast(sender()); + if (page) { + if (page->selectedItems().count() == 1) { BaseDesignIntf* item = dynamic_cast(page->selectedItems().at(0)); if (item) - emit (itemSelected(item)); - } - else if (page->selectedItems().count()>1){ - emit (multiItemSelected()); + emit(itemSelected(item)); + } else if (page->selectedItems().count() > 1) { + emit(multiItemSelected()); } } } -DataSourceManager* ReportDesignWidget::dataManager() -{ - return m_report->dataManager(); -} +DataSourceManager* ReportDesignWidget::dataManager() { return m_report->dataManager(); } -ScriptEngineManager* ReportDesignWidget::scriptManager() -{ - return m_report->scriptManager(); -} +ScriptEngineManager* ReportDesignWidget::scriptManager() { return m_report->scriptManager(); } -ScriptEngineContext*ReportDesignWidget::scriptContext() -{ - return m_report->scriptContext(); -} +ScriptEngineContext* ReportDesignWidget::scriptContext() { return m_report->scriptContext(); } void ReportDesignWidget::slotPagesLoadFinished() { applySettings(); - //setActivePage(m_report->pageAt(0)); + // setActivePage(m_report->pageAt(0)); emit loadFinished(); } void ReportDesignWidget::slotDialogDeleted(QString dialogName) { - for (int i = 0; icount(); ++i ){ - if (m_tabWidget->tabText(i).compare(dialogName) == 0){ + for (int i = 0; i < m_tabWidget->count(); ++i) { + if (m_tabWidget->tabText(i).compare(dialogName) == 0) { delete m_tabWidget->widget(i); break; } @@ -937,43 +928,44 @@ void ReportDesignWidget::selectOneLevelItems() activePage()->selectOneLevelItems(); } -void ReportDesignWidget::slotDatasourceCollectionLoaded(const QString & /*collectionName*/) -{ -} +void ReportDesignWidget::slotDatasourceCollectionLoaded(const QString& /*collectionName*/) { } void ReportDesignWidget::slotSceneRectChanged(QRectF) { - if (activeView()) activeView()->centerOn(0,0); + if (activeView()) + activeView()->centerOn(0, 0); } void ReportDesignWidget::slotCurrentTabChanged(int index) { QGraphicsView* view = dynamic_cast(m_tabWidget->widget(index)); if (view) { - if (view->scene()){ - //foreach (QGraphicsItem* item, view->scene()->selectedItems()) item->setSelected(false); + if (view->scene()) { + // foreach (QGraphicsItem* item, view->scene()->selectedItems()) + // item->setSelected(false); view->scene()->clearSelection(); } m_zoomer->setView(view); } #ifdef HAVE_QTDESIGNER_INTEGRATION - if (activeTabType() == Dialog){ + if (activeTabType() == Dialog) { m_dialogDesignerManager->setActiveEditor(m_tabWidget->widget(index)); } updateDialogs(); #endif - if (activeTabType() == Translations){ + if (activeTabType() == Translations) { m_traslationEditor->setReportEngine(dynamic_cast(report())); } - if (activeTabType() == Script){ + if (activeTabType() == Script) { m_scriptEditor->initCompleter(); m_scriptEditor->setFocus(); } emit activePageChanged(); - if (view) view->centerOn(0,0); + if (view) + view->centerOn(0, 0); } void ReportDesignWidget::slotReportLoaded() @@ -991,14 +983,17 @@ void ReportDesignWidget::slotScriptTextChanged() m_report->scriptContext()->setInitScript(m_scriptEditor->toPlainText()); } -void ReportDesignWidget::slotItemPropertyObjectNameChanged(const QString& oldName, const QString& newName) +void ReportDesignWidget::slotItemPropertyObjectNameChanged(const QString& oldName, + const QString& newName) { PageDesignIntf* page = qobject_cast(sender()); - if (page){ + if (page) { ITranslationContainer* tc = dynamic_cast(report()); - for (int i = 0; i < tc->translations()->values().count(); ++i){ - PageTranslation* pt = tc->translations()->values().at(i)->findPageTranslation(page->pageItem()->objectName()); - if (pt) pt->renameItem(oldName, newName); + for (int i = 0; i < tc->translations()->values().count(); ++i) { + PageTranslation* pt = tc->translations()->values().at(i)->findPageTranslation( + page->pageItem()->objectName()); + if (pt) + pt->renameItem(oldName, newName); } } } @@ -1008,22 +1003,19 @@ void ReportDesignWidget::slotItemPropertyObjectNameChanged(const QString& oldNam void ReportDesignWidget::addNewDialog() { QFile templateUi(":/templates/templates/Dialog.ui"); - templateUi.open(QIODevice::ReadOnly|QIODevice::Text); + templateUi.open(QIODevice::ReadOnly | QIODevice::Text); QString templateStr = templateUi.readAll(); QString dialogName = m_report->scriptContext()->getNewDialogName(); templateStr.replace("$ClassName$", dialogName); - m_report->scriptContext()->addDialog(dialogName,templateStr.toUtf8()); + m_report->scriptContext()->addDialog(dialogName, templateStr.toUtf8()); createNewDialogTab(dialogName, templateStr.toUtf8()); } -void ReportDesignWidget::slotDialogChanged(QString ) -{ - m_dialogChanged = true; -} +void ReportDesignWidget::slotDialogChanged(QString) { m_dialogChanged = true; } void ReportDesignWidget::slotDialogNameChanged(QString oldName, QString newName) { - for (int i = 0; i < m_tabWidget->count(); ++i){ + for (int i = 0; i < m_tabWidget->count(); ++i) { if (m_tabWidget->tabText(i).compare(oldName) == 0) m_tabWidget->setTabText(i, newName); } @@ -1032,17 +1024,18 @@ void ReportDesignWidget::slotDialogNameChanged(QString oldName, QString newName) #endif -void ReportDesignWidget::slotPagePropertyObjectNameChanged(const QString &oldValue, const QString &newValue) +void ReportDesignWidget::slotPagePropertyObjectNameChanged(const QString& oldValue, + const QString& newValue) { ITranslationContainer* tc = dynamic_cast(report()); - foreach(ReportTranslation* translation, tc->translations()->values()){ + foreach (ReportTranslation* translation, tc->translations()->values()) { translation->renamePage(oldValue, newValue); } - for (int i = 0; i < m_tabWidget->count(); ++i ){ - if (m_tabWidget->tabText(i).compare(oldValue) == 0){ + for (int i = 0; i < m_tabWidget->count(); ++i) { + if (m_tabWidget->tabText(i).compare(oldValue) == 0) { QGraphicsView* view = dynamic_cast(m_tabWidget->widget(i)); - if (view){ + if (view) { PageDesignIntf* page = dynamic_cast(view->scene()); if (page->pageItem() == sender()) m_tabWidget->setTabText(i, newValue); @@ -1058,35 +1051,38 @@ void ReportDesignWidget::slotTabMoved(int from, int to) QList pages; - for ( int i = 0; i < m_tabWidget->tabBar()->count(); ++i){ + for (int i = 0; i < m_tabWidget->tabBar()->count(); ++i) { QGraphicsView* view = dynamic_cast(m_tabWidget->widget(i)); - if (view){ + if (view) { PageDesignIntf* page = dynamic_cast(view->scene()); - if (page){ + if (page) { pages.append(page); } } } m_report->reorderPages(pages); - } -bool ReportDesignWidget::eventFilter(QObject *target, QEvent *event) +bool ReportDesignWidget::eventFilter(QObject* target, QEvent* event) { - if (event->type() == QEvent::Wheel){ + if (event->type() == QEvent::Wheel) { QWheelEvent* we = dynamic_cast(event); - if (QApplication::keyboardModifiers()==Qt::ControlModifier){ -#if QT_VERSION < QT_VERSION_CHECK(5,12,3) - if(we->delta()<0) scale(1.2,1.2); - else scale(1/1.2,1/1.2); + if (QApplication::keyboardModifiers() == Qt::ControlModifier) { +#if QT_VERSION < QT_VERSION_CHECK(5, 12, 3) + if (we->delta() < 0) + scale(1.2, 1.2); + else + scale(1 / 1.2, 1 / 1.2); #else - if(we->pixelDelta().x()<0) scale(1.2,1.2); - else scale(1/1.2,1/1.2); + if (we->pixelDelta().x() < 0) + scale(1.2, 1.2); + else + scale(1 / 1.2, 1 / 1.2); #endif } } - return QWidget::eventFilter(target,event); + return QWidget::eventFilter(target, event); } void ReportDesignWidget::clear() @@ -1098,47 +1094,53 @@ void ReportDesignWidget::clear() m_scriptEditor->setPlainText(""); } -void PageView::setPageItem(PageItemDesignIntf *pageItem) +void PageView::setPageItem(PageItemDesignIntf* pageItem) { - if (!pageItem) return; + if (!pageItem) + return; m_pageItem = pageItem; - if (!m_horizontalRuller){ + if (!m_horizontalRuller) { m_horizontalRuller = new Ruler(Ruler::Horizontal, this); m_horizontalRuller->setPage(pageItem); } - if (!m_verticalRuller){ + if (!m_verticalRuller) { m_verticalRuller = new Ruler(Ruler::Vertical, this); m_verticalRuller->setPage(pageItem); } } -bool PageView::viewportEvent(QEvent *event) +bool PageView::viewportEvent(QEvent* event) { switch (event->type()) { case QEvent::MouseMove: - if (m_horizontalRuller && m_verticalRuller){ + if (m_horizontalRuller && m_verticalRuller) { m_horizontalRuller->setMousePos(dynamic_cast(event)->pos()); m_verticalRuller->setMousePos(dynamic_cast(event)->pos()); m_horizontalRuller->update(); m_verticalRuller->update(); } break; - //case QEvent::Resize: + // case QEvent::Resize: case QEvent::Paint: - if (m_horizontalRuller && m_verticalRuller){ - int x = mapFromScene(m_pageItem->boundingRect().x(),m_pageItem->boundingRect().y()).x(); - int y = mapFromScene(m_pageItem->boundingRect().x(),m_pageItem->boundingRect().y()).y(); - int width = mapFromScene(m_pageItem->boundingRect().bottomRight().x(),m_pageItem->boundingRect().bottomRight().y()).x(); - int height = mapFromScene(m_pageItem->boundingRect().bottomRight().x(),m_pageItem->boundingRect().bottomRight().y()).y(); + if (m_horizontalRuller && m_verticalRuller) { + int x + = mapFromScene(m_pageItem->boundingRect().x(), m_pageItem->boundingRect().y()).x(); + int y + = mapFromScene(m_pageItem->boundingRect().x(), m_pageItem->boundingRect().y()).y(); + int width = mapFromScene(m_pageItem->boundingRect().bottomRight().x(), + m_pageItem->boundingRect().bottomRight().y()) + .x(); + int height = mapFromScene(m_pageItem->boundingRect().bottomRight().x(), + m_pageItem->boundingRect().bottomRight().y()) + .y(); x = x < 0 ? 0 : x; y = y < 0 ? 0 : y; - m_horizontalRuller->setGeometry(x+20, 0, (width-x), 20); - m_verticalRuller->setGeometry(0, y+20, 20, (height - y)); + m_horizontalRuller->setGeometry(x + 20, 0, (width - x), 20); + m_verticalRuller->setGeometry(0, y + 20, 20, (height - y)); m_verticalRuller->update(); m_horizontalRuller->update(); - } break; default: @@ -1148,27 +1150,24 @@ bool PageView::viewportEvent(QEvent *event) return QGraphicsView::viewportEvent(event); } -void Ruler::setPage(PageItemDesignIntf *page) +void Ruler::setPage(PageItemDesignIntf* page) { m_page = page; } + +void Ruler::paintEvent(QPaintEvent* event) { - m_page = page; - -} - -void Ruler::paintEvent(QPaintEvent *event){ QPainter painter(this); painter.setBrush(palette().window()); painter.setPen(Qt::NoPen); painter.drawRect(event->rect()); -// painter.setPen(palette().windowText().color()); + // painter.setPen(palette().windowText().color()); - if (m_page){ + if (m_page) { qreal rulerWidth = m_page->geometry().width() / m_page->unitFactor(); qreal rulerHeight = m_page->geometry().height() / m_page->unitFactor(); QGraphicsView* view = qobject_cast(parent()); - int hStartPos = view->mapFromScene(0,0).x(); - int vStartPos = view->mapFromScene(0,0).y(); + int hStartPos = view->mapFromScene(0, 0).x(); + int vStartPos = view->mapFromScene(0, 0).y(); QFont font = painter.font(); font.setPointSize(7); @@ -1186,24 +1185,36 @@ void Ruler::paintEvent(QPaintEvent *event){ drawItemWithChildren(&painter, m_page); painter.setPen(palette().windowText().color()); - for (int i = 0; i < rulerWidth / 10; ++i){ - int hs10 = view->mapFromScene(QPointF(m_page->geometry().topLeft().x() + i * 10 * m_page->unitFactor(), 0)).x(); - int hs5 = view->mapFromScene(QPointF(m_page->geometry().topLeft().x() + i * 10 * m_page->unitFactor() + 5 * m_page->unitFactor(), 0)).x(); - if (hs10 > 0){ - if (hStartPos > 0){ + for (int i = 0; i < rulerWidth / 10; ++i) { + int hs10 = view->mapFromScene(QPointF(m_page->geometry().topLeft().x() + + i * 10 * m_page->unitFactor(), + 0)) + .x(); + int hs5 = view->mapFromScene(QPointF(m_page->geometry().topLeft().x() + + i * 10 * m_page->unitFactor() + + 5 * m_page->unitFactor(), + 0)) + .x(); + if (hs10 > 0) { + if (hStartPos > 0) { hs10 -= hStartPos; - hs5 -= hStartPos; + hs5 -= hStartPos; } painter.drawLine(hs10, 15, hs10, 20); painter.drawLine(hs5, 10, hs5, 20); - if ( i > 0) - painter.drawText(QPoint(hs10 - (painter.fontMetrics().boundingRect(QString::number(i)).width()/2), 12), + if (i > 0) + painter.drawText(QPoint(hs10 + - (painter.fontMetrics() + .boundingRect(QString::number(i)) + .width() + / 2), + 12), QString::number(i)); } } painter.setPen(palette().windowText().color()); - painter.drawLine(m_mousePos.x() - (hStartPos > 0 ? hStartPos : 0) , 0, - m_mousePos.x() - (hStartPos > 0 ? hStartPos : 0) , 20); + painter.drawLine(m_mousePos.x() - (hStartPos > 0 ? hStartPos : 0), 0, + m_mousePos.x() - (hStartPos > 0 ? hStartPos : 0), 20); break; case Vertical: painter.setPen(Qt::NoPen); @@ -1215,66 +1226,86 @@ void Ruler::paintEvent(QPaintEvent *event){ drawItemWithChildren(&painter, m_page); painter.setPen(palette().windowText().color()); - for (int i = 0; i < rulerHeight / 10; ++i){ - int vs10 = view->mapFromScene(QPointF(0, m_page->geometry().topLeft().y()+i * 10 * m_page->unitFactor())).y(); - int vs5 = view->mapFromScene(QPointF(0, m_page->geometry().topLeft().y()+i * 10 * m_page->unitFactor() + 5 * m_page->unitFactor())).y(); - if (vs10 > 0){ - if (vStartPos > 0){ + for (int i = 0; i < rulerHeight / 10; ++i) { + int vs10 = view->mapFromScene(QPointF(0, + m_page->geometry().topLeft().y() + + i * 10 * m_page->unitFactor())) + .y(); + int vs5 = view->mapFromScene(QPointF(0, + m_page->geometry().topLeft().y() + + i * 10 * m_page->unitFactor() + + 5 * m_page->unitFactor())) + .y(); + if (vs10 > 0) { + if (vStartPos > 0) { vs10 -= vStartPos; vs5 -= vStartPos; } painter.drawLine(15, vs10, 20, vs10); - if ( i > 0 ) - painter.drawText(QPoint( (15 - painter.fontMetrics().boundingRect(QString::number(i)).width()) / 2 , - vs10 + (painter.fontMetrics().height()/2)), QString::number(i)); + if (i > 0) + painter.drawText( + QPoint( + (15 + - painter.fontMetrics().boundingRect(QString::number(i)).width()) + / 2, + vs10 + (painter.fontMetrics().height() / 2)), + QString::number(i)); painter.drawLine(10, vs5, 20, vs5); } } painter.setPen(palette().windowText().color()); - painter.drawLine(0, m_mousePos.y() - (vStartPos > 0 ? vStartPos : 0), - 20, m_mousePos.y() - (vStartPos > 0 ? vStartPos : 0)); + painter.drawLine(0, m_mousePos.y() - (vStartPos > 0 ? vStartPos : 0), 20, + m_mousePos.y() - (vStartPos > 0 ? vStartPos : 0)); break; } } } -void Ruler::drawItemWithChildren(QPainter* painter, BaseDesignIntf *item) +void Ruler::drawItemWithChildren(QPainter* painter, BaseDesignIntf* item) { - foreach(BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { if (!child->childBaseItems().isEmpty()) drawItemWithChildren(painter, child); - else drawItem(painter, child); - + else + drawItem(painter, child); } drawItem(painter, item); } -void Ruler::drawItem(QPainter* painter, BaseDesignIntf *item) +void Ruler::drawItem(QPainter* painter, BaseDesignIntf* item) { - if (!item->isSelected()) return; + if (!item->isSelected()) + return; QGraphicsView* view = qobject_cast(parent()); - int hStartPos = view->mapFromScene(0,0).x(); - int vStartPos = view->mapFromScene(0,0).y(); + int hStartPos = view->mapFromScene(0, 0).x(); + int vStartPos = view->mapFromScene(0, 0).y(); - int itemWidth = view->mapFromScene(item->mapToScene(item->geometry().width(),0).x() - item->mapToScene(0,0).x(), 0).x() - hStartPos; - int itemHeight = view->mapFromScene(0, item->mapToScene(0, item->geometry().height()).y() - item->mapToScene(0,0).y()).y() - vStartPos; + int itemWidth + = view->mapFromScene( + item->mapToScene(item->geometry().width(), 0).x() - item->mapToScene(0, 0).x(), 0) + .x() + - hStartPos; + int itemHeight = view->mapFromScene(0, + item->mapToScene(0, item->geometry().height()).y() + - item->mapToScene(0, 0).y()) + .y() + - vStartPos; switch (m_type) { case Horizontal: if (item->isSelected()) - painter->drawRect(view->mapFromScene(item->mapToScene(0,0)).x() - (hStartPos > 0 ? hStartPos : 0) , 0, - itemWidth, 20); + painter->drawRect(view->mapFromScene(item->mapToScene(0, 0)).x() + - (hStartPos > 0 ? hStartPos : 0), + 0, itemWidth, 20); break; case Vertical: if (item->isSelected()) - painter->drawRect(0, view->mapFromScene(item->mapToScene(0, 0)).y() - (vStartPos > 0 ? vStartPos : 0), - 20, itemHeight); + painter->drawRect( + 0, view->mapFromScene(item->mapToScene(0, 0)).y() - (vStartPos > 0 ? vStartPos : 0), + 20, itemHeight); break; } } -} - - - +} // namespace LimeReport diff --git a/limereport/lrreportdesignwidget.h b/limereport/lrreportdesignwidget.h index 9a5a68a..f219df9 100644 --- a/limereport/lrreportdesignwidget.h +++ b/limereport/lrreportdesignwidget.h @@ -30,25 +30,25 @@ #ifndef LRREPORTDESIGNWIDGET_H #define LRREPORTDESIGNWIDGET_H -#include -#include -#include -#include - -#include "lrpagedesignintf.h" +#include "lrcollection.h" #include "lrdatadesignintf.h" #include "lrdatasourcemanager.h" -#include "lrcollection.h" -#include "lrreportengine_p.h" #include "lrgraphicsviewzoom.h" +#include "lrpagedesignintf.h" +#include "lrreportengine_p.h" + +#include +#include +#include +#include #if QT_VERSION < 0x050000 QT_BEGIN_NAMESPACE -class LimeReportTabWidget: public QTabWidget{ +class LimeReportTabWidget: public QTabWidget { Q_OBJECT public: - explicit LimeReportTabWidget(QWidget *parent = 0):QTabWidget(parent){} - QTabBar* tabBar() const{ return QTabWidget::tabBar();} + explicit LimeReportTabWidget(QWidget* parent = 0): QTabWidget(parent) { } + QTabBar* tabBar() const { return QTabWidget::tabBar(); } }; QT_END_NAMESPACE #endif @@ -63,51 +63,59 @@ class DialogDesigner; class TranslationEditor; class ScriptEditor; - -class Ruler: public QWidget{ +class Ruler: public QWidget { public: - enum RulerType{Horizontal, Vertical}; - Ruler(RulerType type, QWidget* parent = 0): QWidget(parent), m_page(0), m_type(type){} + enum RulerType { + Horizontal, + Vertical + }; + Ruler(RulerType type, QWidget* parent = 0): QWidget(parent), m_page(0), m_type(type) { } void setPage(PageItemDesignIntf* page); - void setMousePos(QPoint mousePos){ m_mousePos = mousePos;} + void setMousePos(QPoint mousePos) { m_mousePos = mousePos; } + protected: void paintEvent(QPaintEvent* event); - void drawItemWithChildren(QPainter *painter, BaseDesignIntf* item); - void drawItem(QPainter *painter, BaseDesignIntf* item); + void drawItemWithChildren(QPainter* painter, BaseDesignIntf* item); + void drawItem(QPainter* painter, BaseDesignIntf* item); + private: PageItemDesignIntf* m_page; RulerType m_type; QPoint m_mousePos; }; -class PageView: public QGraphicsView{ +class PageView: public QGraphicsView { public: - PageView(QWidget *parent = NULL): QGraphicsView(parent), - m_horizontalRuller(0), m_verticalRuller(0) + PageView(QWidget* parent = NULL): + QGraphicsView(parent), + m_horizontalRuller(0), + m_verticalRuller(0) { - setViewportMargins(20,20,0,0); + setViewportMargins(20, 20, 0, 0); } - PageView(QGraphicsScene *scene, QWidget *parent = NULL): + PageView(QGraphicsScene* scene, QWidget* parent = NULL): QGraphicsView(scene, parent), - m_horizontalRuller(0), m_verticalRuller(0) + m_horizontalRuller(0), + m_verticalRuller(0) { - setViewportMargins(20,20,0,0); + setViewportMargins(20, 20, 0, 0); } void setPageItem(PageItemDesignIntf* pageItem); + protected: - bool viewportEvent(QEvent *event); + bool viewportEvent(QEvent* event); + private: PageItemDesignIntf* m_pageItem; Ruler* m_horizontalRuller; Ruler* m_verticalRuller; }; -class ReportDesignWidget : public QWidget -{ +class ReportDesignWidget: public QWidget { Q_OBJECT Q_PROPERTY(QObject* datasourcesManager READ dataManager) public: - enum ToolWindowType{ + enum ToolWindowType { WidgetBox = 1, ObjectInspector = 2, ActionEditor = 3, @@ -115,7 +123,7 @@ public: PropertyEditor = 5, ResourceEditor = 6 }; - enum EditorTabType{ + enum EditorTabType { Page, Dialog, Script, @@ -123,9 +131,9 @@ public: TabTypeCount }; ReportDesignWidget(ReportEnginePrivateInterface* report, QSettings* settings, - QMainWindow *mainWindow, QWidget *parent = 0); + QMainWindow* mainWindow, QWidget* parent = 0); ~ReportDesignWidget(); - PageDesignIntf *createStartPage(); + PageDesignIntf* createStartPage(); void createTabs(); void clear(); DataSourceManager* dataManager(); @@ -139,13 +147,13 @@ public: void updateSize(); bool isCanUndo(); bool isCanRedo(); - void deleteItem(QGraphicsItem *item); + void deleteItem(QGraphicsItem* item); PageDesignIntf* activePage(); QGraphicsView* activeView(); - QList selectedItems(); + QList selectedItems(); QStringList datasourcesNames(); - void scale( qreal sx, qreal sy); - ReportEnginePrivateInterface* report(){return m_report;} + void scale(qreal sx, qreal sy); + ReportEnginePrivateInterface* report() { return m_report; } QString reportFileName(); bool isNeedToSave(); bool emitSaveReport(); @@ -155,14 +163,14 @@ public: void loadState(); void applySettings(); void applyUseGrid(); - bool useGrid(){ return m_useGrid;} + bool useGrid() { return m_useGrid; } bool useMagnet() const; void setUseMagnet(bool useMagnet); EditorTabType activeTabType(); #ifdef HAVE_QTDESIGNER_INTEGRATION void initDialogDesignerToolBar(QToolBar* toolBar); void updateDialogs(); - DialogDesignerManager *dialogDesignerManager() const; + DialogDesignerManager* dialogDesignerManager() const; QString activeDialogName(); DialogDesigner* activeDialogPage(); QWidget* toolWindow(ToolWindowType windowType); @@ -191,10 +199,10 @@ public slots: void editLayoutMode(bool value); void addHLayout(); void addVLayout(); - void setFont(const QFont &font); - void setTextAlign(const bool &horizontalAlign, const Qt::AlignmentFlag &alignment); + void setFont(const QFont& font); + void setTextAlign(const bool& horizontalAlign, const Qt::AlignmentFlag& alignment); void setBorders(const BaseDesignIntf::BorderLines& borders); - void setBordersExt(const BaseDesignIntf::BorderLines &border, const double borderWidth, + void setBordersExt(const BaseDesignIntf::BorderLines& border, const double borderWidth, const LimeReport::BaseDesignIntf::BorderStyle style, const QString color); void editSetting(); void setUseGrid(bool value); @@ -211,7 +219,7 @@ public slots: void addNewDialog(); #endif private slots: - void slotItemSelected(LimeReport::BaseDesignIntf *item); + void slotItemSelected(LimeReport::BaseDesignIntf* item); void slotSelectionChanged(); void slotDatasourceCollectionLoaded(const QString&); void slotSceneRectChanged(QRectF); @@ -227,10 +235,11 @@ private slots: void slotTabMoved(int from, int to); signals: void insertModeStarted(); - void itemInserted(LimeReport::PageDesignIntf*,QPointF,const QString&); + void itemInserted(LimeReport::PageDesignIntf*, QPointF, const QString&); void itemInsertCanceled(const QString&); - void itemSelected(LimeReport::BaseDesignIntf *item); - void itemPropertyChanged(const QString& objectName, const QString& propertyName, const QVariant& oldValue, const QVariant& newValue); + void itemSelected(LimeReport::BaseDesignIntf* item); + void itemPropertyChanged(const QString& objectName, const QString& propertyName, + const QVariant& oldValue, const QVariant& newValue); void multiItemSelected(); void commandHistoryChanged(); void cleared(); @@ -243,24 +252,26 @@ signals: void itemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*); void pageAdded(PageDesignIntf* page); void pageDeleted(); + protected: - PageView *createPageView(PageDesignIntf *page); + PageView* createPageView(PageDesignIntf* page); #ifdef HAVE_QTDESIGNER_INTEGRATION - void createNewDialogTab(const QString& dialogName,const QByteArray& description); + void createNewDialogTab(const QString& dialogName, const QByteArray& description); #endif private: - bool eventFilter(QObject *target, QEvent *event); + bool eventFilter(QObject* target, QEvent* event); void prepareReport(); void initThemeIfExist(const QString& themeName, const QString& path); + private: ReportEnginePrivateInterface* m_report; - QGraphicsView *m_view; + QGraphicsView* m_view; ScriptEditor* m_scriptEditor; TranslationEditor* m_traslationEditor; #ifdef HAVE_QTDESIGNER_INTEGRATION DialogDesignerManager* m_dialogDesignerManager; #endif - QMainWindow *m_mainWindow; + QMainWindow* m_mainWindow; #if QT_VERSION < 0x050000 LimeReportTabWidget* m_tabWidget; #else @@ -278,7 +289,6 @@ private: QMap m_themes; QMap m_localToEng; BaseDesignIntf::UnitType m_defaultUnits; - }; } // namespace LimeReport diff --git a/limereport/lrreportdesignwindow.cpp b/limereport/lrreportdesignwindow.cpp index 4564ea0..a0501f7 100644 --- a/limereport/lrreportdesignwindow.cpp +++ b/limereport/lrreportdesignwindow.cpp @@ -27,47 +27,45 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include #include -#include -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include #else #include #endif -#include -#include -#include - -#include "lrreportdesignwindow.h" +#include "lraboutdialog.h" #include "lrbandsmanager.h" -#include "lrobjectinspectorwidget.h" -#include "lrbasedesignobjectmodel.h" -#include "lrreportdesignwidget.h" -#include "lrdatabrowser.h" -#include "scriptbrowser/lrscriptbrowser.h" #include "lrbasedesignintf.h" +#include "lrbasedesignobjectmodel.h" +#include "lrdatabrowser.h" +#include "lrobjectinspectorwidget.h" #include "lrpagedesignintf.h" - #include "lrpreviewreportwindow.h" +#include "lrreportdesignwidget.h" +#include "lrreportdesignwindow.h" +#include "objectsbrowser/lrobjectbrowser.h" +#include "scriptbrowser/lrscriptbrowser.h" #include "serializators/lrstorageintf.h" #include "serializators/lrxmlreader.h" -#include "objectsbrowser/lrobjectbrowser.h" -#include "lraboutdialog.h" +#include +#include +#include -namespace LimeReport{ +namespace LimeReport { -ReportDesignWindow* ReportDesignWindow::m_instance=0; +ReportDesignWindow* ReportDesignWindow::m_instance = 0; void ReportDesignWindow::createProgressBar() { @@ -96,14 +94,24 @@ void ReportDesignWindow::createProgressBar() m_progressWidget->setVisible(false); m_statusBar->addPermanentWidget(m_progressWidget); - connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderStarted()), this, SLOT(renderStarted())); - connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderPageFinished(int)), this, SLOT(renderPageFinished(int))); - connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderFinished()), this, SLOT(renderFinished())); + connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderStarted()), this, + SLOT(renderStarted())); + connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderPageFinished(int)), + this, SLOT(renderPageFinished(int))); + connect(dynamic_cast(m_reportDesignWidget->report()), SIGNAL(renderFinished()), this, + SLOT(renderFinished())); } -ReportDesignWindow::ReportDesignWindow(ReportEnginePrivateInterface* report, QWidget *parent, QSettings* settings) : - ReportDesignWindowInterface(parent), m_textAttibutesIsChanging(false), m_settings(settings), m_ownedSettings(false), - m_progressDialog(0), m_showProgressDialog(true), m_editorTabType(ReportDesignWidget::Page), m_reportItemIsLocked(false) +ReportDesignWindow::ReportDesignWindow(ReportEnginePrivateInterface* report, QWidget* parent, + QSettings* settings): + ReportDesignWindowInterface(parent), + m_textAttibutesIsChanging(false), + m_settings(settings), + m_ownedSettings(false), + m_progressDialog(0), + m_showProgressDialog(true), + m_editorTabType(ReportDesignWidget::Page), + m_reportItemIsLocked(false) { initReportEditor(report); createActions(); @@ -123,10 +131,10 @@ ReportDesignWindow::ReportDesignWindow(ReportEnginePrivateInterface* report, QWi createDialogResourceEditor(); createDialogDesignerToolBar(); #endif - m_instance=this; - m_statusBar=new QStatusBar(this); - m_lblReportName = new QLabel(report->reportFileName(),this); - m_statusBar->insertWidget(0,m_lblReportName); + m_instance = this; + m_statusBar = new QStatusBar(this); + m_lblReportName = new QLabel(report->reportFileName(), this); + m_statusBar->insertWidget(0, m_lblReportName); setStatusBar(m_statusBar); QString windowTitle = "Lime Report Designer"; @@ -139,153 +147,153 @@ ReportDesignWindow::ReportDesignWindow(ReportEnginePrivateInterface* report, QWi m_hideLeftPanel->setChecked(isDockAreaVisible(Qt::LeftDockWidgetArea)); m_hideRightPanel->setChecked(isDockAreaVisible(Qt::RightDockWidgetArea)); createProgressBar(); - m_deletePageAction->setEnabled(report->pageCount()>1); + m_deletePageAction->setEnabled(report->pageCount() > 1); } ReportDesignWindow::~ReportDesignWindow() { - m_instance=0; + m_instance = 0; delete m_validator; - if (m_ownedSettings&&m_settings) delete m_settings; + if (m_ownedSettings && m_settings) + delete m_settings; } void ReportDesignWindow::createActions() { - m_newReportAction = new QAction(tr("New Report"),this); + m_newReportAction = new QAction(tr("New Report"), this); m_newReportAction->setIcon(QIcon(":/report/images/newReport")); m_newReportAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); - connect(m_newReportAction,SIGNAL(triggered()),this,SLOT(slotNewReport())); + connect(m_newReportAction, SIGNAL(triggered()), this, SLOT(slotNewReport())); - m_newPageAction = new QAction(tr("New Report Page"),this); + m_newPageAction = new QAction(tr("New Report Page"), this); m_newPageAction->setIcon(QIcon(":/report/images/addPage")); - connect(m_newPageAction,SIGNAL(triggered()),this,SLOT(slotNewPage())); + connect(m_newPageAction, SIGNAL(triggered()), this, SLOT(slotNewPage())); - m_deletePageAction = new QAction(tr("Delete Report Page"),this); + m_deletePageAction = new QAction(tr("Delete Report Page"), this); m_deletePageAction->setIcon(QIcon(":/report/images/deletePage")); - connect(m_deletePageAction,SIGNAL(triggered()),this,SLOT(slotDeletePage())); + connect(m_deletePageAction, SIGNAL(triggered()), this, SLOT(slotDeletePage())); m_deletePageAction->setEnabled(false); - m_editModeAction = new QAction(tr("Edit Mode"),this); + m_editModeAction = new QAction(tr("Edit Mode"), this); m_editModeAction->setIcon(QIcon(":/report/images/editMode")); m_editModeAction->setCheckable(true); m_editModeAction->setChecked(true); - //m_editModeAction->setShortcut(QKeySequence(Qt::Key_Escape)); - connect(m_editModeAction,SIGNAL(triggered()),this,SLOT(slotEditMode())); + // m_editModeAction->setShortcut(QKeySequence(Qt::Key_Escape)); + connect(m_editModeAction, SIGNAL(triggered()), this, SLOT(slotEditMode())); - m_undoAction = new QAction(tr("Undo"),this); + m_undoAction = new QAction(tr("Undo"), this); m_undoAction->setIcon(QIcon(":/report/images/undo")); m_undoAction->setEnabled(false); m_undoAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Z)); - connect(m_undoAction,SIGNAL(triggered()),this,SLOT(slotUndo())); + connect(m_undoAction, SIGNAL(triggered()), this, SLOT(slotUndo())); - m_redoAction = new QAction(tr("Redo"),this); + m_redoAction = new QAction(tr("Redo"), this); m_redoAction->setIcon(QIcon(":/report/images/redo")); m_redoAction->setEnabled(false); m_redoAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Z)); - connect(m_redoAction,SIGNAL(triggered()),this,SLOT(slotRedo())); + connect(m_redoAction, SIGNAL(triggered()), this, SLOT(slotRedo())); - m_copyAction = new QAction(tr("Copy"),this); + m_copyAction = new QAction(tr("Copy"), this); m_copyAction->setIcon(QIcon(":/report/images/copy")); m_copyAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C)); - connect(m_copyAction,SIGNAL(triggered()),this,SLOT(slotCopy())); + connect(m_copyAction, SIGNAL(triggered()), this, SLOT(slotCopy())); - m_pasteAction = new QAction(tr("Paste"),this); + m_pasteAction = new QAction(tr("Paste"), this); m_pasteAction->setIcon(QIcon(":/report/images/paste")); m_pasteAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_V)); - connect(m_pasteAction,SIGNAL(triggered()),this,SLOT(slotPaste())); + connect(m_pasteAction, SIGNAL(triggered()), this, SLOT(slotPaste())); - m_cutAction = new QAction(tr("Cut"),this); + m_cutAction = new QAction(tr("Cut"), this); m_cutAction->setIcon(QIcon(":/report/images/cut")); m_cutAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X)); - connect(m_cutAction,SIGNAL(triggered()),this,SLOT(slotCut())); + connect(m_cutAction, SIGNAL(triggered()), this, SLOT(slotCut())); - m_settingsAction = new QAction(tr("Settings"),this); + m_settingsAction = new QAction(tr("Settings"), this); m_settingsAction->setIcon(QIcon(":/report/images/settings")); - connect(m_settingsAction,SIGNAL(triggered()),this,SLOT(slotEditSettings())); + connect(m_settingsAction, SIGNAL(triggered()), this, SLOT(slotEditSettings())); - m_useGridAction = new QAction(tr("Use grid"),this); + m_useGridAction = new QAction(tr("Use grid"), this); m_useGridAction->setIcon(QIcon(":/report/images/grid")); m_useGridAction->setCheckable(true); m_useGridAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_G)); - connect(m_useGridAction,SIGNAL(toggled(bool)),this,SLOT(slotUseGrid(bool))); + connect(m_useGridAction, SIGNAL(toggled(bool)), this, SLOT(slotUseGrid(bool))); - m_useMagnetAction = new QAction(tr("Use magnet"),this); + m_useMagnetAction = new QAction(tr("Use magnet"), this); m_useMagnetAction->setIcon(QIcon(":/report/images/magnet")); m_useMagnetAction->setCheckable(true); m_useMagnetAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_M)); - connect(m_useMagnetAction,SIGNAL(toggled(bool)),this,SLOT(slotUseMagnet(bool))); + connect(m_useMagnetAction, SIGNAL(toggled(bool)), this, SLOT(slotUseMagnet(bool))); - - m_newTextItemAction = new QAction(tr("Text Item"),this); + m_newTextItemAction = new QAction(tr("Text Item"), this); m_newTextItemAction->setIcon(QIcon(":/items/TextItem")); - m_actionMap.insert("TextItem",m_newTextItemAction); - connect(m_newTextItemAction,SIGNAL(triggered()),this,SLOT(slotNewTextItem())); + m_actionMap.insert("TextItem", m_newTextItemAction); + connect(m_newTextItemAction, SIGNAL(triggered()), this, SLOT(slotNewTextItem())); - m_saveReportAction = new QAction(tr("Save Report"),this); + m_saveReportAction = new QAction(tr("Save Report"), this); m_saveReportAction->setIcon(QIcon(":/report/images/save")); m_saveReportAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_S)); - connect(m_saveReportAction,SIGNAL(triggered()),this,SLOT(slotSaveReport())); + connect(m_saveReportAction, SIGNAL(triggered()), this, SLOT(slotSaveReport())); - m_saveReportAsAction = new QAction(tr("Save Report As"),this); + m_saveReportAsAction = new QAction(tr("Save Report As"), this); m_saveReportAsAction->setIcon(QIcon(":/report/images/saveas")); m_saveReportAsAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_S)); - connect(m_saveReportAsAction,SIGNAL(triggered()),this,SLOT(slotSaveReportAs())); + connect(m_saveReportAsAction, SIGNAL(triggered()), this, SLOT(slotSaveReportAs())); - m_loadReportAction = new QAction(tr("Load Report"),this); + m_loadReportAction = new QAction(tr("Load Report"), this); m_loadReportAction->setIcon(QIcon(":/report/images/folder")); m_loadReportAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_O)); - connect(m_loadReportAction,SIGNAL(triggered()),this,SLOT(slotLoadReport())); + connect(m_loadReportAction, SIGNAL(triggered()), this, SLOT(slotLoadReport())); - m_deleteItemAction = new QAction(tr("Delete item"),this); + m_deleteItemAction = new QAction(tr("Delete item"), this); m_deleteItemAction->setShortcut(QKeySequence("Del")); m_deleteItemAction->setIcon(QIcon(":/report/images/delete")); - connect(m_deleteItemAction,SIGNAL(triggered()),this,SLOT(slotDelete())); + connect(m_deleteItemAction, SIGNAL(triggered()), this, SLOT(slotDelete())); - m_zoomInReportAction = new QAction(tr("Zoom In"),this); + m_zoomInReportAction = new QAction(tr("Zoom In"), this); m_zoomInReportAction->setIcon(QIcon(":/report/images/zoomIn")); - connect(m_zoomInReportAction,SIGNAL(triggered()),this,SLOT(slotZoomIn())); + connect(m_zoomInReportAction, SIGNAL(triggered()), this, SLOT(slotZoomIn())); - m_zoomOutReportAction = new QAction(tr("Zoom Out"),this); + m_zoomOutReportAction = new QAction(tr("Zoom Out"), this); m_zoomOutReportAction->setIcon(QIcon(":/report/images/zoomOut")); - connect(m_zoomOutReportAction,SIGNAL(triggered()),this,SLOT(slotZoomOut())); + connect(m_zoomOutReportAction, SIGNAL(triggered()), this, SLOT(slotZoomOut())); - m_previewReportAction = new QAction(tr("Render Report"),this); + m_previewReportAction = new QAction(tr("Render Report"), this); m_previewReportAction->setIcon(QIcon(":/report/images/render")); m_previewReportAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_P)); - connect(m_previewReportAction,SIGNAL(triggered()),this,SLOT(slotPreviewReport())); + connect(m_previewReportAction, SIGNAL(triggered()), this, SLOT(slotPreviewReport())); - m_testAction = new QAction("test",this); + m_testAction = new QAction("test", this); m_testAction->setIcon(QIcon(":/report/images/pin")); - connect(m_testAction,SIGNAL(triggered()),this,SLOT(slotTest())); + connect(m_testAction, SIGNAL(triggered()), this, SLOT(slotTest())); - m_editLayoutMode = new QAction(tr("Edit layouts mode"),this); + m_editLayoutMode = new QAction(tr("Edit layouts mode"), this); m_editLayoutMode->setIcon(QIcon(":/report/images/editlayout")); m_editLayoutMode->setCheckable(true); - connect(m_editLayoutMode,SIGNAL(triggered()),this,SLOT(slotEditLayoutMode())); + connect(m_editLayoutMode, SIGNAL(triggered()), this, SLOT(slotEditLayoutMode())); - m_addHLayout = new QAction(tr("Horizontal layout"),this); + m_addHLayout = new QAction(tr("Horizontal layout"), this); m_addHLayout->setIcon(QIcon(":/report/images/hlayout")); - connect(m_addHLayout,SIGNAL(triggered()),this,SLOT(slotHLayout())); + connect(m_addHLayout, SIGNAL(triggered()), this, SLOT(slotHLayout())); - m_addVLayout = new QAction(tr("Vertical layout"),this); + m_addVLayout = new QAction(tr("Vertical layout"), this); m_addVLayout->setIcon(QIcon(":/report/images/vlayout")); - connect(m_addVLayout,SIGNAL(triggered()),this,SLOT(slotVLayout())); + connect(m_addVLayout, SIGNAL(triggered()), this, SLOT(slotVLayout())); - m_aboutAction = new QAction(tr("About"),this); + m_aboutAction = new QAction(tr("About"), this); m_aboutAction->setIcon(QIcon(":/report/images/copyright")); - connect(m_aboutAction,SIGNAL(triggered()),this,SLOT(slotShowAbout())); + connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(slotShowAbout())); - m_hideLeftPanel = new QAction(tr("Hide left panel | Alt+L"),this); + m_hideLeftPanel = new QAction(tr("Hide left panel | Alt+L"), this); m_hideLeftPanel->setCheckable(true); m_hideLeftPanel->setIcon(QIcon(":/report/images/hideLeftPanel")); m_hideLeftPanel->setShortcut(QKeySequence(Qt::ALT | Qt::Key_L)); - connect(m_hideLeftPanel,SIGNAL(toggled(bool)), this, SLOT(slotHideLeftPanel(bool))); + connect(m_hideLeftPanel, SIGNAL(toggled(bool)), this, SLOT(slotHideLeftPanel(bool))); - m_hideRightPanel = new QAction(tr("Hide right panel | Alt+R"),this); + m_hideRightPanel = new QAction(tr("Hide right panel | Alt+R"), this); m_hideRightPanel->setCheckable(true); m_hideRightPanel->setIcon(QIcon(":/report/images/hideRightPanel")); m_hideRightPanel->setShortcut(QKeySequence(Qt::ALT | Qt::Key_R)); - connect(m_hideRightPanel,SIGNAL(toggled(bool)), this, SLOT(slotHideRightPanel(bool))); + connect(m_hideRightPanel, SIGNAL(toggled(bool)), this, SLOT(slotHideRightPanel(bool))); #ifdef HAVE_QTDESIGNER_INTEGRATION m_deleteDialogAction = new QAction(tr("Delete dialog"), this); m_deleteDialogAction->setIcon(QIcon(":/report//images/deleteDialog")); @@ -299,26 +307,24 @@ void ReportDesignWindow::createActions() m_lockSelectedItemsAction = new QAction(tr("Lock selected items"), this); m_lockSelectedItemsAction->setIcon(QIcon(":/report/images/lock")); m_lockSelectedItemsAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L)); - connect(m_lockSelectedItemsAction, SIGNAL(triggered()), - this, SLOT(slotLockSelectedItems())); + connect(m_lockSelectedItemsAction, SIGNAL(triggered()), this, SLOT(slotLockSelectedItems())); m_unlockSelectedItemsAction = new QAction(tr("Unlock selected items"), this); m_unlockSelectedItemsAction->setIcon(QIcon(":/report/images/unlock")); m_unlockSelectedItemsAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_L)); - connect(m_unlockSelectedItemsAction, SIGNAL(triggered()), - this, SLOT(slotUnlockSelectedItems())); + connect(m_unlockSelectedItemsAction, SIGNAL(triggered()), this, + SLOT(slotUnlockSelectedItems())); m_selectOneLevelItems = new QAction(tr("Select one level items"), this); - //m_unlockSelectedItemsAction->setIcon(QIcon(":/report/images/unlock")); + // m_unlockSelectedItemsAction->setIcon(QIcon(":/report/images/unlock")); m_selectOneLevelItems->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A)); - connect(m_selectOneLevelItems, SIGNAL(triggered()), - this, SLOT(slotSelectOneLevelItems())); + connect(m_selectOneLevelItems, SIGNAL(triggered()), this, SLOT(slotSelectOneLevelItems())); } void ReportDesignWindow::createReportToolBar() { - m_reportToolBar = new QToolBar(tr("Report Tools"),this); - m_reportToolBar->setIconSize(QSize(24,24)); + m_reportToolBar = new QToolBar(tr("Report Tools"), this); + m_reportToolBar->setIconSize(QSize(24, 24)); m_reportToolBar->addAction(m_editModeAction); m_reportToolBar->addWidget(m_newBandButton); m_reportToolBar->addAction(m_newTextItemAction); @@ -331,13 +337,12 @@ void ReportDesignWindow::createReportToolBar() m_reportToolBar->addAction(m_deleteItemAction); QWidget* empty = new QWidget(); - empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_reportToolBar->addWidget(empty); m_reportToolBar->addAction(m_hideLeftPanel); m_reportToolBar->addAction(m_hideRightPanel); - addToolBar(Qt::LeftToolBarArea,m_reportToolBar); - + addToolBar(Qt::LeftToolBarArea, m_reportToolBar); } void ReportDesignWindow::createToolBars() @@ -345,8 +350,8 @@ void ReportDesignWindow::createToolBars() createBandsButton(); m_mainToolBar = addToolBar(tr("Main Tools")); - m_mainToolBar->setIconSize(QSize(16,16)); - m_mainToolBar->setAllowedAreas(Qt::LeftToolBarArea | Qt::RightToolBarArea | Qt::TopToolBarArea ); + m_mainToolBar->setIconSize(QSize(16, 16)); + m_mainToolBar->setAllowedAreas(Qt::LeftToolBarArea | Qt::RightToolBarArea | Qt::TopToolBarArea); m_mainToolBar->setFloatable(false); m_mainToolBar->setObjectName("mainTools"); @@ -372,52 +377,55 @@ void ReportDesignWindow::createToolBars() m_mainToolBar->addSeparator(); m_mainToolBar->addAction(m_zoomInReportAction); - m_mainToolBar->addAction(m_zoomOutReportAction); + m_mainToolBar->addAction(m_zoomOutReportAction); m_mainToolBar->addSeparator(); m_mainToolBar->addAction(m_previewReportAction); - //m_mainToolBar->addSeparator(); - //m_mainToolBar->addAction(m_useGridAction); + // m_mainToolBar->addSeparator(); + // m_mainToolBar->addAction(m_useGridAction); - //m_mainToolBar->addAction(m_printReportAction); + // m_mainToolBar->addAction(m_printReportAction); - m_fontEditorBar = new FontEditorWidgetForDesigner(m_reportDesignWidget,tr("Font"),this); + m_fontEditorBar = new FontEditorWidgetForDesigner(m_reportDesignWidget, tr("Font"), this); m_fontEditorBar->setIconSize(m_mainToolBar->iconSize()); m_fontEditorBar->setObjectName("fontTools"); addToolBar(m_fontEditorBar); - m_textAlignmentEditorBar = new TextAlignmentEditorWidgetForDesigner(m_reportDesignWidget,tr("Text alignment"),this); + m_textAlignmentEditorBar = new TextAlignmentEditorWidgetForDesigner(m_reportDesignWidget, + tr("Text alignment"), this); m_textAlignmentEditorBar->setIconSize(m_mainToolBar->iconSize()); m_textAlignmentEditorBar->setObjectName("textAlignmentTools"); addToolBar(m_textAlignmentEditorBar); - m_itemsAlignmentEditorBar = new ItemsAlignmentEditorWidget(m_reportDesignWidget,tr("Items alignment"),this); + m_itemsAlignmentEditorBar + = new ItemsAlignmentEditorWidget(m_reportDesignWidget, tr("Items alignment"), this); m_itemsAlignmentEditorBar->setIconSize(m_mainToolBar->iconSize()); m_itemsAlignmentEditorBar->setObjectName("itemsAlignmentTools"); - m_itemsAlignmentEditorBar->insertAction(m_itemsAlignmentEditorBar->actions().at(0),m_useGridAction); - m_itemsAlignmentEditorBar->insertAction(m_itemsAlignmentEditorBar->actions().at(1),m_useMagnetAction); + m_itemsAlignmentEditorBar->insertAction(m_itemsAlignmentEditorBar->actions().at(0), + m_useGridAction); + m_itemsAlignmentEditorBar->insertAction(m_itemsAlignmentEditorBar->actions().at(1), + m_useMagnetAction); m_itemsAlignmentEditorBar->insertSeparator(m_itemsAlignmentEditorBar->actions().at(2)); addToolBar(m_itemsAlignmentEditorBar); - m_itemsBordersEditorBar = new ItemsBordersEditorWidgetForDesigner(m_reportDesignWidget,tr("Borders"),this); + m_itemsBordersEditorBar + = new ItemsBordersEditorWidgetForDesigner(m_reportDesignWidget, tr("Borders"), this); m_itemsBordersEditorBar->setIconSize(m_mainToolBar->iconSize()); m_itemsBordersEditorBar->setObjectName("itemsBorderTools"); addToolBar(m_itemsBordersEditorBar); createReportToolBar(); - m_pageTools << m_mainToolBar << m_reportToolBar << m_fontEditorBar - << m_textAlignmentEditorBar << m_itemsAlignmentEditorBar - << m_itemsBordersEditorBar; - + m_pageTools << m_mainToolBar << m_reportToolBar << m_fontEditorBar << m_textAlignmentEditorBar + << m_itemsAlignmentEditorBar << m_itemsBordersEditorBar; } void ReportDesignWindow::createItemsActions() { - foreach(ItemAttribs items,DesignElementsFactory::instance().attribsMap().values()){ - if (items.m_tag.compare("Item",Qt::CaseInsensitive)==0){ - QAction* tmpAction = new QAction(QObject::tr(items.m_alias.toLatin1()),this); + foreach (ItemAttribs items, DesignElementsFactory::instance().attribsMap().values()) { + if (items.m_tag.compare("Item", Qt::CaseInsensitive) == 0) { + QAction* tmpAction = new QAction(QObject::tr(items.m_alias.toLatin1()), this); tmpAction->setWhatsThis(DesignElementsFactory::instance().attribsMap().key(items)); - tmpAction->setIcon(QIcon(":/items/"+tmpAction->whatsThis())); - connect(tmpAction,SIGNAL(triggered()),this,SLOT(slotItemActionCliked())); + tmpAction->setIcon(QIcon(":/items/" + tmpAction->whatsThis())); + connect(tmpAction, SIGNAL(triggered()), this, SLOT(slotItemActionCliked())); m_reportToolBar->addAction(tmpAction); - m_actionMap.insert(tmpAction->whatsThis(),tmpAction); + m_actionMap.insert(tmpAction->whatsThis(), tmpAction); } } } @@ -431,81 +439,81 @@ void ReportDesignWindow::createBandsButton() m_bandsAddSignalsMap = new QSignalMapper(this); - m_newReportHeader=new QAction(QIcon(),tr("Report Header"),this); - connect(m_newReportHeader,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newReportHeader,BandDesignIntf::ReportHeader); + m_newReportHeader = new QAction(QIcon(), tr("Report Header"), this); + connect(m_newReportHeader, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newReportHeader, BandDesignIntf::ReportHeader); m_newBandButton->addAction(m_newReportHeader); - m_newReportFooter=new QAction(QIcon(),tr("Report Footer"),this); - connect(m_newReportFooter,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newReportFooter,BandDesignIntf::ReportFooter); + m_newReportFooter = new QAction(QIcon(), tr("Report Footer"), this); + connect(m_newReportFooter, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newReportFooter, BandDesignIntf::ReportFooter); m_newBandButton->addAction(m_newReportFooter); - m_newPageHeader=new QAction(QIcon(),tr("Page Header"),this); - connect(m_newPageHeader,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newPageHeader,BandDesignIntf::PageHeader); + m_newPageHeader = new QAction(QIcon(), tr("Page Header"), this); + connect(m_newPageHeader, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newPageHeader, BandDesignIntf::PageHeader); m_newBandButton->addAction(m_newPageHeader); - m_newPageFooter=new QAction(QIcon(),tr("Page Footer"),this); - connect(m_newPageFooter,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newPageFooter,BandDesignIntf::PageFooter); + m_newPageFooter = new QAction(QIcon(), tr("Page Footer"), this); + connect(m_newPageFooter, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newPageFooter, BandDesignIntf::PageFooter); m_newBandButton->addAction(m_newPageFooter); - m_newData=new QAction(QIcon(),tr("Data"),this); - connect(m_newData,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newData,BandDesignIntf::Data); + m_newData = new QAction(QIcon(), tr("Data"), this); + connect(m_newData, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newData, BandDesignIntf::Data); m_newBandButton->addAction(m_newData); - m_newDataHeader=new QAction(QIcon(),tr("Data Header"),this); + m_newDataHeader = new QAction(QIcon(), tr("Data Header"), this); m_newDataHeader->setEnabled(false); - connect(m_newDataHeader,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newDataHeader,BandDesignIntf::DataHeader); + connect(m_newDataHeader, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newDataHeader, BandDesignIntf::DataHeader); m_newBandButton->addAction(m_newDataHeader); - m_newDataFooter=new QAction(QIcon(),tr("Data Footer"),this); + m_newDataFooter = new QAction(QIcon(), tr("Data Footer"), this); m_newDataFooter->setEnabled(false); - connect(m_newDataFooter,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newDataFooter,BandDesignIntf::DataFooter); + connect(m_newDataFooter, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newDataFooter, BandDesignIntf::DataFooter); m_newBandButton->addAction(m_newDataFooter); - m_newSubDetail=new QAction(QIcon(),tr("SubDetail"),this); + m_newSubDetail = new QAction(QIcon(), tr("SubDetail"), this); m_newSubDetail->setEnabled(false); - connect(m_newSubDetail,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newSubDetail,BandDesignIntf::SubDetailBand); + connect(m_newSubDetail, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newSubDetail, BandDesignIntf::SubDetailBand); m_newBandButton->addAction(m_newSubDetail); - m_newSubDetailHeader=new QAction(QIcon(),tr("SubDetailHeader"),this); + m_newSubDetailHeader = new QAction(QIcon(), tr("SubDetailHeader"), this); m_newSubDetailHeader->setEnabled(false); - connect(m_newSubDetailHeader,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newSubDetailHeader,BandDesignIntf::SubDetailHeader); + connect(m_newSubDetailHeader, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newSubDetailHeader, BandDesignIntf::SubDetailHeader); m_newBandButton->addAction(m_newSubDetailHeader); - m_newSubDetailFooter=new QAction(QIcon(),tr("SubDetailFooter"),this); + m_newSubDetailFooter = new QAction(QIcon(), tr("SubDetailFooter"), this); m_newSubDetailFooter->setEnabled(false); - connect(m_newSubDetailFooter,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newSubDetailFooter,BandDesignIntf::SubDetailFooter); + connect(m_newSubDetailFooter, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newSubDetailFooter, BandDesignIntf::SubDetailFooter); m_newBandButton->addAction(m_newSubDetailFooter); - m_newGroupHeader=new QAction(QIcon(),tr("GroupHeader"),this); + m_newGroupHeader = new QAction(QIcon(), tr("GroupHeader"), this); m_newGroupHeader->setEnabled(false); - connect(m_newGroupHeader,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newGroupHeader,BandDesignIntf::GroupHeader); + connect(m_newGroupHeader, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newGroupHeader, BandDesignIntf::GroupHeader); m_newBandButton->addAction(m_newGroupHeader); - m_newGroupFooter=new QAction(QIcon(),tr("GroupFooter"),this); + m_newGroupFooter = new QAction(QIcon(), tr("GroupFooter"), this); m_newGroupFooter->setEnabled(false); - connect(m_newGroupFooter,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newGroupFooter,BandDesignIntf::GroupFooter); + connect(m_newGroupFooter, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newGroupFooter, BandDesignIntf::GroupFooter); m_newBandButton->addAction(m_newGroupFooter); - m_newTearOffBand=new QAction(QIcon(),tr("Tear-off Band"),this); - connect(m_newTearOffBand,SIGNAL(triggered()),m_bandsAddSignalsMap,SLOT(map())); - m_bandsAddSignalsMap->setMapping(m_newTearOffBand,BandDesignIntf::TearOffBand); + m_newTearOffBand = new QAction(QIcon(), tr("Tear-off Band"), this); + connect(m_newTearOffBand, SIGNAL(triggered()), m_bandsAddSignalsMap, SLOT(map())); + m_bandsAddSignalsMap->setMapping(m_newTearOffBand, BandDesignIntf::TearOffBand); m_newBandButton->addAction(m_newTearOffBand); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - connect(m_bandsAddSignalsMap,SIGNAL(mappedInt(int)),this,SLOT(slotNewBand(int))); + connect(m_bandsAddSignalsMap, SIGNAL(mappedInt(int)), this, SLOT(slotNewBand(int))); #else - connect(m_bandsAddSignalsMap,SIGNAL(mapped(int)),this,SLOT(slotNewBand(int))); + connect(m_bandsAddSignalsMap, SIGNAL(mapped(int)), this, SLOT(slotNewBand(int))); #endif } @@ -517,7 +525,7 @@ void ReportDesignWindow::createMainMenu() m_fileMenu->addAction(m_saveReportAction); m_fileMenu->addAction(m_saveReportAsAction); m_fileMenu->addAction(m_previewReportAction); - //m_fileMenu->addAction(m_printReportAction); + // m_fileMenu->addAction(m_printReportAction); m_editMenu = menuBar()->addMenu(tr("Edit")); m_editMenu->addAction(m_redoAction); m_editMenu->addAction(m_undoAction); @@ -534,34 +542,43 @@ void ReportDesignWindow::createMainMenu() m_recentFilesMenu = m_fileMenu->addMenu(tr("Recent Files")); m_recentFilesSignalMap = new QSignalMapper(this); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - connect(m_recentFilesSignalMap,SIGNAL(mappedString(QString)),this,SLOT(slotLoadRecentFile(QString))); + connect(m_recentFilesSignalMap, SIGNAL(mappedString(QString)), this, + SLOT(slotLoadRecentFile(QString))); #else - connect(m_recentFilesSignalMap,SIGNAL(mapped(QString)),this,SLOT(slotLoadRecentFile(QString))); + connect(m_recentFilesSignalMap, SIGNAL(mapped(QString)), this, + SLOT(slotLoadRecentFile(QString))); #endif m_recentFilesMenu->setDisabled(m_recentFiles.isEmpty()); } void ReportDesignWindow::initReportEditor(ReportEnginePrivateInterface* report) { - m_reportDesignWidget=new ReportDesignWidget(report, m_settings, this,this); + m_reportDesignWidget = new ReportDesignWidget(report, m_settings, this, this); setCentralWidget(m_reportDesignWidget); - connect(m_reportDesignWidget,SIGNAL(itemSelected(LimeReport::BaseDesignIntf*)), - this,SLOT(slotItemSelected(LimeReport::BaseDesignIntf*))); - connect(m_reportDesignWidget,SIGNAL(itemPropertyChanged(QString,QString,QVariant,QVariant)), - this,SLOT(slotItemPropertyChanged(QString,QString,QVariant,QVariant))); - connect(m_reportDesignWidget,SIGNAL(insertModeStarted()),this,SLOT(slotInsertModeStarted())); - connect(m_reportDesignWidget,SIGNAL(multiItemSelected()),this,SLOT(slotMultiItemSelected())); - connect(m_reportDesignWidget,SIGNAL(itemInserted(LimeReport::PageDesignIntf*,QPointF,QString)), - this,SLOT(slotItemInserted(LimeReport::PageDesignIntf*,QPointF,QString))); - connect(m_reportDesignWidget,SIGNAL(itemInsertCanceled(QString)),this,SLOT(slotItemInsertCanceled(QString))); - connect(dynamic_cast(report), SIGNAL(datasourceCollectionLoadFinished(QString)),this,SLOT(slotUpdateDataBrowser(QString))); - connect(m_reportDesignWidget,SIGNAL(commandHistoryChanged()),this,SLOT(slotCommandHistoryChanged())); - connect(m_reportDesignWidget,SIGNAL(activePageChanged()),this,SLOT(slotActivePageChanged())); - connect(m_reportDesignWidget, SIGNAL(bandAdded(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*)), - this, SLOT(slotBandAdded(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*))); - connect(m_reportDesignWidget, SIGNAL(bandDeleted(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*)), - this, SLOT(slotBandDeleted(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*))); - connect(m_reportDesignWidget, SIGNAL(pageAdded(PageDesignIntf*)), this, SLOT(slotPageAdded(PageDesignIntf*))); + connect(m_reportDesignWidget, SIGNAL(itemSelected(LimeReport::BaseDesignIntf*)), this, + SLOT(slotItemSelected(LimeReport::BaseDesignIntf*))); + connect(m_reportDesignWidget, SIGNAL(itemPropertyChanged(QString, QString, QVariant, QVariant)), + this, SLOT(slotItemPropertyChanged(QString, QString, QVariant, QVariant))); + connect(m_reportDesignWidget, SIGNAL(insertModeStarted()), this, SLOT(slotInsertModeStarted())); + connect(m_reportDesignWidget, SIGNAL(multiItemSelected()), this, SLOT(slotMultiItemSelected())); + connect(m_reportDesignWidget, + SIGNAL(itemInserted(LimeReport::PageDesignIntf*, QPointF, QString)), this, + SLOT(slotItemInserted(LimeReport::PageDesignIntf*, QPointF, QString))); + connect(m_reportDesignWidget, SIGNAL(itemInsertCanceled(QString)), this, + SLOT(slotItemInsertCanceled(QString))); + connect(dynamic_cast(report), SIGNAL(datasourceCollectionLoadFinished(QString)), this, + SLOT(slotUpdateDataBrowser(QString))); + connect(m_reportDesignWidget, SIGNAL(commandHistoryChanged()), this, + SLOT(slotCommandHistoryChanged())); + connect(m_reportDesignWidget, SIGNAL(activePageChanged()), this, SLOT(slotActivePageChanged())); + connect(m_reportDesignWidget, + SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, + SLOT(slotBandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); + connect(m_reportDesignWidget, + SIGNAL(bandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, + SLOT(slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); + connect(m_reportDesignWidget, SIGNAL(pageAdded(PageDesignIntf*)), this, + SLOT(slotPageAdded(PageDesignIntf*))); connect(m_reportDesignWidget, SIGNAL(pageDeleted()), this, SLOT(slotPageDeleted())); } @@ -574,7 +591,7 @@ void ReportDesignWindow::createObjectInspector() m_objectInspector->setTranslateProperties(true); m_objectInspector->setAlternatingRowColors(true); m_objectInspector->setRootIsDecorated(!m_objectInspector->subclassesAsLevel()); - QDockWidget *objectDoc = new QDockWidget(this); + QDockWidget* objectDoc = new QDockWidget(this); QWidget* w = new QWidget(objectDoc); QVBoxLayout* l = new QVBoxLayout(w); l->addWidget(m_objectInspector); @@ -584,17 +601,17 @@ void ReportDesignWindow::createObjectInspector() objectDoc->setWidget(w); objectDoc->setObjectName("objectInspector"); m_pageEditors.append(objectDoc); - addDockWidget(Qt::LeftDockWidgetArea,objectDoc); + addDockWidget(Qt::LeftDockWidgetArea, objectDoc); } void ReportDesignWindow::createObjectsBrowser() { - QDockWidget *doc = new QDockWidget(this); + QDockWidget* doc = new QDockWidget(this); doc->setWindowTitle(tr("Report structure")); m_objectsBrowser = new ObjectBrowser(doc); doc->setWidget(m_objectsBrowser); doc->setObjectName("structureDoc"); - addDockWidget(Qt::RightDockWidgetArea,doc); + addDockWidget(Qt::RightDockWidgetArea, doc); m_objectsBrowser->setMainWindow(this); m_pageEditors.append(doc); m_objectsBrowser->setReportEditor(m_reportDesignWidget); @@ -604,63 +621,63 @@ void ReportDesignWindow::createObjectsBrowser() void ReportDesignWindow::createDialogWidgetBox() { - QDockWidget *doc = new QDockWidget(this); + QDockWidget* doc = new QDockWidget(this); doc->setWindowTitle(tr("Widget Box")); doc->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::WidgetBox)); doc->setObjectName("WidgetBox"); - addDockWidget(Qt::LeftDockWidgetArea,doc); + addDockWidget(Qt::LeftDockWidgetArea, doc); m_dialogEditors.append(doc); } void ReportDesignWindow::createDialogPropertyEditor() { - QDockWidget *doc = new QDockWidget(this); + QDockWidget* doc = new QDockWidget(this); doc->setWindowTitle(tr("Property Editor")); doc->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::PropertyEditor)); doc->setObjectName("PropertyEditor"); - addDockWidget(Qt::RightDockWidgetArea,doc); + addDockWidget(Qt::RightDockWidgetArea, doc); m_dialogEditors.append(doc); } void ReportDesignWindow::createDialogObjectInspector() { - QDockWidget *dock = new QDockWidget(this); + QDockWidget* dock = new QDockWidget(this); dock->setWindowTitle(tr("Object Inspector")); dock->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::ObjectInspector)); dock->setObjectName("ObjectInspector"); - addDockWidget(Qt::RightDockWidgetArea,dock); + addDockWidget(Qt::RightDockWidgetArea, dock); m_dialogEditors.append(dock); } void ReportDesignWindow::createDialogActionEditor() { - QDockWidget *dock = new QDockWidget(this); + QDockWidget* dock = new QDockWidget(this); dock->setWindowTitle(tr("Action Editor")); dock->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::ActionEditor)); dock->setObjectName("ActionEditor"); - addDockWidget(Qt::BottomDockWidgetArea,dock); + addDockWidget(Qt::BottomDockWidgetArea, dock); m_dialogEditors.append(dock); m_docksToTabify.append(dock); } void ReportDesignWindow::createDialogResourceEditor() { - QDockWidget *dock = new QDockWidget(this); + QDockWidget* dock = new QDockWidget(this); dock->setWindowTitle(tr("Resource Editor")); dock->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::ResourceEditor)); dock->setObjectName("ResourceEditor"); - addDockWidget(Qt::BottomDockWidgetArea,dock); + addDockWidget(Qt::BottomDockWidgetArea, dock); m_dialogEditors.append(dock); m_docksToTabify.append(dock); } void ReportDesignWindow::createDialogSignalSlotEditor() { - QDockWidget *dock = new QDockWidget(this); + QDockWidget* dock = new QDockWidget(this); dock->setWindowTitle(tr("SignalSlot Editor")); dock->setWidget(m_reportDesignWidget->toolWindow(ReportDesignWidget::SignalSlotEditor)); dock->setObjectName("SignalSlotEditor"); - addDockWidget(Qt::BottomDockWidgetArea,dock); + addDockWidget(Qt::BottomDockWidgetArea, dock); m_dialogEditors.append(dock); m_docksToTabify.append(dock); } @@ -682,12 +699,12 @@ void ReportDesignWindow::createDialogDesignerToolBar() void ReportDesignWindow::createDataWindow() { - QDockWidget *dataDoc = new QDockWidget(this); + QDockWidget* dataDoc = new QDockWidget(this); dataDoc->setWindowTitle(tr("Data Browser")); - m_dataBrowser=new DataBrowser(dataDoc); + m_dataBrowser = new DataBrowser(dataDoc); dataDoc->setWidget(m_dataBrowser); dataDoc->setObjectName("dataDoc"); - addDockWidget(Qt::LeftDockWidgetArea,dataDoc); + addDockWidget(Qt::LeftDockWidgetArea, dataDoc); m_dataBrowser->setSettings(settings()); m_dataBrowser->setMainWindow(this); m_pageEditors.append(dataDoc); @@ -696,12 +713,12 @@ void ReportDesignWindow::createDataWindow() void ReportDesignWindow::createScriptWindow() { - QDockWidget *dataDoc = new QDockWidget(this); + QDockWidget* dataDoc = new QDockWidget(this); dataDoc->setWindowTitle(tr("Script Browser")); - m_scriptBrowser=new ScriptBrowser(dataDoc); + m_scriptBrowser = new ScriptBrowser(dataDoc); dataDoc->setWidget(m_scriptBrowser); dataDoc->setObjectName("scriptDoc"); - addDockWidget(Qt::LeftDockWidgetArea,dataDoc); + addDockWidget(Qt::LeftDockWidgetArea, dataDoc); m_scriptBrowser->setReportEditor(m_reportDesignWidget); m_pageEditors.append(dataDoc); #ifdef HAVE_UI_LOADER @@ -733,27 +750,28 @@ void ReportDesignWindow::startNewReport() m_reportDesignWidget->report()->dataManager()->dropChanges(); m_reportDesignWidget->report()->scriptContext()->dropChanges(); m_reportDesignWidget->loadState(); - } void ReportDesignWindow::writePosition() { settings()->beginGroup("DesignerWindow"); - settings()->setValue("Geometry",saveGeometry()); + settings()->setValue("Geometry", saveGeometry()); settings()->endGroup(); } void ReportDesignWindow::setDocWidgetsVisibility(bool visible) { if (!m_hideLeftPanel->isChecked()) - hideDockWidgets(Qt::LeftDockWidgetArea,!visible); + hideDockWidgets(Qt::LeftDockWidgetArea, !visible); if (!m_hideRightPanel->isChecked()) - hideDockWidgets(Qt::RightDockWidgetArea,!visible); + hideDockWidgets(Qt::RightDockWidgetArea, !visible); } -void ReportDesignWindow::keyPressEvent(QKeyEvent *event) +void ReportDesignWindow::keyPressEvent(QKeyEvent* event) { - if (event->key()==Qt::Key_Escape){m_editModeAction->trigger();} + if (event->key() == Qt::Key_Escape) { + m_editModeAction->trigger(); + } } void ReportDesignWindow::writeState() @@ -763,20 +781,21 @@ void ReportDesignWindow::writeState() setDocWidgetsVisibility(true); m_editorsStates[m_editorTabType] = saveState(); - settings()->setValue("PageEditorsState", m_editorsStates[ReportDesignWidget::Page]); - settings()->setValue("DialogEditorsState", m_editorsStates[ReportDesignWidget::Dialog]); - settings()->setValue("ScriptEditorsState", m_editorsStates[ReportDesignWidget::Script]); - settings()->setValue("TranslationEditorsState", m_editorsStates[ReportDesignWidget::Translations]); + settings()->setValue("PageEditorsState", m_editorsStates[ReportDesignWidget::Page]); + settings()->setValue("DialogEditorsState", m_editorsStates[ReportDesignWidget::Dialog]); + settings()->setValue("ScriptEditorsState", m_editorsStates[ReportDesignWidget::Script]); + settings()->setValue("TranslationEditorsState", + m_editorsStates[ReportDesignWidget::Translations]); settings()->setValue("InspectorFirsColumnWidth", m_objectInspector->columnWidth(0)); settings()->setValue("InspectorTranslateProperties", m_objectInspector->translateProperties()); settings()->endGroup(); settings()->beginGroup("RecentFiles"); - settings()->setValue("filesCount",m_recentFiles.count()); + settings()->setValue("filesCount", m_recentFiles.count()); QMap::const_iterator it = m_recentFiles.constBegin(); int count = 0; while (it != m_recentFiles.constEnd()) { - settings()->setValue("fileName"+QString::number(count),it.key()); - settings()->setValue("fileDate"+QString::number(count),it.value()); + settings()->setValue("fileName" + QString::number(count), it.key()); + settings()->setValue("fileDate" + QString::number(count), it.value()); ++count; ++it; } @@ -786,13 +805,13 @@ void ReportDesignWindow::writeState() void ReportDesignWindow::createRecentFilesMenu() { - if (m_recentFilesMenu){ + if (m_recentFilesMenu) { m_recentFilesMenu->clear(); removeNotExistedRecentFiles(); - foreach(QString fileName, m_recentFiles.keys()){ - QAction* tmpAction = new QAction(QIcon(":/report/images/newReport"),fileName,this); - connect(tmpAction,SIGNAL(triggered()), m_recentFilesSignalMap, SLOT(map())); - m_recentFilesSignalMap->setMapping(tmpAction,fileName); + foreach (QString fileName, m_recentFiles.keys()) { + QAction* tmpAction = new QAction(QIcon(":/report/images/newReport"), fileName, this); + connect(tmpAction, SIGNAL(triggered()), m_recentFilesSignalMap, SLOT(map())); + m_recentFilesSignalMap->setMapping(tmpAction, fileName); m_recentFilesMenu->addAction(tmpAction); } m_recentFilesMenu->setDisabled(m_recentFiles.isEmpty()); @@ -801,9 +820,9 @@ void ReportDesignWindow::createRecentFilesMenu() void ReportDesignWindow::removeNotExistedRecentFiles() { - QMap::iterator it = m_recentFiles.begin(); - while (it!=m_recentFiles.end()){ - if (!QFile::exists(it.key())){ + QMap::iterator it = m_recentFiles.begin(); + while (it != m_recentFiles.end()) { + if (!QFile::exists(it.key())) { it = m_recentFiles.erase(it); } else { ++it; @@ -811,11 +830,11 @@ void ReportDesignWindow::removeNotExistedRecentFiles() } } -void ReportDesignWindow::removeNotExistedRecentFilesFromMenu(const QString &fileName) +void ReportDesignWindow::removeNotExistedRecentFilesFromMenu(const QString& fileName) { - if (m_recentFilesMenu){ - foreach(QAction* action, m_recentFilesMenu->actions()){ - if (action->text().compare(fileName)==0){ + if (m_recentFilesMenu) { + foreach (QAction* action, m_recentFilesMenu->actions()) { + if (action->text().compare(fileName) == 0) { m_recentFilesMenu->removeAction(action); break; } @@ -823,19 +842,20 @@ void ReportDesignWindow::removeNotExistedRecentFilesFromMenu(const QString &file } } -void ReportDesignWindow::addRecentFile(const QString &fileName) +void ReportDesignWindow::addRecentFile(const QString& fileName) { - if (!m_recentFiles.contains(fileName)){ - if (m_recentFiles.count()==10){ + if (!m_recentFiles.contains(fileName)) { + if (m_recentFiles.count() == 10) { QMap::const_iterator it = m_recentFiles.constBegin(); QDateTime minDate = QDateTime::currentDateTime(); while (it != m_recentFiles.constEnd()) { - if (minDate>it.value()) minDate = it.value(); + if (minDate > it.value()) + minDate = it.value(); ++it; } m_recentFiles.remove(m_recentFiles.key(minDate)); } - m_recentFiles.insert(fileName,QDateTime::currentDateTime()); + m_recentFiles.insert(fileName, QDateTime::currentDateTime()); } else { m_recentFiles[fileName] = QDateTime::currentDateTime(); } @@ -846,19 +866,19 @@ void ReportDesignWindow::restoreSetting() { settings()->beginGroup("DesignerWindow"); QVariant v = settings()->value("Geometry"); - if (v.isValid()){ + if (v.isValid()) { restoreGeometry(v.toByteArray()); } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 3) - QScreen *screen = QGuiApplication::primaryScreen(); + QScreen* screen = QGuiApplication::primaryScreen(); int screenWidth = screen->geometry().width(); int screenHeight = screen->geometry().height(); #else - QDesktopWidget *desktop = QApplication::desktop(); + QDesktopWidget* desktop = QApplication::desktop(); int screenWidth = desktop->screenGeometry().width(); - int screenHeight = desktop->screenGeometry().height(); + int screenHeight = desktop->screenGeometry().height(); #endif int x = screenWidth * 0.1; int y = screenHeight * 0.1; @@ -867,31 +887,31 @@ void ReportDesignWindow::restoreSetting() move(x, y); } v = settings()->value("PageEditorsState"); - if (v.isValid()){ + if (v.isValid()) { m_editorsStates[ReportDesignWidget::Page] = v.toByteArray(); m_editorTabType = ReportDesignWidget::Page; } v = settings()->value("DialogEditorsState"); - if (v.isValid()){ + if (v.isValid()) { m_editorsStates[ReportDesignWidget::Dialog] = v.toByteArray(); } v = settings()->value("ScriptEditorsState"); - if (v.isValid()){ + if (v.isValid()) { m_editorsStates[ReportDesignWidget::Script] = v.toByteArray(); } v = settings()->value("TranslationEditorsState"); - if (v.isValid()){ + if (v.isValid()) { m_editorsStates[ReportDesignWidget::Translations] = v.toByteArray(); } v = settings()->value("InspectorFirsColumnWidth"); - if (v.isValid()){ - m_objectInspector->setColumnWidth(0,v.toInt()); + if (v.isValid()) { + m_objectInspector->setColumnWidth(0, v.toInt()); } v = settings()->value("InspectorTranslateProperties"); - if (v.isValid()){ + if (v.isValid()) { m_objectInspector->setTranslateProperties(v.toBool()); } @@ -900,13 +920,13 @@ void ReportDesignWindow::restoreSetting() settings()->beginGroup("RecentFiles"); int filesCount = settings()->value("filesCount").toInt(); QStringList keys = settings()->childKeys(); - for(int i=0;ivalue("fileName"+QString::number(i)).toString()] = - settings()->value("fileData"+QString::number(i)).toDateTime(); - - } else break; + for (int i = 0; i < filesCount; i++) { + if (keys.contains("fileName" + QString::number(i))) { + m_recentFiles[settings()->value("fileName" + QString::number(i)).toString()] + = settings()->value("fileData" + QString::number(i)).toDateTime(); + } else + break; } settings()->endGroup(); @@ -917,16 +937,16 @@ void ReportDesignWindow::restoreSetting() bool ReportDesignWindow::checkNeedToSave() { - if (m_reportDesignWidget->isNeedToSave()){ + if (m_reportDesignWidget->isNeedToSave()) { QMessageBox::StandardButton button = QMessageBox::question( - this,"",tr("Report has been modified! Do you want save the report?"), - QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel, QMessageBox::Yes - ); + this, "", tr("Report has been modified! Do you want save the report?"), + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); switch (button) { case QMessageBox::Cancel: break; case QMessageBox::Yes: - if (!m_reportDesignWidget->save()) break; + if (!m_reportDesignWidget->save()) + break; default: return true; } @@ -938,12 +958,13 @@ bool ReportDesignWindow::checkNeedToSave() void ReportDesignWindow::showModal() { bool deleteOnClose = testAttribute(Qt::WA_DeleteOnClose); - setAttribute(Qt::WA_DeleteOnClose,false); - setAttribute(Qt::WA_ShowModal,true); + setAttribute(Qt::WA_DeleteOnClose, false); + setAttribute(Qt::WA_ShowModal, true); restoreSetting(); show(); m_eventLoop.exec(); - if (deleteOnClose) delete this; + if (deleteOnClose) + delete this; } void ReportDesignWindow::showNonModal() @@ -956,24 +977,24 @@ void ReportDesignWindow::setSettings(QSettings* value) { if (m_ownedSettings) delete m_settings; - m_settings=value; - m_ownedSettings=false; + m_settings = value; + m_ownedSettings = false; restoreSetting(); } -QSettings*ReportDesignWindow::settings() +QSettings* ReportDesignWindow::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QApplication::applicationName()); + m_settings = new QSettings("LimeReport", QApplication::applicationName()); m_ownedSettings = true; return m_settings; } } void ReportDesignWindow::slotNewReport() -{ +{ if (checkNeedToSave()) { m_lblReportName->setText(""); startNewReport(); @@ -982,22 +1003,26 @@ void ReportDesignWindow::slotNewReport() } } -void ReportDesignWindow::slotNewPage(){ - if (m_reportDesignWidget){ +void ReportDesignWindow::slotNewPage() +{ + if (m_reportDesignWidget) { m_reportDesignWidget->addPage(); } } void ReportDesignWindow::slotDeletePage() { - if (m_reportDesignWidget && m_reportDesignWidget->report()->pageCount()>1){ + if (m_reportDesignWidget && m_reportDesignWidget->report()->pageCount() > 1) { m_reportDesignWidget->deleteCurrentPage(); } } void ReportDesignWindow::slotNewTextItem() { - if (m_newTextItemAction->isChecked()) {m_newTextItemAction->setCheckable(false);return;} + if (m_newTextItemAction->isChecked()) { + m_newTextItemAction->setCheckable(false); + return; + } if (m_reportDesignWidget) { m_reportItemIsLocked = QApplication::keyboardModifiers() == Qt::SHIFT; m_reportDesignWidget->startInsertMode("TextItem"); @@ -1008,17 +1033,19 @@ void ReportDesignWindow::slotNewTextItem() void ReportDesignWindow::slotNewBand(const QString& bandType) { - if(m_reportDesignWidget) m_reportDesignWidget->addBand(bandType); + if (m_reportDesignWidget) + m_reportDesignWidget->addBand(bandType); } void ReportDesignWindow::slotNewBand(int bandType) { - if(m_reportDesignWidget) m_reportDesignWidget->addBand(BandDesignIntf::BandsType(bandType)); + if (m_reportDesignWidget) + m_reportDesignWidget->addBand(BandDesignIntf::BandsType(bandType)); } -void ReportDesignWindow::slotItemSelected(LimeReport::BaseDesignIntf *item) +void ReportDesignWindow::slotItemSelected(LimeReport::BaseDesignIntf* item) { - if (m_objectInspector->object()!=item){ + if (m_objectInspector->object() != item) { m_newSubDetail->setEnabled(false); m_newSubDetailHeader->setEnabled(false); @@ -1032,30 +1059,30 @@ void ReportDesignWindow::slotItemSelected(LimeReport::BaseDesignIntf *item) m_objectInspector->setObject(item); if (m_objectInspector->subclassesAsLevel()) - m_objectInspector->expandToDepth(0); + m_objectInspector->expandToDepth(0); QSet bs; - bs<(item); - if (band){ - if (bs.contains(band->bandType())){ + if (band) { + if (bs.contains(band->bandType())) { m_newSubDetail->setEnabled(true); } - if ((band->bandType()==BandDesignIntf::Data)|| - (band->bandType()==BandDesignIntf::SubDetailBand) - ) - { + if ((band->bandType() == BandDesignIntf::Data) + || (band->bandType() == BandDesignIntf::SubDetailBand)) { m_newGroupHeader->setEnabled(true); } - if (band->bandType()==BandDesignIntf::GroupHeader){ + if (band->bandType() == BandDesignIntf::GroupHeader) { m_newGroupFooter->setEnabled(!band->isConnectedToBand(BandDesignIntf::GroupFooter)); m_newGroupHeader->setEnabled(!band->isConnectedToBand(BandDesignIntf::GroupHeader)); } - if (band->bandType()==BandDesignIntf::SubDetailBand){ - m_newSubDetailHeader->setEnabled(!band->isConnectedToBand(BandDesignIntf::SubDetailHeader)); - m_newSubDetailFooter->setEnabled(!band->isConnectedToBand(BandDesignIntf::SubDetailFooter)); + if (band->bandType() == BandDesignIntf::SubDetailBand) { + m_newSubDetailHeader->setEnabled( + !band->isConnectedToBand(BandDesignIntf::SubDetailHeader)); + m_newSubDetailFooter->setEnabled( + !band->isConnectedToBand(BandDesignIntf::SubDetailFooter)); } - if (band->bandType()==BandDesignIntf::Data){ + if (band->bandType() == BandDesignIntf::Data) { m_newDataHeader->setEnabled(!band->isConnectedToBand(BandDesignIntf::DataHeader)); m_newDataFooter->setEnabled(!band->isConnectedToBand(BandDesignIntf::DataFooter)); m_newGroupHeader->setEnabled(!band->isConnectedToBand(BandDesignIntf::GroupHeader)); @@ -1065,15 +1092,19 @@ void ReportDesignWindow::slotItemSelected(LimeReport::BaseDesignIntf *item) m_fontEditorBar->setItem(item); m_textAlignmentEditorBar->setItem(item); m_itemsBordersEditorBar->setItem(item); - } else {m_objectInspector->clearObjectsList();} + } else { + m_objectInspector->clearObjectsList(); + } } -void ReportDesignWindow::slotItemPropertyChanged(const QString &objectName, const QString &propertyName, const QVariant& oldValue, const QVariant& newValue ) +void ReportDesignWindow::slotItemPropertyChanged(const QString& objectName, + const QString& propertyName, + const QVariant& oldValue, const QVariant& newValue) { Q_UNUSED(oldValue) Q_UNUSED(newValue) - if (m_objectInspector->object()&&(m_objectInspector->object()->objectName()==objectName)){ + if (m_objectInspector->object() && (m_objectInspector->object()->objectName() == objectName)) { m_objectInspector->updateProperty(propertyName); } } @@ -1085,21 +1116,19 @@ void ReportDesignWindow::slotMultiItemSelected() QList selectionList; foreach (QGraphicsItem* gi, m_reportDesignWidget->activePage()->selectedItems()) { QObject* oi = dynamic_cast(gi); - if (oi) selectionList.append(oi); + if (oi) + selectionList.append(oi); } m_objectInspector->setMultiObjects(&selectionList); if (m_objectInspector->subclassesAsLevel()) - m_objectInspector->expandToDepth(0); + m_objectInspector->expandToDepth(0); } -void ReportDesignWindow::slotInsertModeStarted() -{ - m_editModeAction->setChecked(false); -} +void ReportDesignWindow::slotInsertModeStarted() { m_editModeAction->setChecked(false); } -void ReportDesignWindow::slotItemInserted(PageDesignIntf *, QPointF, const QString &ItemType) +void ReportDesignWindow::slotItemInserted(PageDesignIntf*, QPointF, const QString& ItemType) { - if (!m_reportItemIsLocked){ + if (!m_reportItemIsLocked) { m_editModeAction->setChecked(true); if (m_actionMap.value(ItemType)) m_actionMap.value(ItemType)->setCheckable(false); @@ -1108,7 +1137,7 @@ void ReportDesignWindow::slotItemInserted(PageDesignIntf *, QPointF, const QStri } } -void ReportDesignWindow::slotItemInsertCanceled(const QString &ItemType) +void ReportDesignWindow::slotItemInsertCanceled(const QString& ItemType) { m_editModeAction->setChecked(true); m_reportItemIsLocked = false; @@ -1116,48 +1145,54 @@ void ReportDesignWindow::slotItemInsertCanceled(const QString &ItemType) m_actionMap.value(ItemType)->setCheckable(false); } -void ReportDesignWindow::slotUpdateDataBrowser(const QString &collectionName) +void ReportDesignWindow::slotUpdateDataBrowser(const QString& collectionName) { - if (collectionName.compare("connections",Qt::CaseInsensitive)==0){ - if (m_dataBrowser) m_dataBrowser->initConnections(); + if (collectionName.compare("connections", Qt::CaseInsensitive) == 0) { + if (m_dataBrowser) + m_dataBrowser->initConnections(); } - if (collectionName.compare("queries",Qt::CaseInsensitive)==0){ - if (m_dataBrowser) m_dataBrowser->updateDataTree(); + if (collectionName.compare("queries", Qt::CaseInsensitive) == 0) { + if (m_dataBrowser) + m_dataBrowser->updateDataTree(); } - if (collectionName.compare("subqueries",Qt::CaseInsensitive)==0){ - if (m_dataBrowser) m_dataBrowser->updateDataTree(); + if (collectionName.compare("subqueries", Qt::CaseInsensitive) == 0) { + if (m_dataBrowser) + m_dataBrowser->updateDataTree(); } - if (collectionName.compare("subproxies",Qt::CaseInsensitive)==0){ - if (m_dataBrowser) m_dataBrowser->updateDataTree(); + if (collectionName.compare("subproxies", Qt::CaseInsensitive) == 0) { + if (m_dataBrowser) + m_dataBrowser->updateDataTree(); } - if (collectionName.compare("variables",Qt::CaseInsensitive)==0){ - if (m_dataBrowser) m_dataBrowser->updateVariablesTree(); + if (collectionName.compare("variables", Qt::CaseInsensitive) == 0) { + if (m_dataBrowser) + m_dataBrowser->updateVariablesTree(); } } -void ReportDesignWindow::slotCommandHistoryChanged() -{ - updateRedoUndo(); -} +void ReportDesignWindow::slotCommandHistoryChanged() { updateRedoUndo(); } void ReportDesignWindow::slotSaveReport() { - if (m_reportDesignWidget->emitSaveReport()) return; // report save as'd via signal + if (m_reportDesignWidget->emitSaveReport()) + return; // report save as'd via signal m_reportDesignWidget->save(); QString filename = m_reportDesignWidget->reportFileName(); m_lblReportName->setText(filename); - if(!filename.isEmpty()) addRecentFile(filename); + if (!filename.isEmpty()) + addRecentFile(filename); setWindowTitle(m_reportDesignWidget->report()->reportName() + " - Lime Report Designer"); } void ReportDesignWindow::slotSaveReportAs() { - if (m_reportDesignWidget->emitSaveReportAs()) return; // report save as'd via signal + if (m_reportDesignWidget->emitSaveReportAs()) + return; // report save as'd via signal - QString fileName = QFileDialog::getSaveFileName(this,tr("Report file name"),"","Report files(*.lrxml);; All files(*)"); - if (!fileName.isEmpty()){ + QString fileName = QFileDialog::getSaveFileName(this, tr("Report file name"), "", + "Report files(*.lrxml);; All files(*)"); + if (!fileName.isEmpty()) { m_reportDesignWidget->saveToFile(fileName); m_lblReportName->setText(m_reportDesignWidget->reportFileName()); addRecentFile(fileName); @@ -1167,40 +1202,42 @@ void ReportDesignWindow::slotSaveReportAs() void ReportDesignWindow::slotLoadReport() { - if (!checkNeedToSave()) return; + if (!checkNeedToSave()) + return; - if (m_reportDesignWidget->emitLoadReport()) return; + if (m_reportDesignWidget->emitLoadReport()) + return; QString fileName = QFileDialog::getOpenFileName( - this,tr("Report file name"), - m_reportDesignWidget->report()->currentReportsDir(), - "Report files(*.lrxml);; All files(*)" - ); + this, tr("Report file name"), m_reportDesignWidget->report()->currentReportsDir(), + "Report files(*.lrxml);; All files(*)"); if (!fileName.isEmpty()) { QApplication::processEvents(); setCursor(Qt::WaitCursor); m_reportDesignWidget->clear(); - if (m_reportDesignWidget->loadFromFile(fileName)){ + if (m_reportDesignWidget->loadFromFile(fileName)) { m_lblReportName->setText(fileName); m_objectInspector->setObject(0); updateRedoUndo(); - setWindowTitle(m_reportDesignWidget->report()->reportName() + " - Lime Report Designer"); - if (!m_recentFiles.contains(fileName)){ - if (m_recentFiles.count()==10){ + setWindowTitle(m_reportDesignWidget->report()->reportName() + + " - Lime Report Designer"); + if (!m_recentFiles.contains(fileName)) { + if (m_recentFiles.count() == 10) { QMap::const_iterator it = m_recentFiles.constBegin(); QDateTime minDate = QDateTime::currentDateTime(); while (it != m_recentFiles.constEnd()) { - if (minDate>it.value()) minDate = it.value(); + if (minDate > it.value()) + minDate = it.value(); ++it; } m_recentFiles.remove(m_recentFiles.key(minDate)); } - m_recentFiles.insert(fileName,QDateTime::currentDateTime()); + m_recentFiles.insert(fileName, QDateTime::currentDateTime()); } else { m_recentFiles[fileName] = QDateTime::currentDateTime(); } createRecentFilesMenu(); - m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount()>1); + m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount() > 1); } else { slotNewReport(); } @@ -1209,18 +1246,11 @@ void ReportDesignWindow::slotLoadReport() addRecentFile(fileName); m_editorTabType = ReportDesignWidget::Page; } - } -void ReportDesignWindow::slotZoomIn() -{ - m_reportDesignWidget->scale(1.2,1.2); -} +void ReportDesignWindow::slotZoomIn() { m_reportDesignWidget->scale(1.2, 1.2); } -void ReportDesignWindow::slotZoomOut() -{ - m_reportDesignWidget->scale(1/1.2,1/1.2); -} +void ReportDesignWindow::slotZoomOut() { m_reportDesignWidget->scale(1 / 1.2, 1 / 1.2); } void ReportDesignWindow::slotEditMode() { @@ -1232,7 +1262,6 @@ void ReportDesignWindow::slotUndo() { m_reportDesignWidget->undo(); updateRedoUndo(); - } void ReportDesignWindow::slotRedo() @@ -1241,44 +1270,24 @@ void ReportDesignWindow::slotRedo() updateRedoUndo(); } -void ReportDesignWindow::slotCopy() -{ - m_reportDesignWidget->copy(); -} +void ReportDesignWindow::slotCopy() { m_reportDesignWidget->copy(); } -void ReportDesignWindow::slotPaste() -{ - m_reportDesignWidget->paste(); -} +void ReportDesignWindow::slotPaste() { m_reportDesignWidget->paste(); } -void ReportDesignWindow::slotCut() -{ - m_reportDesignWidget->cut(); -} +void ReportDesignWindow::slotCut() { m_reportDesignWidget->cut(); } -void ReportDesignWindow::slotDelete() -{ - m_reportDesignWidget->deleteSelectedItems(); -} +void ReportDesignWindow::slotDelete() { m_reportDesignWidget->deleteSelectedItems(); } void ReportDesignWindow::slotEditLayoutMode() { m_reportDesignWidget->editLayoutMode(m_editLayoutMode->isChecked()); } -void ReportDesignWindow::slotHLayout() -{ - m_reportDesignWidget->addHLayout(); -} +void ReportDesignWindow::slotHLayout() { m_reportDesignWidget->addHLayout(); } -void ReportDesignWindow::slotVLayout() -{ - m_reportDesignWidget->addVLayout(); -} +void ReportDesignWindow::slotVLayout() { m_reportDesignWidget->addVLayout(); } -void ReportDesignWindow::slotTest() -{ -} +void ReportDesignWindow::slotTest() { } void ReportDesignWindow::slotPrintReport() { @@ -1296,16 +1305,16 @@ void ReportDesignWindow::slotPreviewReport() void ReportDesignWindow::slotItemActionCliked() { - QAction* action=dynamic_cast(sender()); + QAction* action = dynamic_cast(sender()); action->setCheckable(true); action->setChecked(true); m_reportItemIsLocked = QApplication::keyboardModifiers() == Qt::SHIFT; m_reportDesignWidget->startInsertMode(action->whatsThis()); } -void ReportDesignWindow::slotBandAdded(PageDesignIntf *, BandDesignIntf * band) +void ReportDesignWindow::slotBandAdded(PageDesignIntf*, BandDesignIntf* band) { - if (band->isUnique()){ + if (band->isUnique()) { switch (band->bandType()) { case BandDesignIntf::PageHeader: m_newPageHeader->setDisabled(true); @@ -1328,9 +1337,9 @@ void ReportDesignWindow::slotBandAdded(PageDesignIntf *, BandDesignIntf * band) } } -void ReportDesignWindow::slotBandDeleted(PageDesignIntf *, BandDesignIntf *band) +void ReportDesignWindow::slotBandDeleted(PageDesignIntf*, BandDesignIntf* band) { - if (band->isUnique()){ + if (band->isUnique()) { switch (band->bandType()) { case BandDesignIntf::PageHeader: m_newPageHeader->setEnabled(true); @@ -1351,17 +1360,18 @@ void ReportDesignWindow::slotBandDeleted(PageDesignIntf *, BandDesignIntf *band) } } +void ReportDesignWindow::updateAvaibleBands() +{ -void ReportDesignWindow::updateAvaibleBands(){ - - if (!m_reportDesignWidget || !m_reportDesignWidget->activePage()) return; + if (!m_reportDesignWidget || !m_reportDesignWidget->activePage()) + return; m_newPageHeader->setEnabled(true); m_newPageFooter->setEnabled(true); m_newReportHeader->setEnabled(true); m_newReportFooter->setEnabled(true); m_newTearOffBand->setEnabled(true); - foreach(BandDesignIntf* band, m_reportDesignWidget->activePage()->pageItem()->bands()){ + foreach (BandDesignIntf* band, m_reportDesignWidget->activePage()->pageItem()->bands()) { switch (band->bandType()) { case BandDesignIntf::PageHeader: m_newPageHeader->setEnabled(false); @@ -1382,16 +1392,18 @@ void ReportDesignWindow::updateAvaibleBands(){ } } -void ReportDesignWindow::showDefaultToolBars(){ - foreach (QToolBar* tb, m_pageTools){ +void ReportDesignWindow::showDefaultToolBars() +{ + foreach (QToolBar* tb, m_pageTools) { tb->setVisible(m_editorTabType != ReportDesignWidget::Dialog); } - foreach (QToolBar* tb, m_dialogTools){ + foreach (QToolBar* tb, m_dialogTools) { tb->setVisible(m_editorTabType == ReportDesignWidget::Dialog); } } -void ReportDesignWindow::showDefaultEditors(){ +void ReportDesignWindow::showDefaultEditors() +{ foreach (QDockWidget* w, m_pageEditors) { w->setVisible(m_editorTabType != ReportDesignWidget::Dialog); } @@ -1399,8 +1411,8 @@ void ReportDesignWindow::showDefaultEditors(){ foreach (QDockWidget* w, m_dialogEditors) { w->setVisible(m_editorTabType == ReportDesignWidget::Dialog); } - for ( int i = 0; i < m_docksToTabify.size() - 1; ++i){ - tabifyDockWidget(m_docksToTabify.at(i),m_docksToTabify.at(i+1)); + for (int i = 0; i < m_docksToTabify.size() - 1; ++i) { + tabifyDockWidget(m_docksToTabify.at(i), m_docksToTabify.at(i + 1)); } m_docksToTabify.at(0)->raise(); #endif @@ -1412,7 +1424,7 @@ void ReportDesignWindow::slotActivePageChanged() updateRedoUndo(); updateAvaibleBands(); - if (m_editorTabType == ReportDesignWidget::Dialog){ + if (m_editorTabType == ReportDesignWidget::Dialog) { #ifdef HAVE_UI_LOADER m_scriptBrowser->updateDialogsTree(); #endif @@ -1423,7 +1435,7 @@ void ReportDesignWindow::slotActivePageChanged() m_editorsStates[m_editorTabType] = saveState(); m_editorTabType = m_reportDesignWidget->activeTabType(); - if (!m_editorsStates[m_editorTabType].isEmpty()){ + if (!m_editorsStates[m_editorTabType].isEmpty()) { restoreState(m_editorsStates[m_editorTabType]); } else { showDefaultEditors(); @@ -1433,20 +1445,14 @@ void ReportDesignWindow::slotActivePageChanged() setDocWidgetsVisibility(false); } -void ReportDesignWindow::renderStarted() -{ - m_progressWidget->setVisible(true); -} +void ReportDesignWindow::renderStarted() { m_progressWidget->setVisible(true); } void ReportDesignWindow::renderPageFinished(int renderedPageCount) { m_progressLabel->setText(tr("Rendered %1 pages").arg(renderedPageCount)); } -void ReportDesignWindow::renderFinished() -{ - m_progressWidget->setVisible(false); -} +void ReportDesignWindow::renderFinished() { m_progressWidget->setVisible(false); } void ReportDesignWindow::slotShowAbout() { @@ -1454,17 +1460,19 @@ void ReportDesignWindow::slotShowAbout() about->exec(); } -bool ReportDesignWindow::isDockAreaVisible(Qt::DockWidgetArea area){ - QList dockWidgets = findChildren(); - foreach (QDockWidget* dw, dockWidgets){ +bool ReportDesignWindow::isDockAreaVisible(Qt::DockWidgetArea area) +{ + QList dockWidgets = findChildren(); + foreach (QDockWidget* dw, dockWidgets) { if ((dockWidgetArea(dw) == area) && !dw->isHidden()) return true; } return false; } -void ReportDesignWindow::hideDockWidgets(Qt::DockWidgetArea area, bool value){ - QList dockWidgets = findChildren(); +void ReportDesignWindow::hideDockWidgets(Qt::DockWidgetArea area, bool value) +{ + QList dockWidgets = findChildren(); QMap* currentDocState = 0; switch (area) { @@ -1482,9 +1490,10 @@ void ReportDesignWindow::hideDockWidgets(Qt::DockWidgetArea area, bool value){ } foreach (QDockWidget* dw, dockWidgets) { - if (dockWidgetArea(dw) == area){ - if (!value){ - if (currentDocState->value(dw)) dw->show(); + if (dockWidgetArea(dw) == area) { + if (!value) { + if (currentDocState->value(dw)) + dw->show(); } else { currentDocState->insert(dw, dw->isVisible()); dw->hide(); @@ -1495,34 +1504,25 @@ void ReportDesignWindow::hideDockWidgets(Qt::DockWidgetArea area, bool value){ void ReportDesignWindow::slotHideLeftPanel(bool value) { - hideDockWidgets(Qt::LeftDockWidgetArea,!value); + hideDockWidgets(Qt::LeftDockWidgetArea, !value); } void ReportDesignWindow::slotHideRightPanel(bool value) { - hideDockWidgets(Qt::RightDockWidgetArea,!value); + hideDockWidgets(Qt::RightDockWidgetArea, !value); } -void ReportDesignWindow::slotEditSettings() -{ - m_reportDesignWidget->editSetting(); -} +void ReportDesignWindow::slotEditSettings() { m_reportDesignWidget->editSetting(); } -void ReportDesignWindow::slotUseGrid(bool value) -{ - m_reportDesignWidget->setUseGrid(value); -} +void ReportDesignWindow::slotUseGrid(bool value) { m_reportDesignWidget->setUseGrid(value); } -void ReportDesignWindow::slotUseMagnet(bool value) -{ - m_reportDesignWidget->setUseMagnet(value); -} +void ReportDesignWindow::slotUseMagnet(bool value) { m_reportDesignWidget->setUseMagnet(value); } void ReportDesignWindow::slotLoadRecentFile(const QString fileName) { - if (checkNeedToSave()){ + if (checkNeedToSave()) { QApplication::processEvents(); - if (QFile::exists(fileName)){ + if (QFile::exists(fileName)) { setCursor(Qt::WaitCursor); m_reportDesignWidget->clear(); m_reportDesignWidget->loadFromFile(fileName); @@ -1530,24 +1530,26 @@ void ReportDesignWindow::slotLoadRecentFile(const QString fileName) m_objectInspector->setObject(0); updateRedoUndo(); unsetCursor(); - setWindowTitle(m_reportDesignWidget->report()->reportName() + " - Lime Report Designer"); + setWindowTitle(m_reportDesignWidget->report()->reportName() + + " - Lime Report Designer"); m_recentFiles[fileName] = QDateTime::currentDateTime(); } else { m_recentFiles.remove(fileName); removeNotExistedRecentFilesFromMenu(fileName); - QMessageBox::information(this,tr("Warning"),tr("File \"%1\" not found!").arg(fileName)); + QMessageBox::information(this, tr("Warning"), + tr("File \"%1\" not found!").arg(fileName)); } } } -void ReportDesignWindow::slotPageAdded(PageDesignIntf *) +void ReportDesignWindow::slotPageAdded(PageDesignIntf*) { - m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount()>1); + m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount() > 1); } void ReportDesignWindow::slotPageDeleted() { - m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount()>1); + m_deletePageAction->setEnabled(m_reportDesignWidget->report()->pageCount() > 1); } void ReportDesignWindow::slotFilterTextChanged(const QString& filter) @@ -1555,53 +1557,43 @@ void ReportDesignWindow::slotFilterTextChanged(const QString& filter) #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) m_filterModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::FixedString)); #else - m_filterModel->setFilterRegularExpression(QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption)); + m_filterModel->setFilterRegularExpression( + QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption)); #endif } #ifdef HAVE_QTDESIGNER_INTEGRATION void ReportDesignWindow::slotDeleteDialog() { - if ( m_editorTabType == ReportDesignWidget::Dialog ){ - m_reportDesignWidget->report()->scriptContext()->deleteDialog(m_reportDesignWidget->activeDialogName()); + if (m_editorTabType == ReportDesignWidget::Dialog) { + m_reportDesignWidget->report()->scriptContext()->deleteDialog( + m_reportDesignWidget->activeDialogName()); } } -void ReportDesignWindow::slotAddNewDialog() -{ - m_reportDesignWidget->addNewDialog(); -} +void ReportDesignWindow::slotAddNewDialog() { m_reportDesignWidget->addNewDialog(); } #endif -void ReportDesignWindow::slotLockSelectedItems() -{ - m_reportDesignWidget->lockSelectedItems(); -} +void ReportDesignWindow::slotLockSelectedItems() { m_reportDesignWidget->lockSelectedItems(); } -void ReportDesignWindow::slotUnlockSelectedItems() -{ - m_reportDesignWidget->unlockSelectedItems(); -} +void ReportDesignWindow::slotUnlockSelectedItems() { m_reportDesignWidget->unlockSelectedItems(); } -void ReportDesignWindow::slotSelectOneLevelItems() -{ - m_reportDesignWidget->selectOneLevelItems(); -} +void ReportDesignWindow::slotSelectOneLevelItems() { m_reportDesignWidget->selectOneLevelItems(); } void ReportDesignWindow::slotCancelRendering(bool) { m_reportDesignWidget->report()->cancelRender(); } -void ReportDesignWindow::closeEvent(QCloseEvent * event) +void ReportDesignWindow::closeEvent(QCloseEvent* event) { - if (m_progressWidget->isVisible()){ + if (m_progressWidget->isVisible()) { QMessageBox::critical(this, tr("Attention"), tr("The rendering is in process")); event->ignore(); return; } - if (checkNeedToSave()){ + if (checkNeedToSave()) { m_dataBrowser->closeAllDataWindows(); writeState(); #ifdef Q_OS_WIN @@ -1612,7 +1604,8 @@ void ReportDesignWindow::closeEvent(QCloseEvent * event) #endif m_eventLoop.exit(); event->accept(); - } else event->ignore(); + } else + event->ignore(); } void ReportDesignWindow::resizeEvent(QResizeEvent*) @@ -1626,13 +1619,12 @@ void ReportDesignWindow::showEvent(QShowEvent* event) { QMainWindow::showEvent(event); - if (!m_editorsStates[m_editorTabType].isEmpty()){ + if (!m_editorsStates[m_editorTabType].isEmpty()) { restoreState(m_editorsStates[m_editorTabType]); } else { showDefaultEditors(); showDefaultToolBars(); } - } void ReportDesignWindow::moveEvent(QMoveEvent*) @@ -1642,19 +1634,21 @@ void ReportDesignWindow::moveEvent(QMoveEvent*) #endif } -bool ObjectNameValidator::validate(const QString &propName, const QVariant &propValue, QObject *object, QString &msg) +bool ObjectNameValidator::validate(const QString& propName, const QVariant& propValue, + QObject* object, QString& msg) { - if (propName.compare("objectName")==0){ + if (propName.compare("objectName") == 0) { BaseDesignIntf* bd = dynamic_cast(object); - if (bd){ - if (bd->page()->reportItemByName(propValue.toString())){ - msg = QString(QObject::tr("Object with name %1 already exists!").arg(propValue.toString())); + if (bd) { + if (bd->page()->reportItemByName(propValue.toString())) { + msg = QString( + QObject::tr("Object with name %1 already exists!").arg(propValue.toString())); return false; - } else (bd->emitObjectNamePropertyChanged(object->objectName(),propValue.toString())); + } else + (bd->emitObjectNamePropertyChanged(object->objectName(), propValue.toString())); } } return true; } -} - +} // namespace LimeReport diff --git a/limereport/lrreportdesignwindow.h b/limereport/lrreportdesignwindow.h index b1aef76..438fb29 100644 --- a/limereport/lrreportdesignwindow.h +++ b/limereport/lrreportdesignwindow.h @@ -30,22 +30,23 @@ #ifndef LRREPORTEDITORWINDOW_H #define LRREPORTEDITORWINDOW_H -#include -#include -#include -#include -#include -#include -#include -#include "lrbanddesignintf.h" #include "items/editors/lrfonteditorwidget.h" -#include "items/editors/lrtextalignmenteditorwidget.h" #include "items/editors/lritemsaligneditorwidget.h" #include "items/editors/lritemsborderseditorwidget.h" +#include "items/editors/lrtextalignmenteditorwidget.h" +#include "lrbanddesignintf.h" #include "lrobjectitemmodel.h" #include "lrreportdesignwindowintrerface.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include +#include + +namespace LimeReport { class ObjectInspectorWidget; class QObjectPropertyModel; @@ -56,13 +57,13 @@ class BaseDesignIntf; class PageDesignIntf; class ObjectBrowser; -class ReportDesignWindow : public ReportDesignWindowInterface -{ +class ReportDesignWindow: public ReportDesignWindowInterface { Q_OBJECT public: - explicit ReportDesignWindow(ReportEnginePrivateInterface *report, QWidget *parent = 0, QSettings* settings=0); + explicit ReportDesignWindow(ReportEnginePrivateInterface* report, QWidget* parent = 0, + QSettings* settings = 0); ~ReportDesignWindow(); - static ReportDesignWindow* instance(){return m_instance;} + static ReportDesignWindow* instance() { return m_instance; } bool checkNeedToSave(); void showModal(); @@ -70,7 +71,7 @@ public: void setSettings(QSettings* value); QSettings* settings(); void restoreSetting(); - void setShowProgressDialog(bool value){m_showProgressDialog = value;} + void setShowProgressDialog(bool value) { m_showProgressDialog = value; } private slots: void slotNewReport(); void slotNewPage(); @@ -93,11 +94,12 @@ private slots: void slotEditLayoutMode(); void slotHLayout(); void slotVLayout(); - void slotItemSelected(LimeReport::BaseDesignIntf *item); - void slotItemPropertyChanged(const QString& objectName, const QString& propertyName, const QVariant &oldValue, const QVariant &newValue); + void slotItemSelected(LimeReport::BaseDesignIntf* item); + void slotItemPropertyChanged(const QString& objectName, const QString& propertyName, + const QVariant& oldValue, const QVariant& newValue); void slotMultiItemSelected(); void slotInsertModeStarted(); - void slotItemInserted(LimeReport::PageDesignIntf* , QPointF, const QString& ItemType); + void slotItemInserted(LimeReport::PageDesignIntf*, QPointF, const QString& ItemType); void slotItemInsertCanceled(const QString& ItemType); void slotUpdateDataBrowser(const QString& collectionName); void slotCommandHistoryChanged(); @@ -105,8 +107,8 @@ private slots: void slotPrintReport(); void slotPreviewReport(); void slotItemActionCliked(); - void slotBandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*band); - void slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*band); + void slotBandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf* band); + void slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf* band); void slotActivePageChanged(); void renderStarted(); void renderPageFinished(int renderedPageCount); @@ -118,7 +120,7 @@ private slots: void slotUseGrid(bool value); void slotUseMagnet(bool value); void slotLoadRecentFile(const QString fileName); - void slotPageAdded(PageDesignIntf* ); + void slotPageAdded(PageDesignIntf*); void slotPageDeleted(); void slotFilterTextChanged(const QString& filter); #ifdef HAVE_QTDESIGNER_INTEGRATION @@ -131,14 +133,14 @@ private slots: void slotCancelRendering(bool); protected: - void closeEvent(QCloseEvent *event); - void resizeEvent(QResizeEvent *); + void closeEvent(QCloseEvent* event); + void resizeEvent(QResizeEvent*); void showEvent(QShowEvent* event); - void moveEvent(QMoveEvent *); + void moveEvent(QMoveEvent*); void hideDockWidgets(Qt::DockWidgetArea area, bool value); bool isDockAreaVisible(Qt::DockWidgetArea area); void setDocWidgetsVisibility(bool visible); - void keyPressEvent(QKeyEvent *event); + void keyPressEvent(QKeyEvent* event); private: void initReportEditor(ReportEnginePrivate* report); @@ -173,6 +175,7 @@ private: void addRecentFile(const QString& fileName); void showDefaultToolBars(); void showDefaultEditors(); + private: static ReportDesignWindow* m_instance; QStatusBar* m_statusBar; @@ -243,26 +246,26 @@ private: QAction* m_unlockSelectedItemsAction; QAction* m_selectOneLevelItems; - QMenu* m_recentFilesMenu; + QMenu* m_recentFilesMenu; QSignalMapper* m_bandsAddSignalsMap; QSignalMapper* m_recentFilesSignalMap; ObjectInspectorWidget* m_objectInspector; ReportDesignWidget* m_reportDesignWidget; - DataBrowser * m_dataBrowser; + DataBrowser* m_dataBrowser; ScriptBrowser* m_scriptBrowser; ObjectBrowser* m_objectsBrowser; - QHash m_actionMap; + QHash m_actionMap; QLabel* m_lblReportName; QEventLoop m_eventLoop; QFontComboBox* m_fontNameEditor; QComboBox* m_fontSizeEditor; QStringListModel m_fontSizeModel; bool m_textAttibutesIsChanging; - BaseDesignIntf const * m_fontItem; + BaseDesignIntf const* m_fontItem; FontEditorWidget* m_fontEditorBar; TextAlignmentEditorWidget* m_textAlignmentEditorBar; ItemsAlignmentEditorWidget* m_itemsAlignmentEditorBar; @@ -272,12 +275,12 @@ private: ValidatorIntf* m_validator; QProgressDialog* m_progressDialog; bool m_showProgressDialog; - QMap m_recentFiles; + QMap m_recentFiles; QVector m_pageEditors; QVector m_dialogEditors; QVector m_docksToTabify; ReportDesignWidget::EditorTabType m_editorTabType; - QByteArray m_editorsStates[ReportDesignWidget::TabTypeCount]; + QByteArray m_editorsStates[ReportDesignWidget::TabTypeCount]; QVector m_pageTools; QVector m_dialogTools; bool m_reportItemIsLocked; @@ -292,9 +295,10 @@ private: void createProgressBar(); }; -class ObjectNameValidator : public ValidatorIntf{ - bool validate(const QString &propName, const QVariant &propValue, QObject *object, QString &msg); +class ObjectNameValidator: public ValidatorIntf { + bool validate(const QString& propName, const QVariant& propValue, QObject* object, + QString& msg); }; -} +} // namespace LimeReport #endif // LRREPORTEDITORWINDOW_H diff --git a/limereport/lrreportdesignwindowintrerface.h b/limereport/lrreportdesignwindowintrerface.h index 858881e..beae8d6 100644 --- a/limereport/lrreportdesignwindowintrerface.h +++ b/limereport/lrreportdesignwindowintrerface.h @@ -6,9 +6,9 @@ namespace LimeReport { -class ReportDesignWindowInterface: public QMainWindow{ +class ReportDesignWindowInterface: public QMainWindow { public: - ReportDesignWindowInterface(QWidget* parent = 0): QMainWindow(parent){} + ReportDesignWindowInterface(QWidget* parent = 0): QMainWindow(parent) { } virtual bool checkNeedToSave() = 0; virtual void showModal() = 0; virtual void showNonModal() = 0; diff --git a/limereport/lrreportengine.cpp b/limereport/lrreportengine.cpp index 306aca7..6df5e8c 100644 --- a/limereport/lrreportengine.cpp +++ b/limereport/lrreportengine.cpp @@ -27,48 +27,46 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include -#include -#include #include +#include +#include +#include +#include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include #else #include #endif -#include -#include -#include -#include - +#include "lrdatasourcemanager.h" +#include "lrpagedesignintf.h" +#include "lrreportengine.h" +#include "lrreportengine_p.h" #include "time.h" -#include "lrreportengine_p.h" -#include "lrreportengine.h" - -#include "lrpagedesignintf.h" -#include "lrdatasourcemanager.h" +#include +#include +#include +#include #ifdef HAVE_REPORT_DESIGNER #include "lrdatabrowser.h" #include "lrreportdesignwindow.h" #endif -#include "serializators/lrxmlwriter.h" -#include "serializators/lrxmlreader.h" -#include "lrreportrender.h" -#include "lrpreviewreportwindow.h" -#include "lrpreviewreportwidget.h" -#include "lrpreviewreportwidget_p.h" #include "lrexporterintf.h" #include "lrexportersfactory.h" +#include "lrpreviewreportwidget.h" +#include "lrpreviewreportwidget_p.h" +#include "lrpreviewreportwindow.h" +#include "lrreportrender.h" +#include "serializators/lrxmlreader.h" +#include "serializators/lrxmlwriter.h" #ifdef BUILD_WITH_EASY_PROFILER #include "easy/profiler.h" #else -# define EASY_BLOCK(...) -# define EASY_END_BLOCK +#define EASY_BLOCK(...) +#define EASY_END_BLOCK #endif #include "lrpreparedpages.h" @@ -76,21 +74,36 @@ #include "lrfactoryinitializer.h" #endif -namespace LimeReport{ +namespace LimeReport { QSettings* ReportEngine::m_settings = 0; -ReportEnginePrivate::ReportEnginePrivate(QObject *parent) : - QObject(parent), m_preparedPagesManager(new PreparedPages(&m_preparedPages)), m_fileName(""), m_settings(0), m_ownedSettings(false), - m_printer(new QPrinter(QPrinter::HighResolution)), m_printerSelected(false), - m_showProgressDialog(true), m_reportName(""), m_activePreview(0), - m_previewWindowIcon(":/report/images/logo32"), m_previewWindowTitle(tr("Preview")), - m_reportRendering(false), m_resultIsEditable(true), m_passPhrase("HjccbzHjlbyfCkjy"), - m_fileWatcher( new QFileSystemWatcher( this ) ), m_reportLanguage(QLocale::AnyLanguage), - m_previewLayoutDirection(Qt::LayoutDirectionAuto), m_designerFactory(0), - m_previewScaleType(FitWidth), m_previewScalePercent(0), m_startTOCPage(0), +ReportEnginePrivate::ReportEnginePrivate(QObject* parent): + QObject(parent), + m_preparedPagesManager(new PreparedPages(&m_preparedPages)), + m_fileName(""), + m_settings(0), + m_ownedSettings(false), + m_printer(new QPrinter(QPrinter::HighResolution)), + m_printerSelected(false), + m_showProgressDialog(true), + m_reportName(""), + m_activePreview(0), + m_previewWindowIcon(":/report/images/logo32"), + m_previewWindowTitle(tr("Preview")), + m_reportRendering(false), + m_resultIsEditable(true), + m_passPhrase("HjccbzHjlbyfCkjy"), + m_fileWatcher(new QFileSystemWatcher(this)), + m_reportLanguage(QLocale::AnyLanguage), + m_previewLayoutDirection(Qt::LayoutDirectionAuto), + m_designerFactory(0), + m_previewScaleType(FitWidth), + m_previewScalePercent(0), + m_startTOCPage(0), m_previewPageBackgroundColor(Qt::gray), - m_saveToFileVisible(true), m_printToPdfVisible(true), + m_saveToFileVisible(true), + m_printToPdfVisible(true), m_printVisible(true) { #ifdef HAVE_STATIC_BUILD @@ -106,31 +119,35 @@ ReportEnginePrivate::ReportEnginePrivate(QObject *parent) : scriptManager()->setDataManager(m_datasources); m_scriptEngineContext = new ScriptEngineContext(this); - ICallbackDatasource* tableOfContents = m_datasources->createCallbackDatasource("tableofcontents"); - connect(tableOfContents, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - m_scriptEngineContext->tableOfContents(), SLOT(slotOneSlotDS(LimeReport::CallbackInfo,QVariant&))); + ICallbackDatasource* tableOfContents + = m_datasources->createCallbackDatasource("tableofcontents"); + connect(tableOfContents, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), + m_scriptEngineContext->tableOfContents(), + SLOT(slotOneSlotDS(LimeReport::CallbackInfo, QVariant&))); m_datasources->setObjectName("datasources"); - connect(m_datasources,SIGNAL(loadCollectionFinished(QString)),this,SLOT(slotDataSourceCollectionLoaded(QString))); - connect(m_fileWatcher,SIGNAL(fileChanged(const QString &)),this,SLOT(slotLoadFromFile(const QString &))); + connect(m_datasources, SIGNAL(loadCollectionFinished(QString)), this, + SLOT(slotDataSourceCollectionLoaded(QString))); + connect(m_fileWatcher, SIGNAL(fileChanged(const QString&)), this, + SLOT(slotLoadFromFile(const QString&))); #ifndef HAVE_REPORT_DESIGNER QDir pluginsDir = QCoreApplication::applicationDirPath(); - if (!pluginsDir.cd("../lib" )){ + if (!pluginsDir.cd("../lib")) { pluginsDir.cd("./lib"); } - if (pluginsDir != QCoreApplication::applicationDirPath()){ - foreach( const QString& pluginName, pluginsDir.entryList( QDir::Files ) ) { - QPluginLoader loader( pluginsDir.absoluteFilePath( pluginName ) ); - if( loader.load() ) { + if (pluginsDir != QCoreApplication::applicationDirPath()) { + foreach (const QString& pluginName, pluginsDir.entryList(QDir::Files)) { + QPluginLoader loader(pluginsDir.absoluteFilePath(pluginName)); + if (loader.load()) { - if( LimeReportDesignerPluginInterface* designerPlugin = qobject_cast< LimeReportDesignerPluginInterface* >( loader.instance() ) ) { + if (LimeReportDesignerPluginInterface* designerPlugin + = qobject_cast(loader.instance())) { m_designerFactory = designerPlugin; break; } - } } } @@ -143,115 +160,104 @@ ReportEnginePrivate::~ReportEnginePrivate() if (m_designerWindow) { m_designerWindow->close(); } - if (m_activePreview){ + if (m_activePreview) { m_activePreview->close(); } - foreach(PageDesignIntf* page,m_pages) delete page; + foreach (PageDesignIntf* page, m_pages) + delete page; m_pages.clear(); - foreach(ReportTranslation* translation, m_translations) + foreach (ReportTranslation* translation, m_translations) delete translation; m_translations.clear(); - if (m_ownedSettings&&m_settings) delete m_settings; + if (m_ownedSettings && m_settings) + delete m_settings; delete m_preparedPagesManager; } -QObject* ReportEnginePrivate::createElement(const QString &, const QString &) -{ - return appendPage(); -} +QObject* ReportEnginePrivate::createElement(const QString&, const QString&) { return appendPage(); } -QObject *ReportEnginePrivate::elementAt(const QString &, int index) -{ - return pageAt(index); -} +QObject* ReportEnginePrivate::elementAt(const QString&, int index) { return pageAt(index); } -PageDesignIntf *ReportEnginePrivate::createPage(const QString &pageName, bool preview) +PageDesignIntf* ReportEnginePrivate::createPage(const QString& pageName, bool preview) { - PageDesignIntf* page =new PageDesignIntf(); + PageDesignIntf* page = new PageDesignIntf(); page->setObjectName(pageName); - page->pageItem()->setObjectName("Report"+pageName); + page->pageItem()->setObjectName("Report" + pageName); if (!preview) page->setReportEditor(this); page->setReportSettings(&m_reportSettings); return page; } -PageDesignIntf *ReportEnginePrivate::appendPage(const QString &pageName) +PageDesignIntf* ReportEnginePrivate::appendPage(const QString& pageName) { PageDesignIntf* page = createPage(pageName); m_pages.append(page); return page; } -bool ReportEnginePrivate::deletePage(PageDesignIntf *page){ +bool ReportEnginePrivate::deletePage(PageDesignIntf* page) +{ QList::iterator it = m_pages.begin(); - while (it != m_pages.end()){ + while (it != m_pages.end()) { if (*it == page) { it = m_pages.erase(it); return true; - } else ++it; + } else + ++it; } return false; } -PageDesignIntf *ReportEnginePrivate::createPreviewPage() -{ - return createPage("preview",true); -} +PageDesignIntf* ReportEnginePrivate::createPreviewPage() { return createPage("preview", true); } -int ReportEnginePrivate::elementsCount(const QString &) -{ - return m_pages.count(); -} +int ReportEnginePrivate::elementsCount(const QString&) { return m_pages.count(); } -void ReportEnginePrivate::collectionLoadFinished(const QString &) +void ReportEnginePrivate::collectionLoadFinished(const QString&) { foreach (PageDesignIntf* page, m_pages) { page->setReportEditor(this); page->setReportSettings(&m_reportSettings); - page->setSceneRect(-Const::SCENE_MARGIN,-Const::SCENE_MARGIN, - page->pageItem()->width()+Const::SCENE_MARGIN*2, - page->pageItem()->boundingRect().height()+Const::SCENE_MARGIN*2); + page->setSceneRect(-Const::SCENE_MARGIN, -Const::SCENE_MARGIN, + page->pageItem()->width() + Const::SCENE_MARGIN * 2, + page->pageItem()->boundingRect().height() + Const::SCENE_MARGIN * 2); } emit pagesLoadFinished(); } -void ReportEnginePrivate::saveError(QString message) -{ - m_lastError = message; -} +void ReportEnginePrivate::saveError(QString message) { m_lastError = message; } void ReportEnginePrivate::showError(QString message) { - QMessageBox::critical(0,tr("Error"),message); + QMessageBox::critical(0, tr("Error"), message); } void ReportEnginePrivate::updateTranslations() { - foreach(ReportTranslation* translation, m_translations.values()){ + foreach (ReportTranslation* translation, m_translations.values()) { translation->invalidatePages(); - foreach(PageDesignIntf* page, m_pages){ + foreach (PageDesignIntf* page, m_pages) { translation->updatePageTranslation(page); } translation->clearInvalidPages(); } } -void ReportEnginePrivate::slotDataSourceCollectionLoaded(const QString &collectionName) +void ReportEnginePrivate::slotDataSourceCollectionLoaded(const QString& collectionName) { emit datasourceCollectionLoadFinished(collectionName); } void ReportEnginePrivate::slotPreviewWindowDestroyed(QObject* window) { - if (m_activePreview == window){ + if (m_activePreview == window) { m_activePreview = 0; } } -void ReportEnginePrivate::slotDesignerWindowDestroyed(QObject *window) +void ReportEnginePrivate::slotDesignerWindowDestroyed(QObject* window) { Q_UNUSED(window) dataManager()->setDesignTime(false); @@ -259,73 +265,69 @@ void ReportEnginePrivate::slotDesignerWindowDestroyed(QObject *window) void ReportEnginePrivate::clearReport() { - foreach(PageDesignIntf* page,m_pages) delete page; + foreach (PageDesignIntf* page, m_pages) + delete page; m_pages.clear(); - foreach(ReportTranslation* reportTranslation, m_translations) + foreach (ReportTranslation* reportTranslation, m_translations) delete reportTranslation; m_translations.clear(); m_datasources->clear(DataSourceManager::Owned); - m_fileName=""; + m_fileName = ""; m_scriptEngineContext->clear(); m_reportSettings.setDefaultValues(); emit cleared(); } -bool ReportEnginePrivate::printPages(ReportPages pages, QPrinter *printer) +bool ReportEnginePrivate::printPages(ReportPages pages, QPrinter* printer) { - if (!printer&&!m_printerSelected){ + if (!printer && !m_printerSelected) { QPrinterInfo pi; if (!pi.defaultPrinter().isNull()) #if QT_VERSION >= 0x050300 - m_printer.data()->setPrinterName(pi.defaultPrinterName()); + m_printer.data()->setPrinterName(pi.defaultPrinterName()); #else - m_printer.data()->setPrinterName(pi.defaultPrinter().printerName()); + m_printer.data()->setPrinterName(pi.defaultPrinter().printerName()); #endif - QPrintDialog dialog(m_printer.data(),QApplication::activeWindow()); - m_printerSelected = dialog.exec()!=QDialog::Rejected; + QPrintDialog dialog(m_printer.data(), QApplication::activeWindow()); + m_printerSelected = dialog.exec() != QDialog::Rejected; } - if (!printer&&!m_printerSelected) return false; + if (!printer && !m_printerSelected) + return false; - printer =(printer)?printer:m_printer.data(); - if (printer&&printer->isValid()){ - try{ - if (pages.count()>0){ - internalPrintPages( - pages, - *printer - ); + printer = (printer) ? printer : m_printer.data(); + if (printer && printer->isValid()) { + try { + if (pages.count() > 0) { + internalPrintPages(pages, *printer); } - } catch(ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); } return true; - } else return false; + } else + return false; } -void ReportEnginePrivate::internalPrintPages(ReportPages pages, QPrinter &printer) +void ReportEnginePrivate::internalPrintPages(ReportPages pages, QPrinter& printer) { int currenPage = 1; m_cancelPrinting = false; - QMap > printProcessors; - printProcessors.insert("default",QSharedPointer(new PrintProcessor(&printer))); + QMap> printProcessors; + printProcessors.insert("default", QSharedPointer(new PrintProcessor(&printer))); - int pageCount = (printer.printRange() == QPrinter::AllPages) ? - pages.size() : - printer.toPage() - printer.fromPage(); + int pageCount = (printer.printRange() == QPrinter::AllPages) + ? pages.size() + : printer.toPage() - printer.fromPage(); emit printingStarted(pageCount); - foreach(PageItemDesignIntf::Ptr page, pages){ - if ( !m_cancelPrinting && - ((printer.printRange() == QPrinter::AllPages) || - ( (printer.printRange()==QPrinter::PageRange) && - (currenPage >= printer.fromPage()) && - (currenPage <= printer.toPage()) - )) - ) - { - printProcessors["default"]->printPage(page); - emit pagePrintingFinished(currenPage); - QApplication::processEvents(); + foreach (PageItemDesignIntf::Ptr page, pages) { + if (!m_cancelPrinting + && ((printer.printRange() == QPrinter::AllPages) + || ((printer.printRange() == QPrinter::PageRange) + && (currenPage >= printer.fromPage()) && (currenPage <= printer.toPage())))) { + printProcessors["default"]->printPage(page); + emit pagePrintingFinished(currenPage); + QApplication::processEvents(); } currenPage++; @@ -333,37 +335,46 @@ void ReportEnginePrivate::internalPrintPages(ReportPages pages, QPrinter &printe emit printingFinished(); } -void ReportEnginePrivate::printPages(ReportPages pages, QMap printers, bool printToAllPrinters) +void ReportEnginePrivate::printPages(ReportPages pages, QMap printers, + bool printToAllPrinters) { - if (printers.values().isEmpty()) return; + if (printers.values().isEmpty()) + return; m_cancelPrinting = false; - QMap > printProcessors; + QMap> printProcessors; for (int i = 0; i < printers.keys().count(); ++i) { - printProcessors.insert(printers.keys()[i],QSharedPointer(new PrintProcessor(printers[printers.keys()[i]]))); + printProcessors.insert( + printers.keys()[i], + QSharedPointer(new PrintProcessor(printers[printers.keys()[i]]))); } PrintProcessor* defaultProcessor = 0; int currentPrinter = 0; - if (printProcessors.contains("default")) defaultProcessor = printProcessors["default"].data(); - else defaultProcessor = printProcessors.values().at(0).data(); + if (printProcessors.contains("default")) + defaultProcessor = printProcessors["default"].data(); + else + defaultProcessor = printProcessors.values().at(0).data(); emit printingStarted(pages.size()); - for(int i = 0; i < pages.size(); ++i){ - if (m_cancelPrinting) break; + for (int i = 0; i < pages.size(); ++i) { + if (m_cancelPrinting) + break; PageItemDesignIntf::Ptr page = pages.at(i); - if (!printToAllPrinters){ + if (!printToAllPrinters) { if (printProcessors.contains(page->printerName())) printProcessors[page->printerName()]->printPage(page); - else defaultProcessor->printPage(page); + else + defaultProcessor->printPage(page); } else { printProcessors.values().at(currentPrinter)->printPage(page); - if (currentPrinter < printers.values().count()-1) + if (currentPrinter < printers.values().count() - 1) currentPrinter++; - else currentPrinter = 0; + else + currentPrinter = 0; } - emit pagePrintingFinished(i+1); + emit pagePrintingFinished(i + 1); QApplication::processEvents(); } @@ -373,24 +384,24 @@ void ReportEnginePrivate::printPages(ReportPages pages, QMap QStringList ReportEnginePrivate::aviableReportTranslations() { QStringList result; - foreach (QLocale::Language language, aviableLanguages()){ + foreach (QLocale::Language language, aviableLanguages()) { result << QLocale::languageToString(language); } return result; } -void ReportEnginePrivate::setReportTranslation(const QString &languageName) +void ReportEnginePrivate::setReportTranslation(const QString& languageName) { - foreach(QLocale::Language language, aviableLanguages()){ - if (QLocale::languageToString(language).compare(languageName) == 0){ - setReportLanguage(language); - } + foreach (QLocale::Language language, aviableLanguages()) { + if (QLocale::languageToString(language).compare(languageName) == 0) { + setReportLanguage(language); + } } } bool ReportEnginePrivate::printReport(QPrinter* printer) { - if (!printer&&!m_printerSelected){ + if (!printer && !m_printerSelected) { QPrinterInfo pi; if (!pi.defaultPrinter().isNull()) #if QT_VERSION >= 0x050300 @@ -398,56 +409,58 @@ bool ReportEnginePrivate::printReport(QPrinter* printer) #else m_printer.data()->setPrinterName(pi.defaultPrinter().printerName()); #endif - QPrintDialog dialog(m_printer.data(),QApplication::activeWindow()); - m_printerSelected = dialog.exec()!=QDialog::Rejected; + QPrintDialog dialog(m_printer.data(), QApplication::activeWindow()); + m_printerSelected = dialog.exec() != QDialog::Rejected; } - if (!printer&&!m_printerSelected) return false; + if (!printer && !m_printerSelected) + return false; - printer =(printer)?printer:m_printer.data(); - if (printer&&printer->isValid()){ - try{ + printer = (printer) ? printer : m_printer.data(); + if (printer && printer->isValid()) { + try { bool designTime = dataManager()->designTime(); dataManager()->setDesignTime(false); ReportPages pages = renderToPages(); dataManager()->setDesignTime(designTime); - if (pages.count()>0){ + if (pages.count() > 0) { internalPrintPages(pages, *printer); } - } catch(ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); } return true; - } else return false; + } else + return false; } bool ReportEnginePrivate::printReport(QMap printers, bool printToAllPrinters) { - try{ + try { bool designTime = dataManager()->designTime(); dataManager()->setDesignTime(false); ReportPages pages = renderToPages(); dataManager()->setDesignTime(designTime); - if (pages.count()>0){ + if (pages.count() > 0) { printPages(pages, printers, printToAllPrinters); } - } catch(ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); return false; } return true; } -void ReportEnginePrivate::printToFile(const QString &fileName) +void ReportEnginePrivate::printToFile(const QString& fileName) { - if (!fileName.isEmpty()){ + if (!fileName.isEmpty()) { QFile file(fileName); - if (file.open(QIODevice::WriteOnly)){ + if (file.open(QIODevice::WriteOnly)) { QTextStream out(&file); try { dataManager()->setDesignTime(false); - out<setDesignTime(true); - } catch( ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); } } @@ -455,26 +468,28 @@ void ReportEnginePrivate::printToFile(const QString &fileName) } } -bool ReportEnginePrivate::printToPDF(const QString &fileName) +bool ReportEnginePrivate::printToPDF(const QString& fileName) { return exportReport("PDF", fileName); } -bool ReportEnginePrivate::exportReport(QString exporterName, const QString &fileName, const QMap ¶ms) +bool ReportEnginePrivate::exportReport(QString exporterName, const QString& fileName, + const QMap& params) { QString fn = fileName; - if (ExportersFactory::instance().map().contains(exporterName)){ + if (ExportersFactory::instance().map().contains(exporterName)) { ReportExporterInterface* e = ExportersFactory::instance().objectCreator(exporterName)(this); - if (fn.isEmpty()){ + if (fn.isEmpty()) { QString defaultFileName = reportName().split(".")[0]; QString filter = QString("%1 (*.%2)").arg(e->exporterName()).arg(e->exporterFileExt()); - fn = QFileDialog::getSaveFileName(0, tr("%1 file name").arg(e->exporterName()), defaultFileName, filter); + fn = QFileDialog::getSaveFileName(0, tr("%1 file name").arg(e->exporterName()), + defaultFileName, filter); } - if (!fn.isEmpty()){ + if (!fn.isEmpty()) { QFileInfo fi(fn); if (fi.suffix().isEmpty()) fn += QString(".%1").arg(e->exporterFileExt()); - if (fi.absolutePath().compare(QDir::currentPath())==0) + if (fi.absolutePath().compare(QDir::currentPath()) == 0) fn = defaultExportDir() + fn; bool designTime = dataManager()->designTime(); dataManager()->setDesignTime(false); @@ -488,30 +503,33 @@ bool ReportEnginePrivate::exportReport(QString exporterName, const QString &file return false; } -bool ReportEnginePrivate::showPreviewWindow(ReportPages pages, PreviewHints hints, QPrinter* printer) +bool ReportEnginePrivate::showPreviewWindow(ReportPages pages, PreviewHints hints, + QPrinter* printer) { Q_UNUSED(printer) - if (pages.count()>0){ + if (pages.count() > 0) { Q_Q(ReportEngine); - PreviewReportWindow* w = new PreviewReportWindow(q, QApplication::activeWindow(), settings()); - w->setWindowFlags(Qt::Dialog|Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint| Qt::WindowMinMaxButtonsHint); - w->setAttribute(Qt::WA_DeleteOnClose,true); + PreviewReportWindow* w + = new PreviewReportWindow(q, QApplication::activeWindow(), settings()); + w->setWindowFlags(Qt::Dialog | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint + | Qt::WindowMinMaxButtonsHint); + w->setAttribute(Qt::WA_DeleteOnClose, true); w->setWindowModality(Qt::ApplicationModal); w->setPreviewPageBackgroundColor(m_previewPageBackgroundColor); - //w->setWindowIcon(QIcon(":/report/images/main.ico")); + // w->setWindowIcon(QIcon(":/report/images/main.ico")); w->setWindowIcon(m_previewWindowIcon); w->setWindowTitle(m_previewWindowTitle); w->setSettings(settings()); w->setPages(pages); w->setLayoutDirection(m_previewLayoutDirection); w->setStyleSheet(styleSheet()); -// w->setDefaultPrinter() + // w->setDefaultPrinter() - if (!dataManager()->errorsList().isEmpty()){ + if (!dataManager()->errorsList().isEmpty()) { w->setErrorMessages(dataManager()->errorsList()); } - if (!hints.testFlag(PreviewBarsUserSetting)){ + if (!hints.testFlag(PreviewBarsUserSetting)) { w->setMenuVisible(!hints.testFlag(HidePreviewMenuBar)); w->setStatusBarVisible(!hints.testFlag(HidePreviewStatusBar)); w->setToolBarVisible(!hints.testFlag(HidePreviewToolBar)); @@ -527,81 +545,82 @@ bool ReportEnginePrivate::showPreviewWindow(ReportPages pages, PreviewHints hint w->setPreviewScaleType(m_previewScaleType, m_previewScalePercent); - connect(w,SIGNAL(destroyed(QObject*)), this, SLOT(slotPreviewWindowDestroyed(QObject*))); - connect(w, SIGNAL(onSave(bool&, LimeReport::IPreparedPages*)), - this, SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*))); + connect(w, SIGNAL(destroyed(QObject*)), this, SLOT(slotPreviewWindowDestroyed(QObject*))); + connect(w, SIGNAL(onSave(bool&, LimeReport::IPreparedPages*)), this, + SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*))); w->exec(); return true; } return false; } -void ReportEnginePrivate::previewReport(PreviewHints hints) -{ - previewReport(0, hints); -} +void ReportEnginePrivate::previewReport(PreviewHints hints) { previewReport(0, hints); } void ReportEnginePrivate::previewReport(QPrinter* printer, PreviewHints hints) { - try{ - dataManager()->setDesignTime(false); - ReportPages pages = renderToPages(); - dataManager()->setDesignTime(true); - showPreviewWindow(pages, hints, printer); - } catch (ReportError &exception){ - saveError(exception.what()); - showError(exception.what()); - } + try { + dataManager()->setDesignTime(false); + ReportPages pages = renderToPages(); + dataManager()->setDesignTime(true); + showPreviewWindow(pages, hints, printer); + } catch (ReportError& exception) { + saveError(exception.what()); + showError(exception.what()); + } } -ReportDesignWindowInterface*ReportEnginePrivate::getDesignerWindow() +ReportDesignWindowInterface* ReportEnginePrivate::getDesignerWindow() { if (!m_designerWindow) { - if (m_designerFactory){ - m_designerWindow = m_designerFactory->getDesignerWindow(this,QApplication::activeWindow(),settings()); - m_designerWindow->setAttribute(Qt::WA_DeleteOnClose,true); + if (m_designerFactory) { + m_designerWindow = m_designerFactory->getDesignerWindow( + this, QApplication::activeWindow(), settings()); + m_designerWindow->setAttribute(Qt::WA_DeleteOnClose, true); m_designerWindow->setWindowIcon(QIcon(":report/images/logo32")); m_designerWindow->setShowProgressDialog(m_showProgressDialog); } else { #ifdef HAVE_REPORT_DESIGNER - m_designerWindow = new LimeReport::ReportDesignWindow(this,QApplication::activeWindow(),settings()); - m_designerWindow->setAttribute(Qt::WA_DeleteOnClose,true); + m_designerWindow = new LimeReport::ReportDesignWindow( + this, QApplication::activeWindow(), settings()); + m_designerWindow->setAttribute(Qt::WA_DeleteOnClose, true); m_designerWindow->setWindowIcon(QIcon(":report/images/logo32")); m_designerWindow->setShowProgressDialog(m_showProgressDialog); #endif } - } - if (m_designerWindow){ + } + if (m_designerWindow) { m_datasources->updateDatasourceModel(); } return m_designerWindow; } -PreviewReportWidget* ReportEnginePrivate::createPreviewWidget(QWidget* parent){ +PreviewReportWidget* ReportEnginePrivate::createPreviewWidget(QWidget* parent) +{ Q_Q(ReportEngine); PreviewReportWidget* widget = new PreviewReportWidget(q, parent); - try{ + try { dataManager()->setDesignTime(false); ReportPages pages = renderToPages(); dataManager()->setDesignTime(true); - if (pages.count()>0) + if (pages.count() > 0) widget->d_ptr->setPages(pages); - } catch (ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); showError(exception.what()); } return widget; } -PageDesignIntf* ReportEnginePrivate::createPreviewScene(QObject* parent){ +PageDesignIntf* ReportEnginePrivate::createPreviewScene(QObject* parent) +{ PageDesignIntf* result = 0; try { ReportPages pages = renderToPages(); result = new PageDesignIntf(parent); result->setPageItems(pages); result->setItemMode(PrintMode); - } catch (ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); showError(exception.what()); } @@ -629,81 +648,72 @@ bool ReportEnginePrivate::emitLoadReport() return result; } -void ReportEnginePrivate::emitSaveFinished() -{ - emit saveFinished(); -} +void ReportEnginePrivate::emitSaveFinished() { emit saveFinished(); } -void ReportEnginePrivate::emitLoadFinished() -{ - emit loadFinished(); -} +void ReportEnginePrivate::emitLoadFinished() { emit loadFinished(); } -void ReportEnginePrivate::emitPrintedToPDF(QString fileName) -{ - emit printedToPDF(fileName); -} +void ReportEnginePrivate::emitPrintedToPDF(QString fileName) { emit printedToPDF(fileName); } bool ReportEnginePrivate::isSaved() { foreach (PageDesignIntf* page, m_pages) { - if (!page->isSaved()) return false; + if (!page->isSaved()) + return false; } return true; } -void ReportEnginePrivate::setCurrentReportsDir(const QString &dirName) +void ReportEnginePrivate::setCurrentReportsDir(const QString& dirName) { if (QDir(dirName).exists()) m_reportsDir = dirName; } -bool ReportEnginePrivate::setDefaultExportDir(const QString &dirName) +bool ReportEnginePrivate::setDefaultExportDir(const QString& dirName) { - if (QDir(dirName).exists()){ + if (QDir(dirName).exists()) { m_exportDir = dirName; return true; } return false; } -bool ReportEnginePrivate::slotLoadFromFile(const QString &fileName) +bool ReportEnginePrivate::slotLoadFromFile(const QString& fileName) { EASY_BLOCK("ReportEnginePrivate::slotLoadFromFile") - PreviewReportWindow *currentPreview = qobject_cast(m_activePreview); + PreviewReportWindow* currentPreview = qobject_cast(m_activePreview); - if (!QFile::exists(fileName)) - { - if ( hasActivePreview() ) - { - QMessageBox::information( NULL, - tr( "Report File Change" ), - tr( "The report file \"%1\" has changed names or been deleted.\n\nThis preview is no longer valid." ).arg( fileName ) - ); + if (!QFile::exists(fileName)) { + if (hasActivePreview()) { + QMessageBox::information( + NULL, tr("Report File Change"), + tr("The report file \"%1\" has changed names or been deleted.\n\nThis preview " + "is no longer valid.") + .arg(fileName)); - clearReport(); + clearReport(); - currentPreview->close(); - } + currentPreview->close(); + } - return false; + return false; } clearReport(); ItemsReaderIntf::Ptr reader = FileXMLReader::create(fileName); reader->setPassPhrase(m_passPhrase); - if (reader->first()){ - if (reader->readItem(this)){ - m_fileName=fileName; + if (reader->first()) { + if (reader->readItem(this)) { + m_fileName = fileName; QFileInfo fi(fileName); m_reportName = fi.fileName(); - QString dbSettingFileName = fi.absolutePath()+"/"+fi.baseName()+".db"; - if (QFile::exists(dbSettingFileName)){ + QString dbSettingFileName = fi.absolutePath() + "/" + fi.baseName() + ".db"; + if (QFile::exists(dbSettingFileName)) { QSettings dbcredentals(dbSettingFileName, QSettings::IniFormat); foreach (ConnectionDesc* connection, dataManager()->conections()) { - if (!connection->keepDBCredentials()){ + if (!connection->keepDBCredentials()) { dbcredentals.beginGroup(connection->name()); connection->setUserName(dbcredentals.value("user").toString()); connection->setPassword(dbcredentals.value("password").toString()); @@ -716,9 +726,8 @@ bool ReportEnginePrivate::slotLoadFromFile(const QString &fileName) EASY_END_BLOCK; dropChanges(); - if ( hasActivePreview() ) - { - currentPreview->reloadPreview(); + if (hasActivePreview()) { + currentPreview->reloadPreview(); } EASY_END_BLOCK; return true; @@ -736,12 +745,10 @@ void ReportEnginePrivate::cancelRender() m_reportRendering = false; } -void ReportEnginePrivate::cancelPrinting() -{ - m_cancelPrinting = true; -} +void ReportEnginePrivate::cancelPrinting() { m_cancelPrinting = true; } -QGraphicsScene* ReportEngine::createPreviewScene(QObject* parent){ +QGraphicsScene* ReportEngine::createPreviewScene(QObject* parent) +{ Q_D(ReportEngine); return d->createPreviewScene(parent); } @@ -749,71 +756,72 @@ QGraphicsScene* ReportEngine::createPreviewScene(QObject* parent){ void ReportEnginePrivate::designReport(bool showModal) { ReportDesignWindowInterface* designerWindow = getDesignerWindow(); - if (designerWindow){ + if (designerWindow) { dataManager()->setDesignTime(true); - connect(designerWindow, SIGNAL(destroyed(QObject*)), this, SLOT(slotDesignerWindowDestroyed(QObject*))); + connect(designerWindow, SIGNAL(destroyed(QObject*)), this, + SLOT(slotDesignerWindowDestroyed(QObject*))); #ifdef Q_OS_WIN designerWindow->setWindowModality(Qt::NonModal); #endif - if (!showModal){ - designerWindow->show();; + if (!showModal) { + designerWindow->show(); + ; } else { designerWindow->showModal(); } } else { - qDebug()<<(tr("Designer not found!")); + qDebug() << (tr("Designer not found!")); } } void ReportEnginePrivate::setSettings(QSettings* value) { - if (value){ - if (m_ownedSettings&&m_settings) + if (value) { + if (m_ownedSettings && m_settings) delete m_settings; m_settings = value; m_ownedSettings = false; } } -QSettings*ReportEnginePrivate::settings() +QSettings* ReportEnginePrivate::settings() { - if (m_settings){ + if (m_settings) { return m_settings; } else { - m_settings = new QSettings("LimeReport",QApplication::applicationName()); - m_ownedSettings=true; + m_settings = new QSettings("LimeReport", QApplication::applicationName()); + m_ownedSettings = true; return m_settings; } } -bool ReportEnginePrivate::loadFromFile(const QString &fileName, bool autoLoadPreviewOnChange) +bool ReportEnginePrivate::loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange) { - // only watch one file at a time + // only watch one file at a time - if ( !m_fileWatcher->files().isEmpty() ) - { - m_fileWatcher->removePaths( m_fileWatcher->files() ); - } + if (!m_fileWatcher->files().isEmpty()) { + m_fileWatcher->removePaths(m_fileWatcher->files()); + } - if ( autoLoadPreviewOnChange ) - { - m_fileWatcher->addPath( fileName ); - } + if (autoLoadPreviewOnChange) { + m_fileWatcher->addPath(fileName); + } - bool result = slotLoadFromFile( fileName ); - if (result) { - emit loadFinished(); - } - return result; + bool result = slotLoadFromFile(fileName); + if (result) { + emit loadFinished(); + } + return result; } -bool ReportEnginePrivate::loadFromByteArray(QByteArray* data, const QString &name){ +bool ReportEnginePrivate::loadFromByteArray(QByteArray* data, const QString& name) +{ clearReport(); ItemsReaderIntf::Ptr reader = ByteArrayXMLReader::create(data); reader->setPassPhrase(m_passPhrase); - if (reader->first()){ - if (reader->readItem(this)){ + if (reader->first()) { + if (reader->readItem(this)) { m_fileName = ""; m_reportName = name; emit loadFinished(); @@ -823,14 +831,14 @@ bool ReportEnginePrivate::loadFromByteArray(QByteArray* data, const QString &nam return false; } -bool ReportEnginePrivate::loadFromString(const QString &report, const QString &name) +bool ReportEnginePrivate::loadFromString(const QString& report, const QString& name) { clearReport(); ItemsReaderIntf::Ptr reader = StringXMLreader::create(report); reader->setPassPhrase(m_passPhrase); - if (reader->first()){ - if (reader->readItem(this)){ + if (reader->first()) { + if (reader->readItem(this)) { m_fileName = ""; m_reportName = name; emit loadFinished(); @@ -840,37 +848,38 @@ bool ReportEnginePrivate::loadFromString(const QString &report, const QString &n return false; } -bool ReportEnginePrivate::saveToFile(const QString &fileName) +bool ReportEnginePrivate::saveToFile(const QString& fileName) { - if (fileName.isEmpty() & m_fileName.isEmpty()) return false; + if (fileName.isEmpty() & m_fileName.isEmpty()) + return false; QString fn = fileName.isEmpty() ? m_fileName : fileName; QFileInfo fi(fn); if (fi.suffix().isEmpty()) - fn+=".lrxml"; + fn += ".lrxml"; - QString dbSettingFileName = fi.absolutePath()+"/"+fi.baseName()+".db"; + QString dbSettingFileName = fi.absolutePath() + "/" + fi.baseName() + ".db"; QSettings dbcredentals(dbSettingFileName, QSettings::IniFormat); foreach (ConnectionDesc* connection, dataManager()->conections()) { - if (!connection->keepDBCredentials()){ + if (!connection->keepDBCredentials()) { dbcredentals.beginGroup(connection->name()); - dbcredentals.setValue("user",connection->userName()); - dbcredentals.setValue("password",connection->password()); + dbcredentals.setValue("user", connection->userName()); + dbcredentals.setValue("password", connection->password()); dbcredentals.endGroup(); connection->setPassword(""); connection->setUserName(""); } } - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); + QScopedPointer writer(new XMLWriter()); writer->setPassPhrase(m_passPhrase); writer->putItem(this); - m_fileName=fn; + m_fileName = fn; bool saved = writer->saveToFile(fn); foreach (ConnectionDesc* connection, dataManager()->conections()) { - if (!connection->keepDBCredentials()){ + if (!connection->keepDBCredentials()) { dbcredentals.beginGroup(connection->name()); connection->setUserName(dbcredentals.value("user").toString()); connection->setPassword(dbcredentals.value("password").toString()); @@ -878,8 +887,8 @@ bool ReportEnginePrivate::saveToFile(const QString &fileName) } } - if (saved){ - foreach(PageDesignIntf* page, m_pages){ + if (saved) { + foreach (PageDesignIntf* page, m_pages) { page->setToSaved(); } } @@ -890,12 +899,12 @@ bool ReportEnginePrivate::saveToFile(const QString &fileName) QByteArray ReportEnginePrivate::saveToByteArray() { - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); + QScopedPointer writer(new XMLWriter()); writer->setPassPhrase(m_passPhrase); writer->putItem(this); QByteArray result = writer->saveToByteArray(); - if (!result.isEmpty()){ - foreach(PageDesignIntf* page, m_pages){ + if (!result.isEmpty()) { + foreach (PageDesignIntf* page, m_pages) { page->setToSaved(); } } @@ -903,13 +912,14 @@ QByteArray ReportEnginePrivate::saveToByteArray() return result; } -QString ReportEnginePrivate::saveToString(){ - QScopedPointer< ItemsWriterIntf > writer(new XMLWriter()); +QString ReportEnginePrivate::saveToString() +{ + QScopedPointer writer(new XMLWriter()); writer->setPassPhrase(m_passPhrase); writer->putItem(this); QString result = writer->saveToString(); - if (!result.isEmpty()){ - foreach(PageDesignIntf* page, m_pages){ + if (!result.isEmpty()) { + foreach (PageDesignIntf* page, m_pages) { page->setToSaved(); } } @@ -919,10 +929,11 @@ QString ReportEnginePrivate::saveToString(){ bool ReportEnginePrivate::isNeedToSave() { - foreach(PageDesignIntf* page, m_pages){ - if (page->isHasChanges()) return true; + foreach (PageDesignIntf* page, m_pages) { + if (page->isHasChanges()) + return true; } - if (dataManager()->hasChanges()){ + if (dataManager()->hasChanges()) { return true; } if (scriptContext()->hasChanges()) @@ -936,52 +947,41 @@ QString ReportEnginePrivate::renderToString() updateTranslations(); dataManager()->connectAllDatabases(); dataManager()->setDesignTime(false); - if (m_pages.count()){ + if (m_pages.count()) { render.setDatasources(dataManager()); render.setScriptContext(scriptContext()); return render.renderPageToString(m_pages.at(0)->pageItem()); - } else return QString(); - + } else + return QString(); } -ScaleType ReportEnginePrivate::previewScaleType() -{ - return m_previewScaleType; -} +ScaleType ReportEnginePrivate::previewScaleType() { return m_previewScaleType; } -int ReportEnginePrivate::previewScalePercent() -{ - return m_previewScalePercent; -} +int ReportEnginePrivate::previewScalePercent() { return m_previewScalePercent; } -void ReportEnginePrivate::setPreviewScaleType(const ScaleType &scaleType, int percent) +void ReportEnginePrivate::setPreviewScaleType(const ScaleType& scaleType, int percent) { m_previewScaleType = scaleType; m_previewScalePercent = percent; } -void ReportEnginePrivate::addWatermark(const WatermarkSetting &watermarkSetting) +void ReportEnginePrivate::addWatermark(const WatermarkSetting& watermarkSetting) { m_watermarks.append(watermarkSetting); } -void ReportEnginePrivate::clearWatermarks() -{ - m_watermarks.clear(); -} +void ReportEnginePrivate::clearWatermarks() { m_watermarks.clear(); } PageItemDesignIntf* ReportEnginePrivate::getPageByName(const QString& pageName) { - foreach(PageItemDesignIntf* page, m_renderingPages){ - if ( page->objectName().compare(pageName, Qt::CaseInsensitive) == 0) + foreach (PageItemDesignIntf* page, m_renderingPages) { + if (page->objectName().compare(pageName, Qt::CaseInsensitive) == 0) return page; } return 0; } -IPreparedPages *ReportEnginePrivate::preparedPages(){ - return m_preparedPagesManager; -} +IPreparedPages* ReportEnginePrivate::preparedPages() { return m_preparedPagesManager; } bool ReportEnginePrivate::showPreparedPages(PreviewHints hints) { @@ -995,11 +995,11 @@ bool ReportEnginePrivate::showPreparedPages(QPrinter* defaultPrinter, PreviewHin bool ReportEnginePrivate::prepareReportPages() { - try{ + try { dataManager()->setDesignTime(false); m_preparedPages = renderToPages(); dataManager()->setDesignTime(true); - } catch (ReportError &exception){ + } catch (ReportError& exception) { saveError(exception.what()); showError(exception.what()); return false; @@ -1007,10 +1007,7 @@ bool ReportEnginePrivate::prepareReportPages() return !m_preparedPages.isEmpty(); } -bool ReportEnginePrivate::printPreparedPages() -{ - return printPages(m_preparedPages, 0); -} +bool ReportEnginePrivate::printPreparedPages() { return printPages(m_preparedPages, 0); } Qt::LayoutDirection ReportEnginePrivate::previewLayoutDirection() { @@ -1022,15 +1019,12 @@ void ReportEnginePrivate::setPreviewLayoutDirection(const Qt::LayoutDirection& l m_previewLayoutDirection = layoutDirection; } -void ReportEnginePrivate::setPassPhrase(const QString &passPhrase) -{ - m_passPhrase = passPhrase; -} +void ReportEnginePrivate::setPassPhrase(const QString& passPhrase) { m_passPhrase = passPhrase; } -void ReportEnginePrivate::reorderPages(const QList& reorderedPages) +void ReportEnginePrivate::reorderPages(const QList& reorderedPages) { m_pages.clear(); - foreach(PageDesignIntf* page, reorderedPages){ + foreach (PageDesignIntf* page, reorderedPages) { m_pages.append(page); } } @@ -1038,7 +1032,7 @@ void ReportEnginePrivate::reorderPages(const QList& reorderedP void ReportEnginePrivate::clearSelection() { foreach (PageDesignIntf* page, m_pages) { - foreach(QGraphicsItem* item, page->selectedItems()){ + foreach (QGraphicsItem* item, page->selectedItems()) { item->setSelected(false); } } @@ -1046,17 +1040,17 @@ void ReportEnginePrivate::clearSelection() bool ReportEnginePrivate::addTranslationLanguage(QLocale::Language language) { - if (!m_translations.keys().contains(language)){ + if (!m_translations.keys().contains(language)) { ReportTranslation* translation = 0; - if (!m_translations.contains(QLocale::AnyLanguage)){ - translation = new ReportTranslation(QLocale::AnyLanguage,m_pages); - m_translations.insert(QLocale::AnyLanguage,translation); + if (!m_translations.contains(QLocale::AnyLanguage)) { + translation = new ReportTranslation(QLocale::AnyLanguage, m_pages); + m_translations.insert(QLocale::AnyLanguage, translation); } - translation = new ReportTranslation(language,m_pages); + translation = new ReportTranslation(language, m_pages); m_translations.insert(language, translation); return true; } else { - m_lastError = tr("Language %1 already exists").arg(QLocale::languageToString(language)); + m_lastError = tr("Language %1 already exists").arg(QLocale::languageToString(language)); return false; } } @@ -1068,18 +1062,21 @@ bool ReportEnginePrivate::removeTranslationLanguage(QLocale::Language language) void ReportEnginePrivate::activateLanguage(QLocale::Language language) { - if (!m_translations.keys().contains(language)) return; + if (!m_translations.keys().contains(language)) + return; ReportTranslation* translation = m_translations.value(language); - foreach(PageTranslation* pageTranslation, translation->pagesTranslation()){ + foreach (PageTranslation* pageTranslation, translation->pagesTranslation()) { PageItemDesignIntf* page = getPageByName(pageTranslation->pageName); - if (page){ - foreach(ItemTranslation* itemTranslation, pageTranslation->itemsTranslation){ + if (page) { + foreach (ItemTranslation* itemTranslation, pageTranslation->itemsTranslation) { BaseDesignIntf* item = page->childByName(itemTranslation->itemName); if (item) { - foreach(PropertyTranslation* propertyTranslation, itemTranslation->propertyesTranslation){ + foreach (PropertyTranslation* propertyTranslation, + itemTranslation->propertyesTranslation) { if (propertyTranslation->checked) - item->setProperty(propertyTranslation->propertyName.toLatin1(), propertyTranslation->value); + item->setProperty(propertyTranslation->propertyName.toLatin1(), + propertyTranslation->value); } } } @@ -1107,72 +1104,41 @@ void ReportEnginePrivate::setCurrentDesignerLanguage(QLocale::Language language) emit currentDefaultDesignerLanguageChanged(language); } -QString ReportEnginePrivate::styleSheet() const -{ - return m_styleSheet; -} +QString ReportEnginePrivate::styleSheet() const { return m_styleSheet; } -void ReportEnginePrivate::setStyleSheet(const QString &styleSheet) -{ - m_styleSheet = styleSheet; -} +void ReportEnginePrivate::setStyleSheet(const QString& styleSheet) { m_styleSheet = styleSheet; } -bool ReportEnginePrivate::setReportLanguage(QLocale::Language language){ +bool ReportEnginePrivate::setReportLanguage(QLocale::Language language) +{ m_reportLanguage = language; - if (!m_translations.keys().contains(language)) return false; + if (!m_translations.keys().contains(language)) + return false; // activateLanguage(language); return true; } -QList ReportEnginePrivate::aviableLanguages() -{ - return m_translations.keys(); -} +QList ReportEnginePrivate::aviableLanguages() { return m_translations.keys(); } -ReportTranslation*ReportEnginePrivate::reportTranslation(QLocale::Language language) +ReportTranslation* ReportEnginePrivate::reportTranslation(QLocale::Language language) { return m_translations.value(language); } -bool ReportEnginePrivate::resultIsEditable() const -{ - return m_resultIsEditable; -} +bool ReportEnginePrivate::resultIsEditable() const { return m_resultIsEditable; } -void ReportEnginePrivate::setResultEditable(bool value) -{ - m_resultIsEditable = value; -} +void ReportEnginePrivate::setResultEditable(bool value) { m_resultIsEditable = value; } -bool ReportEnginePrivate::saveToFileIsVisible() const -{ - return m_saveToFileVisible; -} +bool ReportEnginePrivate::saveToFileIsVisible() const { return m_saveToFileVisible; } -void ReportEnginePrivate::setSaveToFileVisible(bool value) -{ - m_saveToFileVisible = value; -} +void ReportEnginePrivate::setSaveToFileVisible(bool value) { m_saveToFileVisible = value; } -bool ReportEnginePrivate::printToPdfIsVisible() const -{ - return m_printToPdfVisible; -} +bool ReportEnginePrivate::printToPdfIsVisible() const { return m_printToPdfVisible; } -void ReportEnginePrivate::setPrintToPdfVisible(bool value) -{ - m_printToPdfVisible = value; -} +void ReportEnginePrivate::setPrintToPdfVisible(bool value) { m_printToPdfVisible = value; } -bool ReportEnginePrivate::printIsVisible() const -{ - return m_printVisible; -} +bool ReportEnginePrivate::printIsVisible() const { return m_printVisible; } -void ReportEnginePrivate::setPrintVisible(bool value) -{ - m_printVisible = value; -} +void ReportEnginePrivate::setPrintVisible(bool value) { m_printVisible = value; } bool ReportEnginePrivate::suppressFieldAndVarError() const { @@ -1184,66 +1150,54 @@ void ReportEnginePrivate::setSuppressFieldAndVarError(bool suppressFieldAndVarEr m_reportSettings.setSuppressAbsentFieldsAndVarsWarnings(suppressFieldAndVarError); } -int ReportEnginePrivate::baseItemPadding() const -{ - return m_reportSettings.baseItemPadding(); -} +int ReportEnginePrivate::baseItemPadding() const { return m_reportSettings.baseItemPadding(); } void ReportEnginePrivate::setBaseItemPadding(int baseTextItemPadding) { m_reportSettings.setBaseItemPadding(baseTextItemPadding); } -bool ReportEnginePrivate::isBusy() -{ - return m_reportRendering; -} +bool ReportEnginePrivate::isBusy() { return m_reportRendering; } -QString ReportEnginePrivate::previewWindowTitle() const -{ - return m_previewWindowTitle; -} +QString ReportEnginePrivate::previewWindowTitle() const { return m_previewWindowTitle; } -void ReportEnginePrivate::setPreviewWindowTitle(const QString &previewWindowTitle) +void ReportEnginePrivate::setPreviewWindowTitle(const QString& previewWindowTitle) { m_previewWindowTitle = previewWindowTitle; } -QColor ReportEnginePrivate::previewWindowPageBackground() -{ - return m_previewPageBackgroundColor; -} +QColor ReportEnginePrivate::previewWindowPageBackground() { return m_previewPageBackgroundColor; } void ReportEnginePrivate::setPreviewWindowPageBackground(QColor color) { m_previewPageBackgroundColor = color; } -QIcon ReportEnginePrivate::previewWindowIcon() const -{ - return m_previewWindowIcon; -} +QIcon ReportEnginePrivate::previewWindowIcon() const { return m_previewWindowIcon; } -void ReportEnginePrivate::setPreviewWindowIcon(const QIcon &previewWindowIcon) +void ReportEnginePrivate::setPreviewWindowIcon(const QIcon& previewWindowIcon) { m_previewWindowIcon = previewWindowIcon; } -PageItemDesignIntf* ReportEnginePrivate::createRenderingPage(PageItemDesignIntf* page){ - PageItemDesignIntf* result = dynamic_cast(page->cloneItem(page->itemMode())); +PageItemDesignIntf* ReportEnginePrivate::createRenderingPage(PageItemDesignIntf* page) +{ + PageItemDesignIntf* result + = dynamic_cast(page->cloneItem(page->itemMode())); ICollectionContainer* co = dynamic_cast(result); - if (co) co->collectionLoadFinished("children"); + if (co) + co->collectionLoadFinished("children"); return result; } void ReportEnginePrivate::initReport() { - for(int index = 0; index < pageCount(); ++index){ - PageDesignIntf* page = pageAt(index); - if (page != 0){ + for (int index = 0; index < pageCount(); ++index) { + PageDesignIntf* page = pageAt(index); + if (page != 0) { foreach (BaseDesignIntf* item, page->pageItem()->childBaseItems()) { - IPainterProxy *proxyItem = dynamic_cast(item); - if (proxyItem){ + IPainterProxy* proxyItem = dynamic_cast(item); + if (proxyItem) { proxyItem->setExternalPainter(this); } } @@ -1251,30 +1205,33 @@ void ReportEnginePrivate::initReport() } } -void ReportEnginePrivate::paintByExternalPainter(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem* options) +void ReportEnginePrivate::paintByExternalPainter(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem* options) { emit externalPaint(objectName, painter, options); } -BaseDesignIntf* ReportEnginePrivate::createWatermark(PageDesignIntf* page, WatermarkSetting watermarkSetting) +BaseDesignIntf* ReportEnginePrivate::createWatermark(PageDesignIntf* page, + WatermarkSetting watermarkSetting) { WatermarkHelper watermarkHelper(watermarkSetting); - BaseDesignIntf* watermark = page->addReportItem("TextItem", watermarkHelper.mapToPage(*page->pageItem()), watermarkHelper.sceneSize()); - if (watermark){ + BaseDesignIntf* watermark = page->addReportItem( + "TextItem", watermarkHelper.mapToPage(*page->pageItem()), watermarkHelper.sceneSize()); + if (watermark) { watermark->setProperty("content", watermarkSetting.text()); - watermark->setProperty("font",watermarkSetting.font()); - watermark->setProperty("watermark",true); - watermark->setProperty("itemLocation",1); + watermark->setProperty("font", watermarkSetting.font()); + watermark->setProperty("watermark", true); + watermark->setProperty("itemLocation", 1); watermark->setProperty("foregroundOpacity", watermarkSetting.opacity()); watermark->setProperty("fontColor", watermarkSetting.color()); } return watermark; - } -void ReportEnginePrivate::clearRenderingPages(){ +void ReportEnginePrivate::clearRenderingPages() +{ qDeleteAll(m_renderingPages.begin(), m_renderingPages.end()); m_renderingPages.clear(); } @@ -1284,14 +1241,15 @@ ReportPages ReportEnginePrivate::renderToPages() int startTOCPage = -1; int pageAfterTOCIndex = -1; - if (m_reportRendering) return ReportPages(); + if (m_reportRendering) + return ReportPages(); initReport(); m_reportRender = ReportRender::Ptr(new ReportRender); updateTranslations(); - connect(m_reportRender.data(),SIGNAL(pageRendered(int)), - this, SIGNAL(renderPageFinished(int))); + connect(m_reportRender.data(), SIGNAL(pageRendered(int)), this, + SIGNAL(renderPageFinished(int))); - if (m_pages.count()){ + if (m_pages.count()) { #ifdef HAVE_UI_LOADER m_scriptEngineContext->initDialogs(); @@ -1304,27 +1262,26 @@ ReportPages ReportEnginePrivate::renderToPages() foreach (PageDesignIntf* page, m_pages) { QVector watermarks; - if (!m_watermarks.isEmpty()){ - foreach(WatermarkSetting watermarkSetting, m_watermarks){ + if (!m_watermarks.isEmpty()) { + foreach (WatermarkSetting watermarkSetting, m_watermarks) { watermarks.append(createWatermark(page, watermarkSetting)); } } PageItemDesignIntf* rp = createRenderingPage(page->pageItem()); - - qDeleteAll(watermarks.begin(),watermarks.end()); + qDeleteAll(watermarks.begin(), watermarks.end()); watermarks.clear(); m_renderingPages.append(rp); scriptContext()->baseDesignIntfToScript(rp->objectName(), rp); } - scriptContext()->qobjectToScript("engine",this); + scriptContext()->qobjectToScript("engine", this); #ifdef USE_QTSCRIPTENGINE - ScriptEngineManager::instance().scriptEngine()->pushContext(); + ScriptEngineManager::instance().scriptEngine()->pushContext(); #endif - if (m_scriptEngineContext->runInitScript()){ + if (m_scriptEngineContext->runInitScript()) { dataManager()->clearErrors(); dataManager()->connectAllDatabases(); @@ -1335,45 +1292,36 @@ ReportPages ReportEnginePrivate::renderToPages() emit renderStarted(); m_scriptEngineContext->setReportPages(&result); - for(int i = 0; i < m_renderingPages.count(); ++i){ + for (int i = 0; i < m_renderingPages.count(); ++i) { PageItemDesignIntf* page = m_renderingPages.at(i); - if (!page->isTOC() && page->isPrintable()){ + if (!page->isTOC() && page->isPrintable()) { page->setReportSettings(&m_reportSettings); - result = appendPages( - result, - m_reportRender->renderPageToPages(page), - page->mixWithPriorPage() ? MixPages : AppendPages - ); - } else if (page->isTOC()){ + result = appendPages(result, m_reportRender->renderPageToPages(page), + page->mixWithPriorPage() ? MixPages : AppendPages); + } else if (page->isTOC()) { startTOCPage = result.count(); - pageAfterTOCIndex = i+1; + pageAfterTOCIndex = i + 1; m_reportRender->createTOCMarker(page->resetPageNumber()); } } - for (int i=0; iisTOC()){ + if (page->isTOC()) { page->setReportSettings(&m_reportSettings); - if (i < m_renderingPages.count()){ + if (i < m_renderingPages.count()) { PageItemDesignIntf* secondPage = 0; - if ( m_renderingPages.count() > (pageAfterTOCIndex)) + if (m_renderingPages.count() > (pageAfterTOCIndex)) secondPage = m_renderingPages.at(pageAfterTOCIndex); ReportPages pages = m_reportRender->renderTOC( - page, - true, - secondPage && secondPage->resetPageNumber() - ); - for (int j=0; jresetPageNumber()); + for (int j = 0; j < pages.count(); ++j) { + result.insert(startTOCPage + j, pages.at(j)); } } else { - result = appendPages( - result, - m_reportRender->renderPageToPages(page), - page->mixWithPriorPage() ? MixPages : AppendPages - ); + result = appendPages(result, m_reportRender->renderPageToPages(page), + page->mixWithPriorPage() ? MixPages : AppendPages); } } } @@ -1387,7 +1335,7 @@ ReportPages ReportEnginePrivate::renderToPages() m_reportRendering = false; #ifdef USE_QTSCRIPTENGINE - ScriptEngineManager::instance().scriptEngine()->popContext(); + ScriptEngineManager::instance().scriptEngine()->popContext(); #endif return result; } else { @@ -1397,11 +1345,11 @@ ReportPages ReportEnginePrivate::renderToPages() ReportPages ReportEnginePrivate::appendPages(ReportPages s1, ReportPages s2, AppendType appendType) { - if (!s1.isEmpty() && s1.size() == s2.size() && appendType == MixPages){ + if (!s1.isEmpty() && s1.size() == s2.size() && appendType == MixPages) { ReportPages result; ReportPages::Iterator s1It; ReportPages::Iterator s2It; - for (s1It = s1.begin(), s2It = s2.begin(); s1It != s1.end(); ++s1It,++s2It){ + for (s1It = s1.begin(), s2It = s2.begin(); s1It != s1.end(); ++s1It, ++s2It) { result.append(*s1It); result.append(*s2It); } @@ -1412,24 +1360,21 @@ ReportPages ReportEnginePrivate::appendPages(ReportPages s1, ReportPages s2, App } } -QString ReportEnginePrivate::lastError() -{ - return m_lastError; -} +QString ReportEnginePrivate::lastError() { return m_lastError; } -ReportEngine::ReportEngine(QObject *parent) - : QObject(parent), d_ptr(new ReportEnginePrivate()), m_showDesignerModal(true) +ReportEngine::ReportEngine(QObject* parent): + QObject(parent), + d_ptr(new ReportEnginePrivate()), + m_showDesignerModal(true) { Q_D(ReportEngine); - d->q_ptr=this; + d->q_ptr = this; connect(d, SIGNAL(renderStarted()), this, SIGNAL(renderStarted())); - connect(d, SIGNAL(renderPageFinished(int)), - this, SIGNAL(renderPageFinished(int))); + connect(d, SIGNAL(renderPageFinished(int)), this, SIGNAL(renderPageFinished(int))); connect(d, SIGNAL(renderFinished()), this, SIGNAL(renderFinished())); connect(d, SIGNAL(printingStarted(int)), this, SIGNAL(printingStarted(int))); - connect(d, SIGNAL(pagePrintingFinished(int)), - this, SIGNAL(pagePrintingFinished(int))); + connect(d, SIGNAL(pagePrintingFinished(int)), this, SIGNAL(pagePrintingFinished(int))); connect(d, SIGNAL(printingFinished()), this, SIGNAL(printingFinished())); connect(d, SIGNAL(onSave(bool&)), this, SIGNAL(onSave(bool&))); @@ -1440,25 +1385,23 @@ ReportEngine::ReportEngine(QObject *parent) connect(d, SIGNAL(cleared()), this, SIGNAL(cleared())); connect(d, SIGNAL(printedToPDF(QString)), this, SIGNAL(printedToPDF(QString))); - connect(d, SIGNAL(getAvailableDesignerLanguages(QList*)), - this, SIGNAL(getAvailableDesignerLanguages(QList*))); - connect(d, SIGNAL(currentDefaultDesignerLanguageChanged(QLocale::Language)), - this, SIGNAL(currentDefaultDesignerLanguageChanged(QLocale::Language))); - connect(d, SIGNAL(getCurrentDefaultDesignerLanguage()), - this, SIGNAL(getCurrentDefaultDesignerLanguage())); + connect(d, SIGNAL(getAvailableDesignerLanguages(QList*)), this, + SIGNAL(getAvailableDesignerLanguages(QList*))); + connect(d, SIGNAL(currentDefaultDesignerLanguageChanged(QLocale::Language)), this, + SIGNAL(currentDefaultDesignerLanguageChanged(QLocale::Language))); + connect(d, SIGNAL(getCurrentDefaultDesignerLanguage()), this, + SIGNAL(getCurrentDefaultDesignerLanguage())); connect(d, SIGNAL(externalPaint(const QString&, QPainter*, const QStyleOptionGraphicsItem*)), - this, SIGNAL(externalPaint(const QString&, QPainter*, const QStyleOptionGraphicsItem*))); - connect(d, SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*)), - this, SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*))); + this, + SIGNAL(externalPaint(const QString&, QPainter*, const QStyleOptionGraphicsItem*))); + connect(d, SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*)), this, + SIGNAL(onSavePreview(bool&, LimeReport::IPreparedPages*))); } -ReportEngine::~ReportEngine() -{ - delete d_ptr; -} +ReportEngine::~ReportEngine() { delete d_ptr; } -bool ReportEngine::printReport(QPrinter *printer) +bool ReportEngine::printReport(QPrinter* printer) { Q_D(ReportEngine); return d->printReport(printer); @@ -1470,24 +1413,26 @@ bool ReportEngine::printReport(QMap printers, bool printToAl return d->printReport(printers, printToAllPrinters); } -bool ReportEngine::printPages(ReportPages pages, QPrinter *printer){ +bool ReportEngine::printPages(ReportPages pages, QPrinter* printer) +{ Q_D(ReportEngine); - return d->printPages(pages,printer); + return d->printPages(pages, printer); } -void ReportEngine::printToFile(const QString &fileName) +void ReportEngine::printToFile(const QString& fileName) { Q_D(ReportEngine); d->printToFile(fileName); } -bool ReportEngine::printToPDF(const QString &fileName) +bool ReportEngine::printToPDF(const QString& fileName) { Q_D(ReportEngine); return d->printToPDF(fileName); } -bool ReportEngine::exportReport(QString exporterName, const QString &fileName, const QMap ¶ms) +bool ReportEngine::exportReport(QString exporterName, const QString& fileName, + const QMap& params) { Q_D(ReportEngine); return d->exportReport(exporterName, fileName, params); @@ -1501,7 +1446,7 @@ void ReportEngine::previewReport(PreviewHints hints) d->previewReport(hints); } -void ReportEngine::previewReport(QPrinter *printer, PreviewHints hints) +void ReportEngine::previewReport(QPrinter* printer, PreviewHints hints) { Q_D(ReportEngine); if (m_settings) @@ -1523,19 +1468,19 @@ ReportDesignWindowInterface* ReportEngine::getDesignerWindow() return d->getDesignerWindow(); } -PreviewReportWidget* ReportEngine::createPreviewWidget(QWidget *parent) +PreviewReportWidget* ReportEngine::createPreviewWidget(QWidget* parent) { Q_D(ReportEngine); return d->createPreviewWidget(parent); } -void ReportEngine::setPreviewWindowTitle(const QString &title) +void ReportEngine::setPreviewWindowTitle(const QString& title) { Q_D(ReportEngine); d->setPreviewWindowTitle(title); } -void ReportEngine::setPreviewWindowIcon(const QIcon &icon) +void ReportEngine::setPreviewWindowIcon(const QIcon& icon) { Q_D(ReportEngine); d->setPreviewWindowIcon(icon); @@ -1601,7 +1546,7 @@ bool ReportEngine::isBusy() return d->isBusy(); } -void ReportEngine::setPassPhrase(QString &passPhrase) +void ReportEngine::setPassPhrase(QString& passPhrase) { Q_D(ReportEngine); d->setPassPhrase(passPhrase); @@ -1655,13 +1600,13 @@ int ReportEngine::previewScalePercent() return d->previewScalePercent(); } -void ReportEngine::setPreviewScaleType(const ScaleType &previewScaleType, int percent) +void ReportEngine::setPreviewScaleType(const ScaleType& previewScaleType, int percent) { Q_D(ReportEngine); d->setPreviewScaleType(previewScaleType, percent); } -void ReportEngine::addWatermark(const WatermarkSetting &watermarkSetting) +void ReportEngine::addWatermark(const WatermarkSetting& watermarkSetting) { Q_D(ReportEngine); d->addWatermark(watermarkSetting); @@ -1673,7 +1618,7 @@ void ReportEngine::clearWatermarks() d->clearWatermarks(); } -IPreparedPages *ReportEngine::preparedPages() +IPreparedPages* ReportEngine::preparedPages() { Q_D(ReportEngine); return d->preparedPages(); @@ -1709,30 +1654,31 @@ bool ReportEngine::isShowProgressDialog() return d->isShowProgressDialog(); } -IDataSourceManager *ReportEngine::dataManager() +IDataSourceManager* ReportEngine::dataManager() { Q_D(ReportEngine); return d->dataManagerIntf(); } -IScriptEngineManager *ReportEngine::scriptManager() +IScriptEngineManager* ReportEngine::scriptManager() { Q_D(ReportEngine); return d->scriptManagerIntf(); } -bool ReportEngine::loadFromFile(const QString &fileName, bool autoLoadPreviewOnChange) +bool ReportEngine::loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange) { Q_D(ReportEngine); return d->loadFromFile(fileName, autoLoadPreviewOnChange); } -bool ReportEngine::loadFromByteArray(QByteArray* data){ +bool ReportEngine::loadFromByteArray(QByteArray* data) +{ Q_D(ReportEngine); return d->loadFromByteArray(data); } -bool ReportEngine::loadFromString(const QString &data) +bool ReportEngine::loadFromString(const QString& data) { Q_D(ReportEngine); return d->loadFromString(data); @@ -1744,13 +1690,13 @@ QString ReportEngine::reportFileName() return d->reportFileName(); } -void ReportEngine::setReportFileName(const QString &fileName) +void ReportEngine::setReportFileName(const QString& fileName) { Q_D(ReportEngine); return d->setReportFileName(fileName); } -bool ReportEngine::saveToFile(const QString &fileName) +bool ReportEngine::saveToFile(const QString& fileName) { Q_D(ReportEngine); return d->saveToFile(fileName); @@ -1774,19 +1720,19 @@ QString ReportEngine::lastError() return d->lastError(); } -void ReportEngine::setCurrentReportsDir(const QString &dirName) +void ReportEngine::setCurrentReportsDir(const QString& dirName) { Q_D(ReportEngine); return d->setCurrentReportsDir(dirName); } -bool ReportEngine::setDefaultExportDir(const QString &dirName) +bool ReportEngine::setDefaultExportDir(const QString& dirName) { Q_D(ReportEngine); return d->setDefaultExportDir(dirName); } -void ReportEngine::setReportName(const QString &name) +void ReportEngine::setReportName(const QString& name) { Q_D(ReportEngine); return d->setReportName(name); @@ -1810,61 +1756,67 @@ void ReportEngine::cancelPrinting() d->cancelPrinting(); } -ReportEngine::ReportEngine(ReportEnginePrivate &dd, QObject *parent) - :QObject(parent), d_ptr(&dd), m_showDesignerModal(true) +ReportEngine::ReportEngine(ReportEnginePrivate& dd, QObject* parent): + QObject(parent), + d_ptr(&dd), + m_showDesignerModal(true) { Q_D(ReportEngine); - d->q_ptr=this; + d->q_ptr = this; connect(d, SIGNAL(renderStarted()), this, SIGNAL(renderStarted())); - connect(d, SIGNAL(renderPageFinished(int)), - this, SIGNAL(renderPageFinished(int))); + connect(d, SIGNAL(renderPageFinished(int)), this, SIGNAL(renderPageFinished(int))); connect(d, SIGNAL(renderFinished()), this, SIGNAL(renderFinished())); } -bool ReportEngine::showDesignerModal() const -{ - return m_showDesignerModal; -} +bool ReportEngine::showDesignerModal() const { return m_showDesignerModal; } void ReportEngine::setShowDesignerModal(bool showDesignerModal) { m_showDesignerModal = showDesignerModal; } -ScriptEngineManager*LimeReport::ReportEnginePrivate::scriptManager(){ +ScriptEngineManager* LimeReport::ReportEnginePrivate::scriptManager() +{ ScriptEngineManager::instance().setContext(scriptContext()); ScriptEngineManager::instance().setDataManager(dataManager()); return &ScriptEngineManager::instance(); } -PrintProcessor::PrintProcessor(QPrinter* printer) - : m_printer(printer), m_painter(0), m_firstPage(true) -{m_renderPage.setItemMode(PrintMode);} - +PrintProcessor::PrintProcessor(QPrinter* printer): + m_printer(printer), + m_painter(0), + m_firstPage(true) +{ + m_renderPage.setItemMode(PrintMode); +} bool PrintProcessor::printPage(PageItemDesignIntf::Ptr page) { - if (!m_firstPage && !m_painter->isActive()) return false; + if (!m_firstPage && !m_painter->isActive()) + return false; PageDesignIntf* backupPage = dynamic_cast(page->scene()); QPointF backupPagePos = page->pos(); - page->setPos(0,0); + page->setPos(0, 0); m_renderPage.setPageItem(page); - m_renderPage.setSceneRect(m_renderPage.pageItem()->mapToScene(m_renderPage.pageItem()->rect()).boundingRect()); + m_renderPage.setSceneRect( + m_renderPage.pageItem()->mapToScene(m_renderPage.pageItem()->rect()).boundingRect()); initPrinter(m_renderPage.pageItem()); - if (!m_firstPage){ + if (!m_firstPage) { m_printer->newPage(); } else { m_painter = new QPainter(m_printer); - if (!m_painter->isActive()) return false; + if (!m_painter->isActive()) + return false; m_firstPage = false; } #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) qreal leftMargin, topMargin, rightMargin, bottomMargin; - m_printer->getPageMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin, QPrinter::Millimeter); + m_printer->getPageMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin, + QPrinter::Millimeter); #else qreal leftMargin = m_printer->pageLayout().margins().left(); qreal topMargin = m_printer->pageLayout().margins().top(); @@ -1873,37 +1825,38 @@ bool PrintProcessor::printPage(PageItemDesignIntf::Ptr page) #endif QRectF printerPageRect = m_printer->pageRect(QPrinter::Millimeter); - printerPageRect = QRectF(0,0,(printerPageRect.size().width() + rightMargin + leftMargin) * page->unitFactor(), - (printerPageRect.size().height() + bottomMargin + topMargin) * page->unitFactor()); + printerPageRect = QRectF( + 0, 0, (printerPageRect.size().width() + rightMargin + leftMargin) * page->unitFactor(), + (printerPageRect.size().height() + bottomMargin + topMargin) * page->unitFactor()); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (page->printBehavior() == PageItemDesignIntf::Split && - m_printer->pageSize() != static_cast(page->pageSize()) && - printerPageRect.width() < page->geometry().width()) - { + if (page->printBehavior() == PageItemDesignIntf::Split + && m_printer->pageSize() != static_cast(page->pageSize()) + && printerPageRect.width() < page->geometry().width()) { #else - if ( - page->printBehavior() == PageItemDesignIntf::Split && - m_printer->pageLayout().pageSize() != QPageSize((QPageSize::PageSizeId)page->pageSize()) && - printerPageRect.width() < page->geometry().width() - ){ + if (page->printBehavior() == PageItemDesignIntf::Split + && m_printer->pageLayout().pageSize() != QPageSize((QPageSize::PageSizeId)page->pageSize()) + && printerPageRect.width() < page->geometry().width()) { #endif qreal pageWidth = page->geometry().width(); - qreal pageHeight = page->geometry().height(); + qreal pageHeight = page->geometry().height(); qreal curHeight = 0; qreal curWidth = 0; - QRectF currentPrintingRect = printerPageRect; + QRectF currentPrintingRect = printerPageRect; bool first = true; - while (pageHeight > 0){ - while (curWidth < pageWidth){ - if (!first) m_printer->newPage(); else first = false; + while (pageHeight > 0) { + while (curWidth < pageWidth) { + if (!first) + m_printer->newPage(); + else + first = false; m_renderPage.render(m_painter, QRectF(), currentPrintingRect); curWidth += printerPageRect.size().width(); - currentPrintingRect = QRectF( - curWidth, 0, - printerPageRect.size().width() > (pageWidth - curWidth) ? (pageWidth - curWidth) : printerPageRect.size().width(), pageHeight - ); - + currentPrintingRect = QRectF(curWidth, 0, + printerPageRect.size().width() > (pageWidth - curWidth) + ? (pageWidth - curWidth) + : printerPageRect.size().width(), + pageHeight); } pageHeight -= printerPageRect.size().height(); curHeight += printerPageRect.size().height(); @@ -1913,10 +1866,10 @@ bool PrintProcessor::printPage(PageItemDesignIntf::Ptr page) } } else { - if (page->getSetPageSizeToPrinter()){ + if (page->getSetPageSizeToPrinter()) { QRectF source = page->geometry(); QSizeF inchSize = source.size() / (100 * 2.54); - QRectF target = QRectF(QPoint(0,0), inchSize * m_printer->resolution()); + QRectF target = QRectF(QPoint(0, 0), inchSize * m_printer->resolution()); m_renderPage.render(m_painter, target, source); } else { m_renderPage.render(m_painter); @@ -1924,223 +1877,139 @@ bool PrintProcessor::printPage(PageItemDesignIntf::Ptr page) } page->setPos(backupPagePos); m_renderPage.removePageItem(page); - if (backupPage) backupPage->reactivatePageItem(page); + if (backupPage) + backupPage->reactivatePageItem(page); return true; } void PrintProcessor::initPrinter(PageItemDesignIntf* page) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) - if (page->oldPrintMode()){ - m_printer->setPageMargins(page->leftMargin(), - page->topMargin(), - page->rightMargin(), - page->bottomMargin(), - QPrinter::Millimeter); + if (page->oldPrintMode()) { + m_printer->setPageMargins(page->leftMargin(), page->topMargin(), page->rightMargin(), + page->bottomMargin(), QPrinter::Millimeter); m_printer->setOrientation(static_cast(page->pageOrientation())); - QSizeF pageSize = (page->pageOrientation()==PageItemDesignIntf::Landscape)? - QSizeF(page->sizeMM().height(),page->sizeMM().width()): - page->sizeMM(); - m_printer->setPaperSize(pageSize,QPrinter::Millimeter); + QSizeF pageSize = (page->pageOrientation() == PageItemDesignIntf::Landscape) + ? QSizeF(page->sizeMM().height(), page->sizeMM().width()) + : page->sizeMM(); + m_printer->setPaperSize(pageSize, QPrinter::Millimeter); } else { m_printer->setFullPage(page->fullPage()); if (page->dropPrinterMargins()) m_printer->setPageMargins(0, 0, 0, 0, QPrinter::Point); m_printer->setOrientation(static_cast(page->pageOrientation())); - if (page->pageSize()==PageItemDesignIntf::Custom){ - QSizeF pageSize = (page->pageOrientation()==PageItemDesignIntf::Landscape)? - QSizeF(page->sizeMM().height(),page->sizeMM().width()): - page->sizeMM(); + if (page->pageSize() == PageItemDesignIntf::Custom) { + QSizeF pageSize = (page->pageOrientation() == PageItemDesignIntf::Landscape) + ? QSizeF(page->sizeMM().height(), page->sizeMM().width()) + : page->sizeMM(); if (page->getSetPageSizeToPrinter() || m_printer->outputFormat() == QPrinter::PdfFormat) - m_printer->setPaperSize(pageSize, QPrinter::Millimeter); + m_printer->setPaperSize(pageSize, QPrinter::Millimeter); } else { if (page->getSetPageSizeToPrinter() || m_printer->outputFormat() == QPrinter::PdfFormat) - m_printer->setPaperSize(static_cast(page->pageSize())); + m_printer->setPaperSize(static_cast(page->pageSize())); } } #else - if (page->oldPrintMode()){ - m_printer->setPageMargins(QMarginsF(page->leftMargin(), page->topMargin(), page->rightMargin(), page->bottomMargin()),QPageLayout::Millimeter); + if (page->oldPrintMode()) { + m_printer->setPageMargins(QMarginsF(page->leftMargin(), page->topMargin(), + page->rightMargin(), page->bottomMargin()), + QPageLayout::Millimeter); m_printer->setPageOrientation((QPageLayout::Orientation)page->pageOrientation()); - QSizeF pageSize = (page->pageOrientation()==PageItemDesignIntf::Landscape)? - QSizeF(page->sizeMM().height(),page->sizeMM().width()): - page->sizeMM(); + QSizeF pageSize = (page->pageOrientation() == PageItemDesignIntf::Landscape) + ? QSizeF(page->sizeMM().height(), page->sizeMM().width()) + : page->sizeMM(); m_printer->setPageSize(QPageSize(pageSize, QPageSize::Millimeter)); - } else { + } else { m_printer->setFullPage(page->fullPage()); if (page->dropPrinterMargins()) m_printer->setPageMargins(QMarginsF(0, 0, 0, 0), QPageLayout::Point); m_printer->setPageOrientation((QPageLayout::Orientation)page->pageOrientation()); - if (page->pageSize()==PageItemDesignIntf::Custom){ - QSizeF pageSize = (page->pageOrientation()==PageItemDesignIntf::Landscape)? - QSizeF(page->sizeMM().height(),page->sizeMM().width()): - page->sizeMM(); + if (page->pageSize() == PageItemDesignIntf::Custom) { + QSizeF pageSize = (page->pageOrientation() == PageItemDesignIntf::Landscape) + ? QSizeF(page->sizeMM().height(), page->sizeMM().width()) + : page->sizeMM(); if (page->getSetPageSizeToPrinter() || m_printer->outputFormat() == QPrinter::PdfFormat) - m_printer->setPageSize(QPageSize(pageSize, QPageSize::Millimeter)); + m_printer->setPageSize(QPageSize(pageSize, QPageSize::Millimeter)); } else { if (page->getSetPageSizeToPrinter() || m_printer->outputFormat() == QPrinter::PdfFormat) - m_printer->setPageSize(QPageSize((QPageSize::PageSizeId)page->pageSize())); + m_printer->setPageSize(QPageSize((QPageSize::PageSizeId)page->pageSize())); } } #endif } -qreal ItemGeometry::x() const -{ - return m_x; -} +qreal ItemGeometry::x() const { return m_x; } -void ItemGeometry::setX(const qreal &x) -{ - m_x = x; -} +void ItemGeometry::setX(const qreal& x) { m_x = x; } -qreal ItemGeometry::y() const -{ - return m_y; -} +qreal ItemGeometry::y() const { return m_y; } -void ItemGeometry::setY(const qreal &y) -{ - m_y = y; -} +void ItemGeometry::setY(const qreal& y) { m_y = y; } -qreal ItemGeometry::width() const -{ - return m_width; -} +qreal ItemGeometry::width() const { return m_width; } -void ItemGeometry::setWidth(const qreal &width) -{ - m_width = width; -} +void ItemGeometry::setWidth(const qreal& width) { m_width = width; } -qreal ItemGeometry::height() const -{ - return m_height; -} +qreal ItemGeometry::height() const { return m_height; } -void ItemGeometry::setHeight(const qreal &height) -{ - m_height = height; -} +void ItemGeometry::setHeight(const qreal& height) { m_height = height; } -ItemGeometry::Type ItemGeometry::type() const -{ - return m_type; -} +ItemGeometry::Type ItemGeometry::type() const { return m_type; } -void ItemGeometry::setType(const Type &type) -{ - m_type = type; -} +void ItemGeometry::setType(const Type& type) { m_type = type; } -Qt::Alignment ItemGeometry::anchor() const -{ - return m_anchor; -} +Qt::Alignment ItemGeometry::anchor() const { return m_anchor; } -void ItemGeometry::setAnchor(const Qt::Alignment &anchor) -{ - m_anchor = anchor; -} +void ItemGeometry::setAnchor(const Qt::Alignment& anchor) { m_anchor = anchor; } -QString WatermarkSetting::text() const -{ - return m_text; -} +QString WatermarkSetting::text() const { return m_text; } -void WatermarkSetting::setText(const QString &text) -{ - m_text = text; -} +void WatermarkSetting::setText(const QString& text) { m_text = text; } -QFont WatermarkSetting::font() const -{ - return m_font; -} +QFont WatermarkSetting::font() const { return m_font; } -void WatermarkSetting::setFont(const QFont &font) -{ - m_font = font; -} +void WatermarkSetting::setFont(const QFont& font) { m_font = font; } -int WatermarkSetting::opacity() const -{ - return m_opacity; -} +int WatermarkSetting::opacity() const { return m_opacity; } -void WatermarkSetting::setOpacity(const int &opacity) -{ - m_opacity = opacity; -} +void WatermarkSetting::setOpacity(const int& opacity) { m_opacity = opacity; } -ItemGeometry WatermarkSetting::geometry() const -{ - return m_geometry; -} +ItemGeometry WatermarkSetting::geometry() const { return m_geometry; } -void WatermarkSetting::setGeometry(const ItemGeometry &geometry) -{ - m_geometry = geometry; -} +void WatermarkSetting::setGeometry(const ItemGeometry& geometry) { m_geometry = geometry; } -QColor WatermarkSetting::color() const -{ - return m_color; -} +QColor WatermarkSetting::color() const { return m_color; } -void WatermarkSetting::setColor(const QColor &color) -{ - m_color = color; -} +void WatermarkSetting::setColor(const QColor& color) { m_color = color; } -qreal WatermarkHelper::sceneX() -{ - return valueToPixels(m_watermark.geometry().x()); -} +qreal WatermarkHelper::sceneX() { return valueToPixels(m_watermark.geometry().x()); } -qreal WatermarkHelper::sceneY() -{ - return valueToPixels(m_watermark.geometry().y()); -} +qreal WatermarkHelper::sceneY() { return valueToPixels(m_watermark.geometry().y()); } -qreal WatermarkHelper::sceneWidth() -{ - return valueToPixels(m_watermark.geometry().width()); -} +qreal WatermarkHelper::sceneWidth() { return valueToPixels(m_watermark.geometry().width()); } -qreal WatermarkHelper::sceneHeight() -{ - return valueToPixels(m_watermark.geometry().height()); -} +qreal WatermarkHelper::sceneHeight() { return valueToPixels(m_watermark.geometry().height()); } -QPointF WatermarkHelper::scenePos() -{ - return (QPointF(sceneX(), sceneY())); -} +QPointF WatermarkHelper::scenePos() { return (QPointF(sceneX(), sceneY())); } -QSizeF WatermarkHelper::sceneSize() -{ - return (QSizeF(sceneWidth(), sceneHeight())); -} +QSizeF WatermarkHelper::sceneSize() { return (QSizeF(sceneWidth(), sceneHeight())); } -QPointF WatermarkHelper::mapToPage(const PageItemDesignIntf &page) +QPointF WatermarkHelper::mapToPage(const PageItemDesignIntf& page) { qreal startX = 0; qreal startY = 0; - if ( m_watermark.geometry().anchor() & Qt::AlignLeft){ + if (m_watermark.geometry().anchor() & Qt::AlignLeft) { startX = 0; - } else if ( m_watermark.geometry().anchor() & Qt::AlignRight){ + } else if (m_watermark.geometry().anchor() & Qt::AlignRight) { startX = page.geometry().width(); } else { startX = page.geometry().width() / 2; } - if ( m_watermark.geometry().anchor() & Qt::AlignTop){ + if (m_watermark.geometry().anchor() & Qt::AlignTop) { startY = 0; - } else if (m_watermark.geometry().anchor() & Qt::AlignBottom){ + } else if (m_watermark.geometry().anchor() & Qt::AlignBottom) { startY = page.geometry().height(); } else { startY = page.geometry().height() / 2; @@ -2160,6 +2029,4 @@ qreal WatermarkHelper::valueToPixels(qreal value) return -1; } - -}// namespace LimeReport - +} // namespace LimeReport diff --git a/limereport/lrreportengine.h b/limereport/lrreportengine.h index a8716e8..fa244e6 100644 --- a/limereport/lrreportengine.h +++ b/limereport/lrreportengine.h @@ -31,61 +31,74 @@ #define LRREPORTDESIGNINTF_H #include -#include #include +#include //#include -#include "lrglobal.h" #include "lrdatasourcemanagerintf.h" -#include "lrscriptenginemanagerintf.h" +#include "lrglobal.h" +#include "lrpreparedpagesintf.h" #include "lrpreviewreportwidget.h" #include "lrreportdesignwindowintrerface.h" -#include "lrpreparedpagesintf.h" +#include "lrscriptenginemanagerintf.h" class QPrinter; class QGraphicsScene; namespace LimeReport { -class PrintRange{ +class PrintRange { public: - int fromPage() const { return m_fromPage;} - int toPage() const { return m_toPage;} - QPrintDialog::PrintRange rangeType() const { return m_rangeType;} - PrintRange(QAbstractPrintDialog::PrintRange rangeType=QPrintDialog::AllPages, int fromPage=0, int toPage=0); - void setRangeType(QAbstractPrintDialog::PrintRange rangeType){ m_rangeType=rangeType;} - void setFromPage(int fromPage){ m_fromPage = fromPage;} - void setToPage(int toPage){ m_toPage = toPage;} + int fromPage() const { return m_fromPage; } + int toPage() const { return m_toPage; } + QPrintDialog::PrintRange rangeType() const { return m_rangeType; } + PrintRange(QAbstractPrintDialog::PrintRange rangeType = QPrintDialog::AllPages, + int fromPage = 0, int toPage = 0); + void setRangeType(QAbstractPrintDialog::PrintRange rangeType) { m_rangeType = rangeType; } + void setFromPage(int fromPage) { m_fromPage = fromPage; } + void setToPage(int toPage) { m_toPage = toPage; } + private: QPrintDialog::PrintRange m_rangeType; int m_fromPage; int m_toPage; }; -class LIMEREPORT_EXPORT ItemGeometry{ +class LIMEREPORT_EXPORT ItemGeometry { public: - enum Type{Millimeters, Pixels}; - ItemGeometry(qreal x, qreal y, qreal width, qreal height, Qt::Alignment anchor, Type type = Millimeters) - :m_x(x), m_y(y), m_width(width), m_height(height), m_type(type), m_anchor(anchor){} - ItemGeometry(): m_x(0), m_y(0), m_width(0), m_height(0), m_type(Millimeters){} + enum Type { + Millimeters, + Pixels + }; + ItemGeometry(qreal x, qreal y, qreal width, qreal height, Qt::Alignment anchor, + Type type = Millimeters): + m_x(x), + m_y(y), + m_width(width), + m_height(height), + m_type(type), + m_anchor(anchor) + { + } + ItemGeometry(): m_x(0), m_y(0), m_width(0), m_height(0), m_type(Millimeters) { } qreal x() const; - void setX(const qreal &x); + void setX(const qreal& x); qreal y() const; - void setY(const qreal &y); + void setY(const qreal& y); qreal width() const; - void setWidth(const qreal &width); + void setWidth(const qreal& width); qreal height() const; - void setHeight(const qreal &height); + void setHeight(const qreal& height); Type type() const; - void setType(const Type &type); + void setType(const Type& type); Qt::Alignment anchor() const; - void setAnchor(const Qt::Alignment &anchor); + void setAnchor(const Qt::Alignment& anchor); private: qreal m_x; @@ -96,42 +109,47 @@ private: Qt::Alignment m_anchor; }; -class LIMEREPORT_EXPORT WatermarkSetting{ +class LIMEREPORT_EXPORT WatermarkSetting { public: - WatermarkSetting(const QString& text, const ItemGeometry& geometry, const QFont& font) - : m_text(text), m_font(font), m_opacity(50), m_geometry(geometry), m_color(QColor(Qt::black)){} - WatermarkSetting(): m_font(QFont()), m_opacity(50), m_geometry(ItemGeometry()){} + WatermarkSetting(const QString& text, const ItemGeometry& geometry, const QFont& font): + m_text(text), + m_font(font), + m_opacity(50), + m_geometry(geometry), + m_color(QColor(Qt::black)) + { + } + WatermarkSetting(): m_font(QFont()), m_opacity(50), m_geometry(ItemGeometry()) { } QString text() const; - void setText(const QString &text); + void setText(const QString& text); QFont font() const; - void setFont(const QFont &font); + void setFont(const QFont& font); int opacity() const; - void setOpacity(const int &opacity); + void setOpacity(const int& opacity); ItemGeometry geometry() const; - void setGeometry(const ItemGeometry &geometry); + void setGeometry(const ItemGeometry& geometry); QColor color() const; - void setColor(const QColor &color); + void setColor(const QColor& color); private: QString m_text; - QFont m_font; - int m_opacity; + QFont m_font; + int m_opacity; ItemGeometry m_geometry; QColor m_color; }; -class ItemBuilder{ +class ItemBuilder { virtual void setProperty(QString name, QVariant value) = 0; virtual QVariant property(QString name) = 0; virtual void setGeometry(ItemGeometry geometry) = 0; - virtual ItemGeometry geometry() = 0; + virtual ItemGeometry geometry() = 0; }; - class DataSourceManager; class ReportEnginePrivate; class PageDesignIntf; @@ -140,47 +158,50 @@ class ReportDesignWidget; class PreviewReportWidget; class PreparedPages; -typedef QList< QSharedPointer > ReportPages; +typedef QList> ReportPages; -class LIMEREPORT_EXPORT ReportEngine : public QObject{ +class LIMEREPORT_EXPORT ReportEngine: public QObject { Q_OBJECT friend class ReportDesignWidget; friend class PreviewReportWidget; friend class TranslationEditor; + public: - static void setSettings(QSettings *value){m_settings=value;} + static void setSettings(QSettings* value) { m_settings = value; } + public: - explicit ReportEngine(QObject *parent = 0); + explicit ReportEngine(QObject* parent = 0); ~ReportEngine(); - bool printReport(QPrinter *printer=0); - bool printReport(QMap printers, bool printToAllPrinters = false); - bool printPages(ReportPages pages, QPrinter *printer); - void printToFile(const QString& fileName); - QGraphicsScene* createPreviewScene(QObject *parent = 0); - bool printToPDF(const QString& fileName); - bool exportReport(QString exporterName, const QString &fileName = "", const QMap& params = QMap()); - void previewReport(PreviewHints hints = PreviewBarsUserSetting); - void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); - void designReport(); + bool printReport(QPrinter* printer = 0); + bool printReport(QMap printers, bool printToAllPrinters = false); + bool printPages(ReportPages pages, QPrinter* printer); + void printToFile(const QString& fileName); + QGraphicsScene* createPreviewScene(QObject* parent = 0); + bool printToPDF(const QString& fileName); + bool exportReport(QString exporterName, const QString& fileName = "", + const QMap& params = QMap()); + void previewReport(PreviewHints hints = PreviewBarsUserSetting); + void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); + void designReport(); ReportDesignWindowInterface* getDesignerWindow(); - void setShowProgressDialog(bool value); - bool isShowProgressDialog(); + void setShowProgressDialog(bool value); + bool isShowProgressDialog(); IDataSourceManager* dataManager(); IScriptEngineManager* scriptManager(); - bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); - bool loadFromByteArray(QByteArray *data); - bool loadFromString(const QString& data); + bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange = false); + bool loadFromByteArray(QByteArray* data); + bool loadFromString(const QString& data); QString reportFileName(); - void setReportFileName(const QString& fileName); - bool saveToFile(const QString& fileName); - QByteArray saveToByteArray(); + void setReportFileName(const QString& fileName); + bool saveToFile(const QString& fileName); + QByteArray saveToByteArray(); QString saveToString(); QString lastError(); void setCurrentReportsDir(const QString& dirName); bool setDefaultExportDir(const QString& dirName); void setReportName(const QString& name); QString reportName(); - PreviewReportWidget *createPreviewWidget(QWidget *parent = 0); + PreviewReportWidget* createPreviewWidget(QWidget* parent = 0); void setPreviewWindowTitle(const QString& title); void setPreviewWindowIcon(const QIcon& icon); void setPreviewPageBackgroundColor(QColor color); @@ -201,8 +222,8 @@ public: QList designerLanguages(); QLocale::Language currentDesignerLanguage(); ScaleType previewScaleType(); - int previewScalePercent(); - void setPreviewScaleType(const ScaleType &previewScaleType, int percent = 0); + int previewScalePercent(); + void setPreviewScaleType(const ScaleType& previewScaleType, int percent = 0); void addWatermark(const WatermarkSetting& watermarkSetting); void clearWatermarks(); IPreparedPages* preparedPages(); @@ -234,14 +255,17 @@ signals: void currentDefaultDesignerLanguageChanged(QLocale::Language); QLocale::Language getCurrentDefaultDesignerLanguage(); - void externalPaint(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem*); + void externalPaint(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem*); public slots: void cancelRender(); void cancelPrinting(); + protected: - ReportEnginePrivate * const d_ptr; - ReportEngine(ReportEnginePrivate &dd, QObject * parent=0); + ReportEnginePrivate* const d_ptr; + ReportEngine(ReportEnginePrivate& dd, QObject* parent = 0); + private: Q_DECLARE_PRIVATE(ReportEngine) static QSettings* m_settings; diff --git a/limereport/lrreportengine_p.h b/limereport/lrreportengine_p.h index 263f91f..0282b12 100644 --- a/limereport/lrreportengine_p.h +++ b/limereport/lrreportengine_p.h @@ -30,103 +30,108 @@ #ifndef LRREPORTDESIGNINTF_P_H #define LRREPORTDESIGNINTF_P_H +#include "lrbanddesignintf.h" +#include "lrcollection.h" +#include "lrdatasourcemanager.h" +#include "lrdesignerplugininterface.h" +#include "lrglobal.h" +#include "lrreportdesignwindowintrerface.h" +#include "lrreportengine.h" +#include "lrreportrender.h" +#include "lrreporttranslation.h" +#include "lrscriptenginemanager.h" +#include "serializators/lrstorageintf.h" + +#include +#include #include #include -#include -#include -#include "lrreportengine.h" -#include "lrcollection.h" -#include "lrglobal.h" -#include "lrdatasourcemanager.h" -#include "lrbanddesignintf.h" -#include "lrreportrender.h" -#include "serializators/lrstorageintf.h" -#include "lrscriptenginemanager.h" -#include "lrreporttranslation.h" -#include "lrdesignerplugininterface.h" -#include "lrreportdesignwindowintrerface.h" class QFileSystemWatcher; - -namespace LimeReport{ +namespace LimeReport { class PageDesignIntf; class PrintRange; class ReportDesignWindow; class ReportExporterInterface; - -class WatermarkHelper{ +class WatermarkHelper { public: - WatermarkHelper(const WatermarkSetting& watermark) - : m_watermark(watermark){} + WatermarkHelper(const WatermarkSetting& watermark): m_watermark(watermark) { } qreal sceneX(); qreal sceneY(); qreal sceneWidth(); qreal sceneHeight(); QPointF scenePos(); - QSizeF sceneSize(); - QPointF mapToPage(const PageItemDesignIntf &page); + QSizeF sceneSize(); + QPointF mapToPage(const PageItemDesignIntf& page); + private: qreal valueToPixels(qreal value); + private: const WatermarkSetting& m_watermark; }; - class ReportEnginePrivateInterface { public: - virtual PageDesignIntf* appendPage(const QString& pageName="") = 0; - virtual bool deletePage(PageDesignIntf *page) = 0; - virtual void reorderPages(const QList &reorderedPages) = 0; - virtual int pageCount() = 0; - virtual PageDesignIntf* pageAt(int index) = 0; - virtual void clearReport() = 0; - virtual ScriptEngineContext* scriptContext() = 0; - virtual ScriptEngineManager* scriptManager() = 0; - virtual DataSourceManager* dataManager() = 0; - virtual QString reportFileName() = 0; - virtual void setReportFileName(const QString& reportFileName) = 0; - virtual bool isNeedToSave() = 0; - virtual bool emitSaveReport() = 0; - virtual bool emitSaveReportAs() = 0; - virtual void emitSaveFinished() = 0; - virtual bool saveToFile(const QString& fileName = "") = 0; - virtual bool isSaved() = 0; - virtual QString reportName() = 0; - virtual bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange) = 0; - virtual bool emitLoadReport() = 0; - virtual void emitLoadFinished() = 0; - virtual void clearSelection() = 0; - virtual bool printReport(QPrinter *printer=0) = 0; - virtual void previewReport(PreviewHints hints = PreviewBarsUserSetting) = 0; - virtual void setCurrentReportsDir(const QString& dirName) = 0; - virtual QString currentReportsDir() = 0; - virtual bool setDefaultExportDir(const QString& dirName) = 0; - virtual QString defaultExportDir() = 0; - virtual bool suppressFieldAndVarError() const = 0; - virtual void setSuppressFieldAndVarError(bool suppressFieldAndVarError) = 0; - virtual void setStyleSheet(const QString& styleSheet) = 0; - virtual QString styleSheet() const = 0; + virtual PageDesignIntf* appendPage(const QString& pageName = "") = 0; + virtual bool deletePage(PageDesignIntf* page) = 0; + virtual void reorderPages(const QList& reorderedPages) = 0; + virtual int pageCount() = 0; + virtual PageDesignIntf* pageAt(int index) = 0; + virtual void clearReport() = 0; + virtual ScriptEngineContext* scriptContext() = 0; + virtual ScriptEngineManager* scriptManager() = 0; + virtual DataSourceManager* dataManager() = 0; + virtual QString reportFileName() = 0; + virtual void setReportFileName(const QString& reportFileName) = 0; + virtual bool isNeedToSave() = 0; + virtual bool emitSaveReport() = 0; + virtual bool emitSaveReportAs() = 0; + virtual void emitSaveFinished() = 0; + virtual bool saveToFile(const QString& fileName = "") = 0; + virtual bool isSaved() = 0; + virtual QString reportName() = 0; + virtual bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange) = 0; + virtual bool emitLoadReport() = 0; + virtual void emitLoadFinished() = 0; + virtual void clearSelection() = 0; + virtual bool printReport(QPrinter* printer = 0) = 0; + virtual void previewReport(PreviewHints hints = PreviewBarsUserSetting) = 0; + virtual void setCurrentReportsDir(const QString& dirName) = 0; + virtual QString currentReportsDir() = 0; + virtual bool setDefaultExportDir(const QString& dirName) = 0; + virtual QString defaultExportDir() = 0; + virtual bool suppressFieldAndVarError() const = 0; + virtual void setSuppressFieldAndVarError(bool suppressFieldAndVarError) = 0; + virtual void setStyleSheet(const QString& styleSheet) = 0; + virtual QString styleSheet() const = 0; virtual QList designerLanguages() = 0; - virtual QLocale::Language currentDesignerLanguage() = 0; - virtual void setCurrentDesignerLanguage(QLocale::Language language) = 0; - virtual void cancelRender() = 0; - virtual void setShowProgressDialog(bool value) = 0; - virtual bool isShowProgressDialog() const = 0; - virtual bool isBusy() = 0; - virtual int baseItemPadding() const = 0; - virtual void setBaseItemPadding(int baseTextItemPadding) = 0; + virtual QLocale::Language currentDesignerLanguage() = 0; + virtual void setCurrentDesignerLanguage(QLocale::Language language) = 0; + virtual void cancelRender() = 0; + virtual void setShowProgressDialog(bool value) = 0; + virtual bool isShowProgressDialog() const = 0; + virtual bool isBusy() = 0; + virtual int baseItemPadding() const = 0; + virtual void setBaseItemPadding(int baseTextItemPadding) = 0; }; -class PrintProcessor{ +class PrintProcessor { public: explicit PrintProcessor(QPrinter* printer); - ~PrintProcessor(){ if (m_painter) delete m_painter;} + ~PrintProcessor() + { + if (m_painter) + delete m_painter; + } bool printPage(LimeReport::PageItemDesignIntf::Ptr page); + private: void initPrinter(PageItemDesignIntf* page); + private: QPrinter* m_printer; QPainter* m_painter; @@ -134,75 +139,87 @@ private: bool m_firstPage; }; -class ReportEnginePrivate : public QObject, - public ICollectionContainer, - public ITranslationContainer, - public IExternalPainter, - public ReportEnginePrivateInterface -{ +class ReportEnginePrivate: + public QObject, + public ICollectionContainer, + public ITranslationContainer, + public IExternalPainter, + public ReportEnginePrivateInterface { Q_OBJECT Q_DECLARE_PUBLIC(ReportEngine) Q_PROPERTY(ACollectionProperty pages READ fakeCollectionReader) Q_PROPERTY(QObject* datasourcesManager READ dataManager) Q_PROPERTY(QObject* scriptContext READ scriptContext) - Q_PROPERTY(bool suppressFieldAndVarError READ suppressFieldAndVarError WRITE setSuppressFieldAndVarError) + Q_PROPERTY(bool suppressFieldAndVarError READ suppressFieldAndVarError WRITE + setSuppressFieldAndVarError) Q_PROPERTY(int baseItemPadding READ baseItemPadding WRITE setBaseItemPadding) Q_PROPERTY(ATranslationProperty translation READ fakeTranslationReader) - enum AppendType{MixPages, AppendPages}; + enum AppendType { + MixPages, + AppendPages + }; friend class PreviewReportWidget; + public: - bool printPages(ReportPages pages, QPrinter *printer); - void printPages(ReportPages pages, QMapprinters, bool printToAllPrinters = false); + bool printPages(ReportPages pages, QPrinter* printer); + void printPages(ReportPages pages, QMap printers, + bool printToAllPrinters = false); Q_INVOKABLE QStringList aviableReportTranslations(); Q_INVOKABLE void setReportTranslation(const QString& languageName); + public: - explicit ReportEnginePrivate(QObject *parent = 0); + explicit ReportEnginePrivate(QObject* parent = 0); virtual ~ReportEnginePrivate(); - PageDesignIntf* appendPage(const QString& pageName=""); - bool deletePage(PageDesignIntf *page); - PageDesignIntf* createPreviewPage(); - PageDesignIntf* pageAt(int index){return (index<=(m_pages.count()-1)) ? m_pages.at(index):0;} - int pageCount() {return m_pages.count();} - DataSourceManager* dataManager(){return m_datasources;} - ScriptEngineContext* scriptContext(){return m_scriptEngineContext;} + PageDesignIntf* appendPage(const QString& pageName = ""); + bool deletePage(PageDesignIntf* page); + PageDesignIntf* createPreviewPage(); + PageDesignIntf* pageAt(int index) + { + return (index <= (m_pages.count() - 1)) ? m_pages.at(index) : 0; + } + int pageCount() { return m_pages.count(); } + DataSourceManager* dataManager() { return m_datasources; } + ScriptEngineContext* scriptContext() { return m_scriptEngineContext; } ScriptEngineManager* scriptManager(); - IDataSourceManager* dataManagerIntf(){return m_datasources;} + IDataSourceManager* dataManagerIntf() { return m_datasources; } - IScriptEngineManager* scriptManagerIntf(){ + IScriptEngineManager* scriptManagerIntf() + { ScriptEngineManager::instance().setDataManager(dataManager()); return &ScriptEngineManager::instance(); } - void clearReport(); - bool printReport(QPrinter* printer=0); - bool printReport(QMapprinters, bool printToAllPrinters); + void clearReport(); + bool printReport(QPrinter* printer = 0); + bool printReport(QMap printers, bool printToAllPrinters); - void printToFile(const QString& fileName); - bool printToPDF(const QString& fileName); - bool exportReport(QString exporterName, const QString &fileName = "", const QMap& params = QMap()); - void previewReport(PreviewHints hints = PreviewBarsUserSetting); - void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); + void printToFile(const QString& fileName); + bool printToPDF(const QString& fileName); + bool exportReport(QString exporterName, const QString& fileName = "", + const QMap& params = QMap()); + void previewReport(PreviewHints hints = PreviewBarsUserSetting); + void previewReport(QPrinter* printer, PreviewHints hints = PreviewBarsUserSetting); ReportDesignWindowInterface* getDesignerWindow(); - void designReport(bool showModal); - void setSettings(QSettings* value); - void setShowProgressDialog(bool value){m_showProgressDialog = value;} - bool isShowProgressDialog() const {return m_showProgressDialog;} - QSettings* settings(); - bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange); - bool loadFromByteArray(QByteArray *data, const QString& name = ""); - bool loadFromString(const QString& report, const QString& name = ""); - QString reportFileName(){return m_fileName;} - void setReportFileName(const QString& reportFileName){ m_fileName = reportFileName;} - bool saveToFile(const QString& fileName = ""); - QByteArray saveToByteArray(); + void designReport(bool showModal); + void setSettings(QSettings* value); + void setShowProgressDialog(bool value) { m_showProgressDialog = value; } + bool isShowProgressDialog() const { return m_showProgressDialog; } + QSettings* settings(); + bool loadFromFile(const QString& fileName, bool autoLoadPreviewOnChange); + bool loadFromByteArray(QByteArray* data, const QString& name = ""); + bool loadFromString(const QString& report, const QString& name = ""); + QString reportFileName() { return m_fileName; } + void setReportFileName(const QString& reportFileName) { m_fileName = reportFileName; } + bool saveToFile(const QString& fileName = ""); + QByteArray saveToByteArray(); QString saveToString(); - bool isNeedToSave(); + bool isNeedToSave(); QString lastError(); - ReportEngine * q_ptr; + ReportEngine* q_ptr; bool emitSaveReport(); bool emitSaveReportAs(); bool emitLoadReport(); @@ -211,18 +228,18 @@ public: void emitPrintedToPDF(QString fileName); bool isSaved(); void setCurrentReportsDir(const QString& dirName); - QString currentReportsDir(){ return m_reportsDir;} + QString currentReportsDir() { return m_reportsDir; } bool setDefaultExportDir(const QString& dirname); - QString defaultExportDir(){ return m_exportDir;} - void setReportName(const QString& reportName){ m_reportName=reportName;} - QString reportName(){ return m_reportName;} - bool hasActivePreview(){return m_activePreview;} - PageDesignIntf *createPreviewScene(QObject *parent); - PreviewReportWidget *createPreviewWidget(QWidget *parent); + QString defaultExportDir() { return m_exportDir; } + void setReportName(const QString& reportName) { m_reportName = reportName; } + QString reportName() { return m_reportName; } + bool hasActivePreview() { return m_activePreview; } + PageDesignIntf* createPreviewScene(QObject* parent); + PreviewReportWidget* createPreviewWidget(QWidget* parent); QIcon previewWindowIcon() const; - void setPreviewWindowIcon(const QIcon &previewWindowIcon); + void setPreviewWindowIcon(const QIcon& previewWindowIcon); QString previewWindowTitle() const; - void setPreviewWindowTitle(const QString &previewWindowTitle); + void setPreviewWindowTitle(const QString& previewWindowTitle); QColor previewWindowPageBackground(); void setPreviewWindowPageBackground(QColor color); @@ -240,90 +257,99 @@ public: bool printIsVisible() const; void setPrintVisible(bool value); - void setPassPhrase(const QString &passPhrase); + void setPassPhrase(const QString& passPhrase); bool addTranslationLanguage(QLocale::Language language); bool removeTranslationLanguage(QLocale::Language language); bool setReportLanguage(QLocale::Language language); QList aviableLanguages(); ReportTranslation* reportTranslation(QLocale::Language language); - void reorderPages(const QList &reorderedPages); + void reorderPages(const QList& reorderedPages); void clearSelection(); Qt::LayoutDirection previewLayoutDirection(); void setPreviewLayoutDirection(const Qt::LayoutDirection& previewLayoutDirection); QString styleSheet() const; - void setStyleSheet(const QString &styleSheet); + void setStyleSheet(const QString& styleSheet); QList designerLanguages(); QLocale::Language currentDesignerLanguage(); void setCurrentDesignerLanguage(QLocale::Language language); ScaleType previewScaleType(); - int previewScalePercent(); - void setPreviewScaleType(const ScaleType &previewScaleType, int percent = 0); - void addWatermark(const WatermarkSetting& watermarkSetting); - void clearWatermarks(); + int previewScalePercent(); + void setPreviewScaleType(const ScaleType& previewScaleType, int percent = 0); + void addWatermark(const WatermarkSetting& watermarkSetting); + void clearWatermarks(); IPreparedPages* preparedPages(); bool showPreparedPages(PreviewHints hints); - bool showPreparedPages(QPrinter *defaultPrinter, PreviewHints hints); + bool showPreparedPages(QPrinter* defaultPrinter, PreviewHints hints); bool prepareReportPages(); bool printPreparedPages(); signals: - void pagesLoadFinished(); - void datasourceCollectionLoadFinished(const QString& collectionName); - void cleared(); - void renderStarted(); - void renderFinished(); - void renderPageFinished(int renderedPageCount); - void onSave(bool& saved); - void onSaveAs(bool& saved); - void onSavePreview(bool& saved, LimeReport::IPreparedPages* pages); - void onLoad(bool& loaded); - void saveFinished(); - void loadFinished(); - void printedToPDF(QString fileName); + void pagesLoadFinished(); + void datasourceCollectionLoadFinished(const QString& collectionName); + void cleared(); + void renderStarted(); + void renderFinished(); + void renderPageFinished(int renderedPageCount); + void onSave(bool& saved); + void onSaveAs(bool& saved); + void onSavePreview(bool& saved, LimeReport::IPreparedPages* pages); + void onLoad(bool& loaded); + void saveFinished(); + void loadFinished(); + void printedToPDF(QString fileName); - void getAvailableDesignerLanguages(QList* languages); - void currentDefaultDesignerLanguageChanged(QLocale::Language); - QLocale::Language getCurrentDefaultDesignerLanguage(); - void externalPaint(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem*); - void printingStarted(int pageCount); - void printingFinished(); - void pagePrintingFinished(int index); + void getAvailableDesignerLanguages(QList* languages); + void currentDefaultDesignerLanguageChanged(QLocale::Language); + QLocale::Language getCurrentDefaultDesignerLanguage(); + void externalPaint(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem*); + void printingStarted(int pageCount); + void printingFinished(); + void pagePrintingFinished(int index); public slots: - bool slotLoadFromFile(const QString& fileName); - void cancelRender(); - void cancelPrinting(); + bool slotLoadFromFile(const QString& fileName); + void cancelRender(); + void cancelPrinting(); + protected: - PageDesignIntf* createPage(const QString& pageName="", bool preview = false); - bool showPreviewWindow(ReportPages pages, PreviewHints hints, QPrinter *printer); - void internalPrintPages(ReportPages pages, QPrinter &printer); + PageDesignIntf* createPage(const QString& pageName = "", bool preview = false); + bool showPreviewWindow(ReportPages pages, PreviewHints hints, QPrinter* printer); + void internalPrintPages(ReportPages pages, QPrinter& printer); protected slots: - void slotDataSourceCollectionLoaded(const QString& collectionName); + void slotDataSourceCollectionLoaded(const QString& collectionName); private slots: void slotPreviewWindowDestroyed(QObject* window); void slotDesignerWindowDestroyed(QObject* window); + private: - //ICollectionContainer - virtual QObject* createElement(const QString&,const QString&); - virtual int elementsCount(const QString&); - virtual QObject* elementAt(const QString&, int index); - virtual void collectionLoadFinished(const QString&); - void saveError(QString message); - void showError(QString message); - //ICollectionContainer - //ITranslationContainer - Translations* translations(){ return &m_translations;} + // ICollectionContainer + virtual QObject* createElement(const QString&, const QString&); + virtual int elementsCount(const QString&); + virtual QObject* elementAt(const QString&, int index); + virtual void collectionLoadFinished(const QString&); + void saveError(QString message); + void showError(QString message); + // ICollectionContainer + // ITranslationContainer + Translations* translations() { return &m_translations; } void updateTranslations(); - //ITranslationContainer + // ITranslationContainer ReportPages renderToPages(); ReportPages appendPages(ReportPages s1, ReportPages s2, AppendType appendType); QString renderToString(); - PageItemDesignIntf *getPageByName(const QString& pageName); - ATranslationProperty fakeTranslationReader(){ return ATranslationProperty();} - PageItemDesignIntf *createRenderingPage(PageItemDesignIntf *page); + PageItemDesignIntf* getPageByName(const QString& pageName); + ATranslationProperty fakeTranslationReader() { return ATranslationProperty(); } + PageItemDesignIntf* createRenderingPage(PageItemDesignIntf* page); void initReport(); - void paintByExternalPainter(const QString& objectName, QPainter* painter, const QStyleOptionGraphicsItem* options); - void dropChanges(){ m_datasources->dropChanges(); m_scriptEngineContext->dropChanges();} + void paintByExternalPainter(const QString& objectName, QPainter* painter, + const QStyleOptionGraphicsItem* options); + void dropChanges() + { + m_datasources->dropChanges(); + m_scriptEngineContext->dropChanges(); + } void clearRenderingPages(); + private: QList m_pages; QList m_renderingPages; @@ -350,7 +376,7 @@ private: bool m_reportRendering; bool m_resultIsEditable; QString m_passPhrase; - QFileSystemWatcher *m_fileWatcher; + QFileSystemWatcher* m_fileWatcher; Translations m_translations; QLocale::Language m_reportLanguage; void activateLanguage(QLocale::Language language); @@ -364,12 +390,12 @@ private: int m_startTOCPage; QColor m_previewPageBackgroundColor; QVector m_watermarks; - BaseDesignIntf *createWatermark(PageDesignIntf *page, WatermarkSetting watermarkSetting); + BaseDesignIntf* createWatermark(PageDesignIntf* page, WatermarkSetting watermarkSetting); bool m_saveToFileVisible; bool m_printToPdfVisible; bool m_printVisible; bool m_cancelPrinting; }; -} +} // namespace LimeReport #endif // LRREPORTDESIGNINTF_P_H diff --git a/limereport/lrreportrender.cpp b/limereport/lrreportrender.cpp index 2ae479b..b9d588f 100644 --- a/limereport/lrreportrender.cpp +++ b/limereport/lrreportrender.cpp @@ -27,22 +27,24 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include - -#include "lrglobal.h" #include "lrreportrender.h" -#include "lrpagedesignintf.h" -#include "lrbanddesignintf.h" -#include "lritemdesignintf.h" -#include "lrscriptenginemanager.h" +#include "lrbanddesignintf.h" +#include "lrglobal.h" +#include "lritemdesignintf.h" +#include "lrpagedesignintf.h" +#include "lrscriptenginemanager.h" #include "serializators/lrxmlreader.h" #include "serializators/lrxmlwriter.h" -namespace LimeReport{ +#include -void ReportRender::initColumns(){ +#include + +namespace LimeReport { + +void ReportRender::initColumns() +{ m_maxHeightByColumn.clear(); m_currentStartDataPos.clear(); m_maxHeightByColumn.append(0); @@ -52,57 +54,59 @@ void ReportRender::initColumns(){ bool ReportRender::isNeedToRearrangeColumnsItems() { - if (m_columnedBandItems.size()<=1) return false; - if (m_columnedBandItems[0]->columnsFillDirection()!=BandDesignIntf::VerticalUniform) + if (m_columnedBandItems.size() <= 1) + return false; + if (m_columnedBandItems[0]->columnsFillDirection() != BandDesignIntf::VerticalUniform) return false; - int avg = m_columnedBandItems.size()/m_columnedBandItems[0]->columnsCount(); + int avg = m_columnedBandItems.size() / m_columnedBandItems[0]->columnsCount(); - for (int i=0;imaxHeight){ + if (m_maxHeightByColumn[i] > maxHeight) { maxHeight = m_maxHeightByColumn[i]; maxHeightColumn = i; } - if (maxHeightColumn>0 && columnItemsCount(maxHeightColumn) lastColumnItem(maxHeightColumn-1)->height() - ){ - return true; + if (maxHeightColumn > 0 && columnItemsCount(maxHeightColumn) < avg + && maxHeight > lastColumnItem(maxHeightColumn - 1)->height()) { + return true; } } return false; } -BandDesignIntf *ReportRender::lastColumnItem(int columnIndex) +BandDesignIntf* ReportRender::lastColumnItem(int columnIndex) { - if (columnIndex<0) return 0; - for(int i=0;icolumnIndex()>columnIndex) - return m_columnedBandItems[i-1]; + if (columnIndex < 0) + return 0; + for (int i = 0; i < m_columnedBandItems.size(); ++i) { + if (m_columnedBandItems[i]->columnIndex() > columnIndex) + return m_columnedBandItems[i - 1]; } return m_columnedBandItems.last(); } void ReportRender::rearrangeColumnsItems() { - if (isNeedToRearrangeColumnsItems()){ + if (isNeedToRearrangeColumnsItems()) { qreal startHeight = columnHeigth(0); int avg = m_columnedBandItems.size() / m_columnedBandItems[0]->columnsCount(); - for (int i = 1; i < m_columnedBandItems[0]->columnsCount(); ++i){ - if (columnItemsCount(i) < avg){ - int getCount = avg * (m_columnedBandItems[0]->columnsCount()-i) - columnItemsCount(i); - for (int j = 0; j < getCount; ++j){ - BandDesignIntf* band = lastColumnItem(i-1); - band->setPos(band->pos().x()+band->width(),m_columnedBandItems[0]->pos().y()); - band->setColumnIndex(i); - } - - } + for (int i = 1; i < m_columnedBandItems[0]->columnsCount(); ++i) { + if (columnItemsCount(i) < avg) { + int getCount + = avg * (m_columnedBandItems[0]->columnsCount() - i) - columnItemsCount(i); + for (int j = 0; j < getCount; ++j) { + BandDesignIntf* band = lastColumnItem(i - 1); + band->setPos(band->pos().x() + band->width(), + m_columnedBandItems[0]->pos().y()); + band->setColumnIndex(i); + } + } } m_renderPageItem->relocateBands(); - m_maxHeightByColumn[0]+=startHeight-maxColumnHeight(); - m_currentStartDataPos[0]-=startHeight-maxColumnHeight(); + m_maxHeightByColumn[0] += startHeight - maxColumnHeight(); + m_currentStartDataPos[0] -= startHeight - maxColumnHeight(); m_columnedBandItems.clear(); } } @@ -110,10 +114,11 @@ void ReportRender::rearrangeColumnsItems() int ReportRender::columnItemsCount(int columnIndex) { int result = 0; - foreach(BandDesignIntf* band, m_columnedBandItems){ - if (band->columnIndex()==columnIndex) + foreach (BandDesignIntf* band, m_columnedBandItems) { + if (band->columnIndex() == columnIndex) ++result; - if (band->columnIndex()>columnIndex) break; + if (band->columnIndex() > columnIndex) + break; } return result; } @@ -121,10 +126,11 @@ int ReportRender::columnItemsCount(int columnIndex) qreal ReportRender::columnHeigth(int columnIndex) { qreal result = 0; - for(int i=0;icolumnIndex()==columnIndex) - result += m_columnedBandItems[i]->height(); - if (m_columnedBandItems[i]->columnIndex()>columnIndex) break; + for (int i = 0; i < m_columnedBandItems.size(); ++i) { + if (m_columnedBandItems[i]->columnIndex() == columnIndex) + result += m_columnedBandItems[i]->height(); + if (m_columnedBandItems[i]->columnIndex() > columnIndex) + break; } return result; } @@ -132,119 +138,137 @@ qreal ReportRender::columnHeigth(int columnIndex) qreal ReportRender::maxColumnHeight() { qreal result = 0; - for (int i=0;icolumnsCount();++i){ + for (int i = 0; i < m_columnedBandItems[0]->columnsCount(); ++i) { qreal curColumnHeight = columnHeigth(i); - if (curColumnHeight>result) result = curColumnHeight; + if (curColumnHeight > result) + result = curColumnHeight; } return result; } -void ReportRender::renameChildItems(BaseDesignIntf *item){ - foreach(BaseDesignIntf* child, item->childBaseItems()){ - if (!child->childBaseItems().isEmpty()) renameChildItems(child); - child->setObjectName(child->metaObject()->className()+QString::number(++m_currentNameIndex)); +void ReportRender::renameChildItems(BaseDesignIntf* item) +{ + foreach (BaseDesignIntf* child, item->childBaseItems()) { + if (!child->childBaseItems().isEmpty()) + renameChildItems(child); + child->setObjectName(child->metaObject()->className() + + QString::number(++m_currentNameIndex)); } } -ReportRender::ReportRender(QObject *parent) - :QObject(parent), m_renderPageItem(0), m_pageCount(0), - m_lastRenderedHeader(0), m_lastDataBand(0), m_lastRenderedFooter(0), - m_lastRenderedBand(0), m_currentColumn(0), m_newPageStarted(false), +ReportRender::ReportRender(QObject* parent): + QObject(parent), + m_renderPageItem(0), + m_pageCount(0), + m_lastRenderedHeader(0), + m_lastDataBand(0), + m_lastRenderedFooter(0), + m_lastRenderedBand(0), + m_currentColumn(0), + m_newPageStarted(false), m_lostHeadersMoved(false) { initColumns(); } -void ReportRender::setDatasources(DataSourceManager *value) +void ReportRender::setDatasources(DataSourceManager* value) { - m_datasources=value; + m_datasources = value; initVariables(); resetPageNumber(BandReset); } void ReportRender::setScriptContext(ScriptEngineContext* scriptContext) { - m_scriptEngineContext=scriptContext; + m_scriptEngineContext = scriptContext; } -void ReportRender::initDatasources(){ - try{ +void ReportRender::initDatasources() +{ + try { datasources()->setAllDatasourcesToFirst(); - } catch(ReportError &exception){ - //TODO possible should thow exeption - QMessageBox::critical(0,tr("Error"),exception.what()); + } catch (ReportError& exception) { + // TODO possible should thow exeption + QMessageBox::critical(0, tr("Error"), exception.what()); return; } } -void ReportRender::initDatasource(const QString& name){ - try{ - if (datasources()->containsDatasource(name)){ +void ReportRender::initDatasource(const QString& name) +{ + try { + if (datasources()->containsDatasource(name)) { IDataSource* ds = datasources()->dataSource(name); if (ds) ds->first(); } - } catch(ReportError &exception){ - QMessageBox::critical(0,tr("Error"),exception.what()); + } catch (ReportError& exception) { + QMessageBox::critical(0, tr("Error"), exception.what()); return; } } -void ReportRender::analizeItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band){ +void ReportRender::analizeItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band) +{ Q_UNUSED(band) - if (contentItem){ + if (contentItem) { QString content = contentItem->content(); QVector functions; - foreach(const QString &functionName, m_datasources->groupFunctionNames()){ + foreach (const QString& functionName, m_datasources->groupFunctionNames()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getGroupFunctionRegEx(functionName); - if(content.indexOf(rx)>=0){ + if (content.indexOf(rx) >= 0) { functions.append(functionName); } #else QRegExp rx(QString(Const::GROUP_FUNCTION_RX).arg(functionName)); rx.setMinimal(true); - if (rx.indexIn(content)>=0){ + if (rx.indexIn(content) >= 0) { functions.append(functionName); - } + } #endif } - if (functions.size()>0) + if (functions.size() > 0) m_groupfunctionItems.insert(contentItem->patternName(), functions); } } -void ReportRender::analizeContainer(BaseDesignIntf* item, BandDesignIntf* band){ - if (item){ - foreach(BaseDesignIntf* child, item->childBaseItems()){ +void ReportRender::analizeContainer(BaseDesignIntf* item, BandDesignIntf* band) +{ + if (item) { + foreach (BaseDesignIntf* child, item->childBaseItems()) { ContentItemDesignIntf* contentItem = dynamic_cast(child); - if (contentItem) analizeItem(contentItem, band); - else analizeContainer(child, band); + if (contentItem) + analizeItem(contentItem, band); + else + analizeContainer(child, band); } } } -void ReportRender::analizePage(PageItemDesignIntf* patternPage){ +void ReportRender::analizePage(PageItemDesignIntf* patternPage) +{ m_groupfunctionItems.clear(); - foreach(BandDesignIntf* band, patternPage->bands()){ - if (band->isFooter() || band->isHeader()){ - analizeContainer(band,band); + foreach (BandDesignIntf* band, patternPage->bands()) { + if (band->isFooter() || band->isHeader()) { + analizeContainer(band, band); } } } -void ReportRender::renderPage(PageItemDesignIntf* patternPage, bool isTOC, bool /*isFirst*/, bool /*resetPageNumbers*/) +void ReportRender::renderPage(PageItemDesignIntf* patternPage, bool isTOC, bool /*isFirst*/, + bool /*resetPageNumbers*/) { m_currentNameIndex = 0; m_patternPageItem = patternPage; analizePage(patternPage); - if (m_patternPageItem->resetPageNumber() && m_pageCount>0 && !isTOC) { + if (m_patternPageItem->resetPageNumber() && m_pageCount > 0 && !isTOC) { resetPageNumber(PageReset); } - if (m_patternPageItem->resetPageNumber() && !isTOC && m_pageCount == 0){ + if (m_patternPageItem->resetPageNumber() && !isTOC && m_pageCount == 0) { m_pagesRanges.startNewRange(); } @@ -257,12 +281,12 @@ void ReportRender::renderPage(PageItemDesignIntf* patternPage, bool isTOC, bool initGroups(); clearPageMap(); - try{ + try { datasources()->setAllDatasourcesToFirst(); datasources()->clearGroupFuntionsExpressions(); - } catch(ReportError &exception){ - //TODO possible should thow exeption - QMessageBox::critical(0,tr("Error"),exception.what()); + } catch (ReportError& exception) { + // TODO possible should thow exeption + QMessageBox::critical(0, tr("Error"), exception.what()); return; } @@ -272,11 +296,12 @@ void ReportRender::renderPage(PageItemDesignIntf* patternPage, bool isTOC, bool renderReportHeader(m_patternPageItem, AfterPageHeader); BandDesignIntf* lastRenderedBand = 0; - for (int i=0;idataBandCount() && !m_renderCanceled; i++){ + for (int i = 0; i < m_patternPageItem->dataBandCount() && !m_renderCanceled; i++) { lastRenderedBand = m_patternPageItem->dataBandAt(i); initDatasource(lastRenderedBand->datasourceName()); renderDataBand(lastRenderedBand); - if (i < m_patternPageItem->dataBandCount()-1) closeFooterGroup(lastRenderedBand); + if (i < m_patternPageItem->dataBandCount() - 1) + closeFooterGroup(lastRenderedBand); } if (reportFooter) @@ -289,33 +314,32 @@ void ReportRender::renderPage(PageItemDesignIntf* patternPage, bool isTOC, bool renderBand(tearOffBand, 0, StartNewPageAsNeeded); savePage(true); - } -int ReportRender::pageCount() -{ - return m_renderedPages.count(); -} +int ReportRender::pageCount() { return m_renderedPages.count(); } PageItemDesignIntf::Ptr ReportRender::pageAt(int index) { - if ((index>m_renderedPages.count()-1)||(index<0)) throw ReportError(tr("page index out of range")); - else return m_renderedPages.at(index); + if ((index > m_renderedPages.count() - 1) || (index < 0)) + throw ReportError(tr("page index out of range")); + else + return m_renderedPages.at(index); } -QString ReportRender::renderPageToString(PageItemDesignIntf *patternPage) +QString ReportRender::renderPageToString(PageItemDesignIntf* patternPage) { renderPage(patternPage); return toString(); } -ReportPages ReportRender::renderPageToPages(PageItemDesignIntf *patternPage) +ReportPages ReportRender::renderPageToPages(PageItemDesignIntf* patternPage) { renderPage(patternPage); return m_renderedPages; } -ReportPages ReportRender::renderTOC(PageItemDesignIntf* patternPage, bool first, bool resetPages){ +ReportPages ReportRender::renderTOC(PageItemDesignIntf* patternPage, bool first, bool resetPages) +{ renderPage(patternPage, true, first, resetPages); return m_renderedPages; } @@ -323,7 +347,8 @@ ReportPages ReportRender::renderTOC(PageItemDesignIntf* patternPage, bool first, void ReportRender::initRenderPage() { if (!m_renderPageItem) { - m_renderPageItem = new PageItemDesignIntf(m_patternPageItem->pageSize(), m_patternPageItem->pageRect()); + m_renderPageItem + = new PageItemDesignIntf(m_patternPageItem->pageSize(), m_patternPageItem->pageRect()); m_renderPageItem->initFromItem(m_patternPageItem); m_renderPageItem->setItemMode(PreviewMode); m_renderPageItem->setPatternName(m_patternPageItem->objectName()); @@ -337,43 +362,38 @@ void ReportRender::initRenderPage() se->globalObject().setProperty("currentPage", svCurrentPage); #else svCurrentPage = se->globalObject().property("currentPage"); - if (svCurrentPage.isValid()){ + if (svCurrentPage.isValid()) { se->newQObject(svCurrentPage, m_renderPageItem); } else { svCurrentPage = se->newQObject(m_renderPageItem); se->globalObject().setProperty("currentPage", svCurrentPage); } #endif - - } } void ReportRender::initVariables() { - m_datasources->setReportVariable("#PAGE",1); - m_datasources->setReportVariable("#PAGE_COUNT",0); - m_datasources->setReportVariable("#IS_LAST_PAGEFOOTER",false); - m_datasources->setReportVariable("#IS_FIRST_PAGEFOOTER",false); + m_datasources->setReportVariable("#PAGE", 1); + m_datasources->setReportVariable("#PAGE_COUNT", 0); + m_datasources->setReportVariable("#IS_LAST_PAGEFOOTER", false); + m_datasources->setReportVariable("#IS_FIRST_PAGEFOOTER", false); } -void ReportRender::clearPageMap() +void ReportRender::clearPageMap() { m_renderedPages.clear(); } + +bool checkContentItem(ContentItemDesignIntf* item, DataSourceManager* datasources) { - m_renderedPages.clear(); -} - - -bool checkContentItem(ContentItemDesignIntf* item, DataSourceManager* datasources){ QString content = item->content(); - foreach(QString functionName, datasources->groupFunctionNames()){ + foreach (QString functionName, datasources->groupFunctionNames()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getGroupFunctionRegEx(functionName); - if(content.indexOf(rx)>=0){ + if (content.indexOf(rx) >= 0) { return true; } #else QRegExp rx(QString(Const::GROUP_FUNCTION_RX).arg(functionName)); - if (rx.indexIn(content)>=0){ + if (rx.indexIn(content) >= 0) { return true; } #endif @@ -381,143 +401,173 @@ bool checkContentItem(ContentItemDesignIntf* item, DataSourceManager* datasource return false; } -bool ReportRender::containsGroupFunctions(BaseDesignIntf *container){ - if (container){ +bool ReportRender::containsGroupFunctions(BaseDesignIntf* container) +{ + if (container) { foreach (BaseDesignIntf* item, container->childBaseItems()) { ContentItemDesignIntf* contentItem = dynamic_cast(item); - if (contentItem){ - if (checkContentItem(contentItem, m_datasources)) return true; + if (contentItem) { + if (checkContentItem(contentItem, m_datasources)) + return true; } else { - if (containsGroupFunctions(item)) return true; + if (containsGroupFunctions(item)) + return true; } } } return false; } -void ReportRender::extractGroupFuntionsFromItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band){ +void ReportRender::extractGroupFuntionsFromItem(ContentItemDesignIntf* contentItem, + BandDesignIntf* band) +{ #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) - if ( contentItem && contentItem->content().contains(getScriptRegEx())){ - foreach(const QString &functionName, m_datasources->groupFunctionNames()){ + if (contentItem && contentItem->content().contains(getScriptRegEx())) { + foreach (const QString& functionName, m_datasources->groupFunctionNames()) { QRegularExpression rx = getGroupFunctionRegEx(functionName); QRegularExpression rxName = getGroupFunctionNameRegEx(functionName); QRegularExpressionMatch match = rx.match(contentItem->content()); - if (match.hasMatch()){ + if (match.hasMatch()) { QRegularExpressionMatchIterator iter = rx.globalMatch(contentItem->content()); - while(iter.hasNext()){ + while (iter.hasNext()) { match = iter.next(); QVector captures = normalizeCaptures(match); - if (captures.size() >= 3){ - int dsIndex = captures.size() == 3 ? Const::DATASOURCE_INDEX - 1 : Const::DATASOURCE_INDEX; - BandDesignIntf* dataBand = m_patternPageItem->bandByName(captures.at(dsIndex)); - if (dataBand){ + if (captures.size() >= 3) { + int dsIndex = captures.size() == 3 ? Const::DATASOURCE_INDEX - 1 + : Const::DATASOURCE_INDEX; + BandDesignIntf* dataBand + = m_patternPageItem->bandByName(captures.at(dsIndex)); + if (dataBand) { GroupFunction* gf = datasources()->addGroupFunction( - functionName, captures.at(Const::VALUE_INDEX), band->objectName(), dataBand->objectName() - ); - if (gf){ - connect(dataBand, SIGNAL(bandRendered(BandDesignIntf*)), - gf, SLOT(slotBandRendered(BandDesignIntf*))); - connect(dataBand, SIGNAL(bandReRendered(BandDesignIntf*, BandDesignIntf*)), - gf, SLOT(slotBandReRendered(BandDesignIntf*, BandDesignIntf*))); + functionName, captures.at(Const::VALUE_INDEX), band->objectName(), + dataBand->objectName()); + if (gf) { + connect(dataBand, SIGNAL(bandRendered(BandDesignIntf*)), gf, + SLOT(slotBandRendered(BandDesignIntf*))); + connect(dataBand, + SIGNAL(bandReRendered(BandDesignIntf*, BandDesignIntf*)), + gf, + SLOT(slotBandReRendered(BandDesignIntf*, BandDesignIntf*))); } } else { GroupFunction* gf = datasources()->addGroupFunction( - functionName, captures.at(Const::VALUE_INDEX), band->objectName(), captures.at(dsIndex) - ); - gf->setInvalid(tr("Databand \"%1\" not found").arg(captures.at(dsIndex))); + functionName, captures.at(Const::VALUE_INDEX), band->objectName(), + captures.at(dsIndex)); + gf->setInvalid( + tr("Databand \"%1\" not found").arg(captures.at(dsIndex))); } } } - } else if (contentItem->content().indexOf(rxName)>=0){ + } else if (contentItem->content().indexOf(rxName) >= 0) { match = rxName.match(contentItem->content()); - GroupFunction* gf = datasources()->addGroupFunction(functionName, match.captured(1), band->objectName(), ""); + GroupFunction* gf = datasources()->addGroupFunction(functionName, match.captured(1), + band->objectName(), ""); gf->setInvalid(tr("Wrong using function %1").arg(functionName)); } } } #else - if ( contentItem && contentItem->content().contains(QRegExp("\\$S\\s*\\{.*\\}"))){ - foreach(const QString &functionName, m_datasources->groupFunctionNames()){ + if (contentItem && contentItem->content().contains(QRegExp("\\$S\\s*\\{.*\\}"))) { + foreach (const QString& functionName, m_datasources->groupFunctionNames()) { QRegExp rx(QString(Const::GROUP_FUNCTION_RX).arg(functionName)); rx.setMinimal(true); QRegExp rxName(QString(Const::GROUP_FUNCTION_NAME_RX).arg(functionName)); rxName.setMinimal(true); - if (rx.indexIn(contentItem->content())>=0){ + if (rx.indexIn(contentItem->content()) >= 0) { int pos = 0; - while ( (pos = rx.indexIn(contentItem->content(),pos)) != -1){ + while ((pos = rx.indexIn(contentItem->content(), pos)) != -1) { QVector captures = normalizeCaptures(rx); - if (captures.size()>=3){ - int dsIndex = captures.size() == 3 ? Const::DATASOURCE_INDEX - 1 : Const::DATASOURCE_INDEX; - BandDesignIntf* dataBand = m_patternPageItem->bandByName(captures.at(dsIndex)); - if (dataBand){ - GroupFunction* gf = datasources()->addGroupFunction(functionName,captures.at(Const::VALUE_INDEX),band->objectName(),dataBand->objectName()); - if (gf){ - connect(dataBand, SIGNAL(bandRendered(BandDesignIntf*)), - gf, SLOT(slotBandRendered(BandDesignIntf*))); - connect(dataBand, SIGNAL(bandReRendered(BandDesignIntf*, BandDesignIntf*)), - gf, SLOT(slotBandReRendered(BandDesignIntf*, BandDesignIntf*))); + if (captures.size() >= 3) { + int dsIndex = captures.size() == 3 ? Const::DATASOURCE_INDEX - 1 + : Const::DATASOURCE_INDEX; + BandDesignIntf* dataBand + = m_patternPageItem->bandByName(captures.at(dsIndex)); + if (dataBand) { + GroupFunction* gf = datasources()->addGroupFunction( + functionName, captures.at(Const::VALUE_INDEX), band->objectName(), + dataBand->objectName()); + if (gf) { + connect(dataBand, SIGNAL(bandRendered(BandDesignIntf*)), gf, + SLOT(slotBandRendered(BandDesignIntf*))); + connect(dataBand, + SIGNAL(bandReRendered(BandDesignIntf*, BandDesignIntf*)), + gf, + SLOT(slotBandReRendered(BandDesignIntf*, BandDesignIntf*))); } } else { - GroupFunction* gf = datasources()->addGroupFunction(functionName,captures.at(Const::VALUE_INDEX),band->objectName(),captures.at(dsIndex)); - gf->setInvalid(tr("Databand \"%1\" not found").arg(captures.at(dsIndex))); + GroupFunction* gf = datasources()->addGroupFunction( + functionName, captures.at(Const::VALUE_INDEX), band->objectName(), + captures.at(dsIndex)); + gf->setInvalid( + tr("Databand \"%1\" not found").arg(captures.at(dsIndex))); } } pos += rx.matchedLength(); } - } else if (rxName.indexIn(contentItem->content())>=0){ - GroupFunction* gf = datasources()->addGroupFunction(functionName,rxName.cap(1),band->objectName(),""); + } else if (rxName.indexIn(contentItem->content()) >= 0) { + GroupFunction* gf = datasources()->addGroupFunction(functionName, rxName.cap(1), + band->objectName(), ""); gf->setInvalid(tr("Wrong using function %1").arg(functionName)); } } - } + } #endif } -void ReportRender::extractGroupFunctionsFromContainer(BaseDesignIntf* baseItem, BandDesignIntf* band){ - if (baseItem){ +void ReportRender::extractGroupFunctionsFromContainer(BaseDesignIntf* baseItem, + BandDesignIntf* band) +{ + if (baseItem) { foreach (BaseDesignIntf* item, baseItem->childBaseItems()) { ContentItemDesignIntf* contentItem = dynamic_cast(item); - if (contentItem) extractGroupFuntionsFromItem(contentItem, band); - else extractGroupFunctionsFromContainer(item, band); + if (contentItem) + extractGroupFuntionsFromItem(contentItem, band); + else + extractGroupFunctionsFromContainer(item, band); } } } -void ReportRender::extractGroupFunctions(BandDesignIntf *band) +void ReportRender::extractGroupFunctions(BandDesignIntf* band) { extractGroupFunctionsFromContainer(band, band); } -void ReportRender::replaceGroupFunctionsInItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band){ - if (contentItem){ - if (m_groupfunctionItems.contains(contentItem->patternName())){ +void ReportRender::replaceGroupFunctionsInItem(ContentItemDesignIntf* contentItem, + BandDesignIntf* band) +{ + if (contentItem) { + if (m_groupfunctionItems.contains(contentItem->patternName())) { QString content = contentItem->content(); - foreach(QString functionName, m_groupfunctionItems.value(contentItem->patternName())){ + foreach (QString functionName, m_groupfunctionItems.value(contentItem->patternName())) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 1) QRegularExpression rx = getGroupFunctionRegEx(functionName); QRegularExpressionMatch match = rx.match(content); - if (match.capturedStart() != -1){ + if (match.capturedStart() != -1) { int pos = 0; - while ( (pos = match.capturedStart()) != -1 ){ + while ((pos = match.capturedStart()) != -1) { QVector captures = normalizeCaptures(match); - if (captures.size() >= 3){ - QString expressionIndex = datasources()->putGroupFunctionsExpressions(captures.at(Const::VALUE_INDEX)); - if (captures.size()<5){ - content.replace(captures.at(0), QString("%1(%2,%3)") - .arg(functionName).arg('"'+expressionIndex+'"').arg('"'+band->objectName()+'"')); + if (captures.size() >= 3) { + QString expressionIndex = datasources()->putGroupFunctionsExpressions( + captures.at(Const::VALUE_INDEX)); + if (captures.size() < 5) { + content.replace(captures.at(0), + QString("%1(%2,%3)") + .arg(functionName) + .arg('"' + expressionIndex + '"') + .arg('"' + band->objectName() + '"')); } else { - content.replace(captures.at(0), QString("%1(%2,%3,%4)").arg( - functionName, - '"'+expressionIndex+'"', - '"'+band->objectName()+'"', - captures.at(4) - )); + content.replace(captures.at(0), + QString("%1(%2,%3,%4)") + .arg(functionName, '"' + expressionIndex + '"', + '"' + band->objectName() + '"', + captures.at(4))); } } match = rx.match(content, pos + match.capturedLength()); @@ -526,21 +576,25 @@ void ReportRender::replaceGroupFunctionsInItem(ContentItemDesignIntf* contentIte #else QRegExp rx(QString(Const::GROUP_FUNCTION_RX).arg(functionName)); rx.setMinimal(true); - if (rx.indexIn(content)>=0){ + if (rx.indexIn(content) >= 0) { int pos = 0; - while ( (pos = rx.indexIn(content,pos))!= -1 ){ + while ((pos = rx.indexIn(content, pos)) != -1) { QVector captures = normalizeCaptures(rx); - if (captures.size() >= 3){ - QString expressionIndex = datasources()->putGroupFunctionsExpressions(captures.at(Const::VALUE_INDEX)); - if (captures.size()<5){ - content.replace(captures.at(0),QString("%1(%2,%3)").arg(functionName).arg('"'+expressionIndex+'"').arg('"'+band->objectName()+'"')); + if (captures.size() >= 3) { + QString expressionIndex = datasources()->putGroupFunctionsExpressions( + captures.at(Const::VALUE_INDEX)); + if (captures.size() < 5) { + content.replace(captures.at(0), + QString("%1(%2,%3)") + .arg(functionName) + .arg('"' + expressionIndex + '"') + .arg('"' + band->objectName() + '"')); } else { - content.replace(captures.at(0),QString("%1(%2,%3,%4)").arg( - functionName, - '"'+expressionIndex+'"', - '"'+band->objectName()+'"', - captures.at(4) - )); + content.replace(captures.at(0), + QString("%1(%2,%3,%4)") + .arg(functionName, '"' + expressionIndex + '"', + '"' + band->objectName() + '"', + captures.at(4))); } } pos += rx.matchedLength(); @@ -556,49 +610,58 @@ void ReportRender::replaceGroupFunctionsInItem(ContentItemDesignIntf* contentIte void ReportRender::replaceGroupFunctionsInContainer(BaseDesignIntf* baseItem, BandDesignIntf* band) { - if (baseItem){ - foreach(BaseDesignIntf* item, baseItem->childBaseItems()){ + if (baseItem) { + foreach (BaseDesignIntf* item, baseItem->childBaseItems()) { ContentItemDesignIntf* contentItem = dynamic_cast(item); - if (contentItem) replaceGroupFunctionsInItem(contentItem, band); - else replaceGroupFunctionsInContainer(item, band); + if (contentItem) + replaceGroupFunctionsInItem(contentItem, band); + else + replaceGroupFunctionsInContainer(item, band); } } } -void ReportRender::replaceGroupsFunction(BandDesignIntf *band) +void ReportRender::replaceGroupsFunction(BandDesignIntf* band) { replaceGroupFunctionsInContainer(band, band); } -QColor ReportRender::makeBackgroundColor(BandDesignIntf* band){ - if (band->useAlternateBackgroundColor()){ - return datasources()->variable(QLatin1String("line_") + band->objectName().toLower()).toInt() %2 == 0 ? - band->backgroundColor() : - band->alternateBackgroundColor(); +QColor ReportRender::makeBackgroundColor(BandDesignIntf* band) +{ + if (band->useAlternateBackgroundColor()) { + return datasources() + ->variable(QLatin1String("line_") + band->objectName().toLower()) + .toInt() + % 2 + == 0 + ? band->backgroundColor() + : band->alternateBackgroundColor(); } return band->backgroundColor(); } -BandDesignIntf* ReportRender::renderBand(BandDesignIntf *patternBand, BandDesignIntf* bandData, ReportRender::DataRenderMode mode, bool isLast) +BandDesignIntf* ReportRender::renderBand(BandDesignIntf* patternBand, BandDesignIntf* bandData, + ReportRender::DataRenderMode mode, bool isLast) { QCoreApplication::processEvents(); bool bandIsSliced = false; - if (patternBand){ + if (patternBand) { if (patternBand->isHeader()) m_lastRenderedHeader = patternBand; BandDesignIntf* bandClone = 0; - if (bandData){ - bandClone = bandData; + if (bandData) { + bandClone = bandData; } else { bandClone = renderData(patternBand); } - if (isLast) bandClone->setBottomSpace(1); + if (isLast) + bandClone->setBottomSpace(1); - if (mode == ForcedStartPage){ + if (mode == ForcedStartPage) { savePage(); startNewPage(); } @@ -610,48 +673,51 @@ BandDesignIntf* ReportRender::renderBand(BandDesignIntf *patternBand, BandDesign patternBand->emitBandRendered(bandClone); m_scriptEngineContext->setCurrentBand(bandClone); - if ( isLast && bandClone->keepFooterTogether() && bandClone->sliceLastRow() ){ - if (m_maxHeightByColumn[m_currentColumn] < (bandClone->height()+m_reportFooterHeight)) - m_maxHeightByColumn[m_currentColumn] -= ((m_maxHeightByColumn[m_currentColumn]-bandClone->height())+(bandClone->height()*calcSlicePercent(bandClone->height()))); - } + if (isLast && bandClone->keepFooterTogether() && bandClone->sliceLastRow()) { + if (m_maxHeightByColumn[m_currentColumn] < (bandClone->height() + m_reportFooterHeight)) + m_maxHeightByColumn[m_currentColumn] + -= ((m_maxHeightByColumn[m_currentColumn] - bandClone->height()) + + (bandClone->height() * calcSlicePercent(bandClone->height()))); + } - if (!bandClone->isEmpty() || patternBand->printIfEmpty()){ - if (!registerBand(bandClone)){ + if (!bandClone->isEmpty() || patternBand->printIfEmpty()) { + if (!registerBand(bandClone)) { if (patternBand && patternBand->isHeader() && patternBand->reprintOnEachPage()) m_reprintableBands.removeOne(patternBand); - if (bandClone->canBeSplitted(m_maxHeightByColumn[m_currentColumn])){ + if (bandClone->canBeSplitted(m_maxHeightByColumn[m_currentColumn])) { bandClone = sliceBand(bandClone, patternBand, isLast); bandIsSliced = true; } else { - qreal percent = (bandClone->height()-m_maxHeightByColumn[m_currentColumn])/(bandClone->height()/100); - if (bandClone->maxScalePercent()>=percent){ - if (percentmaxScalePercent()){ + qreal percent = (bandClone->height() - m_maxHeightByColumn[m_currentColumn]) + / (bandClone->height() / 100); + if (bandClone->maxScalePercent() >= percent) { + if (percent < bandClone->maxScalePercent()) { percent += 2; - bandClone->setScale((100-percent)/100); - BandDesignIntf* upperPart = dynamic_cast(bandClone->cloneUpperPart(m_maxHeightByColumn[m_currentColumn])); + bandClone->setScale((100 - percent) / 100); + BandDesignIntf* upperPart = dynamic_cast( + bandClone->cloneUpperPart(m_maxHeightByColumn[m_currentColumn])); registerBand(upperPart); delete bandClone; bandClone = NULL; } } else { - if (mode==StartNewPageAsNeeded){ - if (bandClone->columnsCount()>1 && - (bandClone->columnsFillDirection()==BandDesignIntf::Vertical || - bandClone->columnsFillDirection()==BandDesignIntf::VerticalUniform)) - { + if (mode == StartNewPageAsNeeded) { + if (bandClone->columnsCount() > 1 + && (bandClone->columnsFillDirection() == BandDesignIntf::Vertical + || bandClone->columnsFillDirection() + == BandDesignIntf::VerticalUniform)) { startNewColumn(); - if (patternBand->bandHeader() && - patternBand->bandHeader()->columnsCount()>1 && - !m_lostHeadersMoved && - patternBand->bandNestingLevel() == 0 - ){ + if (patternBand->bandHeader() + && patternBand->bandHeader()->columnsCount() > 1 + && !m_lostHeadersMoved + && patternBand->bandNestingLevel() == 0) { renderBand(patternBand->bandHeader(), 0, mode); } } else { savePage(); startNewPage(); - if (!bandIsSliced){ + if (!bandIsSliced) { BandDesignIntf* t = renderData(patternBand, false); t->copyBandAttributes(bandClone); patternBand->emitBandReRendered(bandClone, t); @@ -660,7 +726,9 @@ BandDesignIntf* ReportRender::renderBand(BandDesignIntf *patternBand, BandDesign } } if (!registerBand(bandClone)) { - BandDesignIntf* upperPart = dynamic_cast(bandClone->cloneUpperPart(m_maxHeightByColumn[m_currentColumn])); + BandDesignIntf* upperPart + = dynamic_cast(bandClone->cloneUpperPart( + m_maxHeightByColumn[m_currentColumn])); registerBand(upperPart); patternBand->emitBandReRendered(bandClone, upperPart); delete bandClone; @@ -678,7 +746,7 @@ BandDesignIntf* ReportRender::renderBand(BandDesignIntf *patternBand, BandDesign return 0; } - if (patternBand->isFooter()){ + if (patternBand->isFooter()) { datasources()->clearGroupFunctionValues(patternBand->objectName()); } @@ -688,26 +756,27 @@ BandDesignIntf* ReportRender::renderBand(BandDesignIntf *patternBand, BandDesign return 0; } -void ReportRender::renderDataBand(BandDesignIntf *dataBand) +void ReportRender::renderDataBand(BandDesignIntf* dataBand) { - if (dataBand == NULL ) + if (dataBand == NULL) return; IDataSource* bandDatasource = 0; m_lastRenderedFooter = 0; if (!dataBand->datasourceName().isEmpty()) - bandDatasource = datasources()->dataSource(dataBand->datasourceName()); + bandDatasource = datasources()->dataSource(dataBand->datasourceName()); BandDesignIntf* header = dataBand->bandHeader(); BandDesignIntf* footer = dataBand->bandFooter(); - if (header && header->printAlways()) renderDataHeader(header); + if (header && header->printAlways()) + renderDataHeader(header); - if(bandDatasource && !bandDatasource->eof() && !m_renderCanceled){ + if (bandDatasource && !bandDatasource->eof() && !m_renderCanceled) { - QString varName = QLatin1String("line_")+dataBand->objectName().toLower(); - datasources()->setReportVariable(varName,1); + QString varName = QLatin1String("line_") + dataBand->objectName().toLower(); + datasources()->setReportVariable(varName, 1); if (header && header->reprintOnEachPage()) m_reprintableBands.append(dataBand->bandHeader()); @@ -719,22 +788,22 @@ void ReportRender::renderDataBand(BandDesignIntf *dataBand) bool firstTime = true; - - while(!bandDatasource->eof() && !m_renderCanceled){ + while (!bandDatasource->eof() && !m_renderCanceled) { datasources()->updateChildrenData(dataBand->datasourceName()); BandDesignIntf* rawData = renderData(dataBand); - if (!rawData->isEmpty() || dataBand->printIfEmpty()){ + if (!rawData->isEmpty() || dataBand->printIfEmpty()) { - if ((firstTime && dataBand->startFromNewPage()) || - (!firstTime && dataBand->startNewPage())) { + if ((firstTime && dataBand->startFromNewPage()) + || (!firstTime && dataBand->startNewPage())) { savePage(); startNewPage(); } - if (dataBand->tryToKeepTogether()) openDataGroup(dataBand); + if (dataBand->tryToKeepTogether()) + openDataGroup(dataBand); if (dataBand->keepFooterTogether() && !bandDatasource->hasNext()) openFooterGroup(dataBand); @@ -747,47 +816,47 @@ void ReportRender::renderDataBand(BandDesignIntf *dataBand) renderBand(dataBand, rawData, StartNewPageAsNeeded, !bandDatasource->hasNext()); m_newPageStarted = false; renderChildBands(dataBand); - } bandDatasource->next(); - datasources()->setReportVariable(varName,datasources()->variable(varName).toInt()+1); + datasources()->setReportVariable(varName, datasources()->variable(varName).toInt() + 1); - QList bandList; - QList childList; + QList bandList; + QList childList; bandList = dataBand->childrenByType(BandDesignIntf::GroupHeader); - while (bandList.size() > 0) - { + while (bandList.size() > 0) { childList.clear(); - foreach (BandDesignIntf* band, bandList) - { + foreach (BandDesignIntf* band, bandList) { childList.append(band->childrenByType(BandDesignIntf::GroupHeader)); - QString groupLineVar = QLatin1String("line_")+band->objectName().toLower(); + QString groupLineVar = QLatin1String("line_") + band->objectName().toLower(); if (datasources()->containsVariable(groupLineVar)) - datasources()->setReportVariable(groupLineVar,datasources()->variable(groupLineVar).toInt()+1); + datasources()->setReportVariable( + groupLineVar, datasources()->variable(groupLineVar).toInt() + 1); } bandList = childList; } renderGroupHeader(dataBand, bandDatasource, false); - if (dataBand->tryToKeepTogether()) closeDataGroup(dataBand); + if (dataBand->tryToKeepTogether()) + closeDataGroup(dataBand); firstTime = false; } if (!dataBand->keepFooterTogether()) - m_reprintableBands.removeOne(header); - if (header) recalcIfNeeded(header); + m_reprintableBands.removeOne(header); + if (header) + recalcIfNeeded(header); bool didGoBack = !bandDatasource->eof() && bandDatasource->prior(); renderGroupFooterByHeader(dataBand); - if (didGoBack){ + if (didGoBack) { bandDatasource->next(); } - if (footer && !footer->printAlways()){ + if (footer && !footer->printAlways()) { renderBand(footer, 0, StartNewPageAsNeeded); if (dataBand->keepFooterTogether()) m_reprintableBands.removeOne(dataBand); @@ -795,52 +864,54 @@ void ReportRender::renderDataBand(BandDesignIntf *dataBand) datasources()->deleteVariable(varName); - } else if (bandDatasource==0) { + } else if (bandDatasource == 0) { renderBand(dataBand, 0, StartNewPageAsNeeded); } - if (footer && footer->printAlways()){ + if (footer && footer->printAlways()) { renderBand(footer, 0, StartNewPageAsNeeded); if (dataBand->keepFooterTogether()) m_reprintableBands.removeOne(dataBand); } } -void ReportRender::renderPageHeader(PageItemDesignIntf *patternPage) +void ReportRender::renderPageHeader(PageItemDesignIntf* patternPage) { BandDesignIntf* band = patternPage->bandByType(BandDesignIntf::PageHeader); - if (band){ - if (m_datasources->variable("#PAGE").toInt()!=1 || - band->property("printOnFirstPage").toBool() - ) + if (band) { + if (m_datasources->variable("#PAGE").toInt() != 1 + || band->property("printOnFirstPage").toBool()) renderBand(band, 0); } } -void ReportRender::renderReportHeader(PageItemDesignIntf *patternPage, PageRenderStage stage) +void ReportRender::renderReportHeader(PageItemDesignIntf* patternPage, PageRenderStage stage) { BandDesignIntf* band = patternPage->bandByType(BandDesignIntf::ReportHeader); BandDesignIntf* resBand = 0; - if (band){ - if (band->property("printBeforePageHeader").toBool() && stage == BeforePageHeader ) + if (band) { + if (band->property("printBeforePageHeader").toBool() && stage == BeforePageHeader) resBand = renderBand(band, 0, StartNewPageAsNeeded); - if (!band->property("printBeforePageHeader").toBool() && stage == AfterPageHeader ) + if (!band->property("printBeforePageHeader").toBool() && stage == AfterPageHeader) resBand = renderBand(band, 0, StartNewPageAsNeeded); - if (resBand && containsGroupFunctions(band)) m_recalcBands.append(resBand); + if (resBand && containsGroupFunctions(band)) + m_recalcBands.append(resBand); } } -void ReportRender::renderPageFooter(PageItemDesignIntf *patternPage) +void ReportRender::renderPageFooter(PageItemDesignIntf* patternPage) { BandDesignIntf* band = patternPage->bandByType(BandDesignIntf::PageFooter); - if (band){ - BandDesignIntf* bandClone = dynamic_cast(band->cloneItem(PreviewMode, m_renderPageItem, m_renderPageItem)); + if (band) { + BandDesignIntf* bandClone = dynamic_cast( + band->cloneItem(PreviewMode, m_renderPageItem, m_renderPageItem)); replaceGroupsFunction(bandClone); bandClone->updateItemSize(m_datasources); - bandClone->setItemPos(m_renderPageItem->pageRect().x(),m_renderPageItem->pageRect().bottom()-bandClone->height()); + bandClone->setItemPos(m_renderPageItem->pageRect().x(), + m_renderPageItem->pageRect().bottom() - bandClone->height()); bandClone->setHeight(m_pageFooterHeight); - for(int i=0;isetPageFooter(bandClone); registerBand(bandClone); datasources()->clearGroupFunctionValues(band->objectName()); @@ -852,28 +923,27 @@ void ReportRender::renderPageItems(PageItemDesignIntf* patternPage) QList pageItems; foreach (BaseDesignIntf* item, patternPage->childBaseItems()) { ItemDesignIntf* id = dynamic_cast(item); - if (id&&id->itemLocation()==ItemDesignIntf::Page){ - BaseDesignIntf* cloneItem = item->cloneItem(m_renderPageItem->itemMode(), - m_renderPageItem, - m_renderPageItem); + if (id && id->itemLocation() == ItemDesignIntf::Page) { + BaseDesignIntf* cloneItem + = item->cloneItem(m_renderPageItem->itemMode(), m_renderPageItem, m_renderPageItem); pageItems.append(cloneItem); } } m_renderPageItem->restoreLinks(); - m_renderPageItem->updateSubItemsSize(FirstPass,m_datasources); - foreach(BaseDesignIntf* item, pageItems){ + m_renderPageItem->updateSubItemsSize(FirstPass, m_datasources); + foreach (BaseDesignIntf* item, pageItems) { if (!item->isWatermark()) - item->setZValue(item->zValue()-100000); + item->setZValue(item->zValue() - 100000); else - item->setZValue(item->zValue()+100000); + item->setZValue(item->zValue() + 100000); } } -qreal ReportRender::calcPageFooterHeight(PageItemDesignIntf *patternPage) +qreal ReportRender::calcPageFooterHeight(PageItemDesignIntf* patternPage) { BandDesignIntf* band = patternPage->bandByType(BandDesignIntf::PageFooter); - if (band){ - if (m_datasources->variable("#PAGE")!=1) + if (band) { + if (m_datasources->variable("#PAGE") != 1) return band->height(); else if (band->property("printOnFirstPage").toBool()) return band->height(); @@ -881,48 +951,50 @@ qreal ReportRender::calcPageFooterHeight(PageItemDesignIntf *patternPage) return 0; } -void ReportRender::renderChildHeader(BandDesignIntf *parent, BandPrintMode printMode) +void ReportRender::renderChildHeader(BandDesignIntf* parent, BandPrintMode printMode) { - foreach(BandDesignIntf* band,parent->childrenByType(BandDesignIntf::SubDetailHeader)){ - bool printAlways=false; - if (band->metaObject()->indexOfProperty("printAlways")>0){ - printAlways=band->property("printAlways").toBool(); + foreach (BandDesignIntf* band, parent->childrenByType(BandDesignIntf::SubDetailHeader)) { + bool printAlways = false; + if (band->metaObject()->indexOfProperty("printAlways") > 0) { + printAlways = band->property("printAlways").toBool(); } if (printAlways == (printMode == PrintAlwaysPrintable)) renderBand(band, 0, StartNewPageAsNeeded); } } -void ReportRender::renderChildFooter(BandDesignIntf *parent, BandPrintMode printMode) +void ReportRender::renderChildFooter(BandDesignIntf* parent, BandPrintMode printMode) { - foreach(BandDesignIntf* band,parent->childrenByType(BandDesignIntf::SubDetailFooter)){ - bool printAlways=false; - if (band->metaObject()->indexOfProperty("printAlways")>0){ - printAlways=band->property("printAlways").toBool(); + foreach (BandDesignIntf* band, parent->childrenByType(BandDesignIntf::SubDetailFooter)) { + bool printAlways = false; + if (band->metaObject()->indexOfProperty("printAlways") > 0) { + printAlways = band->property("printAlways").toBool(); } - if ( (band != m_lastRenderedFooter) && (printAlways == (printMode == PrintAlwaysPrintable)) ) + if ((band != m_lastRenderedFooter) && (printAlways == (printMode == PrintAlwaysPrintable))) renderBand(band, 0, StartNewPageAsNeeded); } } -void ReportRender::renderChildBands(BandDesignIntf *parentBand) +void ReportRender::renderChildBands(BandDesignIntf* parentBand) { - foreach(BandDesignIntf* band,parentBand->childrenByType(BandDesignIntf::SubDetailBand)){ + foreach (BandDesignIntf* band, parentBand->childrenByType(BandDesignIntf::SubDetailBand)) { IDataSource* ds = 0; if (!band->datasourceName().isEmpty()) ds = m_datasources->dataSource(band->datasourceName()); - if (ds) ds->first(); + if (ds) + ds->first(); renderDataBand(band); closeFooterGroup(band); } } -BandDesignIntf* ReportRender::findRecalcableBand(BandDesignIntf* patternBand){ +BandDesignIntf* ReportRender::findRecalcableBand(BandDesignIntf* patternBand) +{ QList::iterator it = m_recalcBands.begin(); - for (;it !=m_recalcBands.end() ;++it){ - if ((*it)->patternItem() == patternBand){ + for (; it != m_recalcBands.end(); ++it) { + if ((*it)->patternItem() == patternBand) { BandDesignIntf* result = (*it); m_recalcBands.erase(it); return result; @@ -931,19 +1003,22 @@ BandDesignIntf* ReportRender::findRecalcableBand(BandDesignIntf* patternBand){ return 0; } -void restoreItemsWithGroupFunctions(BaseDesignIntf* container, DataSourceManager* datasources){ - foreach(BaseDesignIntf* bi, container->childBaseItems()){ +void restoreItemsWithGroupFunctions(BaseDesignIntf* container, DataSourceManager* datasources) +{ + foreach (BaseDesignIntf* bi, container->childBaseItems()) { ContentItemDesignIntf* pci = dynamic_cast(bi->patternItem()); - if (pci && checkContentItem(pci, datasources)){ + if (pci && checkContentItem(pci, datasources)) { ContentItemDesignIntf* ci = dynamic_cast(bi); ci->setContent(pci->content()); - } else restoreItemsWithGroupFunctions(bi, datasources); + } else + restoreItemsWithGroupFunctions(bi, datasources); } } -void ReportRender::recalcIfNeeded(BandDesignIntf* band){ +void ReportRender::recalcIfNeeded(BandDesignIntf* band) +{ BandDesignIntf* recalcBand = findRecalcableBand(band); - if (recalcBand){ + if (recalcBand) { QString bandName = recalcBand->objectName(); restoreItemsWithGroupFunctions(recalcBand, m_datasources); recalcBand->setObjectName(recalcBand->patternItem()->objectName()); @@ -954,7 +1029,7 @@ void ReportRender::recalcIfNeeded(BandDesignIntf* band){ } } -void ReportRender::renderDataHeader(BandDesignIntf *header) +void ReportRender::renderDataHeader(BandDesignIntf* header) { recalcIfNeeded(header); BandDesignIntf* renderedHeader = renderBand(header, 0, StartNewPageAsNeeded); @@ -962,31 +1037,33 @@ void ReportRender::renderDataHeader(BandDesignIntf *header) m_recalcBands.append(renderedHeader); } -void ReportRender::renderGroupHeader(BandDesignIntf *parentBand, IDataSource* dataSource, bool firstTime) +void ReportRender::renderGroupHeader(BandDesignIntf* parentBand, IDataSource* dataSource, + bool firstTime) { - foreach(BandDesignIntf* band,parentBand->childrenByType(BandDesignIntf::GroupHeader)){ + foreach (BandDesignIntf* band, parentBand->childrenByType(BandDesignIntf::GroupHeader)) { IGroupBand* gb = dynamic_cast(band); - if (gb&&gb->isNeedToClose(datasources())){ - if (band->childBands().count()>0){ + if (gb && gb->isNeedToClose(datasources())) { + if (band->childBands().count() > 0) { bool didGoBack = !dataSource->eof() && dataSource->prior(); renderGroupFooterByHeader(band); - if (didGoBack){ + if (didGoBack) { dataSource->next(); } } closeDataGroup(band); } - if (gb && !gb->isStarted()){ - if (band->reprintOnEachPage()){ + if (gb && !gb->isStarted()) { + if (band->reprintOnEachPage()) { m_reprintableBands.append(band); } gb->startGroup(m_datasources); openDataGroup(band); BandDesignIntf* renderedHeader = 0; - if (!firstTime && gb->startNewPage() && !m_newPageStarted){ - if (gb->resetPageNumber()) resetPageNumber(BandReset); - if (band->reprintOnEachPage()){ + if (!firstTime && gb->startNewPage() && !m_newPageStarted) { + if (gb->resetPageNumber()) + resetPageNumber(BandReset); + if (band->reprintOnEachPage()) { savePage(); startNewPage(); } else { @@ -1003,22 +1080,24 @@ void ReportRender::renderGroupHeader(BandDesignIntf *parentBand, IDataSource* da } } -void ReportRender::renderGroupFooterByHeader(BandDesignIntf* groupHeader){ - if (groupHeader->reprintOnEachPage()) m_reprintableBands.removeOne(groupHeader); - foreach (BandDesignIntf* header, groupHeader->childrenByType(BandDesignIntf::GroupHeader)){ +void ReportRender::renderGroupFooterByHeader(BandDesignIntf* groupHeader) +{ + if (groupHeader->reprintOnEachPage()) + m_reprintableBands.removeOne(groupHeader); + foreach (BandDesignIntf* header, groupHeader->childrenByType(BandDesignIntf::GroupHeader)) { renderGroupFooterByHeader(header); } - foreach (BandDesignIntf* footer, groupHeader->childrenByType(BandDesignIntf::GroupFooter)){ + foreach (BandDesignIntf* footer, groupHeader->childrenByType(BandDesignIntf::GroupFooter)) { renderBand(footer, 0, StartNewPageAsNeeded); } closeDataGroup(groupHeader); } -void ReportRender::renderGroupFooter(BandDesignIntf *parentBand) +void ReportRender::renderGroupFooter(BandDesignIntf* parentBand) { - foreach(BandDesignIntf* band,parentBand->childrenByType(BandDesignIntf::GroupHeader)){ + foreach (BandDesignIntf* band, parentBand->childrenByType(BandDesignIntf::GroupHeader)) { IGroupBand* gb = dynamic_cast(band); - if (gb && gb->isStarted()){ + if (gb && gb->isStarted()) { renderGroupFooterByHeader(band); } } @@ -1027,26 +1106,30 @@ void ReportRender::renderGroupFooter(BandDesignIntf *parentBand) void ReportRender::initGroups() { m_datasources->clearGroupFunction(); - foreach(BandDesignIntf* band, m_patternPageItem->childBands()){ - if (band->isFooter()) extractGroupFunctions(band); - if (band->isHeader()){ + foreach (BandDesignIntf* band, m_patternPageItem->childBands()) { + if (band->isFooter()) + extractGroupFunctions(band); + if (band->isHeader()) { IGroupBand* gb = dynamic_cast(band); - if (gb) gb->closeGroup(); + if (gb) + gb->closeGroup(); extractGroupFunctions(band); } } } -void ReportRender::popPageFooterGroupValues(BandDesignIntf *dataBand) +void ReportRender::popPageFooterGroupValues(BandDesignIntf* dataBand) { BandDesignIntf* pageFooter = m_patternPageItem->bandByType(BandDesignIntf::PageFooter); - if (pageFooter){ - foreach(GroupFunction* gf, datasources()->groupFunctionsByBand(pageFooter->objectName())){ - if ((gf->dataBandName()==dataBand->objectName())){ + if (pageFooter) { + foreach (GroupFunction* gf, datasources()->groupFunctionsByBand(pageFooter->objectName())) { + if ((gf->dataBandName() == dataBand->objectName())) { // FIXME Probably coincidence Field and Variables - if ((!m_popupedExpression.contains(dataBand))||(!m_popupedExpression.values(dataBand).contains(gf->data()))){ - m_popupedExpression.insert(dataBand,gf->data()); - m_popupedValues.insert(QString("%1").arg((quintptr)dataBand)+'|'+gf->data(), gf->values()[gf->values().count()-1]); + if ((!m_popupedExpression.contains(dataBand)) + || (!m_popupedExpression.values(dataBand).contains(gf->data()))) { + m_popupedExpression.insert(dataBand, gf->data()); + m_popupedValues.insert(QString("%1").arg((quintptr)dataBand) + '|' + gf->data(), + gf->values()[gf->values().count() - 1]); gf->values().pop_back(); } } @@ -1054,29 +1137,31 @@ void ReportRender::popPageFooterGroupValues(BandDesignIntf *dataBand) } } -void ReportRender::pushPageFooterGroupValues(BandDesignIntf *dataBand) +void ReportRender::pushPageFooterGroupValues(BandDesignIntf* dataBand) { BandDesignIntf* pageFooter = m_patternPageItem->bandByType(BandDesignIntf::PageFooter); - if (pageFooter){ - foreach(GroupFunction* gf, datasources()->groupFunctionsByBand(pageFooter->objectName())){ - if ((gf->dataBandName()==dataBand->objectName())){ + if (pageFooter) { + foreach (GroupFunction* gf, datasources()->groupFunctionsByBand(pageFooter->objectName())) { + if ((gf->dataBandName() == dataBand->objectName())) { // FIXME Probably coincidence Field and Variables - if ((m_popupedExpression.contains(dataBand))&&(m_popupedExpression.values(dataBand).contains(gf->data()))){ - gf->values().push_back(m_popupedValues.value(QString("%1").arg((quintptr)dataBand)+'|'+gf->data())); + if ((m_popupedExpression.contains(dataBand)) + && (m_popupedExpression.values(dataBand).contains(gf->data()))) { + gf->values().push_back(m_popupedValues.value( + QString("%1").arg((quintptr)dataBand) + '|' + gf->data())); } } } } } -void ReportRender::closeGroup(BandDesignIntf *band) +void ReportRender::closeGroup(BandDesignIntf* band) { - QMultiMap< BandDesignIntf*, GroupBandsHolder* >::iterator it; + QMultiMap::iterator it; it = m_childBands.find(band); - while (it!=m_childBands.end()&&it.key()==band){ + while (it != m_childBands.end() && it.key() == band) { GroupBandsHolder* bl = it.value(); - if (bl){ + if (bl) { bl->clear(); delete bl; } @@ -1086,28 +1171,29 @@ void ReportRender::closeGroup(BandDesignIntf *band) m_childBands.remove(band); } -void ReportRender::openDataGroup(BandDesignIntf *band) +void ReportRender::openDataGroup(BandDesignIntf* band) { - m_childBands.insert(band,new GroupBandsHolder(band->tryToKeepTogether())); + m_childBands.insert(band, new GroupBandsHolder(band->tryToKeepTogether())); } -void ReportRender::openFooterGroup(BandDesignIntf *band) +void ReportRender::openFooterGroup(BandDesignIntf* band) { GroupBandsHolder* holder = new GroupBandsHolder(true); holder->setIsFooterGroup(); - m_childBands.insert(band,holder); + m_childBands.insert(band, holder); } -void ReportRender::closeDataGroup(BandDesignIntf *band) +void ReportRender::closeDataGroup(BandDesignIntf* band) { IGroupBand* groupBand = dynamic_cast(band); - if (groupBand){ + if (groupBand) { groupBand->closeGroup(); - if (band->reprintOnEachPage()) m_reprintableBands.removeOne(band); + if (band->reprintOnEachPage()) + m_reprintableBands.removeOne(band); QList::Iterator it = m_reprintableBands.begin(); - while (it != m_reprintableBands.end()){ - if ((*it)->bandIndex()>band->bandIndex()) + while (it != m_reprintableBands.end()) { + if ((*it)->bandIndex() > band->bandIndex()) it = m_reprintableBands.erase(it); else ++it; @@ -1117,33 +1203,36 @@ void ReportRender::closeDataGroup(BandDesignIntf *band) closeGroup(band); } -void ReportRender::closeFooterGroup(BandDesignIntf *band){ - closeGroup(band); -} +void ReportRender::closeFooterGroup(BandDesignIntf* band) { closeGroup(band); } -qreal maxVectorValue(QVector vector){ +qreal maxVectorValue(QVector vector) +{ qreal curValue = 0; foreach (qreal value, vector) { - if (curValue vector){ +qreal minVectorValue(QVector vector) +{ qreal curValue = vector[0]; foreach (qreal value, vector) { - if (curValue>value) curValue=value; + if (curValue > value) + curValue = value; } return curValue; } -void ReportRender::placeBandOnPage(BandDesignIntf* band, int columnIndex){ +void ReportRender::placeBandOnPage(BandDesignIntf* band, int columnIndex) +{ qreal bandPos = m_currentStartDataPos[columnIndex]; m_currentStartDataPos[columnIndex] += band->height(); m_maxHeightByColumn[columnIndex] -= band->height(); - band->setPos(m_renderPageItem->pageRect().x()+band->width()*columnIndex, bandPos); + band->setPos(m_renderPageItem->pageRect().x() + band->width() * columnIndex, bandPos); band->setBandIndex(++m_currentIndex); band->setColumnIndex(columnIndex); @@ -1151,17 +1240,19 @@ void ReportRender::placeBandOnPage(BandDesignIntf* band, int columnIndex){ m_currentColumn = columnIndex; } -bool isMultiColumnHeader(BandDesignIntf* band){ - return ( (band->columnsCount() > 1 ) && - (band->isHeader() && - ((band->bandNestingLevel() == 0) || (band->columnsFillDirection() == BandDesignIntf::Horizontal)))); +bool isMultiColumnHeader(BandDesignIntf* band) +{ + return ((band->columnsCount() > 1) + && (band->isHeader() + && ((band->bandNestingLevel() == 0) + || (band->columnsFillDirection() == BandDesignIntf::Horizontal)))); } -bool ReportRender::registerBand(BandDesignIntf *band, bool registerInChildren) +bool ReportRender::registerBand(BandDesignIntf* band, bool registerInChildren) { - if (band->columnsCount() == 1 && m_maxHeightByColumn.size() > 1 ){ - if (band->bandType() != BandDesignIntf::PageFooter){ + if (band->columnsCount() == 1 && m_maxHeightByColumn.size() > 1) { + if (band->bandType() != BandDesignIntf::PageFooter) { rearrangeColumnsItems(); m_currentColumn = 0; qreal minValue = minVectorValue(m_maxHeightByColumn); @@ -1173,88 +1264,85 @@ bool ReportRender::registerBand(BandDesignIntf *band, bool registerInChildren) } } - if (band->columnsCount() != m_maxHeightByColumn.size()){ - for(int i=1;icolumnsCount();++i){ + if (band->columnsCount() != m_maxHeightByColumn.size()) { + for (int i = 1; i < band->columnsCount(); ++i) { m_maxHeightByColumn.append(m_maxHeightByColumn[0]); m_currentStartDataPos.append(m_currentStartDataPos[0]); } m_currentColumn = -1; } - if ( (band->columnsCount() > 1) && - (!band->isHeader() || (band->bandNestingLevel() > 0 && band->columnsFillDirection() != BandDesignIntf::Horizontal ))){ + if ((band->columnsCount() > 1) + && (!band->isHeader() + || (band->bandNestingLevel() > 0 + && band->columnsFillDirection() != BandDesignIntf::Horizontal))) { - if (band->columnsFillDirection() == BandDesignIntf::Horizontal){ - if (m_currentColumn < band->columnsCount()-1) - m_currentColumn = m_currentColumn+1; + if (band->columnsFillDirection() == BandDesignIntf::Horizontal) { + if (m_currentColumn < band->columnsCount() - 1) + m_currentColumn = m_currentColumn + 1; else m_currentColumn = 0; } else { - m_currentColumn = m_currentColumn == -1 ? 0: m_currentColumn; - if ((m_currentColumn !=0) && - (m_maxHeightByColumn[0] == m_maxHeightByColumn[m_currentColumn]) && - (m_maxHeightByColumn[0] >= band->height()) - ){ + m_currentColumn = m_currentColumn == -1 ? 0 : m_currentColumn; + if ((m_currentColumn != 0) + && (m_maxHeightByColumn[0] == m_maxHeightByColumn[m_currentColumn]) + && (m_maxHeightByColumn[0] >= band->height())) { m_currentColumn = 0; } } } - m_currentColumn = m_currentColumn == -1 ? 0: m_currentColumn; + m_currentColumn = m_currentColumn == -1 ? 0 : m_currentColumn; - if ( (band->height() <= m_maxHeightByColumn[m_currentColumn]) || - m_patternPageItem->endlessHeight() || - (isMultiColumnHeader(band) && (band->height() <= m_maxHeightByColumn[0])) - ){ + if ((band->height() <= m_maxHeightByColumn[m_currentColumn]) + || m_patternPageItem->endlessHeight() + || (isMultiColumnHeader(band) && (band->height() <= m_maxHeightByColumn[0]))) { - if ( (band->bandType() == BandDesignIntf::PageFooter) ){ - for (int i=0; i < m_maxHeightByColumn.size(); ++i) - m_maxHeightByColumn[i]+=band->height(); + if ((band->bandType() == BandDesignIntf::PageFooter)) { + for (int i = 0; i < m_maxHeightByColumn.size(); ++i) + m_maxHeightByColumn[i] += band->height(); } - if ( isMultiColumnHeader(band)){ + if (isMultiColumnHeader(band)) { - if (!band->parent()){ - for (int i = 0; i < band->columnsCount(); ++i){ + if (!band->parent()) { + for (int i = 0; i < band->columnsCount(); ++i) { m_currentColumn = i; - if (i != 0) band = dynamic_cast(band->cloneItem(PreviewMode)); + if (i != 0) + band = dynamic_cast(band->cloneItem(PreviewMode)); placeBandOnPage(band, i); } } else { placeBandOnPage(band, band->columnIndex()); } - } else { - if (band->bandType() != BandDesignIntf::PageFooter){ + if (band->bandType() != BandDesignIntf::PageFooter) { placeBandOnPage(band, m_currentColumn); } - if (band->columnsCount() > 1){ + if (band->columnsCount() > 1) { m_columnedBandItems.append(band); } - } - foreach(QList* list, m_childBands.values()){ - if (registerInChildren && - band->bandType()!=BandDesignIntf::PageHeader && - band->bandType()!=BandDesignIntf::PageFooter && - band->bandType()!=BandDesignIntf::ReportHeader && - band->bandType()!=BandDesignIntf::ReportFooter && - !list->contains(band) && - !band->reprintOnEachPage() - ) + foreach (QList* list, m_childBands.values()) { + if (registerInChildren && band->bandType() != BandDesignIntf::PageHeader + && band->bandType() != BandDesignIntf::PageFooter + && band->bandType() != BandDesignIntf::ReportHeader + && band->bandType() != BandDesignIntf::ReportFooter && !list->contains(band) + && !band->reprintOnEachPage()) list->append(band); } - if (band->isData()) m_renderedDataBandCount++; - band->setObjectName(band->objectName()+QString::number(++m_currentNameIndex)); + if (band->isData()) + m_renderedDataBandCount++; + band->setObjectName(band->objectName() + QString::number(++m_currentNameIndex)); renameChildItems(band); - if (m_lastDataBand){ + if (m_lastDataBand) { #if QT_VERSION < 0x050000 - m_lastDataBand->metaObject()->invokeMethod(m_lastDataBand,"bandRegistred"); + m_lastDataBand->metaObject()->invokeMethod(m_lastDataBand, "bandRegistred"); #else emit m_lastDataBand->bandRegistred(); #endif @@ -1262,34 +1350,38 @@ bool ReportRender::registerBand(BandDesignIntf *band, bool registerInChildren) if (band->bandType() != BandDesignIntf::PageFooter) m_lastRenderedBand = band; return true; - } else return false; + } else + return false; } -qreal ReportRender::calcSlicePercent(qreal height){ - return (height*3/(m_dataAreaSize))/100; -} +qreal ReportRender::calcSlicePercent(qreal height) { return (height * 3 / (m_dataAreaSize)) / 100; } -BandDesignIntf* ReportRender::sliceBand(BandDesignIntf *band, BandDesignIntf* patternBand, bool isLast) +BandDesignIntf* ReportRender::sliceBand(BandDesignIntf* band, BandDesignIntf* patternBand, + bool isLast) { - while (band->height()>m_maxHeightByColumn[m_currentColumn]) { - band = saveUppperPartReturnBottom(band,m_maxHeightByColumn[m_currentColumn],patternBand); + while (band->height() > m_maxHeightByColumn[m_currentColumn]) { + band = saveUppperPartReturnBottom(band, m_maxHeightByColumn[m_currentColumn], patternBand); if (!band->isEmpty()) { - if (band->autoHeight()){ - if (band->isNeedUpdateSize(FirstPass)){ + if (band->autoHeight()) { + if (band->isNeedUpdateSize(FirstPass)) { band->setHeight(0); } band->updateItemSize(m_datasources); } DataBandDesignIntf* data = dynamic_cast(band); - if (isLast && data && data->keepFooterTogether() && - band->height()sliceLastRow() - ){ - if (band->height()>(m_maxHeightByColumn[m_currentColumn]-m_reportFooterHeight)){ - m_maxHeightByColumn[m_currentColumn] -= ((m_maxHeightByColumn[m_currentColumn]-band->height())+(band->height()*calcSlicePercent(band->height()))); + if (isLast && data && data->keepFooterTogether() + && band->height() < m_maxHeightByColumn[m_currentColumn] && band->sliceLastRow()) { + if (band->height() + > (m_maxHeightByColumn[m_currentColumn] - m_reportFooterHeight)) { + m_maxHeightByColumn[m_currentColumn] + -= ((m_maxHeightByColumn[m_currentColumn] - band->height()) + + (band->height() * calcSlicePercent(band->height()))); } } - if (registerBand(band)) break; - } else break; + if (registerBand(band)) + break; + } else + break; } if (band->isEmpty()) { @@ -1298,14 +1390,15 @@ BandDesignIntf* ReportRender::sliceBand(BandDesignIntf *band, BandDesignIntf* pa } return band; - } -void ReportRender::updateTOC(BaseDesignIntf* item, int pageNumber){ - BookmarkContainerDesignIntf* bookmarkContainer = dynamic_cast(item); - if (bookmarkContainer){ +void ReportRender::updateTOC(BaseDesignIntf* item, int pageNumber) +{ + BookmarkContainerDesignIntf* bookmarkContainer + = dynamic_cast(item); + if (bookmarkContainer) { TableOfContents* toc = m_scriptEngineContext->tableOfContents(); - foreach (QString key, bookmarkContainer->bookmarks()){ + foreach (QString key, bookmarkContainer->bookmarks()) { toc->setItem(key, bookmarkContainer->getBookMark(key).toString(), pageNumber); } } @@ -1313,21 +1406,21 @@ void ReportRender::updateTOC(BaseDesignIntf* item, int pageNumber){ void ReportRender::secondRenderPass(ReportPages renderedPages) { - if (!m_scriptEngineContext->tableOfContents()->isEmpty()){ - for(int i = 0; i < renderedPages.count(); ++i){ + if (!m_scriptEngineContext->tableOfContents()->isEmpty()) { + for (int i = 0; i < renderedPages.count(); ++i) { PageItemDesignIntf::Ptr page = renderedPages.at(i); updateTOC(page.data(), m_pagesRanges.findPageNumber(i)); - foreach(BaseDesignIntf* item, page->childBaseItems()){ + foreach (BaseDesignIntf* item, page->childBaseItems()) { updateTOC(item, m_pagesRanges.findPageNumber(i)); } } } - for(int i = 0; i < renderedPages.count(); ++i){ + for (int i = 0; i < renderedPages.count(); ++i) { PageItemDesignIntf::Ptr page = renderedPages.at(i); - m_datasources->setReportVariable("#PAGE",m_pagesRanges.findPageNumber(i)); - m_datasources->setReportVariable("#PAGE_COUNT",m_pagesRanges.findLastPageNumber(i)); - foreach(BaseDesignIntf* item, page->childBaseItems()){ + m_datasources->setReportVariable("#PAGE", m_pagesRanges.findPageNumber(i)); + m_datasources->setReportVariable("#PAGE_COUNT", m_pagesRanges.findLastPageNumber(i)); + foreach (BaseDesignIntf* item, page->childBaseItems()) { if (item->isNeedUpdateSize(SecondPass)) item->updateItemSize(m_datasources, SecondPass); } @@ -1339,35 +1432,34 @@ void ReportRender::createTOCMarker(bool startNewRange) m_pagesRanges.addTOCMarker(startNewRange); } -BandDesignIntf *ReportRender::saveUppperPartReturnBottom(BandDesignIntf *band, int height, BandDesignIntf* patternBand) +BandDesignIntf* ReportRender::saveUppperPartReturnBottom(BandDesignIntf* band, int height, + BandDesignIntf* patternBand) { - //int sliceHeight = height; + // int sliceHeight = height; BandDesignIntf* upperBandPart = dynamic_cast(band->cloneUpperPart(height)); BandDesignIntf* bottomBandPart = dynamic_cast(band->cloneBottomPart(height)); - if (!bottomBandPart->isEmpty()){ + if (!bottomBandPart->isEmpty()) { if (patternBand->keepFooterTogether()) closeFooterGroup(patternBand); if (upperBandPart->isEmpty()) bottomBandPart->copyBookmarks(band); } - if (!upperBandPart->isEmpty()){ + if (!upperBandPart->isEmpty()) { upperBandPart->setBottomSpace(0); upperBandPart->updateItemSize(m_datasources, FirstPass, height); registerBand(upperBandPart); upperBandPart->copyBookmarks(band); if (patternBand->isFooter()) closeFooterGroup(m_lastDataBand); - } else delete upperBandPart; + } else + delete upperBandPart; - if (band->columnsCount()>1 && - (band->columnsFillDirection()==BandDesignIntf::Vertical || - band->columnsFillDirection()==BandDesignIntf::VerticalUniform)){ + if (band->columnsCount() > 1 + && (band->columnsFillDirection() == BandDesignIntf::Vertical + || band->columnsFillDirection() == BandDesignIntf::VerticalUniform)) { startNewColumn(); - if (patternBand->bandHeader() && - patternBand->bandHeader()->columnsCount()>1 && - !m_lostHeadersMoved && - patternBand->bandNestingLevel() == 0 - ){ + if (patternBand->bandHeader() && patternBand->bandHeader()->columnsCount() > 1 + && !m_lostHeadersMoved && patternBand->bandNestingLevel() == 0) { renderBand(patternBand->bandHeader(), 0, StartNewPageAsNeeded); } @@ -1380,7 +1472,7 @@ BandDesignIntf *ReportRender::saveUppperPartReturnBottom(BandDesignIntf *band, i return bottomBandPart; } -BandDesignIntf *ReportRender::renderData(BandDesignIntf *patternBand, bool emitBeforeRender) +BandDesignIntf* ReportRender::renderData(BandDesignIntf* patternBand, bool emitBeforeRender) { BandDesignIntf* bandClone = dynamic_cast(patternBand->cloneItem(PreviewMode)); @@ -1389,11 +1481,11 @@ BandDesignIntf *ReportRender::renderData(BandDesignIntf *patternBand, bool emitB if (emitBeforeRender) emit(patternBand->beforeRender()); - if (patternBand->isFooter()){ + if (patternBand->isFooter()) { replaceGroupsFunction(bandClone); } - if (patternBand->isHeader()){ + if (patternBand->isHeader()) { replaceGroupsFunction(bandClone); } @@ -1401,14 +1493,15 @@ BandDesignIntf *ReportRender::renderData(BandDesignIntf *patternBand, bool emitB bandClone->setBottomSpace(patternBand->height() - patternBand->findMaxBottom()); bandClone->updateItemSize(m_datasources); - //m_scriptEngineContext->baseDesignIntfToScript(bandClone); + // m_scriptEngineContext->baseDesignIntfToScript(bandClone); emit(patternBand->afterData()); return bandClone; } -void ReportRender::startNewColumn(){ - if (m_currentColumn < m_maxHeightByColumn.size()-1){ +void ReportRender::startNewColumn() +{ + if (m_currentColumn < m_maxHeightByColumn.size() - 1) { m_currentColumn++; checkLostHeadersInPrevColumn(); } else { @@ -1424,10 +1517,11 @@ void ReportRender::startNewPage(bool isFirst) initColumns(); initRenderPage(); m_scriptEngineContext->setCurrentPage(m_renderPageItem); - m_scriptEngineContext->baseDesignIntfToScript(m_renderPageItem->patternName(), m_renderPageItem); + m_scriptEngineContext->baseDesignIntfToScript(m_renderPageItem->patternName(), + m_renderPageItem); emit m_patternPageItem->beforeRender(); - m_renderPageItem->setObjectName(QLatin1String("ReportPage")+QString::number(m_pageCount)); + m_renderPageItem->setObjectName(QLatin1String("ReportPage") + QString::number(m_pageCount)); m_maxHeightByColumn[m_currentColumn] = m_renderPageItem->pageRect().height(); m_currentStartDataPos[m_currentColumn] = m_patternPageItem->topMargin() * Const::mmFACTOR; m_currentIndex = 0; @@ -1439,7 +1533,7 @@ void ReportRender::startNewPage(bool isFirst) renderPageHeader(m_patternPageItem); - m_pageFooterHeight = calcPageFooterHeight(m_patternPageItem)+2; + m_pageFooterHeight = calcPageFooterHeight(m_patternPageItem) + 2; m_maxHeightByColumn[m_currentColumn] -= m_pageFooterHeight; m_currentIndex = 10; m_dataAreaSize = m_maxHeightByColumn[m_currentColumn]; @@ -1451,24 +1545,23 @@ void ReportRender::startNewPage(bool isFirst) checkLostHeadersOnPrevPage(); pasteGroups(); - } void ReportRender::resetPageNumber(ResetPageNuberType resetType) { m_pagesRanges.startNewRange(); if (resetType == PageReset) - m_datasources->setReportVariable("#PAGE",1); + m_datasources->setReportVariable("#PAGE", 1); } void ReportRender::cutGroups() { m_popupedExpression.clear(); m_popupedValues.clear(); - //foreach(BandDesignIntf* groupBand,m_childBands.keys()){ - foreach(BandDesignIntf* groupBand, m_childBands.keys()){ - if (m_childBands.value(groupBand)->tryToKeepTogether()){ - foreach(BandDesignIntf* band, *m_childBands.value(groupBand)){ + // foreach(BandDesignIntf* groupBand,m_childBands.keys()){ + foreach (BandDesignIntf* groupBand, m_childBands.keys()) { + if (m_childBands.value(groupBand)->tryToKeepTogether()) { + foreach (BandDesignIntf* band, *m_childBands.value(groupBand)) { m_renderPageItem->removeBand(band); popPageFooterGroupValues(band); band->setParent(0); @@ -1476,17 +1569,16 @@ void ReportRender::cutGroups() } } } - } -void ReportRender::checkFooterGroup(BandDesignIntf *groupBand) +void ReportRender::checkFooterGroup(BandDesignIntf* groupBand) { - if (m_childBands.contains(groupBand)){ + if (m_childBands.contains(groupBand)) { GroupBandsHolder* holder = m_childBands.value(groupBand); - foreach(BandDesignIntf* band, *holder){ - qreal percent = band->height()*100 / m_dataAreaSize; - if (m_renderedDataBandCount<=1 || percent>20 ){ - holder->removeAll(band); + foreach (BandDesignIntf* band, *holder) { + qreal percent = band->height() * 100 / m_dataAreaSize; + if (m_renderedDataBandCount <= 1 || percent > 20) { + holder->removeAll(band); } } } @@ -1495,20 +1587,22 @@ void ReportRender::checkFooterGroup(BandDesignIntf *groupBand) void ReportRender::pasteGroups() { BandDesignIntf* groupBand = findEnclosingGroup(); - if (groupBand){ - foreach(BandDesignIntf* band, *m_childBands.value(groupBand)){ - registerBand(band,false); - if (band->isData()) m_renderedDataBandCount++; + if (groupBand) { + foreach (BandDesignIntf* band, *m_childBands.value(groupBand)) { + registerBand(band, false); + if (band->isData()) + m_renderedDataBandCount++; pushPageFooterGroupValues(band); } - foreach(GroupBandsHolder* holder, m_childBands.values()) + foreach (GroupBandsHolder* holder, m_childBands.values()) holder->setTryToKeepTogether(false); } m_popupedExpression.clear(); m_popupedValues.clear(); } -bool bandLessThen(BandDesignIntf* b1, BandDesignIntf* b2){ +bool bandLessThen(BandDesignIntf* b1, BandDesignIntf* b2) +{ return b1->bandIndex() < b2->bandIndex(); } @@ -1516,73 +1610,83 @@ void ReportRender::checkLostHeadersOnPrevPage() { QVector lostHeaders; - if (m_renderedPages.isEmpty()) return; + if (m_renderedPages.isEmpty()) + return; PageItemDesignIntf::Ptr page = m_renderedPages.last(); - if (page->bands().isEmpty()) return; + if (page->bands().isEmpty()) + return; - QMutableListIteratorit(page->bands()); + QMutableListIterator it(page->bands()); it.toBack(); - if (it.hasPrevious()){ - if (it.previous()->isFooter()){ - if (it.hasPrevious()) it.previous(); - else return; + if (it.hasPrevious()) { + if (it.previous()->isFooter()) { + if (it.hasPrevious()) + it.previous(); + else + return; } } - while (it.hasPrevious()){ - if (it.value()->isHeader()){ - if (it.value()->reprintOnEachPage()){ + while (it.hasPrevious()) { + if (it.value()->isHeader()) { + if (it.value()->reprintOnEachPage()) { delete it.value(); - } else { lostHeaders.append(it.value());} + } else { + lostHeaders.append(it.value()); + } it.remove(); it.previous(); - } else break; + } else + break; } - if (lostHeaders.size() > 0){ + if (lostHeaders.size() > 0) { m_lostHeadersMoved = true; - //std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); + // std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); - foreach(BandDesignIntf* header, lostHeaders){ + foreach (BandDesignIntf* header, lostHeaders) { registerBand(header); } } else { m_lostHeadersMoved = false; } - - } void ReportRender::checkLostHeadersInPrevColumn() { QVector lostHeaders; - QMutableListIteratorit(m_renderPageItem->bands()); + QMutableListIterator it(m_renderPageItem->bands()); it.toBack(); - if (it.hasPrevious()){ - if (it.previous()->isFooter()){ - if (it.hasPrevious()) it.previous(); - else return; + if (it.hasPrevious()) { + if (it.previous()->isFooter()) { + if (it.hasPrevious()) + it.previous(); + else + return; } } - while (it.hasPrevious()){ - if (it.value()->isHeader()){ - if (it.value()->reprintOnEachPage()){ + while (it.hasPrevious()) { + if (it.value()->isHeader()) { + if (it.value()->reprintOnEachPage()) { delete it.value(); - } else { lostHeaders.append(it.value());} + } else { + lostHeaders.append(it.value()); + } it.remove(); it.previous(); - } else break; + } else + break; } - if (lostHeaders.size() > 0){ + if (lostHeaders.size() > 0) { m_lostHeadersMoved = true; -// std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); + // std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); std::sort(lostHeaders.begin(), lostHeaders.end(), bandLessThen); - foreach(BandDesignIntf* header, lostHeaders){ + foreach (BandDesignIntf* header, lostHeaders) { registerBand(header); } } else { @@ -1592,15 +1696,14 @@ void ReportRender::checkLostHeadersInPrevColumn() BandDesignIntf* ReportRender::findEnclosingGroup() { - BandDesignIntf* result=0; + BandDesignIntf* result = 0; int groupIndex = -1; - if (!m_childBands.isEmpty()){ - foreach(BandDesignIntf* gb, m_childBands.keys()){ - if (m_childBands.value(gb)->tryToKeepTogether()&& - ((gb->bandIndex()bandIndex(); + if (!m_childBands.isEmpty()) { + foreach (BandDesignIntf* gb, m_childBands.keys()) { + if (m_childBands.value(gb)->tryToKeepTogether() + && ((gb->bandIndex() < groupIndex) || (groupIndex == -1))) { + result = gb; + groupIndex = result->bandIndex(); } } } @@ -1610,12 +1713,14 @@ BandDesignIntf* ReportRender::findEnclosingGroup() void ReportRender::savePage(bool isLast) { - m_datasources->setReportVariable("#IS_LAST_PAGEFOOTER",isLast); - m_datasources->setReportVariable("#IS_FIRST_PAGEFOOTER",m_datasources->variable("#PAGE").toInt()==1); + m_datasources->setReportVariable("#IS_LAST_PAGEFOOTER", isLast); + m_datasources->setReportVariable("#IS_FIRST_PAGEFOOTER", + m_datasources->variable("#PAGE").toInt() == 1); renderPageItems(m_patternPageItem); - if (m_renderPageItem->isEmpty() && m_renderPageItem->notPrintIfEmpty()) return; + if (m_renderPageItem->isEmpty() && m_renderPageItem->notPrintIfEmpty()) + return; if (m_renderPageItem->isTOC()) m_pagesRanges.addTOCPage(); @@ -1628,78 +1733,77 @@ void ReportRender::savePage(bool isLast) m_columnedBandItems.clear(); BandDesignIntf* pf = m_patternPageItem->bandByType(BandDesignIntf::PageFooter); - if (pf && m_datasources->variable("#PAGE").toInt()!=1 && !isLast){ + if (pf && m_datasources->variable("#PAGE").toInt() != 1 && !isLast) { renderPageFooter(m_patternPageItem); } else { - if (pf && pf->property("printOnFirstPage").toBool() && m_datasources->variable("#PAGE").toInt()==1){ + if (pf && pf->property("printOnFirstPage").toBool() + && m_datasources->variable("#PAGE").toInt() == 1) { renderPageFooter(m_patternPageItem); - } else if(pf && pf->property("printOnLastPage").toBool() && isLast){ + } else if (pf && pf->property("printOnLastPage").toBool() && isLast) { renderPageFooter(m_patternPageItem); } } if (m_pagesRanges.currentRange(m_patternPageItem->isTOC()).firstPage == 0) { - m_datasources->setReportVariable("#PAGE",1); + m_datasources->setReportVariable("#PAGE", 1); } else { - m_datasources->setReportVariable("#PAGE",m_datasources->variable("#PAGE").toInt()+1); + m_datasources->setReportVariable("#PAGE", m_datasources->variable("#PAGE").toInt() + 1); } m_renderedPages.append(PageItemDesignIntf::Ptr(m_renderPageItem)); m_pageCount++; emit pageRendered(m_pageCount); - if (isLast){ + if (isLast) { BandDesignIntf* ph = m_renderPageItem->bandByType(BandDesignIntf::PageHeader); - if (ph && !ph->property("printOnLastPage").toBool()){ + if (ph && !ph->property("printOnLastPage").toBool()) { delete ph; } } - if (m_renderPageItem->pageFooter()){ + if (m_renderPageItem->pageFooter()) { m_renderPageItem->pageFooter()->setBandIndex(++m_currentIndex); - if (m_renderPageItem->pageFooter()->property("removeGap").toBool()){ + if (m_renderPageItem->pageFooter()->property("removeGap").toBool()) { m_renderPageItem->pageFooter()->setPos(m_lastRenderedBand->geometry().bottomLeft()); } } m_renderPageItem->placeTearOffBand(); - //m_scriptEngineContext->setCurrentPage(m_renderPageItem); + // m_scriptEngineContext->setCurrentPage(m_renderPageItem); emit m_patternPageItem->afterRender(); if (isLast) emit m_patternPageItem->afterLastPageRendered(); - if (isLast && m_patternPageItem->endlessHeight()){ + if (isLast && m_patternPageItem->endlessHeight()) { qreal pageHeight = 0; foreach (BandDesignIntf* band, m_renderPageItem->bands()) { pageHeight += band->height(); } - m_renderPageItem->setHeight(pageHeight + 10 + - (m_patternPageItem->topMargin() + m_patternPageItem->bottomMargin()) * Const::mmFACTOR); + m_renderPageItem->setHeight( + pageHeight + 10 + + (m_patternPageItem->topMargin() + m_patternPageItem->bottomMargin()) + * Const::mmFACTOR); } } QString ReportRender::toString() { QScopedPointer writer(new XMLWriter()); - foreach(PageItemDesignIntf::Ptr page,m_renderedPages){ + foreach (PageItemDesignIntf::Ptr page, m_renderedPages) { writer->putItem(page.data()); } return writer->saveToString(); } -ReportRender::~ReportRender(){ - m_renderedPages.clear(); -} +ReportRender::~ReportRender() { m_renderedPages.clear(); } -void ReportRender::cancelRender(){ - m_renderCanceled = true; -} +void ReportRender::cancelRender() { m_renderCanceled = true; } int PagesRanges::findLastPageNumber(int index) { index++; foreach (PagesRange range, m_ranges) { - if ( range.firstPage <= (index) && range.lastPage>= (index) ) - return (range.lastPage-(range.firstPage))+1; + if (range.firstPage <= (index) && range.lastPage >= (index)) + return (range.lastPage - (range.firstPage)) + 1; } return 0; } @@ -1708,23 +1812,24 @@ int PagesRanges::findPageNumber(int index) { index++; foreach (PagesRange range, m_ranges) { - if ( range.firstPage <= (index) && range.lastPage >= (index) ) - return (index - range.firstPage)+1; + if (range.firstPage <= (index) && range.lastPage >= (index)) + return (index - range.firstPage) + 1; } return 0; } -PagesRange&PagesRanges::currentRange(bool isTOC) +PagesRange& PagesRanges::currentRange(bool isTOC) { - Q_ASSERT( (isTOC && m_TOCRangeIndex!=-1) || !isTOC); - if (isTOC && m_TOCRangeIndex !=-1) return m_ranges[m_TOCRangeIndex]; + Q_ASSERT((isTOC && m_TOCRangeIndex != -1) || !isTOC); + if (isTOC && m_TOCRangeIndex != -1) + return m_ranges[m_TOCRangeIndex]; return m_ranges.last(); } void PagesRanges::startNewRange(bool isTOC) { PagesRange range; - if (!m_ranges.isEmpty()){ + if (!m_ranges.isEmpty()) { range.firstPage = 0; range.lastPage = m_ranges.last().lastPage + 1; } else { @@ -1733,23 +1838,25 @@ void PagesRanges::startNewRange(bool isTOC) } range.isTOC = isTOC; m_ranges.append(range); - if (isTOC) m_TOCRangeIndex = m_ranges.size()-1; + if (isTOC) + m_TOCRangeIndex = m_ranges.size() - 1; } void PagesRanges::addTOCMarker(bool addNewRange) { - if ( addNewRange || m_ranges.isEmpty()){ + if (addNewRange || m_ranges.isEmpty()) { startNewRange(true); } else { - m_TOCRangeIndex = m_ranges.size()-1; + m_TOCRangeIndex = m_ranges.size() - 1; m_ranges.last().isTOC = true; } } void PagesRanges::addPage() { - if (m_ranges.isEmpty()) startNewRange(); - if (m_ranges.last().firstPage == 0){ + if (m_ranges.isEmpty()) + startNewRange(); + if (m_ranges.last().firstPage == 0) { m_ranges.last().firstPage = m_ranges.last().lastPage == 0 ? 1 : m_ranges.last().lastPage; m_ranges.last().lastPage = m_ranges.last().lastPage == 0 ? 1 : m_ranges.last().lastPage; } else { @@ -1757,8 +1864,9 @@ void PagesRanges::addPage() } } -void PagesRanges::shiftRangesNextToTOC(){ - for(int i = m_TOCRangeIndex+1; i < m_ranges.size(); ++i){ +void PagesRanges::shiftRangesNextToTOC() +{ + for (int i = m_TOCRangeIndex + 1; i < m_ranges.size(); ++i) { m_ranges[i].firstPage++; m_ranges[i].lastPage++; } @@ -1767,11 +1875,11 @@ void PagesRanges::shiftRangesNextToTOC(){ void PagesRanges::addTOCPage() { Q_ASSERT(m_TOCRangeIndex != -1); - if (m_TOCRangeIndex != -1){ + if (m_TOCRangeIndex != -1) { PagesRange& tocRange = m_ranges[m_TOCRangeIndex]; if (tocRange.firstPage == 0) { - tocRange.firstPage = tocRange.lastPage == 0 ? 1 : tocRange.lastPage; - tocRange.lastPage = tocRange.lastPage == 0 ? 1 : tocRange.lastPage; + tocRange.firstPage = tocRange.lastPage == 0 ? 1 : tocRange.lastPage; + tocRange.lastPage = tocRange.lastPage == 0 ? 1 : tocRange.lastPage; if (tocRange.firstPage == 1 && tocRange.lastPage == 1) shiftRangesNextToTOC(); } else { @@ -1781,9 +1889,6 @@ void PagesRanges::addTOCPage() } } -void PagesRanges::clear() -{ - m_ranges.clear(); -} +void PagesRanges::clear() { m_ranges.clear(); } } // namespace LimeReport diff --git a/limereport/lrreportrender.h b/limereport/lrreportrender.h index 97f818b..67f480a 100644 --- a/limereport/lrreportrender.h +++ b/limereport/lrreportrender.h @@ -29,44 +29,54 @@ ****************************************************************************/ #ifndef LRREPORTRENDER_H #define LRREPORTRENDER_H -#include #include "lrcollection.h" #include "lrdatasourcemanager.h" #include "lrpageitemdesignintf.h" #include "lrscriptenginemanager.h" #include "serializators/lrstorageintf.h" -namespace LimeReport{ +#include + +namespace LimeReport { class PageDesignIntf; class BandDesignIntf; class ContentItemDesignIntf; -class GroupBandsHolder: public QList{ +class GroupBandsHolder: public QList { public: - GroupBandsHolder(bool tryToKeepTogether):QList(),m_tryToKeepTogether(tryToKeepTogether), - m_dataGroup(true), m_footerGroup(false){} - bool tryToKeepTogether(){return m_tryToKeepTogether;} - void setTryToKeepTogether(bool value){m_tryToKeepTogether=value;} - bool isDataGroup(){return m_dataGroup;} - bool isFooterGroup(){ return m_footerGroup;} - void setIsFooterGroup(){m_footerGroup=true;m_dataGroup=false;} + GroupBandsHolder(bool tryToKeepTogether): + QList(), + m_tryToKeepTogether(tryToKeepTogether), + m_dataGroup(true), + m_footerGroup(false) + { + } + bool tryToKeepTogether() { return m_tryToKeepTogether; } + void setTryToKeepTogether(bool value) { m_tryToKeepTogether = value; } + bool isDataGroup() { return m_dataGroup; } + bool isFooterGroup() { return m_footerGroup; } + void setIsFooterGroup() + { + m_footerGroup = true; + m_dataGroup = false; + } + private: bool m_tryToKeepTogether; bool m_dataGroup; bool m_footerGroup; }; - -struct PagesRange{ +struct PagesRange { int firstPage; int lastPage; bool isTOC; }; -class PagesRanges{ +class PagesRanges { public: - PagesRanges(): m_TOCRangeIndex(-1) {} + PagesRanges(): m_TOCRangeIndex(-1) { } int findLastPageNumber(int index); int findPageNumber(int index); PagesRange& currentRange(bool isTOC); @@ -75,152 +85,172 @@ public: void addPage(); void addTOCPage(); void clear(); + private: void shiftRangesNextToTOC(); + private: QVector m_ranges; int m_TOCRangeIndex; }; - -class ReportRender: public QObject -{ +class ReportRender: public QObject { Q_OBJECT Q_PROPERTY(QObject* datasourcesManager READ datasources) public: - enum DataRenderMode {StartNewPageAsNeeded, NotStartNewPage, ForcedStartPage}; - enum BandPrintMode {PrintAlwaysPrintable, PrintNotAlwaysPrintable }; - enum ResetPageNuberType{BandReset, PageReset}; - enum PageRenderStage{BeforePageHeader, AfterPageHeader}; - typedef QSharedPointer Ptr; + enum DataRenderMode { + StartNewPageAsNeeded, + NotStartNewPage, + ForcedStartPage + }; + enum BandPrintMode { + PrintAlwaysPrintable, + PrintNotAlwaysPrintable + }; + enum ResetPageNuberType { + BandReset, + PageReset + }; + enum PageRenderStage { + BeforePageHeader, + AfterPageHeader + }; + typedef QSharedPointer Ptr; ~ReportRender(); - ReportRender(QObject *parent = 0); + ReportRender(QObject* parent = 0); void setDatasources(DataSourceManager* value); void setScriptContext(ScriptEngineContext* scriptContext); - DataSourceManager* datasources(){return m_datasources;} - int pageCount(); + DataSourceManager* datasources() { return m_datasources; } + int pageCount(); PageItemDesignIntf::Ptr pageAt(int index); - QString renderPageToString(PageItemDesignIntf *patternPage); - ReportPages renderPageToPages(PageItemDesignIntf *patternPage); - ReportPages renderTOC(PageItemDesignIntf *patternPage, bool first, bool resetPages); - void secondRenderPass(ReportPages renderedPages); - void createTOCMarker(bool startNewRange); + QString renderPageToString(PageItemDesignIntf* patternPage); + ReportPages renderPageToPages(PageItemDesignIntf* patternPage); + ReportPages renderTOC(PageItemDesignIntf* patternPage, bool first, bool resetPages); + void secondRenderPass(ReportPages renderedPages); + void createTOCMarker(bool startNewRange); signals: - void pageRendered(int renderedPageCount); + void pageRendered(int renderedPageCount); public slots: - void cancelRender(); + void cancelRender(); + private: - void analizeContainer(BaseDesignIntf *item, BandDesignIntf *band); - void analizeItem(ContentItemDesignIntf *item, BandDesignIntf *band); - void analizePage(PageItemDesignIntf *patternPage); + void analizeContainer(BaseDesignIntf* item, BandDesignIntf* band); + void analizeItem(ContentItemDesignIntf* item, BandDesignIntf* band); + void analizePage(PageItemDesignIntf* patternPage); - void initDatasources(); - void initDatasource(const QString &name); - void initRenderPage(); - void initVariables(); - void initGroups(); - void clearPageMap(); + void initDatasources(); + void initDatasource(const QString& name); + void initRenderPage(); + void initVariables(); + void initGroups(); + void clearPageMap(); - void renderPage(PageItemDesignIntf *patternPage, bool isTOC = false, bool isFirst = false, bool = false); - BandDesignIntf* renderBand(BandDesignIntf *patternBand, BandDesignIntf *bandData, DataRenderMode mode = NotStartNewPage, bool isLast = false); - void renderDataBand(BandDesignIntf* dataBand); - void renderPageHeader(PageItemDesignIntf* patternPage); - void renderReportHeader(PageItemDesignIntf* patternPage, PageRenderStage stage); - void renderPageFooter(PageItemDesignIntf* patternPage); - void renderPageItems(PageItemDesignIntf* patternPage); - void renderChildHeader(BandDesignIntf* parent, BandPrintMode printMode); - void renderChildFooter(BandDesignIntf* parent, BandPrintMode printMode); - void renderChildBands(BandDesignIntf* parentBand); - void recalcIfNeeded(BandDesignIntf *band); - void renderDataHeader(BandDesignIntf* header); - void renderGroupHeader(BandDesignIntf* parentBand, IDataSource* dataSource, bool firstTime); - void renderGroupFooter(BandDesignIntf* parentBand); - void moveTearOffBand(); - qreal calcPageFooterHeight(PageItemDesignIntf* patternPage); - qreal calcSlicePercent(qreal height); + void renderPage(PageItemDesignIntf* patternPage, bool isTOC = false, bool isFirst = false, + bool = false); + BandDesignIntf* renderBand(BandDesignIntf* patternBand, BandDesignIntf* bandData, + DataRenderMode mode = NotStartNewPage, bool isLast = false); + void renderDataBand(BandDesignIntf* dataBand); + void renderPageHeader(PageItemDesignIntf* patternPage); + void renderReportHeader(PageItemDesignIntf* patternPage, PageRenderStage stage); + void renderPageFooter(PageItemDesignIntf* patternPage); + void renderPageItems(PageItemDesignIntf* patternPage); + void renderChildHeader(BandDesignIntf* parent, BandPrintMode printMode); + void renderChildFooter(BandDesignIntf* parent, BandPrintMode printMode); + void renderChildBands(BandDesignIntf* parentBand); + void recalcIfNeeded(BandDesignIntf* band); + void renderDataHeader(BandDesignIntf* header); + void renderGroupHeader(BandDesignIntf* parentBand, IDataSource* dataSource, bool firstTime); + void renderGroupFooter(BandDesignIntf* parentBand); + void moveTearOffBand(); + qreal calcPageFooterHeight(PageItemDesignIntf* patternPage); + qreal calcSlicePercent(qreal height); - bool containsGroupFunctions(BaseDesignIntf *container); - void extractGroupFuntionsFromItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band); - void extractGroupFunctionsFromContainer(BaseDesignIntf* baseItem, BandDesignIntf* band); - void extractGroupFunctions(BandDesignIntf* band); - void replaceGroupFunctionsInItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band); - void replaceGroupFunctionsInContainer(BaseDesignIntf* baseItem, BandDesignIntf* band); - void replaceGroupsFunction(BandDesignIntf* band); + bool containsGroupFunctions(BaseDesignIntf* container); + void extractGroupFuntionsFromItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band); + void extractGroupFunctionsFromContainer(BaseDesignIntf* baseItem, BandDesignIntf* band); + void extractGroupFunctions(BandDesignIntf* band); + void replaceGroupFunctionsInItem(ContentItemDesignIntf* contentItem, BandDesignIntf* band); + void replaceGroupFunctionsInContainer(BaseDesignIntf* baseItem, BandDesignIntf* band); + void replaceGroupsFunction(BandDesignIntf* band); - BandDesignIntf *findRecalcableBand(BandDesignIntf *patternBand); + BandDesignIntf* findRecalcableBand(BandDesignIntf* patternBand); - void popPageFooterGroupValues(BandDesignIntf* dataBand); - void pushPageFooterGroupValues(BandDesignIntf* dataBand); + void popPageFooterGroupValues(BandDesignIntf* dataBand); + void pushPageFooterGroupValues(BandDesignIntf* dataBand); - enum GroupType{DATA,FOOTER}; - void closeGroup(BandDesignIntf* band); - void openDataGroup(BandDesignIntf* band); - void closeDataGroup(BandDesignIntf* band); - void openFooterGroup(BandDesignIntf* band); - void closeFooterGroup(BandDesignIntf* band); - void cutGroups(); - void checkFooterGroup(BandDesignIntf* groupBand); - void pasteGroups(); - void checkLostHeadersOnPrevPage(); - void checkLostHeadersInPrevColumn(); + enum GroupType { + DATA, + FOOTER + }; + void closeGroup(BandDesignIntf* band); + void openDataGroup(BandDesignIntf* band); + void closeDataGroup(BandDesignIntf* band); + void openFooterGroup(BandDesignIntf* band); + void closeFooterGroup(BandDesignIntf* band); + void cutGroups(); + void checkFooterGroup(BandDesignIntf* groupBand); + void pasteGroups(); + void checkLostHeadersOnPrevPage(); + void checkLostHeadersInPrevColumn(); BandDesignIntf* findEnclosingGroup(); - bool registerBand(BandDesignIntf* band, bool registerInChildren=true); - BandDesignIntf *sliceBand(BandDesignIntf* band, BandDesignIntf *patternBand, bool isLast); + bool registerBand(BandDesignIntf* band, bool registerInChildren = true); + BandDesignIntf* sliceBand(BandDesignIntf* band, BandDesignIntf* patternBand, bool isLast); - BandDesignIntf* saveUppperPartReturnBottom(BandDesignIntf *band, int height, BandDesignIntf *patternBand); + BandDesignIntf* saveUppperPartReturnBottom(BandDesignIntf* band, int height, + BandDesignIntf* patternBand); BandDesignIntf* renderData(BandDesignIntf* patternBand, bool emitBeforeRender = true); - void startNewColumn(); - void startNewPage(bool isFirst = false); - void resetPageNumber(ResetPageNuberType resetType); - void savePage(bool isLast = false); + void startNewColumn(); + void startNewPage(bool isFirst = false); + void resetPageNumber(ResetPageNuberType resetType); + void savePage(bool isLast = false); QString toString(); void initColumns(); bool isNeedToRearrangeColumnsItems(); BandDesignIntf* lastColumnItem(int columnIndex); void rearrangeColumnsItems(); - int columnItemsCount(int columnIndex); + int columnItemsCount(int columnIndex); qreal columnHeigth(int columnIndex); qreal maxColumnHeight(); - void renameChildItems(BaseDesignIntf *item); - void renderGroupFooterByHeader(BandDesignIntf *groupHeader); + void renameChildItems(BaseDesignIntf* item); + void renderGroupFooterByHeader(BandDesignIntf* groupHeader); void updateTOC(BaseDesignIntf* item, int pageNumber); - void placeBandOnPage(BandDesignIntf *band, int columnIndex); - QColor makeBackgroundColor(BandDesignIntf *band); + void placeBandOnPage(BandDesignIntf* band, int columnIndex); + QColor makeBackgroundColor(BandDesignIntf* band); + private: DataSourceManager* m_datasources; ScriptEngineContext* m_scriptEngineContext; PageItemDesignIntf* m_renderPageItem; PageItemDesignIntf* m_patternPageItem; QList m_renderedPages; - QMultiMap< BandDesignIntf*, GroupBandsHolder* > m_childBands; + QMultiMap m_childBands; QList m_reprintableBands; QList m_recalcBands; - QMap > m_groupfunctionItems; + QMap> m_groupfunctionItems; int m_currentIndex; int m_pageCount; - QMap m_popupedValues; - QMultiMap m_popupedExpression; + QMap m_popupedValues; + QMultiMap m_popupedExpression; - qreal m_pageFooterHeight; - qreal m_dataAreaSize; - qreal m_reportFooterHeight; - int m_renderedDataBandCount; + qreal m_pageFooterHeight; + qreal m_dataAreaSize; + qreal m_reportFooterHeight; + int m_renderedDataBandCount; BandDesignIntf* m_lastRenderedHeader; BandDesignIntf* m_lastDataBand; BandDesignIntf* m_lastRenderedFooter; BandDesignIntf* m_lastRenderedBand; - bool m_renderCanceled; - QVector m_maxHeightByColumn; - QVector m_currentStartDataPos; - int m_currentColumn; - PagesRanges m_pagesRanges; + bool m_renderCanceled; + QVector m_maxHeightByColumn; + QVector m_currentStartDataPos; + int m_currentColumn; + PagesRanges m_pagesRanges; QVector m_columnedBandItems; unsigned long long m_currentNameIndex; - bool m_newPageStarted; - bool m_lostHeadersMoved; - + bool m_newPageStarted; + bool m_lostHeadersMoved; }; } // namespace LimeReport #endif // LRREPORTRENDER_H diff --git a/limereport/lrreporttranslation.cpp b/limereport/lrreporttranslation.cpp index d25b0d5..329e71f 100644 --- a/limereport/lrreporttranslation.cpp +++ b/limereport/lrreporttranslation.cpp @@ -3,27 +3,27 @@ #include "lrbasedesignintf.h" #include "lrpagedesignintf.h" -namespace LimeReport{ +namespace LimeReport { -ReportTranslation::ReportTranslation(QLocale::Language language, QList pages) - : m_language(language) +ReportTranslation::ReportTranslation(QLocale::Language language, QList pages): + m_language(language) { - foreach (PageDesignIntf* page, pages){ + foreach (PageDesignIntf* page, pages) { m_pagesTranslation.append(createPageTranslation(page)); } } -ReportTranslation::ReportTranslation(const ReportTranslation& reportTranslation) - :m_language(reportTranslation.m_language) +ReportTranslation::ReportTranslation(const ReportTranslation& reportTranslation): + m_language(reportTranslation.m_language) { - foreach(PageTranslation* pageTranslation, reportTranslation.m_pagesTranslation){ + foreach (PageTranslation* pageTranslation, reportTranslation.m_pagesTranslation) { m_pagesTranslation.append(pageTranslation); } } ReportTranslation::~ReportTranslation() { - foreach(PageTranslation* page, m_pagesTranslation){ + foreach (PageTranslation* page, m_pagesTranslation) { delete page; } m_pagesTranslation.clear(); @@ -34,19 +34,21 @@ PageTranslation* ReportTranslation::createPageTranslation(PageDesignIntf* page) PageTranslation* pageTranslation = new PageTranslation; pageTranslation->checked = true; pageTranslation->pageName = page->pageItem()->objectName(); - foreach(BaseDesignIntf* item, page->pageItem()->allChildBaseItems()){ + foreach (BaseDesignIntf* item, page->pageItem()->allChildBaseItems()) { createItemTranslation(item, pageTranslation); } return pageTranslation; } -void ReportTranslation::createItemTranslation(BaseDesignIntf* item, PageTranslation* pageTranslation){ - QMap stringsForTranslation = item->getStringForTranslation(); - if (!stringsForTranslation.isEmpty()){ +void ReportTranslation::createItemTranslation(BaseDesignIntf* item, + PageTranslation* pageTranslation) +{ + QMap stringsForTranslation = item->getStringForTranslation(); + if (!stringsForTranslation.isEmpty()) { ItemTranslation* itemTranslation = new ItemTranslation; itemTranslation->checked = true; itemTranslation->itemName = item->objectName(); - foreach(QString propertyName, stringsForTranslation.keys()){ + foreach (QString propertyName, stringsForTranslation.keys()) { PropertyTranslation* propertyTranslation = new PropertyTranslation; propertyTranslation->propertyName = propertyName; propertyTranslation->value = stringsForTranslation.value(propertyName); @@ -61,25 +63,25 @@ void ReportTranslation::createItemTranslation(BaseDesignIntf* item, PageTranslat PageTranslation* ReportTranslation::findPageTranslation(const QString& pageName) { - foreach(PageTranslation* page, m_pagesTranslation){ - if (page->pageName.compare(pageName) == 0){ + foreach (PageTranslation* page, m_pagesTranslation) { + if (page->pageName.compare(pageName) == 0) { return page; } } return 0; } -void ReportTranslation::renamePage(const QString &oldName, const QString &newName) +void ReportTranslation::renamePage(const QString& oldName, const QString& newName) { PageTranslation* page = findPageTranslation(oldName); - if (page){ + if (page) { page->pageName = newName; } } void ReportTranslation::invalidatePages() { - foreach(PageTranslation* page, m_pagesTranslation){ + foreach (PageTranslation* page, m_pagesTranslation) { page->checked = false; } } @@ -87,78 +89,81 @@ void ReportTranslation::invalidatePages() void ReportTranslation::clearInvalidPages() { QList::Iterator it = m_pagesTranslation.begin(); - while (it != m_pagesTranslation.end()){ - if (!(*it)->checked){ + while (it != m_pagesTranslation.end()) { + if (!(*it)->checked) { delete *it; it = m_pagesTranslation.erase(it); - } else ++it; + } else + ++it; } } void ReportTranslation::updatePageTranslation(PageDesignIntf* page) { PageTranslation* pageTranslation = findPageTranslation(page->pageItem()->objectName()); - if (!pageTranslation){ - pageTranslation = createPageTranslation(page); - m_pagesTranslation.append(pageTranslation); + if (!pageTranslation) { + pageTranslation = createPageTranslation(page); + m_pagesTranslation.append(pageTranslation); } - if (pageTranslation){ + if (pageTranslation) { pageTranslation->checked = true; - foreach(ItemTranslation* item, pageTranslation->itemsTranslation){ + foreach (ItemTranslation* item, pageTranslation->itemsTranslation) { item->checked = false; } - foreach(BaseDesignIntf* item, page->pageItem()->allChildBaseItems()){ - QMap stringsForTranslation = item->getStringForTranslation(); - if (!stringsForTranslation.isEmpty()){ - ItemTranslation* itemTranslation = pageTranslation->itemsTranslation.value(item->objectName()); - if (itemTranslation){ - foreach(QString propertyName, stringsForTranslation.keys()){ - PropertyTranslation* propertyTranslation = itemTranslation->findProperty(propertyName); - bool translated = propertyTranslation->sourceValue != propertyTranslation->value; + foreach (BaseDesignIntf* item, page->pageItem()->allChildBaseItems()) { + QMap stringsForTranslation = item->getStringForTranslation(); + if (!stringsForTranslation.isEmpty()) { + ItemTranslation* itemTranslation + = pageTranslation->itemsTranslation.value(item->objectName()); + if (itemTranslation) { + foreach (QString propertyName, stringsForTranslation.keys()) { + PropertyTranslation* propertyTranslation + = itemTranslation->findProperty(propertyName); + bool translated + = propertyTranslation->sourceValue != propertyTranslation->value; if (propertyTranslation->checked) - propertyTranslation->sourceHasBeenChanged = propertyTranslation->sourceValue != stringsForTranslation.value(propertyName); + propertyTranslation->sourceHasBeenChanged + = propertyTranslation->sourceValue + != stringsForTranslation.value(propertyName); if (propertyTranslation->sourceHasBeenChanged) propertyTranslation->checked = false; - propertyTranslation->sourceValue = stringsForTranslation.value(propertyName); - if (!translated) propertyTranslation->value = propertyTranslation->sourceValue; + propertyTranslation->sourceValue + = stringsForTranslation.value(propertyName); + if (!translated) + propertyTranslation->value = propertyTranslation->sourceValue; } itemTranslation->checked = true; } else { - createItemTranslation(item, pageTranslation); + createItemTranslation(item, pageTranslation); } } } QHash::Iterator it = pageTranslation->itemsTranslation.begin(); - while( it != pageTranslation->itemsTranslation.end()){ + while (it != pageTranslation->itemsTranslation.end()) { if (!it.value()->checked) { delete it.value(); it = pageTranslation->itemsTranslation.erase(it); - } else ++it; + } else + ++it; } } } -QList& ReportTranslation::pagesTranslation() -{ - return m_pagesTranslation; -} +QList& ReportTranslation::pagesTranslation() { return m_pagesTranslation; } -PageTranslation*ReportTranslation::createEmptyPageTranslation() +PageTranslation* ReportTranslation::createEmptyPageTranslation() { PageTranslation* pageTranslation = new PageTranslation; m_pagesTranslation.append(pageTranslation); return pageTranslation; } -QLocale::Language ReportTranslation::language() const -{ - return m_language; -} +QLocale::Language ReportTranslation::language() const { return m_language; } PropertyTranslation* ItemTranslation::findProperty(const QString& propertyName) { - foreach(PropertyTranslation* propertyTranslation, propertyesTranslation){ - if (propertyTranslation->propertyName.compare(propertyName) == 0){ + foreach (PropertyTranslation* propertyTranslation, propertyesTranslation) { + if (propertyTranslation->propertyName.compare(propertyName) == 0) { return propertyTranslation; } } @@ -167,26 +172,26 @@ PropertyTranslation* ItemTranslation::findProperty(const QString& propertyName) ItemTranslation::~ItemTranslation() { - foreach(PropertyTranslation* property, propertyesTranslation){ + foreach (PropertyTranslation* property, propertyesTranslation) { delete property; } } PageTranslation::~PageTranslation() { - foreach(ItemTranslation* item, itemsTranslation){ + foreach (ItemTranslation* item, itemsTranslation) { delete item; } } -void PageTranslation::renameItem(const QString &oldName, const QString &newName) +void PageTranslation::renameItem(const QString& oldName, const QString& newName) { ItemTranslation* item = itemsTranslation.value(oldName); - if (item){ + if (item) { itemsTranslation.remove(oldName); item->itemName = newName; itemsTranslation[newName] = item; } } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrreporttranslation.h b/limereport/lrreporttranslation.h index 8fb6e1e..e0dce17 100644 --- a/limereport/lrreporttranslation.h +++ b/limereport/lrreporttranslation.h @@ -1,35 +1,34 @@ #ifndef REPORTTRANSLATION_H #define REPORTTRANSLATION_H -#include +#include "lrpagedesignintf.h" + #include #include #include +#include -#include "lrpagedesignintf.h" - - -class ATranslationProperty{ +class ATranslationProperty { public: - ATranslationProperty(){} - ATranslationProperty(const ACollectionProperty& ){} - virtual ~ATranslationProperty(){} + ATranslationProperty() { } + ATranslationProperty(const ACollectionProperty&) { } + virtual ~ATranslationProperty() { } }; Q_DECLARE_METATYPE(ATranslationProperty) const int TRANSLATION_TYPE_ID = qMetaTypeId(); -namespace LimeReport{ +namespace LimeReport { -struct PropertyTranslation{ +struct PropertyTranslation { QString propertyName; QString value; QString sourceValue; - bool checked; - bool sourceHasBeenChanged; + bool checked; + bool sourceHasBeenChanged; }; -struct ItemTranslation{ +struct ItemTranslation { QString itemName; bool checked; PropertyTranslation* findProperty(const QString& propertyName); @@ -37,7 +36,7 @@ struct ItemTranslation{ QList propertyesTranslation; }; -struct PageTranslation{ +struct PageTranslation { QString pageName; bool checked; ~PageTranslation(); @@ -45,35 +44,36 @@ struct PageTranslation{ QHash itemsTranslation; }; -class ReportTranslation{ +class ReportTranslation { public: - ReportTranslation(QLocale::Language language) :m_language(language){} + ReportTranslation(QLocale::Language language): m_language(language) { } ReportTranslation(QLocale::Language language, QList pages); ReportTranslation(const ReportTranslation& reportTranslation); ~ReportTranslation(); QLocale::Language language() const; - QList &pagesTranslation(); + QList& pagesTranslation(); PageTranslation* createEmptyPageTranslation(); void updatePageTranslation(PageDesignIntf* page); PageTranslation* findPageTranslation(const QString& pageName); void renamePage(const QString& oldName, const QString& newName); void invalidatePages(); void clearInvalidPages(); + private: void createItemTranslation(BaseDesignIntf* item, PageTranslation* pageTranslation); PageTranslation* createPageTranslation(PageDesignIntf* page); + private: QLocale::Language m_language; QLocale::Script m_script; QList m_pagesTranslation; }; - typedef QMap Translations; -class ITranslationContainer{ +class ITranslationContainer { public: - virtual ~ITranslationContainer(){} + virtual ~ITranslationContainer() { } virtual Translations* translations() = 0; virtual void updateTranslations() = 0; virtual bool addTranslationLanguage(QLocale::Language language) = 0; @@ -83,6 +83,6 @@ public: } // namespace LimeReport -//Q_DECLARE_METATYPE(ReportTranslation) +// Q_DECLARE_METATYPE(ReportTranslation) #endif // REPORTTRANSLATION_H diff --git a/limereport/lrscriptenginemanager.cpp b/limereport/lrscriptenginemanager.cpp index c940f8b..3d1a4aa 100644 --- a/limereport/lrscriptenginemanager.cpp +++ b/limereport/lrscriptenginemanager.cpp @@ -37,50 +37,53 @@ #endif #include #ifdef HAVE_UI_LOADER -#include #include +#include #include #endif -#include "lrdatasourcemanager.h" -#include "lrbasedesignintf.h" #include "lrbanddesignintf.h" +#include "lrbasedesignintf.h" +#include "lrdatasourcemanager.h" #include "lrpageitemdesignintf.h" Q_DECLARE_METATYPE(QColor) Q_DECLARE_METATYPE(QFont) -Q_DECLARE_METATYPE(LimeReport::ScriptEngineManager *) +Q_DECLARE_METATYPE(LimeReport::ScriptEngineManager*) #ifdef USE_QTSCRIPTENGINE -QScriptValue constructColor(QScriptContext *context, QScriptEngine *engine) +QScriptValue constructColor(QScriptContext* context, QScriptEngine* engine) { QColor color(context->argument(0).toString()); return engine->toScriptValue(color); } #endif -namespace LimeReport{ +namespace LimeReport { -ScriptEngineNode::ScriptEngineNode(const QString &name, const QString &description, - ScriptEngineNode::NodeType type, ScriptEngineNode *parent, const QIcon &icon) - :m_name(name), m_description(description), m_icon(icon), m_type(type), m_parent(parent) -{} - -ScriptEngineNode::~ScriptEngineNode() +ScriptEngineNode::ScriptEngineNode(const QString& name, const QString& description, + ScriptEngineNode::NodeType type, ScriptEngineNode* parent, + const QIcon& icon): + m_name(name), + m_description(description), + m_icon(icon), + m_type(type), + m_parent(parent) { - qDeleteAll(m_childs.begin(), m_childs.end()); } -ScriptEngineNode*ScriptEngineNode::addChild(const QString& name, const QString& description, - ScriptEngineNode::NodeType type, const QIcon& icon) +ScriptEngineNode::~ScriptEngineNode() { qDeleteAll(m_childs.begin(), m_childs.end()); } + +ScriptEngineNode* ScriptEngineNode::addChild(const QString& name, const QString& description, + ScriptEngineNode::NodeType type, const QIcon& icon) { - ScriptEngineNode* res = new ScriptEngineNode(name, description, type,this,icon); + ScriptEngineNode* res = new ScriptEngineNode(name, description, type, this, icon); m_childs.push_back(res); return res; } int ScriptEngineNode::row() { - if (m_parent){ + if (m_parent) { return m_parent->m_childs.indexOf(const_cast(this)); } return 0; @@ -88,32 +91,33 @@ int ScriptEngineNode::row() void ScriptEngineNode::clear() { - for (int i=0; iparent(); - if ((parentNode == m_rootNode) || (!parentNode)) return QModelIndex(); - return createIndex(parentNode->row(),0,parentNode); + if ((parentNode == m_rootNode) || (!parentNode)) + return QModelIndex(); + return createIndex(parentNode->row(), 0, parentNode); } QModelIndex ScriptEngineModel::index(int row, int column, const QModelIndex& parent) const @@ -121,25 +125,27 @@ QModelIndex ScriptEngineModel::index(int row, int column, const QModelIndex& par if (!m_rootNode) return QModelIndex(); - if (!hasIndex(row,column,parent)) + if (!hasIndex(row, column, parent)) return QModelIndex(); ScriptEngineNode* parentNode; - if (parent.isValid()){ + if (parent.isValid()) { parentNode = nodeFromIndex(parent); } else { parentNode = m_rootNode; } ScriptEngineNode* childNode = parentNode->child(row); - if (childNode){ - return createIndex(row,column,childNode); - } else return QModelIndex(); + if (childNode) { + return createIndex(row, column, childNode); + } else + return QModelIndex(); } int ScriptEngineModel::rowCount(const QModelIndex& parent) const { - if (!m_rootNode) return 0; + if (!m_rootNode) + return 0; ScriptEngineNode* parentNode; if (parent.isValid()) parentNode = nodeFromIndex(parent); @@ -156,14 +162,16 @@ int ScriptEngineModel::columnCount(const QModelIndex& parent) const QVariant ScriptEngineModel::data(const QModelIndex& index, int role) const { - ScriptEngineNode *node = nodeFromIndex(index); + ScriptEngineNode* node = nodeFromIndex(index); switch (role) { case Qt::DisplayRole: - if (!node) return QVariant(); + if (!node) + return QVariant(); return node->name(); break; - case Qt::DecorationRole : - if (!node) return QIcon(); + case Qt::DecorationRole: + if (!node) + return QIcon(); return node->icon(); break; default: @@ -177,33 +185,33 @@ void ScriptEngineModel::setScriptEngineManager(ScriptEngineManager* scriptManage updateModel(); } -void ScriptEngineModel::slotScriptEngineChanged() -{ - updateModel(); -} +void ScriptEngineModel::slotScriptEngineChanged() { updateModel(); } -ScriptEngineNode*ScriptEngineModel::nodeFromIndex(const QModelIndex& index) const +ScriptEngineNode* ScriptEngineModel::nodeFromIndex(const QModelIndex& index) const { - if (index.isValid()){ + if (index.isValid()) { return static_cast(index.internalPointer()); - } else return m_rootNode; + } else + return m_rootNode; } void ScriptEngineModel::updateModel() { beginResetModel(); m_rootNode->clear(); - QMap categories; - foreach(ScriptFunctionDesc funcDesc, m_scriptManager->functionsDescribers()){ + QMap categories; + foreach (ScriptFunctionDesc funcDesc, m_scriptManager->functionsDescribers()) { ScriptEngineNode* categ; - QString categoryName = (!funcDesc.category.isEmpty())?funcDesc.category:"NO CATEGORY"; - if (categories.contains(categoryName)){ + QString categoryName = (!funcDesc.category.isEmpty()) ? funcDesc.category : "NO CATEGORY"; + if (categories.contains(categoryName)) { categ = categories.value(categoryName); } else { - categ = m_rootNode->addChild(categoryName,"",ScriptEngineNode::Category,QIcon(":/report/images/folder")); - categories.insert(categoryName,categ); + categ = m_rootNode->addChild(categoryName, "", ScriptEngineNode::Category, + QIcon(":/report/images/folder")); + categories.insert(categoryName, categ); } - categ->addChild(funcDesc.name,funcDesc.description,ScriptEngineNode::Function,QIcon(":/report/images/function")); + categ->addChild(funcDesc.name, funcDesc.description, ScriptEngineNode::Function, + QIcon(":/report/images/function")); } endResetModel(); } @@ -215,7 +223,7 @@ ScriptEngineManager::~ScriptEngineManager() delete m_scriptEngine; } -bool ScriptEngineManager::isFunctionExists(const QString &functionName) const +bool ScriptEngineManager::isFunctionExists(const QString& functionName) const { return m_functions.contains(functionName); // foreach (ScriptFunctionDesc desc, m_functions.values()) { @@ -226,30 +234,30 @@ bool ScriptEngineManager::isFunctionExists(const QString &functionName) const // return false; } -void ScriptEngineManager::deleteFunction(const QString &functionsName) +void ScriptEngineManager::deleteFunction(const QString& functionsName) { m_functions.remove(functionsName); } -bool ScriptEngineManager::addFunction(const JSFunctionDesc &functionDescriber) +bool ScriptEngineManager::addFunction(const JSFunctionDesc& functionDescriber) { - if (m_functions.contains(functionDescriber.name())) return false; - ScriptValueType functionManager = scriptEngine()->globalObject().property(functionDescriber.managerName()); + if (m_functions.contains(functionDescriber.name())) + return false; + ScriptValueType functionManager + = scriptEngine()->globalObject().property(functionDescriber.managerName()); #ifdef USE_QJSENGINE - if (functionManager.isUndefined()){ + if (functionManager.isUndefined()) { #else - if (!functionManager.isValid()){ + if (!functionManager.isValid()) { #endif functionManager = scriptEngine()->newQObject(functionDescriber.manager()); - scriptEngine()->globalObject().setProperty( - functionDescriber.managerName(), - functionManager - ); + scriptEngine()->globalObject().setProperty(functionDescriber.managerName(), + functionManager); } - if (functionManager.toQObject() == functionDescriber.manager()){ + if (functionManager.toQObject() == functionDescriber.manager()) { ScriptValueType checkWrapper = scriptEngine()->evaluate(functionDescriber.scriptWrapper()); - if (!checkWrapper.isError()){ + if (!checkWrapper.isError()) { ScriptFunctionDesc funct; funct.name = functionDescriber.name(); funct.description = functionDescriber.description(); @@ -267,7 +275,6 @@ bool ScriptEngineManager::addFunction(const JSFunctionDesc &functionDescriber) m_lastError = tr("Function manager with name \"%1\" already exists!"); return false; } - } #ifdef USE_QTSCRIPTENGINE @@ -276,10 +283,9 @@ Q_DECL_DEPRECATED #endif bool ScriptEngineManager::addFunction(const QString& name, QScriptEngine::FunctionSignature function, - const QString& category, - const QString& description) + const QString& category, const QString& description) { - if (!isFunctionExists(name)){ + if (!isFunctionExists(name)) { ScriptFunctionDesc funct; funct.name = name; funct.description = description; @@ -299,13 +305,14 @@ bool ScriptEngineManager::addFunction(const QString& name, } #endif -bool ScriptEngineManager::addFunction(const QString& name, const QString& script, const QString& category, const QString& description) +bool ScriptEngineManager::addFunction(const QString& name, const QString& script, + const QString& category, const QString& description) { ScriptValueType functionValue = m_scriptEngine->evaluate(script); - if (!functionValue.isError()){ + if (!functionValue.isError()) { ScriptFunctionDesc funct; funct.scriptValue = functionValue; - funct.name = name; + funct.name = name; funct.category = category; funct.description = description; funct.type = ScriptFunctionDesc::Script; @@ -328,90 +335,92 @@ QStringList ScriptEngineManager::functionsNames() // return res; } -void ScriptEngineManager::setDataManager(DataSourceManager *dataManager){ - if (dataManager && m_dataManager != dataManager){ +void ScriptEngineManager::setDataManager(DataSourceManager* dataManager) +{ + if (dataManager && m_dataManager != dataManager) { m_dataManager = dataManager; - if (m_dataManager){ - foreach(QString func, m_dataManager->groupFunctionNames()){ + if (m_dataManager) { + foreach (QString func, m_dataManager->groupFunctionNames()) { JSFunctionDesc describer( - func, - tr("GROUP FUNCTIONS"), - func+"(\""+tr("FieldName")+"\",\""+tr("BandName")+"\")", - LimeReport::Const::FUNCTION_MANAGER_NAME, - m_functionManager, - QString("function %1(fieldName, bandName, pageitem){\ + func, tr("GROUP FUNCTIONS"), + func + "(\"" + tr("FieldName") + "\",\"" + tr("BandName") + "\")", + LimeReport::Const::FUNCTION_MANAGER_NAME, m_functionManager, + QString("function %1(fieldName, bandName, pageitem){\ if (typeof pageitem == 'undefined') return %2.calcGroupFunction(\"%1\", fieldName, bandName); \ - else return %2.calcGroupFunction(\"%1\", fieldName, bandName, pageitem);}" - ).arg(func) - .arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); - addFunction(describer); + else return %2.calcGroupFunction(\"%1\", fieldName, bandName, pageitem);}") + .arg(func) + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); + addFunction(describer); } - moveQObjectToScript(new DatasourceFunctions(dataManager), LimeReport::Const::DATAFUNCTIONS_MANAGER_NAME); + moveQObjectToScript(new DatasourceFunctions(dataManager), + LimeReport::Const::DATAFUNCTIONS_MANAGER_NAME); } } } -QString ScriptEngineManager::expandUserVariables(QString context, RenderPass /* pass */, ExpandType expandType, QVariant &varValue) +QString ScriptEngineManager::expandUserVariables(QString context, RenderPass /* pass */, + ExpandType expandType, QVariant& varValue) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(Const::VARIABLE_RX); - if (context.contains(rx)){ + if (context.contains(rx)) { int pos = 0; - while ((pos = rx.indexIn(context,pos))!=-1){ - QString variable=rx.cap(1); + while ((pos = rx.indexIn(context, pos)) != -1) { + QString variable = rx.cap(1); pos += rx.matchedLength(); - if (dataManager()->containsVariable(variable) ){ + if (dataManager()->containsVariable(variable)) { try { varValue = dataManager()->variable(variable); - switch (expandType){ + switch (expandType) { case EscapeSymbols: - context.replace(rx.cap(0),escapeSimbols(varValue.toString())); + context.replace(rx.cap(0), escapeSimbols(varValue.toString())); break; case NoEscapeSymbols: - context.replace(rx.cap(0),varValue.toString()); + context.replace(rx.cap(0), varValue.toString()); break; case ReplaceHTMLSymbols: - context.replace(rx.cap(0),replaceHTMLSymbols(varValue.toString())); + context.replace(rx.cap(0), replaceHTMLSymbols(varValue.toString())); break; } - pos=0; + pos = 0; - } catch (ReportError &e){ + } catch (ReportError& e) { dataManager()->putError(e.what()); - if (!dataManager()->reportSettings() || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) - context.replace(rx.cap(0),e.what()); + if (!dataManager()->reportSettings() + || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + context.replace(rx.cap(0), e.what()); else - context.replace(rx.cap(0),""); + context.replace(rx.cap(0), ""); } } else { QString error; error = tr("Variable %1 not found").arg(variable); dataManager()->putError(error); - if (!dataManager()->reportSettings() || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) - context.replace(rx.cap(0),error); + if (!dataManager()->reportSettings() + || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + context.replace(rx.cap(0), error); else - context.replace(rx.cap(0),""); + context.replace(rx.cap(0), ""); } } } return context; #else QRegularExpression rx = getVariableRegEx(); - if (context.contains(rx)){ + if (context.contains(rx)) { int pos = 0; QRegularExpressionMatch match = rx.match(context, pos); - while (match.hasMatch()){ + while (match.hasMatch()) { - QString variable=match.captured(1); + QString variable = match.captured(1); pos = match.capturedEnd(); - if (dataManager()->containsVariable(variable) ){ + if (dataManager()->containsVariable(variable)) { try { varValue = dataManager()->variable(variable); - switch (expandType){ + switch (expandType) { case EscapeSymbols: context.replace(match.captured(0), escapeSimbols(varValue.toString())); break; @@ -425,9 +434,10 @@ QString ScriptEngineManager::expandUserVariables(QString context, RenderPass /* pos = 0; - } catch (ReportError &e){ + } catch (ReportError& e) { dataManager()->putError(e.what()); - if (!dataManager()->reportSettings() || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + if (!dataManager()->reportSettings() + || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) context.replace(match.captured(0), e.what()); else context.replace(match.captured(0), ""); @@ -437,7 +447,8 @@ QString ScriptEngineManager::expandUserVariables(QString context, RenderPass /* QString error; error = tr("Variable %1 not found").arg(variable); dataManager()->putError(error); - if (!dataManager()->reportSettings() || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + if (!dataManager()->reportSettings() + || dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) context.replace(match.captured(0), error); else context.replace(match.captured(0), ""); @@ -450,21 +461,22 @@ QString ScriptEngineManager::expandUserVariables(QString context, RenderPass /* #endif } -QString ScriptEngineManager::expandDataFields(QString context, ExpandType expandType, QVariant &varValue, QObject *reportItem) +QString ScriptEngineManager::expandDataFields(QString context, ExpandType expandType, + QVariant& varValue, QObject* reportItem) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(Const::FIELD_RX); - if (context.contains(rx)){ - while ((rx.indexIn(context))!=-1){ - QString field=rx.cap(1); + if (context.contains(rx)) { + while ((rx.indexIn(context)) != -1) { + QString field = rx.cap(1); if (dataManager()->containsField(field)) { QString fieldValue; varValue = dataManager()->fieldData(field); if (expandType == EscapeSymbols) { if (varValue.isNull()) { - fieldValue="\"\""; + fieldValue = "\"\""; } else { fieldValue = escapeSimbols(varValue.toString()); switch (dataManager()->fieldData(field).type()) { @@ -473,7 +485,7 @@ QString ScriptEngineManager::expandDataFields(QString context, ExpandType expand case QVariant::StringList: case QVariant::Date: case QVariant::DateTime: - fieldValue = "\""+fieldValue+"\""; + fieldValue = "\"" + fieldValue + "\""; break; default: break; @@ -482,22 +494,25 @@ QString ScriptEngineManager::expandDataFields(QString context, ExpandType expand } else { if (expandType == ReplaceHTMLSymbols) fieldValue = replaceHTMLSymbols(varValue.toString()); - else fieldValue = varValue.toString(); + else + fieldValue = varValue.toString(); } - context.replace(rx.cap(0),fieldValue); + context.replace(rx.cap(0), fieldValue); } else { QString error; - if (reportItem){ - error = tr("Field %1 not found in %2!").arg(field).arg(reportItem->objectName()); + if (reportItem) { + error + = tr("Field %1 not found in %2!").arg(field).arg(reportItem->objectName()); dataManager()->putError(error); } varValue = QVariant(); - if (!dataManager()->reportSettings() || !dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) - context.replace(rx.cap(0),error); + if (!dataManager()->reportSettings() + || !dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + context.replace(rx.cap(0), error); else - context.replace(rx.cap(0),""); + context.replace(rx.cap(0), ""); } } } @@ -505,63 +520,66 @@ QString ScriptEngineManager::expandDataFields(QString context, ExpandType expand return context; #else QRegularExpression rx = getFieldRegEx(); - if (context.contains(rx)){ + if (context.contains(rx)) { QRegularExpressionMatch match = rx.match(context); - while (match.hasMatch()){ + while (match.hasMatch()) { - QString field=match.captured(1); + QString field = match.captured(1); if (dataManager()->containsField(field)) { QString fieldValue; varValue = dataManager()->fieldData(field); if (expandType == EscapeSymbols) { if (varValue.isNull()) { - fieldValue="\"\""; + fieldValue = "\"\""; } else { fieldValue = escapeSimbols(varValue.toString()); - //TODO: Migrate to QMetaType + // TODO: Migrate to QMetaType #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) switch (dataManager()->fieldData(field).typeId()) { - case QMetaType::QChar: - case QMetaType::QString: - case QMetaType::QStringList: - case QMetaType::QDate: - case QMetaType::QDateTime: - fieldValue = "\""+fieldValue+"\""; - break; - default: - break; + case QMetaType::QChar: + case QMetaType::QString: + case QMetaType::QStringList: + case QMetaType::QDate: + case QMetaType::QDateTime: + fieldValue = "\"" + fieldValue + "\""; + break; + default: + break; } #else switch (dataManager()->fieldData(field).type()) { - case QVariant::Char: - case QVariant::String: - case QVariant::StringList: - case QVariant::Date: - case QVariant::DateTime: - fieldValue = "\""+fieldValue+"\""; - break; - default: - break; + case QVariant::Char: + case QVariant::String: + case QVariant::StringList: + case QVariant::Date: + case QVariant::DateTime: + fieldValue = "\"" + fieldValue + "\""; + break; + default: + break; } #endif } } else { if (expandType == ReplaceHTMLSymbols) fieldValue = replaceHTMLSymbols(varValue.toString()); - else fieldValue = varValue.toString(); + else + fieldValue = varValue.toString(); } - context.replace(match.captured(0),fieldValue); + context.replace(match.captured(0), fieldValue); } else { QString error; - if (reportItem){ - error = tr("Field %1 not found in %2!").arg(field).arg(reportItem->objectName()); + if (reportItem) { + error + = tr("Field %1 not found in %2!").arg(field).arg(reportItem->objectName()); dataManager()->putError(error); } varValue = QVariant(); - if (!dataManager()->reportSettings() || !dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) + if (!dataManager()->reportSettings() + || !dataManager()->reportSettings()->suppressAbsentFieldsAndVarsWarnings()) context.replace(match.captured(0), error); else context.replace(match.captured(0), ""); @@ -574,15 +592,15 @@ QString ScriptEngineManager::expandDataFields(QString context, ExpandType expand #endif } -QString ScriptEngineManager::expandScripts(QString context, QVariant& varValue, QObject *reportItem) +QString ScriptEngineManager::expandScripts(QString context, QVariant& varValue, QObject* reportItem) { #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(Const::SCRIPT_RX); - if (context.contains(rx)){ + if (context.contains(rx)) { #else QRegularExpression rx = getScriptRegEx(); - if(context.contains(rx)){ + if (context.contains(rx)) { #endif if (ScriptEngineManager::instance().dataManager() != dataManager()) @@ -590,41 +608,43 @@ QString ScriptEngineManager::expandScripts(QString context, QVariant& varValue, ScriptEngineType* se = ScriptEngineManager::instance().scriptEngine(); - if (reportItem){ + if (reportItem) { ScriptValueType svThis; #ifdef USE_QJSENGINE svThis = getJSValue(*se, reportItem); - se->globalObject().setProperty("THIS",svThis); + se->globalObject().setProperty("THIS", svThis); #else svThis = se->globalObject().property("THIS"); - if (svThis.isValid()){ + if (svThis.isValid()) { se->newQObject(svThis, reportItem); } else { svThis = se->newQObject(reportItem); - se->globalObject().setProperty("THIS",svThis); + se->globalObject().setProperty("THIS", svThis); } #endif } ScriptExtractor scriptExtractor(context); - if (scriptExtractor.parse()){ - context = replaceScripts(context, varValue, reportItem, se, scriptExtractor.scriptTree()); + if (scriptExtractor.parse()) { + context + = replaceScripts(context, varValue, reportItem, se, scriptExtractor.scriptTree()); } - } return context; } -QString ScriptEngineManager::replaceScripts(QString context, QVariant &varValue, QObject *reportItem, ScriptEngineType* se, ScriptNode::Ptr scriptTree) +QString ScriptEngineManager::replaceScripts(QString context, QVariant& varValue, + QObject* reportItem, ScriptEngineType* se, + ScriptNode::Ptr scriptTree) { - foreach(ScriptNode::Ptr item, scriptTree->children()){ + foreach (ScriptNode::Ptr item, scriptTree->children()) { QString scriptBody = expandDataFields(item->body(), EscapeSymbols, varValue, reportItem); if (item->children().size() > 0) scriptBody = replaceScripts(scriptBody, varValue, reportItem, se, item); scriptBody = expandUserVariables(scriptBody, FirstPass, EscapeSymbols, varValue); ScriptValueType value = se->evaluate(scriptBody); #ifdef USE_QJSENGINE - if (!value.isError()){ + if (!value.isError()) { varValue = value.toVariant(); context.replace(item->script(), value.toString()); } else { @@ -642,32 +662,34 @@ QString ScriptEngineManager::replaceScripts(QString context, QVariant &varValue, return context; } -QVariant ScriptEngineManager::evaluateScript(const QString& script){ +QVariant ScriptEngineManager::evaluateScript(const QString& script) +{ #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QRegExp rx(Const::SCRIPT_RX); QVariant varValue; - if (script.contains(rx)){ -#else + if (script.contains(rx)) { +#else QRegularExpression rx = getScriptRegEx(); QVariant varValue; - if (script.contains(rx)){ + if (script.contains(rx)) { #endif - if (ScriptEngineManager::instance().dataManager()!=dataManager()) + if (ScriptEngineManager::instance().dataManager() != dataManager()) ScriptEngineManager::instance().setDataManager(dataManager()); ScriptEngineType* se = ScriptEngineManager::instance().scriptEngine(); ScriptExtractor scriptExtractor(script); - if (scriptExtractor.parse()){ - QString scriptBody = expandDataFields(scriptExtractor.scriptTree()->body(), EscapeSymbols, varValue, 0); + if (scriptExtractor.parse()) { + QString scriptBody = expandDataFields(scriptExtractor.scriptTree()->body(), + EscapeSymbols, varValue, 0); scriptBody = expandUserVariables(scriptBody, FirstPass, EscapeSymbols, varValue); ScriptValueType value = se->evaluate(scriptBody); #ifdef USE_QJSENGINE - if (!value.isError()){ + if (!value.isError()) { #else if (!se->hasUncaughtException()) { #endif @@ -678,9 +700,10 @@ QVariant ScriptEngineManager::evaluateScript(const QString& script){ return QVariant(); } -void ScriptEngineManager::addBookMark(const QString& uniqKey, const QString& content){ +void ScriptEngineManager::addBookMark(const QString& uniqKey, const QString& content) +{ Q_ASSERT(m_context != 0); - if (m_context){ + if (m_context) { BandDesignIntf* currentBand = m_context->currentBand(); if (currentBand) currentBand->addBookmark(uniqKey, content); @@ -690,43 +713,47 @@ void ScriptEngineManager::addBookMark(const QString& uniqKey, const QString& con } } -int ScriptEngineManager::findPageIndexByBookmark(const QString &uniqKey) +int ScriptEngineManager::findPageIndexByBookmark(const QString& uniqKey) { - for (int i=0; i < m_context->reportPages()->size(); ++i){ + for (int i = 0; i < m_context->reportPages()->size(); ++i) { if (m_context->reportPages()->at(i)->bookmarks().contains(uniqKey)) - return i+1; - foreach(BandDesignIntf* band, m_context->reportPages()->at(i)->bands()){ + return i + 1; + foreach (BandDesignIntf* band, m_context->reportPages()->at(i)->bands()) { if (band->bookmarks().contains(uniqKey)) - return i+1; + return i + 1; } } return -1; } -int ScriptEngineManager::getPageFreeSpace(PageItemDesignIntf* page){ - if (page){ +int ScriptEngineManager::getPageFreeSpace(PageItemDesignIntf* page) +{ + if (page) { int height = 0; - foreach(BandDesignIntf* band, page->bands()){ - if(band->type() == BandDesignIntf::Data) - { - height += band->geometry().height() * m_dataManager->dataSource(band->datasourceName())->model()->rowCount(); - } - else height += band->height(); + foreach (BandDesignIntf* band, page->bands()) { + if (band->type() == BandDesignIntf::Data) { + height += band->geometry().height() + * m_dataManager->dataSource(band->datasourceName())->model()->rowCount(); + } else + height += band->height(); } - return page->height() - height - (page->pageFooter()?page->pageFooter()->height() : 0); - } else return -1; + return page->height() - height - (page->pageFooter() ? page->pageFooter()->height() : 0); + } else + return -1; } -void ScriptEngineManager::addTableOfContentsItem(const QString& uniqKey, const QString& content, int indent) +void ScriptEngineManager::addTableOfContentsItem(const QString& uniqKey, const QString& content, + int indent) { Q_ASSERT(m_context != 0); - if (m_context){ + if (m_context) { m_context->tableOfContents()->setItem(uniqKey, content, 0, indent); addBookMark(uniqKey, content); } } -void ScriptEngineManager::clearTableOfContents(){ +void ScriptEngineManager::clearTableOfContents() +{ if (m_context) { if (m_context->tableOfContents()) m_context->tableOfContents()->clear(); @@ -736,16 +763,14 @@ void ScriptEngineManager::clearTableOfContents(){ ScriptValueType ScriptEngineManager::moveQObjectToScript(QObject* object, const QString objectName) { ScriptValueType obj = scriptEngine()->globalObject().property(objectName); - if (!obj.isNull()) delete obj.toQObject(); + if (!obj.isNull()) + delete obj.toQObject(); ScriptValueType result = scriptEngine()->newQObject(object); scriptEngine()->globalObject().setProperty(objectName, result); return result; } -void ScriptEngineManager::updateModel() -{ - -} +void ScriptEngineManager::updateModel() { } bool ScriptEngineManager::createLineFunction() { @@ -755,11 +780,11 @@ bool ScriptEngineManager::createLineFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("SYSTEM")); fd.setName("line"); - fd.setDescription("line(\""+tr("BandName")+"\")"); - fd.setScriptWrapper(QString("function line(bandName){ return %1.line(bandName);}").arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); + fd.setDescription("line(\"" + tr("BandName") + "\")"); + fd.setScriptWrapper(QString("function line(bandName){ return %1.line(bandName);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); - } bool ScriptEngineManager::createNumberFomatFunction() @@ -770,65 +795,64 @@ bool ScriptEngineManager::createNumberFomatFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("NUMBER")); fd.setName("numberFormat"); - fd.setDescription("numberFormat(\""+tr("Value")+"\",\""+tr("Format")+"\",\""+ - tr("Precision")+"\",\""+ - tr("Locale")+"\")" - ); + fd.setDescription("numberFormat(\"" + tr("Value") + "\",\"" + tr("Format") + "\",\"" + + tr("Precision") + "\",\"" + tr("Locale") + "\")"); fd.setScriptWrapper(QString("function numberFormat(value, format, precision, locale){" " if(typeof(format)==='undefined') format = \"f\"; " " if(typeof(precision)==='undefined') precision=2; " " if(typeof(locale)==='undefined') locale=\"\"; " - "return %1.numberFormat(value,format,precision,locale);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.numberFormat(value,format,precision,locale);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createDateFormatFunction(){ +bool ScriptEngineManager::createDateFormatFunction() +{ JSFunctionDesc fd; fd.setManager(m_functionManager); fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("DATE&TIME")); fd.setName("dateFormat"); - fd.setDescription("dateFormat(\""+tr("Value")+"\",\""+tr("Format")+"\", \""+tr("Locale")+"\")"); + fd.setDescription("dateFormat(\"" + tr("Value") + "\",\"" + tr("Format") + "\", \"" + + tr("Locale") + "\")"); fd.setScriptWrapper(QString("function dateFormat(value, format, locale){" " if(typeof(format)==='undefined') format = \"dd.MM.yyyy\"; " - "return %1.dateFormat(value,format, locale);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.dateFormat(value,format, locale);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createTimeFormatFunction(){ +bool ScriptEngineManager::createTimeFormatFunction() +{ JSFunctionDesc fd; fd.setManager(m_functionManager); fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("DATE&TIME")); fd.setName("timeFormat"); - fd.setDescription("timeFormat(\""+tr("Value")+"\",\""+tr("Format")+"\")"); + fd.setDescription("timeFormat(\"" + tr("Value") + "\",\"" + tr("Format") + "\")"); fd.setScriptWrapper(QString("function timeFormat(value, format){" " if(typeof(format)==='undefined') format = \"hh:mm\"; " - "return %1.timeFormat(value,format);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.timeFormat(value,format);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createDateTimeFormatFunction(){ +bool ScriptEngineManager::createDateTimeFormatFunction() +{ JSFunctionDesc fd; fd.setManager(m_functionManager); fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("DATE&TIME")); fd.setName("dateTimeFormat"); - fd.setDescription("dateTimeFormat(\""+tr("Value")+"\",\""+tr("Format")+"\", \""+tr("Locale")+"\")"); + fd.setDescription("dateTimeFormat(\"" + tr("Value") + "\",\"" + tr("Format") + "\", \"" + + tr("Locale") + "\")"); fd.setScriptWrapper(QString("function dateTimeFormat(value, format, locale){" " if(typeof(format)==='undefined') format = \"dd.MM.yyyy hh:mm\"; " - "return %1.dateTimeFormat(value, format, locale);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.dateTimeFormat(value, format, locale);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -840,16 +864,16 @@ bool ScriptEngineManager::createSectotimeFormatFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("DATE&TIME")); fd.setName("sectotimeFormat"); - fd.setDescription("sectotimeFormat(\""+tr("Value")+"\",\""+tr("Format")+"\")"); + fd.setDescription("sectotimeFormat(\"" + tr("Value") + "\",\"" + tr("Format") + "\")"); fd.setScriptWrapper(QString("function sectotimeFormat(value, format){" " if(typeof(format)==='undefined') format = \"hh:mm:ss\"; " - "return %1.sectotimeFormat(value,format);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.sectotimeFormat(value,format);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createDateFunction(){ +bool ScriptEngineManager::createDateFunction() +{ // addFunction("date",date,"DATE&TIME","date()"); JSFunctionDesc fd; @@ -859,14 +883,13 @@ bool ScriptEngineManager::createDateFunction(){ fd.setName("date"); fd.setDescription("date()"); fd.setScriptWrapper(QString("function date(){" - "return %1.date();}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.date();}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } - -bool ScriptEngineManager::createNowFunction(){ +bool ScriptEngineManager::createNowFunction() +{ // addFunction("now",now,"DATE&TIME","now()"); JSFunctionDesc fd; @@ -876,13 +899,13 @@ bool ScriptEngineManager::createNowFunction(){ fd.setName("now"); fd.setDescription("now()"); fd.setScriptWrapper(QString("function now(){" - "return %1.now();}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.now();}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createCurrencyFormatFunction(){ +bool ScriptEngineManager::createCurrencyFormatFunction() +{ // addFunction("currencyFormat",currencyFormat,"NUMBER","currencyFormat(\""+tr("Value")+"\",\""+tr("Locale")+"\")"); JSFunctionDesc fd; @@ -890,16 +913,16 @@ bool ScriptEngineManager::createCurrencyFormatFunction(){ fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("NUMBER")); fd.setName("currencyFormat"); - fd.setDescription("currencyFormat(\""+tr("Value")+"\",\""+tr("Locale")+"\")"); + fd.setDescription("currencyFormat(\"" + tr("Value") + "\",\"" + tr("Locale") + "\")"); fd.setScriptWrapper(QString("function currencyFormat(value, locale){" " if(typeof(locale)==='undefined') locale = \"\"; " - "return %1.currencyFormat(value,locale);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.currencyFormat(value,locale);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createCurrencyUSBasedFormatFunction(){ +bool ScriptEngineManager::createCurrencyUSBasedFormatFunction() +{ // addFunction("currencyUSBasedFormat",currencyUSBasedFormat,"NUMBER","currencyUSBasedFormat(\""+tr("Value")+",\""+tr("CurrencySymbol")+"\")"); JSFunctionDesc fd; @@ -907,28 +930,29 @@ bool ScriptEngineManager::createCurrencyUSBasedFormatFunction(){ fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("NUMBER")); fd.setName("currencyUSBasedFormat"); - fd.setDescription("currencyUSBasedFormat(\""+tr("Value")+",\""+tr("CurrencySymbol")+"\")"); + fd.setDescription("currencyUSBasedFormat(\"" + tr("Value") + ",\"" + tr("CurrencySymbol") + + "\")"); fd.setScriptWrapper(QString("function currencyUSBasedFormat(value, currencySymbol){" " if(typeof(currencySymbol)==='undefined') currencySymbol = \"\"; " - "return %1.currencyUSBasedFormat(value,currencySymbol);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.currencyUSBasedFormat(value,currencySymbol);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } -bool ScriptEngineManager::createSetVariableFunction(){ - // addFunction("setVariable", setVariable, "GENERAL", "setVariable(\""+tr("Name")+"\",\""+tr("Value")+"\")"); +bool ScriptEngineManager::createSetVariableFunction() +{ + // addFunction("setVariable", setVariable, "GENERAL", + // "setVariable(\""+tr("Name")+"\",\""+tr("Value")+"\")"); JSFunctionDesc fd; fd.setManager(m_functionManager); fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("setVariable"); - fd.setDescription("setVariable(\""+tr("Name")+"\",\""+tr("Value")+"\")"); + fd.setDescription("setVariable(\"" + tr("Name") + "\",\"" + tr("Value") + "\")"); fd.setScriptWrapper(QString("function setVariable(name, value){" - "return %1.setVariable(name,value);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.setVariable(name,value);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -939,11 +963,10 @@ bool ScriptEngineManager::createGetVariableFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("getVariable"); - fd.setDescription("getVariable(\""+tr("Name")+"\")"); + fd.setDescription("getVariable(\"" + tr("Name") + "\")"); fd.setScriptWrapper(QString("function getVariable(name){" - "return %1.getVariable(name);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.getVariable(name);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -954,11 +977,10 @@ bool ScriptEngineManager::createGetFieldFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("getField"); - fd.setDescription("getField(\""+tr("Name")+"\")"); + fd.setDescription("getField(\"" + tr("Name") + "\")"); fd.setScriptWrapper(QString("function getField(name){" - "return %1.getField(name);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.getField(name);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -969,15 +991,13 @@ bool ScriptEngineManager::createGetFieldByKeyFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("getFieldByKeyField"); - fd.setDescription("getFieldByKeyField(\""+tr("Datasource")+"\", \""+ - tr("ValueField")+"\",\""+ - tr("KeyField")+"\", \""+ - tr("KeyFieldValue")+"\")" - ); - fd.setScriptWrapper(QString("function getFieldByKeyField(datasource, valueFieldName, keyFieldName, keyValue){" - "return %1.getFieldByKeyField(datasource, valueFieldName, keyFieldName, keyValue);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + fd.setDescription("getFieldByKeyField(\"" + tr("Datasource") + "\", \"" + tr("ValueField") + + "\",\"" + tr("KeyField") + "\", \"" + tr("KeyFieldValue") + "\")"); + fd.setScriptWrapper( + QString("function getFieldByKeyField(datasource, valueFieldName, keyFieldName, keyValue){" + "return %1.getFieldByKeyField(datasource, valueFieldName, keyFieldName, " + "keyValue);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -988,13 +1008,11 @@ bool ScriptEngineManager::createGetFieldByRowIndex() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("getFieldByRowIndex"); - fd.setDescription("getFieldByRowIndex(\""+tr("FieldName")+"\", \""+ - tr("RowIndex")+"\")" - ); + fd.setDescription("getFieldByRowIndex(\"" + tr("FieldName") + "\", \"" + tr("RowIndex") + + "\")"); fd.setScriptWrapper(QString("function getFieldByRowIndex(fieldName, rowIndex){" - "return %1.getFieldByRowIndex(fieldName, rowIndex);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.getFieldByRowIndex(fieldName, rowIndex);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1005,11 +1023,10 @@ bool ScriptEngineManager::createAddBookmarkFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("addBookmark"); - fd.setDescription("addBookmark(\""+tr("Unique identifier")+" \""+tr("Content")+"\")"); + fd.setDescription("addBookmark(\"" + tr("Unique identifier") + " \"" + tr("Content") + "\")"); fd.setScriptWrapper(QString("function addBookmark(uniqKey, content){" - "return %1.addBookmark(uniqKey, content);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.addBookmark(uniqKey, content);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1020,11 +1037,10 @@ bool ScriptEngineManager::createFindPageIndexByBookmark() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("findPageIndexByBookmark"); - fd.setDescription("findPageIndexByBookmark(\""+tr("Unique identifier")+"\")"); + fd.setDescription("findPageIndexByBookmark(\"" + tr("Unique identifier") + "\")"); fd.setScriptWrapper(QString("function findPageIndexByBookmark(uniqKey){" - "return %1.findPageIndexByBookmark(uniqKey);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.findPageIndexByBookmark(uniqKey);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1035,11 +1051,11 @@ bool ScriptEngineManager::createAddTableOfContentsItemFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("addTableOfContentsItem"); - fd.setDescription("addTableOfContentsItem(\""+tr("Unique identifier")+" \""+tr("Content")+"\", \""+tr("Indent")+"\")"); + fd.setDescription("addTableOfContentsItem(\"" + tr("Unique identifier") + " \"" + tr("Content") + + "\", \"" + tr("Indent") + "\")"); fd.setScriptWrapper(QString("function addTableOfContentsItem(uniqKey, content, indent){" - "return %1.addTableOfContentsItem(uniqKey, content, indent);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.addTableOfContentsItem(uniqKey, content, indent);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1052,9 +1068,8 @@ bool ScriptEngineManager::createClearTableOfContentsFunction() fd.setName("clearTableOfContents"); fd.setDescription("clearTableOfContents()"); fd.setScriptWrapper(QString("function clearTableOfContents(){" - "return %1.clearTableOfContents();}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.clearTableOfContents();}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1065,11 +1080,10 @@ bool ScriptEngineManager::createReopenDatasourceFunction() fd.setManagerName(LimeReport::Const::FUNCTION_MANAGER_NAME); fd.setCategory(tr("GENERAL")); fd.setName("reopenDatasource"); - fd.setDescription("reopenDatasource(\""+tr("datasourceName")+"\")"); + fd.setDescription("reopenDatasource(\"" + tr("datasourceName") + "\")"); fd.setScriptWrapper(QString("function reopenDatasource(datasourceName){" - "return %1.reopenDatasource(datasourceName);}" - ).arg(LimeReport::Const::FUNCTION_MANAGER_NAME) - ); + "return %1.reopenDatasource(datasourceName);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1081,10 +1095,10 @@ bool ScriptEngineManager::createGetFieldByRowIndexEx() fd.setCategory(tr("GENERAL")); fd.setName("getFieldByRowIndexEx"); fd.setDescription("getFieldByRowIndexEx(\"" + tr("FieldName") + "\", \"" + tr("RowIndex") - + "\", \"" + tr("RoleIndex") + "\")"); + + "\", \"" + tr("RoleIndex") + "\")"); fd.setScriptWrapper(QString("function getFieldByRowIndexEx(fieldName, rowIndex, role){" - "return %1.getFieldByRowIndexEx(fieldName, rowIndex, role);}") - .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); + "return %1.getFieldByRowIndexEx(fieldName, rowIndex, role);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1126,9 +1140,10 @@ bool ScriptEngineManager::createHeaderColumnNameByIndex() fd.setName("getHeaderColumnNameByIndex"); fd.setDescription("getHeaderColumnNameByIndex(\"" + tr("datasourceName") + "\", \"" + tr("columnIndex") + "\")"); - fd.setScriptWrapper(QString("function getHeaderColumnNameByIndex(datasourceName, columnIndex){" - "return %1.getHeaderColumnNameByIndex(datasourceName, columnIndex);}") - .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); + fd.setScriptWrapper( + QString("function getHeaderColumnNameByIndex(datasourceName, columnIndex){" + "return %1.getHeaderColumnNameByIndex(datasourceName, columnIndex);}") + .arg(LimeReport::Const::FUNCTION_MANAGER_NAME)); return addFunction(fd); } @@ -1146,8 +1161,7 @@ bool ScriptEngineManager::createColumnCount() return addFunction(fd); } -ScriptEngineManager::ScriptEngineManager() - :m_model(0), m_context(0), m_dataManager(0) +ScriptEngineManager::ScriptEngineManager(): m_model(0), m_context(0), m_dataManager(0) { m_scriptEngine = new ScriptEngineType; m_functionManager = new ScriptFunctionsManager(this); @@ -1164,7 +1178,7 @@ ScriptEngineManager::ScriptEngineManager() createSectotimeFormatFunction(); createDateFunction(); createNowFunction(); -#if QT_VERSION>0x040800 +#if QT_VERSION > 0x040800 createCurrencyFormatFunction(); createCurrencyUSBasedFormatFunction(); #endif @@ -1177,9 +1191,11 @@ ScriptEngineManager::ScriptEngineManager() QScriptValue colorCtor = m_scriptEngine->newFunction(constructColor); m_scriptEngine->globalObject().setProperty("QColor", colorCtor); - QScriptValue fontProto(m_scriptEngine->newQObject(new QFontPrototype,QScriptEngine::ScriptOwnership)); + QScriptValue fontProto( + m_scriptEngine->newQObject(new QFontPrototype, QScriptEngine::ScriptOwnership)); m_scriptEngine->setDefaultPrototype(qMetaTypeId(), fontProto); - QScriptValue fontConstructor = m_scriptEngine->newFunction(QFontPrototype::constructorQFont, fontProto); + QScriptValue fontConstructor + = m_scriptEngine->newFunction(QFontPrototype::constructorQFont, fontProto); m_scriptEngine->globalObject().setProperty("QFont", fontConstructor); #endif createAddBookmarkFunction(); @@ -1203,22 +1219,23 @@ bool ScriptExtractor::parse() return m_scriptTree->children().count() > 0; } -bool ScriptExtractor::parse(int &curPos, const State& state, ScriptNode::Ptr scriptNode) +bool ScriptExtractor::parse(int& curPos, const State& state, ScriptNode::Ptr scriptNode) { - while (curPos < m_context.length()){ + while (curPos < m_context.length()) { switch (state) { case OpenBracketFound: - if (m_context[curPos]=='}'){ + if (m_context[curPos] == '}') { return true; } else { - if (m_context[curPos]=='{') + if (m_context[curPos] == '{') extractBracket(curPos, scriptNode); } case None: - if (m_context[curPos]=='$'){ + if (m_context[curPos] == '$') { int startPos = curPos; if (isStartScriptLexem(curPos)) - extractScript(curPos, substring(m_context,startPos,curPos), scriptNode->createChildNode()); + extractScript(curPos, substring(m_context, startPos, curPos), + scriptNode->createChildNode()); if (isStartFieldLexem(curPos) || isStartVariableLexem(curPos)) skipField(curPos); } @@ -1230,19 +1247,21 @@ bool ScriptExtractor::parse(int &curPos, const State& state, ScriptNode::Ptr scr return false; } -void ScriptExtractor::extractScript(int &curPos, const QString& startStr, ScriptNode::Ptr scriptNode) +void ScriptExtractor::extractScript(int& curPos, const QString& startStr, + ScriptNode::Ptr scriptNode) { int startPos = curPos; - if (extractBracket(curPos, scriptNode)){ - QString scriptBody = substring(m_context,startPos+1,curPos); + if (extractBracket(curPos, scriptNode)) { + QString scriptBody = substring(m_context, startPos + 1, curPos); scriptNode->setBody(scriptBody); - scriptNode->setStartLex(startStr+'{'); + scriptNode->setStartLex(startStr + '{'); } } -void ScriptExtractor::skipField(int &curPos){ - while (curPosname().compare(name) == 0){ + foreach (DialogDescriber::Ptr describer, m_dialogs) { + if (describer->name().compare(name) == 0) { describer->setDescription(description); { QList::Iterator it = m_createdDialogs.begin(); - while(it!=m_createdDialogs.end()){ - if ((*it)->objectName()==name){ + while (it != m_createdDialogs.end()) { + if ((*it)->objectName() == name) { it = m_createdDialogs.erase(it); } else { ++it; @@ -1354,13 +1361,13 @@ bool ScriptEngineContext::changeDialog(const QString& name, const QByteArray& de bool ScriptEngineContext::changeDialogName(const QString& oldName, const QString& newName) { - foreach( DialogDescriber::Ptr describer, m_dialogs){ - if (describer->name().compare(oldName) == 0){ + foreach (DialogDescriber::Ptr describer, m_dialogs) { + if (describer->name().compare(oldName) == 0) { describer->setName(newName); { QList::Iterator it = m_createdDialogs.begin(); - while(it!=m_createdDialogs.end()){ - if ((*it)->objectName()==oldName){ + while (it != m_createdDialogs.end()) { + if ((*it)->objectName() == oldName) { it = m_createdDialogs.erase(it); } else { ++it; @@ -1387,8 +1394,8 @@ bool ScriptEngineContext::previewDialog(const QString& dialogName) bool ScriptEngineContext::containsDialog(const QString& dialogName) { - foreach(DialogDescriber::Ptr dialog, m_dialogs){ - if (dialog->name()==dialogName) + foreach (DialogDescriber::Ptr dialog, m_dialogs) { + if (dialog->name() == dialogName) return true; } return false; @@ -1398,8 +1405,8 @@ void ScriptEngineContext::deleteDialog(const QString& dialogName) { { QVector::Iterator it = m_dialogs.begin(); - while(it!=m_dialogs.end()){ - if ((*it)->name()==dialogName){ + while (it != m_dialogs.end()) { + if ((*it)->name() == dialogName) { it = m_dialogs.erase(it); emit dialogDeleted(dialogName); } else { @@ -1409,8 +1416,8 @@ void ScriptEngineContext::deleteDialog(const QString& dialogName) } { QList::Iterator it = m_createdDialogs.begin(); - while(it!=m_createdDialogs.end()){ - if ((*it)->objectName()==dialogName){ + while (it != m_createdDialogs.end()) { + if ((*it)->objectName() == dialogName) { it = m_createdDialogs.erase(it); } else { ++it; @@ -1429,16 +1436,17 @@ void ScriptEngineContext::clear() #endif m_initScript.clear(); m_tableOfContents->clear(); - m_lastError=""; + m_lastError = ""; } -QObject* ScriptEngineContext::createElement(const QString& collectionName, const QString& elementType) +QObject* ScriptEngineContext::createElement(const QString& collectionName, + const QString& elementType) { Q_UNUSED(elementType) #ifdef HAVE_UI_LOADER - if (collectionName.compare("dialogs",Qt::CaseInsensitive)==0){ + if (collectionName.compare("dialogs", Qt::CaseInsensitive) == 0) { m_dialogs.push_back(DialogDescriber::create()); - return m_dialogs.at(m_dialogs.count()-1).data(); + return m_dialogs.at(m_dialogs.count() - 1).data(); } #else Q_UNUSED(collectionName) @@ -1449,7 +1457,7 @@ QObject* ScriptEngineContext::createElement(const QString& collectionName, const int ScriptEngineContext::elementsCount(const QString& collectionName) { #ifdef HAVE_UI_LOADER - if (collectionName.compare("dialogs",Qt::CaseInsensitive)==0){ + if (collectionName.compare("dialogs", Qt::CaseInsensitive) == 0) { return m_dialogs.count(); }; #else @@ -1461,7 +1469,7 @@ int ScriptEngineContext::elementsCount(const QString& collectionName) QObject* ScriptEngineContext::elementAt(const QString& collectionName, int index) { #ifdef HAVE_UI_LOADER - if (collectionName.compare("dialogs",Qt::CaseInsensitive)==0){ + if (collectionName.compare("dialogs", Qt::CaseInsensitive) == 0) { return m_dialogs.at(index).data(); }; #else @@ -1476,15 +1484,9 @@ void ScriptEngineContext::collectionLoadFinished(const QString& collectionName) Q_UNUSED(collectionName); } -ReportPages* ScriptEngineContext::reportPages() const -{ - return m_reportPages; -} +ReportPages* ScriptEngineContext::reportPages() const { return m_reportPages; } -void ScriptEngineContext::setReportPages(ReportPages *value) -{ - m_reportPages = value; -} +void ScriptEngineContext::setReportPages(ReportPages* value) { m_reportPages = value; } #ifdef HAVE_UI_LOADER QDialog* ScriptEngineContext::createDialog(DialogDescriber* cont) @@ -1495,7 +1497,7 @@ QDialog* ScriptEngineContext::createDialog(DialogDescriber* cont) buffer.open(QIODevice::ReadOnly); QDialog* dialog = dynamic_cast(loader.load(&buffer)); m_createdDialogs.push_back(QSharedPointer(dialog)); - if (cont->name().compare(dialog->objectName())){ + if (cont->name().compare(dialog->objectName())) { cont->setName(dialog->objectName()); emit dialogNameChanged(dialog->objectName()); } @@ -1504,8 +1506,8 @@ QDialog* ScriptEngineContext::createDialog(DialogDescriber* cont) QDialog* ScriptEngineContext::findDialog(const QString& dialogName) { - foreach(DialogPtr dialog, m_createdDialogs){ - if (dialog->objectName()==dialogName) + foreach (DialogPtr dialog, m_createdDialogs) { + if (dialog->objectName() == dialogName) return dialog.data(); } return 0; @@ -1513,8 +1515,8 @@ QDialog* ScriptEngineContext::findDialog(const QString& dialogName) DialogDescriber* ScriptEngineContext::findDialogContainer(const QString& dialogName) { - foreach (DialogDescriber::Ptr dialogCont , m_dialogs) { - if (dialogCont->name().compare(dialogName,Qt::CaseInsensitive)==0){ + foreach (DialogDescriber::Ptr dialogCont, m_dialogs) { + if (dialogCont->name().compare(dialogName, Qt::CaseInsensitive) == 0) { return dialogCont.data(); } } @@ -1523,20 +1525,14 @@ DialogDescriber* ScriptEngineContext::findDialogContainer(const QString& dialogN #endif -TableOfContents* ScriptEngineContext::tableOfContents() const -{ - return m_tableOfContents; -} +TableOfContents* ScriptEngineContext::tableOfContents() const { return m_tableOfContents; } void ScriptEngineContext::setTableOfContents(TableOfContents* tableOfContents) { m_tableOfContents = tableOfContents; } -PageItemDesignIntf* ScriptEngineContext::currentPage() const -{ - return m_currentPage; -} +PageItemDesignIntf* ScriptEngineContext::currentPage() const { return m_currentPage; } void ScriptEngineContext::setCurrentPage(PageItemDesignIntf* currentPage) { @@ -1544,10 +1540,7 @@ void ScriptEngineContext::setCurrentPage(PageItemDesignIntf* currentPage) m_currentBand = 0; } -BandDesignIntf* ScriptEngineContext::currentBand() const -{ - return m_currentBand; -} +BandDesignIntf* ScriptEngineContext::currentBand() const { return m_currentBand; } void ScriptEngineContext::setCurrentBand(BandDesignIntf* currentBand) { @@ -1559,11 +1552,11 @@ void ScriptEngineContext::setCurrentBand(BandDesignIntf* currentBand) QDialog* ScriptEngineContext::getDialog(const QString& dialogName) { QDialog* dialog = findDialog(dialogName); - if (dialog){ + if (dialog) { return dialog; } else { DialogDescriber* cont = findDialogContainer(dialogName); - if (cont){ + if (cont) { dialog = createDialog(cont); if (dialog) return dialog; @@ -1576,7 +1569,7 @@ QString ScriptEngineContext::getNewDialogName() { QString result = "Dialog"; int index = m_dialogs.size() - 1; - while (containsDialog(result)){ + while (containsDialog(result)) { index++; result = QString("Dialog%1").arg(index); } @@ -1587,37 +1580,41 @@ QString ScriptEngineContext::getNewDialogName() void ScriptEngineContext::baseDesignIntfToScript(const QString& pageName, BaseDesignIntf* item) { - if ( item ) { - if (item->metaObject()->indexOfSignal("beforeRender()")!=-1) + if (item) { + if (item->metaObject()->indexOfSignal("beforeRender()") != -1) item->disconnect(SIGNAL(beforeRender())); - if (item->metaObject()->indexOfSignal("afterData()")!=-1) + if (item->metaObject()->indexOfSignal("afterData()") != -1) item->disconnect(SIGNAL(afterData())); - if (item->metaObject()->indexOfSignal("afterRender()")!=-1) + if (item->metaObject()->indexOfSignal("afterRender()") != -1) item->disconnect(SIGNAL(afterRender())); ScriptEngineType* engine = ScriptEngineManager::instance().scriptEngine(); #ifdef USE_QJSENGINE ScriptValueType sItem = getJSValue(*engine, item); - QString on = item->patternName().compare(pageName) == 0 ? pageName : pageName+"_"+item->patternName(); + QString on = item->patternName().compare(pageName) == 0 + ? pageName + : pageName + "_" + item->patternName(); engine->globalObject().setProperty(on, sItem); #else - QString on = item->patternName().compare(pageName) == 0 ? pageName : pageName+"_"+item->patternName(); + QString on = item->patternName().compare(pageName) == 0 + ? pageName + : pageName + "_" + item->patternName(); ScriptValueType sItem = engine->globalObject().property(on); - if (sItem.isValid()){ + if (sItem.isValid()) { engine->newQObject(sItem, item); } else { sItem = engine->newQObject(item); - engine->globalObject().setProperty(on,sItem); + engine->globalObject().setProperty(on, sItem); } #endif - foreach(BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { baseDesignIntfToScript(pageName, child); } } } -void ScriptEngineContext::qobjectToScript(const QString& name, QObject *item) +void ScriptEngineContext::qobjectToScript(const QString& name, QObject* item) { ScriptEngineType* engine = ScriptEngineManager::instance().scriptEngine(); #ifdef USE_QJSENGINE @@ -1625,11 +1622,11 @@ void ScriptEngineContext::qobjectToScript(const QString& name, QObject *item) engine->globalObject().setProperty(name, sItem); #else ScriptValueType sItem = engine->globalObject().property(name); - if (sItem.isValid()){ + if (sItem.isValid()) { engine->newQObject(sItem, item); } else { sItem = engine->newQObject(item); - engine->globalObject().setProperty(name,sItem); + engine->globalObject().setProperty(name, sItem); } #endif } @@ -1637,149 +1634,118 @@ void ScriptEngineContext::qobjectToScript(const QString& name, QObject *item) #ifdef HAVE_UI_LOADER #ifdef USE_QJSENGINE -void registerChildObjects(ScriptEngineType* se, ScriptValueType* root, QObject* currObj){ - foreach(QObject* obj, currObj->children()){ - if (!obj->objectName().isEmpty()){ +void registerChildObjects(ScriptEngineType* se, ScriptValueType* root, QObject* currObj) +{ + foreach (QObject* obj, currObj->children()) { + if (!obj->objectName().isEmpty()) { ScriptValueType child = se->newQObject(obj); - root->setProperty(obj->objectName(),child); + root->setProperty(obj->objectName(), child); } registerChildObjects(se, root, obj); } } #endif -void ScriptEngineContext::initDialogs(){ +void ScriptEngineContext::initDialogs() +{ ScriptEngineType* se = ScriptEngineManager::instance().scriptEngine(); - foreach(DialogDescriber::Ptr dialog, dialogDescribers()){ + foreach (DialogDescriber::Ptr dialog, dialogDescribers()) { ScriptValueType sv = se->newQObject(getDialog(dialog->name())); #ifdef USE_QJSENGINE registerChildObjects(se, &sv, sv.toQObject()); #endif - se->globalObject().setProperty(dialog->name(),sv); + se->globalObject().setProperty(dialog->name(), sv); } } #endif - -bool ScriptEngineContext::runInitScript(){ +bool ScriptEngineContext::runInitScript() +{ ScriptEngineType* engine = ScriptEngineManager::instance().scriptEngine(); ScriptEngineManager::instance().setContext(this); m_tableOfContents->clear(); ScriptValueType res = engine->evaluate(initScript()); - if (res.isBool()) return res.toBool(); -#ifdef USE_QJSENGINE - if (res.isError()){ - QMessageBox::critical(0,tr("Error"), - QString("Line %1: %2 ").arg(res.property("lineNumber").toString()) - .arg(res.toString()) - ); + if (res.isBool()) + return res.toBool(); +#ifdef USE_QJSENGINE + if (res.isError()) { + QMessageBox::critical( + 0, tr("Error"), + QString("Line %1: %2 ").arg(res.property("lineNumber").toString()).arg(res.toString())); return false; } #else if (engine->hasUncaughtException()) { - QMessageBox::critical(0,tr("Error"), - QString("Line %1: %2 ").arg(engine->uncaughtExceptionLineNumber()) - .arg(engine->uncaughtException().toString()) - ); + QMessageBox::critical(0, tr("Error"), + QString("Line %1: %2 ") + .arg(engine->uncaughtExceptionLineNumber()) + .arg(engine->uncaughtException().toString())); return false; } #endif return true; } -QString ScriptEngineContext::initScript() const -{ - return m_initScript; -} +QString ScriptEngineContext::initScript() const { return m_initScript; } void ScriptEngineContext::setInitScript(const QString& initScript) { - if (m_initScript != initScript){ + if (m_initScript != initScript) { m_initScript = initScript; m_hasChanges = true; } } -DialogDescriber::Ptr DialogDescriber::create(const QString& name, const QByteArray& desc) { +DialogDescriber::Ptr DialogDescriber::create(const QString& name, const QByteArray& desc) +{ Ptr res(new DialogDescriber()); res->setName(name); res->setDescription(desc); return res; } -QString JSFunctionDesc::name() const -{ - return m_name; -} +QString JSFunctionDesc::name() const { return m_name; } -void JSFunctionDesc::setName(const QString &name) -{ - m_name = name; -} +void JSFunctionDesc::setName(const QString& name) { m_name = name; } -QString JSFunctionDesc::category() const -{ - return m_category; -} +QString JSFunctionDesc::category() const { return m_category; } -void JSFunctionDesc::setCategory(const QString &category) -{ - m_category = category; -} +void JSFunctionDesc::setCategory(const QString& category) { m_category = category; } -QString JSFunctionDesc::description() const -{ - return m_description; -} +QString JSFunctionDesc::description() const { return m_description; } -void JSFunctionDesc::setDescription(const QString &description) -{ - m_description = description; -} +void JSFunctionDesc::setDescription(const QString& description) { m_description = description; } -QString JSFunctionDesc::managerName() const -{ - return m_managerName; -} +QString JSFunctionDesc::managerName() const { return m_managerName; } -void JSFunctionDesc::setManagerName(const QString &managerName) -{ - m_managerName = managerName; -} +void JSFunctionDesc::setManagerName(const QString& managerName) { m_managerName = managerName; } -QObject *JSFunctionDesc::manager() const -{ - return m_manager; -} +QObject* JSFunctionDesc::manager() const { return m_manager; } -void JSFunctionDesc::setManager(QObject *manager) -{ - m_manager = manager; -} +void JSFunctionDesc::setManager(QObject* manager) { m_manager = manager; } -QString JSFunctionDesc::scriptWrapper() const -{ - return m_scriptWrapper; -} +QString JSFunctionDesc::scriptWrapper() const { return m_scriptWrapper; } -void JSFunctionDesc::setScriptWrapper(const QString &scriptWrapper) +void JSFunctionDesc::setScriptWrapper(const QString& scriptWrapper) { m_scriptWrapper = scriptWrapper; } -QVariant ScriptFunctionsManager::calcGroupFunction(const QString &name, const QString &expressionID, const QString &bandName, QObject* currentPage) +QVariant ScriptFunctionsManager::calcGroupFunction(const QString& name, const QString& expressionID, + const QString& bandName, QObject* currentPage) { - if (m_scriptEngineManager->dataManager()){ + if (m_scriptEngineManager->dataManager()) { PageItemDesignIntf* pageItem = dynamic_cast(currentPage); QString expression = m_scriptEngineManager->dataManager()->getExpression(expressionID); - GroupFunction* gf = m_scriptEngineManager->dataManager()->groupFunction(name,expression,bandName); - if (gf){ - if (gf->isValid()){ + GroupFunction* gf + = m_scriptEngineManager->dataManager()->groupFunction(name, expression, bandName); + if (gf) { + if (gf->isValid()) { return gf->calculate(pageItem); - } else{ + } else { return gf->error(); } } else { @@ -1790,45 +1756,50 @@ QVariant ScriptFunctionsManager::calcGroupFunction(const QString &name, const QS } } -QVariant ScriptFunctionsManager::calcGroupFunction(const QString& name, const QString& expressionID, const QString& bandName) +QVariant ScriptFunctionsManager::calcGroupFunction(const QString& name, const QString& expressionID, + const QString& bandName) { return calcGroupFunction(name, expressionID, bandName, 0); } -QVariant ScriptFunctionsManager::line(const QString &bandName) +QVariant ScriptFunctionsManager::line(const QString& bandName) { - QString varName = QLatin1String("line_")+bandName.toLower(); + QString varName = QLatin1String("line_") + bandName.toLower(); QVariant res; - if (scriptEngineManager()->dataManager()->variable(varName).isValid()){ - res=scriptEngineManager()->dataManager()->variable(varName); - } else res=QString("Variable line for band %1 not found").arg(bandName); + if (scriptEngineManager()->dataManager()->variable(varName).isValid()) { + res = scriptEngineManager()->dataManager()->variable(varName); + } else + res = QString("Variable line for band %1 not found").arg(bandName); return res; } -QVariant ScriptFunctionsManager::numberFormat(QVariant value, const char &format, int precision, const QString& locale) +QVariant ScriptFunctionsManager::numberFormat(QVariant value, const char& format, int precision, + const QString& locale) { - return (locale.isEmpty()) ? QString::number(value.toDouble(),format,precision): - QLocale(locale).toString(value.toDouble(),format,precision); + return (locale.isEmpty()) ? QString::number(value.toDouble(), format, precision) + : QLocale(locale).toString(value.toDouble(), format, precision); } -QVariant ScriptFunctionsManager::dateFormat(QVariant value, const QString &format, const QString& locale) +QVariant ScriptFunctionsManager::dateFormat(QVariant value, const QString& format, + const QString& locale) { - return (locale.isEmpty()) ? QLocale().toString(value.toDate(),format) : - QLocale(locale).toString(value.toDate(),format); + return (locale.isEmpty()) ? QLocale().toString(value.toDate(), format) + : QLocale(locale).toString(value.toDate(), format); } -QVariant ScriptFunctionsManager::timeFormat(QVariant value, const QString &format) +QVariant ScriptFunctionsManager::timeFormat(QVariant value, const QString& format) { - return QLocale().toString(value.toTime(),format); + return QLocale().toString(value.toTime(), format); } -QVariant ScriptFunctionsManager::dateTimeFormat(QVariant value, const QString &format, const QString& locale) +QVariant ScriptFunctionsManager::dateTimeFormat(QVariant value, const QString& format, + const QString& locale) { - return (locale.isEmpty()) ? QLocale().toString(value.toDateTime(),format) : - QLocale(locale).toString(value.toDateTime(),format); + return (locale.isEmpty()) ? QLocale().toString(value.toDateTime(), format) + : QLocale(locale).toString(value.toDateTime(), format); } -QVariant ScriptFunctionsManager::sectotimeFormat(QVariant value, const QString &format) +QVariant ScriptFunctionsManager::sectotimeFormat(QVariant value, const QString& format) { int seconds = value.toInt(); int minutes = seconds / 60; @@ -1837,69 +1808,76 @@ QVariant ScriptFunctionsManager::sectotimeFormat(QVariant value, const QString & QString result = format; bool hasHour = format.contains("h"); bool hasMinute = format.contains("m"); - for(int len = 2; len; len--) { - if(hasHour) result.replace(QString('h').repeated(len), QString::number(hours).rightJustified(len, '0')); - if(hasMinute) result.replace(QString('m').repeated(len), QString::number(hasHour ? minutes % 60 : minutes).rightJustified(len, '0')); - result.replace(QString('s').repeated(len), QString::number(hasMinute ? seconds % 60 : seconds).rightJustified(len, '0')); + for (int len = 2; len; len--) { + if (hasHour) + result.replace(QString('h').repeated(len), + QString::number(hours).rightJustified(len, '0')); + if (hasMinute) + result.replace( + QString('m').repeated(len), + QString::number(hasHour ? minutes % 60 : minutes).rightJustified(len, '0')); + result.replace( + QString('s').repeated(len), + QString::number(hasMinute ? seconds % 60 : seconds).rightJustified(len, '0')); } return result; } -QVariant ScriptFunctionsManager::date() -{ - return QDate::currentDate(); -} +QVariant ScriptFunctionsManager::date() { return QDate::currentDate(); } -QVariant ScriptFunctionsManager::now() -{ - return QDateTime::currentDateTime(); -} +QVariant ScriptFunctionsManager::now() { return QDateTime::currentDateTime(); } -QVariant ScriptFunctionsManager::currencyFormat(QVariant value, const QString &locale) +QVariant ScriptFunctionsManager::currencyFormat(QVariant value, const QString& locale) { - QString l = (!locale.isEmpty())?locale:QLocale::system().name(); + QString l = (!locale.isEmpty()) ? locale : QLocale::system().name(); return QLocale(l).toCurrencyString(value.toDouble()); } -QVariant ScriptFunctionsManager::currencyUSBasedFormat(QVariant value, const QString ¤cySymbol) +QVariant ScriptFunctionsManager::currencyUSBasedFormat(QVariant value, + const QString& currencySymbol) { - QString CurrencySymbol = (!currencySymbol.isEmpty())?currencySymbol:QLocale::system().currencySymbol(); + QString CurrencySymbol + = (!currencySymbol.isEmpty()) ? currencySymbol : QLocale::system().currencySymbol(); // Format it using USA locale - QString vTempStr=QLocale(QLocale::English, QLocale::UnitedStates).toCurrencyString(value.toDouble()); + QString vTempStr + = QLocale(QLocale::English, QLocale::UnitedStates).toCurrencyString(value.toDouble()); // Replace currency symbol if necesarry - if (CurrencySymbol!="") vTempStr.replace("$", CurrencySymbol); + if (CurrencySymbol != "") + vTempStr.replace("$", CurrencySymbol); return vTempStr; } -void ScriptFunctionsManager::setVariable(const QString &name, QVariant value) +void ScriptFunctionsManager::setVariable(const QString& name, QVariant value) { DataSourceManager* dm = scriptEngineManager()->dataManager(); - if (dm->containsVariable(name)){ - dm->changeVariable(name,value); + if (dm->containsVariable(name)) { + dm->changeVariable(name, value); } else { dm->addVariable(name, value, VarDesc::User); } } -QVariant ScriptFunctionsManager::getVariable(const QString &name) +QVariant ScriptFunctionsManager::getVariable(const QString& name) { DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->variable(name); } -QVariant ScriptFunctionsManager::getField(const QString &field) +QVariant ScriptFunctionsManager::getField(const QString& field) { DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->fieldData(field); } -QVariant ScriptFunctionsManager::getFieldByKeyField(const QString& datasourceName, const QString& valueFieldName, const QString& keyFieldName, QVariant keyValue) +QVariant ScriptFunctionsManager::getFieldByKeyField(const QString& datasourceName, + const QString& valueFieldName, + const QString& keyFieldName, QVariant keyValue) { DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->fieldDataByKey(datasourceName, valueFieldName, keyFieldName, keyValue); } -QVariant ScriptFunctionsManager::getFieldByRowIndex(const QString &fieldName, int rowIndex) +QVariant ScriptFunctionsManager::getFieldByRowIndex(const QString& fieldName, int rowIndex) { DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->fieldDataByRowIndex(fieldName, rowIndex); @@ -1911,21 +1889,23 @@ void ScriptFunctionsManager::reopenDatasource(const QString& datasourceName) return dm->reopenDatasource(datasourceName); } -void ScriptFunctionsManager::addBookmark(const QString &uniqKey, const QString &content) +void ScriptFunctionsManager::addBookmark(const QString& uniqKey, const QString& content) { scriptEngineManager()->addBookMark(uniqKey, content); } -int ScriptFunctionsManager::findPageIndexByBookmark(const QString &uniqKey) +int ScriptFunctionsManager::findPageIndexByBookmark(const QString& uniqKey) { return scriptEngineManager()->findPageIndexByBookmark(uniqKey); } -int ScriptFunctionsManager::getPageFreeSpace(QObject* page){ +int ScriptFunctionsManager::getPageFreeSpace(QObject* page) +{ return scriptEngineManager()->getPageFreeSpace(dynamic_cast(page)); } -void ScriptFunctionsManager::addTableOfContentsItem(const QString& uniqKey, const QString& content, int indent) +void ScriptFunctionsManager::addTableOfContentsItem(const QString& uniqKey, const QString& content, + int indent) { scriptEngineManager()->addTableOfContentsItem(uniqKey, content, indent); } @@ -1935,59 +1915,63 @@ void ScriptFunctionsManager::clearTableOfContents() scriptEngineManager()->clearTableOfContents(); } -QFont ScriptFunctionsManager::font(const QString &family, int pointSize, bool italic, bool bold, bool underLine) +QFont ScriptFunctionsManager::font(const QString& family, int pointSize, bool italic, bool bold, + bool underLine) { - QFont result (family, pointSize); + QFont result(family, pointSize); result.setBold(bold); result.setItalic(italic); result.setUnderline(underLine); return result; } -QVariant ScriptFunctionsManager::getFieldByRowIndexEx(const QString &fieldName, int rowIndex, const int role) +QVariant ScriptFunctionsManager::getFieldByRowIndexEx(const QString& fieldName, int rowIndex, + const int role) { - DataSourceManager *dm = scriptEngineManager()->dataManager(); + DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->fieldDataByRowIndex(fieldName, rowIndex, role); } -QVariant ScriptFunctionsManager::getFieldByRowIndexEx2(const QString &fieldName, int rowIndex, const QString &roleName) +QVariant ScriptFunctionsManager::getFieldByRowIndexEx2(const QString& fieldName, int rowIndex, + const QString& roleName) { - DataSourceManager *dm = scriptEngineManager()->dataManager(); + DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->fieldDataByRowIndex(fieldName, rowIndex, roleName); } -QVariant ScriptFunctionsManager::getHeaderData(const QString &fieldName, const QString &roleName) +QVariant ScriptFunctionsManager::getHeaderData(const QString& fieldName, const QString& roleName) { - DataSourceManager *dm = scriptEngineManager()->dataManager(); + DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->headerData(fieldName, roleName); } -QVariant ScriptFunctionsManager::getHeaderColumnNameByIndex(const QString &datasourceName, const int columnIndex) +QVariant ScriptFunctionsManager::getHeaderColumnNameByIndex(const QString& datasourceName, + const int columnIndex) { - DataSourceManager *dm = scriptEngineManager()->dataManager(); + DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->columnName(datasourceName, columnIndex); } -int ScriptFunctionsManager::getColumnCount(const QString &datasourceName) +int ScriptFunctionsManager::getColumnCount(const QString& datasourceName) { - DataSourceManager *dm = scriptEngineManager()->dataManager(); + DataSourceManager* dm = scriptEngineManager()->dataManager(); return dm->columnCount(datasourceName); } #ifdef USE_QJSENGINE -void ScriptFunctionsManager::addItemsToComboBox(QJSValue object, const QStringList &values) +void ScriptFunctionsManager::addItemsToComboBox(QJSValue object, const QStringList& values) { QComboBox* comboBox = dynamic_cast(object.toQObject()); - if (comboBox){ + if (comboBox) { comboBox->addItems(values); } } -void ScriptFunctionsManager::addItemToComboBox(QJSValue object, const QString &value) +void ScriptFunctionsManager::addItemToComboBox(QJSValue object, const QString& value) { QComboBox* comboBox = dynamic_cast(object.toQObject()); - if (comboBox){ + if (comboBox) { comboBox->addItem(value); } } @@ -1995,7 +1979,7 @@ void ScriptFunctionsManager::addItemToComboBox(QJSValue object, const QString &v QJSValue ScriptFunctionsManager::createComboBoxWrapper(QJSValue comboBox) { QComboBox* item = dynamic_cast(comboBox.toQObject()); - if (item){ + if (item) { ComboBoxWrapper* wrapper = new ComboBoxWrapper(item); return m_scriptEngineManager->scriptEngine()->newQObject(wrapper); } @@ -2005,10 +1989,11 @@ QJSValue ScriptFunctionsManager::createComboBoxWrapper(QJSValue comboBox) QJSValue ScriptFunctionsManager::createWrapper(QJSValue item) { QObject* object = item.toQObject(); - if (object){ + if (object) { IWrapperCreator* wrapper = m_wrappersFactory.value(object->metaObject()->className()); - if (wrapper){ - return m_scriptEngineManager->scriptEngine()->newQObject(wrapper->createWrapper(item.toQObject())); + if (wrapper) { + return m_scriptEngineManager->scriptEngine()->newQObject( + wrapper->createWrapper(item.toQObject())); } } return QJSValue(); @@ -2016,18 +2001,18 @@ QJSValue ScriptFunctionsManager::createWrapper(QJSValue item) #else -void ScriptFunctionsManager::addItemsToComboBox(QScriptValue object, const QStringList &values) +void ScriptFunctionsManager::addItemsToComboBox(QScriptValue object, const QStringList& values) { QComboBox* comboBox = dynamic_cast(object.toQObject()); - if (comboBox){ + if (comboBox) { comboBox->addItems(values); } } -void ScriptFunctionsManager::addItemToComboBox(QScriptValue object, const QString &value) +void ScriptFunctionsManager::addItemToComboBox(QScriptValue object, const QString& value) { QComboBox* comboBox = dynamic_cast(object.toQObject()); - if (comboBox){ + if (comboBox) { comboBox->addItem(value); } } @@ -2035,7 +2020,7 @@ void ScriptFunctionsManager::addItemToComboBox(QScriptValue object, const QStrin QScriptValue ScriptFunctionsManager::createComboBoxWrapper(QScriptValue comboBox) { QComboBox* item = dynamic_cast(comboBox.toQObject()); - if (item){ + if (item) { ComboBoxWrapper* wrapper = new ComboBoxWrapper(item); return m_scriptEngineManager->scriptEngine()->newQObject(wrapper); } @@ -2045,10 +2030,11 @@ QScriptValue ScriptFunctionsManager::createComboBoxWrapper(QScriptValue comboBox QScriptValue ScriptFunctionsManager::createWrapper(QScriptValue item) { QObject* object = item.toQObject(); - if (object){ + if (object) { IWrapperCreator* wrapper = m_wrappersFactory.value(object->metaObject()->className()); - if (wrapper){ - return m_scriptEngineManager->scriptEngine()->newQObject(wrapper->createWrapper(item.toQObject())); + if (wrapper) { + return m_scriptEngineManager->scriptEngine()->newQObject( + wrapper->createWrapper(item.toQObject())); } } return QScriptValue(); @@ -2056,8 +2042,9 @@ QScriptValue ScriptFunctionsManager::createWrapper(QScriptValue item) #endif -QFont ScriptFunctionsManager::font(QVariantMap params){ - if (!params.contains("family")){ +QFont ScriptFunctionsManager::font(QVariantMap params) +{ + if (!params.contains("family")) { return QFont(); } else { QFont result(params.value("family").toString()); @@ -2073,29 +2060,27 @@ QFont ScriptFunctionsManager::font(QVariantMap params){ } } -ScriptEngineManager *ScriptFunctionsManager::scriptEngineManager() const +ScriptEngineManager* ScriptFunctionsManager::scriptEngineManager() const { return m_scriptEngineManager; } -void ScriptFunctionsManager::setScriptEngineManager(ScriptEngineManager *scriptEngineManager) +void ScriptFunctionsManager::setScriptEngineManager(ScriptEngineManager* scriptEngineManager) { m_scriptEngineManager = scriptEngineManager; } -TableOfContents::~TableOfContents() -{ - clear(); -} +TableOfContents::~TableOfContents() { clear(); } -void TableOfContents::setItem(const QString& uniqKey, const QString& content, int pageNumber, int indent) +void TableOfContents::setItem(const QString& uniqKey, const QString& content, int pageNumber, + int indent) { - ContentItem * item = 0; - if (m_hash.contains(uniqKey)){ + ContentItem* item = 0; + if (m_hash.contains(uniqKey)) { item = m_hash.value(uniqKey); item->content = content; item->pageNumber = pageNumber; - if (indent>0) + if (indent > 0) item->indent = indent; } else { item = new ContentItem; @@ -2106,13 +2091,14 @@ void TableOfContents::setItem(const QString& uniqKey, const QString& content, in m_tableOfContents.append(item); m_hash.insert(uniqKey, item); } - } void TableOfContents::slotOneSlotDS(CallbackInfo info, QVariant& data) { QStringList columns; - columns << "Content" << "Page number" << "Content Key"; + columns << "Content" + << "Page number" + << "Content Key"; switch (info.dataType) { case LimeReport::CallbackInfo::RowCount: @@ -2126,49 +2112,51 @@ void TableOfContents::slotOneSlotDS(CallbackInfo info, QVariant& data) break; } case LimeReport::CallbackInfo::ColumnData: - if (info.index < m_tableOfContents.count()){ + if (info.index < m_tableOfContents.count()) { ContentItem* item = m_tableOfContents.at(info.index); - if (info.columnName.compare("Content",Qt::CaseInsensitive) == 0) - data = item->content.rightJustified(item->indent+item->content.size()); - if (info.columnName.compare("Content Key",Qt::CaseInsensitive) == 0) + if (info.columnName.compare("Content", Qt::CaseInsensitive) == 0) + data = item->content.rightJustified(item->indent + item->content.size()); + if (info.columnName.compare("Content Key", Qt::CaseInsensitive) == 0) data = item->uniqKey; - if (info.columnName.compare("Page number",Qt::CaseInsensitive) == 0) + if (info.columnName.compare("Page number", Qt::CaseInsensitive) == 0) data = QString::number(item->pageNumber); } break; - default: break; + default: + break; } } -void LimeReport::TableOfContents::clear(){ +void LimeReport::TableOfContents::clear() +{ m_hash.clear(); - foreach(ContentItem* item, m_tableOfContents){ + foreach (ContentItem* item, m_tableOfContents) { delete item; } m_tableOfContents.clear(); - } -QObject* ComboBoxWrapperCreator::createWrapper(QObject *item) +QObject* ComboBoxWrapperCreator::createWrapper(QObject* item) { QComboBox* comboBox = dynamic_cast(item); - if (comboBox){ - return new ComboBoxWrapper(comboBox); + if (comboBox) { + return new ComboBoxWrapper(comboBox); } return 0; } bool DatasourceFunctions::first(const QString& datasourceName) { - if (m_dataManager && m_dataManager->dataSource(datasourceName)){ + if (m_dataManager && m_dataManager->dataSource(datasourceName)) { m_dataManager->dataSource(datasourceName)->first(); return true; } return false; } -bool DatasourceFunctions::next(const QString &datasourceName){ +bool DatasourceFunctions::next(const QString& datasourceName) +{ if (m_dataManager && m_dataManager->dataSource(datasourceName)) return m_dataManager->dataSource(datasourceName)->next(); return false; @@ -2181,14 +2169,14 @@ bool DatasourceFunctions::prior(const QString& datasourceName) return false; } -bool DatasourceFunctions::isEOF(const QString &datasourceName) +bool DatasourceFunctions::isEOF(const QString& datasourceName) { if (m_dataManager && m_dataManager->dataSource(datasourceName)) return m_dataManager->dataSource(datasourceName)->eof(); return true; } -int DatasourceFunctions::rowCount(const QString &datasourceName) +int DatasourceFunctions::rowCount(const QString& datasourceName) { if (m_dataManager && m_dataManager->dataSource(datasourceName)) return m_dataManager->dataSource(datasourceName)->model()->rowCount(); @@ -2197,7 +2185,7 @@ int DatasourceFunctions::rowCount(const QString &datasourceName) bool DatasourceFunctions::invalidate(const QString& datasourceName) { - if (m_dataManager && m_dataManager->dataSource(datasourceName)){ + if (m_dataManager && m_dataManager->dataSource(datasourceName)) { m_dataManager->dataSourceHolder(datasourceName)->invalidate(IDataSource::RENDER_MODE); return true; } @@ -2212,41 +2200,45 @@ QObject* DatasourceFunctions::createTableBuilder(QObject* horizontalLayout) return 0; } -TableBuilder::TableBuilder(HorizontalLayout* layout, DataSourceManager* dataManager) - : m_horizontalLayout(layout), m_baseLayout(0), m_dataManager(dataManager) +TableBuilder::TableBuilder(HorizontalLayout* layout, DataSourceManager* dataManager): + m_horizontalLayout(layout), + m_baseLayout(0), + m_dataManager(dataManager) { if (m_horizontalLayout) - m_patternLayout = dynamic_cast(m_horizontalLayout->cloneItem(m_horizontalLayout->itemMode())); + m_patternLayout = dynamic_cast( + m_horizontalLayout->cloneItem(m_horizontalLayout->itemMode())); } QObject* TableBuilder::addRow() { checkBaseLayout(); - if (m_baseLayout && m_patternLayout){ + if (m_baseLayout && m_patternLayout) { HorizontalLayout* newRow = new HorizontalLayout(m_baseLayout, m_baseLayout); newRow->setLayoutSpacing(m_horizontalLayout->layoutSpacing()); - for(int i = 0; i < m_horizontalLayout->childrenCount(); ++i){ + for (int i = 0; i < m_horizontalLayout->childrenCount(); ++i) { BaseDesignIntf* item = dynamic_cast(m_patternLayout->at(i)); BaseDesignIntf* cloneItem = item->cloneItem(item->itemMode(), newRow, newRow); newRow->addChild(cloneItem); } m_baseLayout->addChild(newRow); return newRow; - } else return 0; + } else + return 0; } QObject* TableBuilder::currentRow() { checkBaseLayout(); - if (m_baseLayout && m_baseLayout->childrenCount()>0) - return m_baseLayout->at(m_baseLayout->childrenCount()-1); + if (m_baseLayout && m_baseLayout->childrenCount() > 0) + return m_baseLayout->at(m_baseLayout->childrenCount() - 1); return 0; } void TableBuilder::fillInRowData(QObject* row) { HorizontalLayout* layout = dynamic_cast(row); - if (layout){ + if (layout) { for (int i = 0; i < layout->childrenCount(); ++i) { BaseDesignIntf* item = dynamic_cast(layout->at(i)); DataSourceManager* dm = dynamic_cast(m_dataManager); @@ -2263,12 +2255,14 @@ void TableBuilder::buildTable(const QString& datasourceName) if (dh) { dh->invalidate(IDataSource::RENDER_MODE); IDataSource* ds = m_dataManager->dataSource(datasourceName); - if (ds){ + if (ds) { bool firstTime = true; QObject* row = m_horizontalLayout; - while(!ds->eof()){ - if (!firstTime) row = addRow(); - else firstTime = false; + while (!ds->eof()) { + if (!firstTime) + row = addRow(); + else + firstTime = false; fillInRowData(row); ds->next(); } @@ -2278,10 +2272,11 @@ void TableBuilder::buildTable(const QString& datasourceName) void TableBuilder::checkBaseLayout() { - if (!m_baseLayout){ + if (!m_baseLayout) { m_baseLayout = dynamic_cast(m_horizontalLayout->parentItem()); - if (!m_baseLayout){ - m_baseLayout = new VerticalLayout(m_horizontalLayout->parent(), m_horizontalLayout->parentItem()); + if (!m_baseLayout) { + m_baseLayout = new VerticalLayout(m_horizontalLayout->parent(), + m_horizontalLayout->parentItem()); m_baseLayout->setItemLocation(m_horizontalLayout->itemLocation()); m_baseLayout->setPos(m_horizontalLayout->pos()); m_baseLayout->setWidth(m_horizontalLayout->width()); @@ -2294,22 +2289,21 @@ void TableBuilder::checkBaseLayout() } #ifdef USE_QTSCRIPTENGINE -void ComboBoxPrototype::addItem(const QString &text) +void ComboBoxPrototype::addItem(const QString& text) { QComboBox* comboBox = qscriptvalue_cast(thisObject()); - if (comboBox){ + if (comboBox) { comboBox->addItem(text); } } -void ComboBoxPrototype::addItems(const QStringList &texts) +void ComboBoxPrototype::addItems(const QStringList& texts) { QComboBox* comboBox = qscriptvalue_cast(thisObject()); - if (comboBox){ + if (comboBox) { comboBox->addItems(texts); } } #endif -} //namespace LimeReport - +} // namespace LimeReport diff --git a/limereport/lrscriptenginemanager.h b/limereport/lrscriptenginemanager.h index 1763190..dd9a319 100644 --- a/limereport/lrscriptenginemanager.h +++ b/limereport/lrscriptenginemanager.h @@ -30,16 +30,16 @@ #ifndef LRSCRIPTENGINEMANAGER_H #define LRSCRIPTENGINEMANAGER_H #ifdef USE_QTSCRIPTENGINE -#include #include +#include #endif -#include -#include #include -#include -#include -#include #include +#include +#include +#include +#include +#include //#include @@ -48,16 +48,16 @@ #endif #include "base/lrsingleton.h" -#include "lrglobal.h" -#include "lrscriptenginemanagerintf.h" #include "lrcallbackdatasourceintf.h" #include "lrcollection.h" #include "lrdatasourceintf.h" #include "lrdatasourcemanagerintf.h" +#include "lrglobal.h" #include "lrhorizontallayout.h" +#include "lrscriptenginemanagerintf.h" #include "lrverticallayout.h" -namespace LimeReport{ +namespace LimeReport { class DataSourceManager; class BaseDesignIntf; @@ -66,29 +66,32 @@ class BandDesignIntf; struct ContentItem { QString content; - int indent; - int pageNumber; + int indent; + int pageNumber; QString uniqKey; }; -class TableOfContents : public QObject{ +class TableOfContents: public QObject { Q_OBJECT public: - TableOfContents(QObject* parent = 0):QObject(parent){} + TableOfContents(QObject* parent = 0): QObject(parent) { } ~TableOfContents(); void setItem(const QString& uniqKey, const QString& content, int pageNumber, int indent = 0); void clear(); - bool isEmpty(){ return m_tableOfContents.isEmpty();} + bool isEmpty() { return m_tableOfContents.isEmpty(); } private slots: - void slotOneSlotDS(LimeReport::CallbackInfo info, QVariant &data); + void slotOneSlotDS(LimeReport::CallbackInfo info, QVariant& data); + private: - QVector m_tableOfContents; - QHash m_hash; + QVector m_tableOfContents; + QHash m_hash; }; - -struct ScriptFunctionDesc{ - enum FuncType {Native,Script}; +struct ScriptFunctionDesc { + enum FuncType { + Native, + Script + }; ScriptValueType scriptValue; QString name; QString description; @@ -98,78 +101,87 @@ struct ScriptFunctionDesc{ class ScriptEngineNode { public: - enum NodeType{Root, Category, Function, Dialog, DialogElement}; - ScriptEngineNode(const QString& name = "", const QString& description = "", NodeType type = Root, - ScriptEngineNode* parent = 0, const QIcon& icon = QIcon()); + enum NodeType { + Root, + Category, + Function, + Dialog, + DialogElement + }; + ScriptEngineNode(const QString& name = "", const QString& description = "", + NodeType type = Root, ScriptEngineNode* parent = 0, + const QIcon& icon = QIcon()); virtual ~ScriptEngineNode(); - int childCount(){return m_childs.count();} - ScriptEngineNode* child(int index){return m_childs[index];} - ScriptEngineNode* parent(){return m_parent;} - ScriptEngineNode* addChild(const QString& name = "", const QString &description = "", + int childCount() { return m_childs.count(); } + ScriptEngineNode* child(int index) { return m_childs[index]; } + ScriptEngineNode* parent() { return m_parent; } + ScriptEngineNode* addChild(const QString& name = "", const QString& description = "", NodeType type = Root, const QIcon& icon = QIcon()); - int row(); - QString name(){return m_name;} - QString description(){return m_description;} - QIcon icon(){return m_icon;} - void clear(); - NodeType type(){return m_type;} + int row(); + QString name() { return m_name; } + QString description() { return m_description; } + QIcon icon() { return m_icon; } + void clear(); + NodeType type() { return m_type; } + private: - QString m_name; - QString m_description; - QIcon m_icon; - NodeType m_type; - ScriptEngineNode* m_parent; + QString m_name; + QString m_description; + QIcon m_icon; + NodeType m_type; + ScriptEngineNode* m_parent; QVector m_childs; }; class ScriptEngineManager; -class ScriptEngineModel : public QAbstractItemModel{ +class ScriptEngineModel: public QAbstractItemModel { Q_OBJECT public: friend class ScriptEngineManager; - explicit ScriptEngineModel():m_scriptManager(0), m_rootNode(new ScriptEngineNode()){} + explicit ScriptEngineModel(): m_scriptManager(0), m_rootNode(new ScriptEngineNode()) { } explicit ScriptEngineModel(ScriptEngineManager* scriptManager); ~ScriptEngineModel(); - QModelIndex parent(const QModelIndex &child) const; - QModelIndex index(int row, int column, const QModelIndex &parent) const; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; + QModelIndex parent(const QModelIndex& child) const; + QModelIndex index(int row, int column, const QModelIndex& parent) const; + int rowCount(const QModelIndex& parent) const; + int columnCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& index, int role) const; void setScriptEngineManager(ScriptEngineManager* scriptManager); - inline ScriptEngineManager* scriptEngineManager(){return m_scriptManager;} + inline ScriptEngineManager* scriptEngineManager() { return m_scriptManager; } private slots: void slotScriptEngineChanged(); + private: - ScriptEngineNode* nodeFromIndex(const QModelIndex &index) const; + ScriptEngineNode* nodeFromIndex(const QModelIndex& index) const; void updateModel(); + private: ScriptEngineManager* m_scriptManager; ScriptEngineNode* m_rootNode; }; -class DialogDescriber : public QObject -{ +class DialogDescriber: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QByteArray description READ description WRITE setDescription) public: typedef QSharedPointer Ptr; - static Ptr create(const QString& name, const QByteArray &desc); - static Ptr create(){return Ptr(new DialogDescriber);} + static Ptr create(const QString& name, const QByteArray& desc); + static Ptr create() { return Ptr(new DialogDescriber); } QString name() const; void setName(const QString& name); QByteArray description() const; void setDescription(const QByteArray& description); -private : + +private: QString m_name; QByteArray m_description; }; -typedef QList< QSharedPointer > ReportPages; +typedef QList> ReportPages; -class ScriptEngineContext : public QObject, public ICollectionContainer -{ +class ScriptEngineContext: public QObject, public ICollectionContainer { Q_OBJECT Q_PROPERTY(ACollectionProperty dialogs READ fakeCollectionReader) Q_PROPERTY(QString initScript READ initScript WRITE setInitScript) @@ -177,27 +189,32 @@ public: #ifdef HAVE_UI_LOADER typedef QSharedPointer DialogPtr; #endif - explicit ScriptEngineContext(QObject* parent=0): - QObject(parent), m_currentBand(0), m_currentPage(0), - m_tableOfContents(new TableOfContents(this)), m_hasChanges(false) {} + explicit ScriptEngineContext(QObject* parent = 0): + QObject(parent), + m_currentBand(0), + m_currentPage(0), + m_tableOfContents(new TableOfContents(this)), + m_hasChanges(false) + { + } #ifdef HAVE_UI_LOADER - void addDialog(const QString& name, const QByteArray& description); - bool changeDialog(const QString& name, const QByteArray &description); - bool changeDialogName(const QString& oldName, const QString& newName); - bool previewDialog(const QString& dialogName); - bool containsDialog(const QString& dialogName); - const QVector& dialogDescribers(){return m_dialogs;} - void deleteDialog(const QString& dialogName); - QDialog *getDialog(const QString &dialogName); + void addDialog(const QString& name, const QByteArray& description); + bool changeDialog(const QString& name, const QByteArray& description); + bool changeDialogName(const QString& oldName, const QString& newName); + bool previewDialog(const QString& dialogName); + bool containsDialog(const QString& dialogName); + const QVector& dialogDescribers() { return m_dialogs; } + void deleteDialog(const QString& dialogName); + QDialog* getDialog(const QString& dialogName); QString getNewDialogName(); - void initDialogs(); + void initDialogs(); #endif - void baseDesignIntfToScript(const QString& pageName, BaseDesignIntf *item); - void qobjectToScript(const QString &name, QObject* item); - void clear(); + void baseDesignIntfToScript(const QString& pageName, BaseDesignIntf* item); + void qobjectToScript(const QString& name, QObject* item); + void clear(); QString initScript() const; - void setInitScript(const QString& initScript); - bool runInitScript(); + void setInitScript(const QString& initScript); + bool runInitScript(); BandDesignIntf* currentBand() const; void setCurrentBand(BandDesignIntf* currentBand); @@ -205,24 +222,24 @@ public: void setCurrentPage(PageItemDesignIntf* currentPage); TableOfContents* tableOfContents() const; void setTableOfContents(TableOfContents* tableOfContents); - void dropChanges(){ m_hasChanges = false;} - bool hasChanges(){ return m_hasChanges;} + void dropChanges() { m_hasChanges = false; } + bool hasChanges() { return m_hasChanges; } ReportPages* reportPages() const; void setReportPages(ReportPages* value); #ifdef HAVE_UI_LOADER signals: - void dialogNameChanged(QString dialogName); - void dialogDeleted(QString dialogName); - void dialogAdded(QString dialogName); + void dialogNameChanged(QString dialogName); + void dialogDeleted(QString dialogName); + void dialogAdded(QString dialogName); #endif protected: - QObject* createElement(const QString& collectionName,const QString& elementType); - int elementsCount(const QString& collectionName); - QObject* elementAt(const QString& collectionName,int index); - void collectionLoadFinished(const QString &collectionName); + QObject* createElement(const QString& collectionName, const QString& elementType); + int elementsCount(const QString& collectionName); + QObject* elementAt(const QString& collectionName, int index); + void collectionLoadFinished(const QString& collectionName); #ifdef HAVE_UI_LOADER - QDialog *createDialog(DialogDescriber *cont); - QDialog *findDialog(const QString &dialogName); + QDialog* createDialog(DialogDescriber* cont); + QDialog* findDialog(const QString& dialogName); DialogDescriber* findDialogContainer(const QString& dialogName); #endif private: @@ -239,88 +256,95 @@ private: ReportPages* m_reportPages; }; -class JSFunctionDesc{ +class JSFunctionDesc { public: - JSFunctionDesc(){} - JSFunctionDesc(const QString& functionName, - const QString& functionCategory, - const QString& functionDescription, - const QString& functionManagerName, - QObject* functionManager, - const QString& functionScriptWrapper - ): m_name(functionName), m_category(functionCategory), m_description(functionDescription), - m_managerName(functionManagerName), m_manager(functionManager), m_scriptWrapper(functionScriptWrapper) - {} + JSFunctionDesc() { } + JSFunctionDesc(const QString& functionName, const QString& functionCategory, + const QString& functionDescription, const QString& functionManagerName, + QObject* functionManager, const QString& functionScriptWrapper): + m_name(functionName), + m_category(functionCategory), + m_description(functionDescription), + m_managerName(functionManagerName), + m_manager(functionManager), + m_scriptWrapper(functionScriptWrapper) + { + } QString name() const; - void setName(const QString &name); + void setName(const QString& name); QString category() const; - void setCategory(const QString &category); + void setCategory(const QString& category); QString description() const; - void setDescription(const QString &description); + void setDescription(const QString& description); QString managerName() const; - void setManagerName(const QString &managerName); + void setManagerName(const QString& managerName); - QObject *manager() const; - void setManager(QObject *manager); + QObject* manager() const; + void setManager(QObject* manager); QString scriptWrapper() const; - void setScriptWrapper(const QString &scriptWrapper); + void setScriptWrapper(const QString& scriptWrapper); private: - QString m_name; - QString m_category; - QString m_description; - QString m_managerName; + QString m_name; + QString m_category; + QString m_description; + QString m_managerName; QObject* m_manager; - QString m_scriptWrapper; + QString m_scriptWrapper; }; #ifdef USE_QTSCRIPTENGINE -class ComboBoxPrototype : public QObject, public QScriptable{ +class ComboBoxPrototype: public QObject, public QScriptable { Q_OBJECT public: - ComboBoxPrototype(QObject* parent = 0):QObject(parent){} + ComboBoxPrototype(QObject* parent = 0): QObject(parent) { } public slots: - void addItem( const QString& text); + void addItem(const QString& text); void addItems(const QStringList& texts); }; #endif -class IWrapperCreator{ +class IWrapperCreator { public: virtual QObject* createWrapper(QObject* item) = 0; - virtual ~IWrapperCreator(){} + virtual ~IWrapperCreator() { } }; -class ComboBoxWrapper : public QObject{ +class ComboBoxWrapper: public QObject { Q_OBJECT public: - ComboBoxWrapper(QComboBox* comboBox, QObject* parent = 0) : QObject(parent), m_comboBox(comboBox){} - Q_INVOKABLE void addItems(const QStringList& texts){ m_comboBox->addItems(texts);} - Q_INVOKABLE void addItem(const QString& text){ m_comboBox->addItem(text);} + ComboBoxWrapper(QComboBox* comboBox, QObject* parent = 0): QObject(parent), m_comboBox(comboBox) + { + } + Q_INVOKABLE void addItems(const QStringList& texts) { m_comboBox->addItems(texts); } + Q_INVOKABLE void addItem(const QString& text) { m_comboBox->addItem(text); } + private: QComboBox* m_comboBox; }; -class ComboBoxWrapperCreator: public IWrapperCreator{ +class ComboBoxWrapperCreator: public IWrapperCreator { private: QObject* createWrapper(QObject* item); }; -class TableBuilder: public QObject{ +class TableBuilder: public QObject { Q_OBJECT public: TableBuilder(LimeReport::HorizontalLayout* layout, DataSourceManager* dataManager); - ~TableBuilder(){delete m_patternLayout;} + ~TableBuilder() { delete m_patternLayout; } Q_INVOKABLE QObject* addRow(); Q_INVOKABLE QObject* currentRow(); Q_INVOKABLE void fillInRowData(QObject* row); Q_INVOKABLE void buildTable(const QString& datasourceName); + private: void checkBaseLayout(); + private: LimeReport::HorizontalLayout* m_horizontalLayout; LimeReport::HorizontalLayout* m_patternLayout; @@ -328,92 +352,110 @@ private: DataSourceManager* m_dataManager; }; -class DatasourceFunctions : public QObject{ +class DatasourceFunctions: public QObject { Q_OBJECT public: - explicit DatasourceFunctions(IDataSourceManager* dataManager) - : m_dataManager(dynamic_cast(dataManager)){} + explicit DatasourceFunctions(IDataSourceManager* dataManager): + m_dataManager(dynamic_cast(dataManager)) + { + } Q_INVOKABLE bool first(const QString& datasourceName); Q_INVOKABLE bool next(const QString& datasourceName); Q_INVOKABLE bool prior(const QString& datasourceName); Q_INVOKABLE bool isEOF(const QString& datasourceName); Q_INVOKABLE int rowCount(const QString& datasourceName); Q_INVOKABLE bool invalidate(const QString& datasourceName); - Q_INVOKABLE QObject *createTableBuilder(QObject *horizontalLayout); + Q_INVOKABLE QObject* createTableBuilder(QObject* horizontalLayout); + private: DataSourceManager* m_dataManager; }; -class ScriptFunctionsManager : public QObject{ +class ScriptFunctionsManager: public QObject { Q_OBJECT public: - explicit ScriptFunctionsManager(QObject* parent = 0):QObject(parent){ - m_wrappersFactory.insert("QComboBox",new ComboBoxWrapperCreator()); - + explicit ScriptFunctionsManager(QObject* parent = 0): QObject(parent) + { + m_wrappersFactory.insert("QComboBox", new ComboBoxWrapperCreator()); } - ~ScriptFunctionsManager(){ - foreach(IWrapperCreator* wrapper, m_wrappersFactory.values()){ delete wrapper;} m_wrappersFactory.clear(); + ~ScriptFunctionsManager() + { + foreach (IWrapperCreator* wrapper, m_wrappersFactory.values()) { + delete wrapper; + } + m_wrappersFactory.clear(); } - Q_INVOKABLE QVariant calcGroupFunction(const QString& name, const QString& expressionID, const QString& bandName, QObject* currentPage); - Q_INVOKABLE QVariant calcGroupFunction(const QString& name, const QString& expressionID, const QString& bandName); + Q_INVOKABLE QVariant calcGroupFunction(const QString& name, const QString& expressionID, + const QString& bandName, QObject* currentPage); + Q_INVOKABLE QVariant calcGroupFunction(const QString& name, const QString& expressionID, + const QString& bandName); Q_INVOKABLE QVariant line(const QString& bandName); - Q_INVOKABLE QVariant numberFormat(QVariant value, const char &format, int precision, const QString& locale); + Q_INVOKABLE QVariant numberFormat(QVariant value, const char& format, int precision, + const QString& locale); Q_INVOKABLE QVariant dateFormat(QVariant value, const QString& format, const QString& locale); Q_INVOKABLE QVariant timeFormat(QVariant value, const QString& format); - Q_INVOKABLE QVariant dateTimeFormat(QVariant value, const QString& format, const QString& locale); + Q_INVOKABLE QVariant dateTimeFormat(QVariant value, const QString& format, + const QString& locale); Q_INVOKABLE QVariant sectotimeFormat(QVariant value, const QString& format); Q_INVOKABLE QVariant date(); Q_INVOKABLE QVariant now(); Q_INVOKABLE QVariant currencyFormat(QVariant value, const QString& locale); Q_INVOKABLE QVariant currencyUSBasedFormat(QVariant value, const QString& currencySymbol); - Q_INVOKABLE void setVariable(const QString& name, QVariant value); + Q_INVOKABLE void setVariable(const QString& name, QVariant value); Q_INVOKABLE QVariant getVariable(const QString& name); Q_INVOKABLE QVariant getField(const QString& field); - Q_INVOKABLE QVariant getFieldByKeyField(const QString& datasourceName, const QString& valueFieldName, const QString& keyFieldName, QVariant keyValue); + Q_INVOKABLE QVariant getFieldByKeyField(const QString& datasourceName, + const QString& valueFieldName, + const QString& keyFieldName, QVariant keyValue); Q_INVOKABLE QVariant getFieldByRowIndex(const QString& fieldName, int rowIndex); - Q_INVOKABLE void reopenDatasource(const QString& datasourceName); - Q_INVOKABLE QVariant color(const QString& color){ return QColor(color);} - Q_INVOKABLE void addBookmark(const QString& uniqKey, const QString& content); - Q_INVOKABLE int findPageIndexByBookmark(const QString &uniqKey); - Q_INVOKABLE void addTableOfContentsItem(const QString& uniqKey, const QString& content, int indent = 0); - Q_INVOKABLE void clearTableOfContents(); - Q_INVOKABLE QFont font(const QString& family, int pointSize = -1, bool bold = false, bool italic = false, bool underLine = false); + Q_INVOKABLE void reopenDatasource(const QString& datasourceName); + Q_INVOKABLE QVariant color(const QString& color) { return QColor(color); } + Q_INVOKABLE void addBookmark(const QString& uniqKey, const QString& content); + Q_INVOKABLE int findPageIndexByBookmark(const QString& uniqKey); + Q_INVOKABLE void addTableOfContentsItem(const QString& uniqKey, const QString& content, + int indent = 0); + Q_INVOKABLE void clearTableOfContents(); + Q_INVOKABLE QFont font(const QString& family, int pointSize = -1, bool bold = false, + bool italic = false, bool underLine = false); /*! * \brief getFieldByRowIndexEx Выдает для поля значение заданной роли * \param fieldName имя источника данных + имя поля * \param rowIndex индекс строки * \param role код роли * \return - */ - Q_INVOKABLE QVariant getFieldByRowIndexEx(const QString &fieldName, int rowIndex, const int role); + */ + Q_INVOKABLE QVariant getFieldByRowIndexEx(const QString& fieldName, int rowIndex, + const int role); /*! * \brief getFieldByRowIndexEx2 Выдает для поля значение заданной роли * \param fieldName имя источника данных + имя поля * \param rowIndex индекс строки * \param roleName имя роли из roleNames() * \return - */ - Q_INVOKABLE QVariant getFieldByRowIndexEx2(const QString &fieldName, int rowIndex, const QString &roleName); + */ + Q_INVOKABLE QVariant getFieldByRowIndexEx2(const QString& fieldName, int rowIndex, + const QString& roleName); /*! * \brief getHeaderData Выдает для поля заголовка значение заданной роли * \param fieldName имя источника данных + имя поля * \param role имя роли из roleNames() * \return - */ - Q_INVOKABLE QVariant getHeaderData(const QString &fieldName, const QString &roleName); + */ + Q_INVOKABLE QVariant getHeaderData(const QString& fieldName, const QString& roleName); /*! * \brief getHeaderColumnNameByIndex Выдает имя колонки по ее индексу (имя используемое LR) * \param datasourceName имя источника данных * \param columnIndex индекс колонки * \return - */ - Q_INVOKABLE QVariant getHeaderColumnNameByIndex(const QString &datasourceName, const int columnIndex); + */ + Q_INVOKABLE QVariant getHeaderColumnNameByIndex(const QString& datasourceName, + const int columnIndex); /*! * \brief getColumnCount Выдает число столбцов в источнике данных * \param datasourceName имя источника данных * \return возможно -1 при ошибке - */ - Q_INVOKABLE int getColumnCount(const QString &datasourceName); + */ + Q_INVOKABLE int getColumnCount(const QString& datasourceName); #ifdef USE_QJSENGINE Q_INVOKABLE void addItemsToComboBox(QJSValue object, const QStringList& values); @@ -427,100 +469,126 @@ public: Q_INVOKABLE QScriptValue createWrapper(QScriptValue item); #endif Q_INVOKABLE QFont font(QVariantMap params); - Q_INVOKABLE int getPageFreeSpace(QObject *page); - ScriptEngineManager *scriptEngineManager() const; - void setScriptEngineManager(ScriptEngineManager *scriptEngineManager); - static QColor createQColor(const QString& color){ return QColor(color);} + Q_INVOKABLE int getPageFreeSpace(QObject* page); + ScriptEngineManager* scriptEngineManager() const; + void setScriptEngineManager(ScriptEngineManager* scriptEngineManager); + static QColor createQColor(const QString& color) { return QColor(color); } + private: ScriptEngineManager* m_scriptEngineManager; QMap m_wrappersFactory; }; -class ScriptNode{ +class ScriptNode { public: typedef QSharedPointer Ptr; - QString body(){ + QString body() + { if (m_body.isEmpty() && m_children.count() > 0) - return m_children.at(0)->body(); + return m_children.at(0)->body(); return m_body; } - void setBody(const QString& body){ m_body = body;} - void setStartLex(const QString startLex){ m_startLex = startLex;} - QString script(){return m_startLex + m_body + '}';} - Ptr createChildNode(){ + void setBody(const QString& body) { m_body = body; } + void setStartLex(const QString startLex) { m_startLex = startLex; } + QString script() { return m_startLex + m_body + '}'; } + Ptr createChildNode() + { Ptr result = Ptr(new ScriptNode()); m_children.append(result); return result; } - QVector children() const {return m_children;} + QVector children() const { return m_children; } + private: QVector m_children; QString m_body; QString m_startLex; }; -class ScriptExtractor -{ +class ScriptExtractor { public: - enum State{None,BuksFound,SFound,StartScriptFound,OpenBracketFound,CloseBracketFound,DFound,VFound, SignFound}; + enum State { + None, + BuksFound, + SFound, + StartScriptFound, + OpenBracketFound, + CloseBracketFound, + DFound, + VFound, + SignFound + }; explicit ScriptExtractor(const QString& value): - m_context(value), m_scriptTree(ScriptNode::Ptr(new ScriptNode())){} + m_context(value), + m_scriptTree(ScriptNode::Ptr(new ScriptNode())) + { + } bool parse(); - ScriptNode::Ptr scriptTree(){return m_scriptTree;} + ScriptNode::Ptr scriptTree() { return m_scriptTree; } + private: - bool isStartLexem(int &curPos, QChar value); - bool parse(int& curPos, const State &state, ScriptNode::Ptr scriptNode); - void skipField(int &curPos); - void extractScript(int& curPos, const QString &startStr, ScriptNode::Ptr scriptNode); + bool isStartLexem(int& curPos, QChar value); + bool parse(int& curPos, const State& state, ScriptNode::Ptr scriptNode); + void skipField(int& curPos); + void extractScript(int& curPos, const QString& startStr, ScriptNode::Ptr scriptNode); bool extractBracket(int& curPos, ScriptNode::Ptr scriptNode); - bool isStartScriptLexem(int &curPos); - bool isStartFieldLexem(int &curPos); - bool isStartVariableLexem(int &curPos); + bool isStartScriptLexem(int& curPos); + bool isStartFieldLexem(int& curPos); + bool isStartVariableLexem(int& curPos); QString substring(const QString& value, int start, int end); + private: QString m_context; ScriptNode::Ptr m_scriptTree; }; -class ScriptEngineManager : public QObject, public Singleton, public IScriptEngineManager -{ +class ScriptEngineManager: + public QObject, + public Singleton, + public IScriptEngineManager { Q_OBJECT public: friend class Singleton; - ScriptEngineType* scriptEngine(){return m_scriptEngine;} + ScriptEngineType* scriptEngine() { return m_scriptEngine; } ~ScriptEngineManager(); bool isFunctionExists(const QString& functionName) const; void deleteFunction(const QString& functionsName); bool addFunction(const JSFunctionDesc& functionsDescriber); #ifdef USE_QTSCRIPTENGINE - bool addFunction(const QString &name, QScriptEngine::FunctionSignature function, const QString &category, const QString &description); + bool addFunction(const QString& name, QScriptEngine::FunctionSignature function, + const QString& category, const QString& description); #endif - bool addFunction(const QString &name, const QString& script, - const QString &category="", const QString &description=""); - const QString& lastError() const {return m_lastError;} + bool addFunction(const QString& name, const QString& script, const QString& category = "", + const QString& description = ""); + const QString& lastError() const { return m_lastError; } QStringList functionsNames(); - const QHash& functionsDescribers(){return m_functions;} - ScriptEngineModel* model(){return m_model;} - void setContext(ScriptEngineContext* context){m_context=context;} - DataSourceManager* dataManager() const {return m_dataManager;} + const QHash& functionsDescribers() { return m_functions; } + ScriptEngineModel* model() { return m_model; } + void setContext(ScriptEngineContext* context) { m_context = context; } + DataSourceManager* dataManager() const { return m_dataManager; } void setDataManager(DataSourceManager* dataManager); - QString expandUserVariables(QString context, RenderPass pass, ExpandType expandType, QVariant &varValue); - QString expandDataFields(QString context, ExpandType expandType, QVariant &varValue, QObject* reportItem); - QString expandScripts(QString context, QVariant &varValue, QObject* reportItem); + QString expandUserVariables(QString context, RenderPass pass, ExpandType expandType, + QVariant& varValue); + QString expandDataFields(QString context, ExpandType expandType, QVariant& varValue, + QObject* reportItem); + QString expandScripts(QString context, QVariant& varValue, QObject* reportItem); - QString replaceScripts(QString context, QVariant& varValue, QObject *reportItem, ScriptEngineType *se, ScriptNode::Ptr scriptTree); + QString replaceScripts(QString context, QVariant& varValue, QObject* reportItem, + ScriptEngineType* se, ScriptNode::Ptr scriptTree); - QVariant evaluateScript(const QString &script); - void addBookMark(const QString &uniqKey, const QString &content); - int findPageIndexByBookmark(const QString& uniqKey); - void addTableOfContentsItem(const QString& uniqKey, const QString& content, int indent); - void clearTableOfContents(); - int getPageFreeSpace(PageItemDesignIntf *page); + QVariant evaluateScript(const QString& script); + void addBookMark(const QString& uniqKey, const QString& content); + int findPageIndexByBookmark(const QString& uniqKey); + void addTableOfContentsItem(const QString& uniqKey, const QString& content, int indent); + void clearTableOfContents(); + int getPageFreeSpace(PageItemDesignIntf* page); ScriptValueType moveQObjectToScript(QObject* object, const QString objectName); + protected: void updateModel(); + private: Q_DISABLE_COPY(ScriptEngineManager) bool createLineFunction(); @@ -551,18 +619,17 @@ private: private: ScriptEngineManager(); - ScriptEngineType* m_scriptEngine; + ScriptEngineType* m_scriptEngine; QString m_lastError; - QHash m_functions; + QHash m_functions; ScriptEngineModel* m_model; ScriptEngineContext* m_context; DataSourceManager* m_dataManager; ScriptFunctionsManager* m_functionManager; }; - #ifdef USE_QTSCRIPTENGINE -class QFontPrototype : public QObject, public QScriptable { +class QFontPrototype: public QObject, public QScriptable { Q_OBJECT Q_PROPERTY(QString family READ family) Q_PROPERTY(int size READ size) @@ -570,38 +637,51 @@ class QFontPrototype : public QObject, public QScriptable { Q_PROPERTY(bool italic READ italic) Q_PROPERTY(bool underline READ underline) public: - QFontPrototype(QObject * parent = NULL) : QObject(parent) , QScriptable() { + QFontPrototype(QObject* parent = NULL): QObject(parent), QScriptable() + { this->setObjectName("QFontPrototype"); } - QString family() const { + QString family() const + { QFont font(qScriptValueToValue(this->thisObject())); return font.family(); } - int size(){ + int size() + { QFont font = qScriptValueToValue(thisObject()); return font.pointSize(); } - bool bold(){ + bool bold() + { QFont font = qScriptValueToValue(thisObject()); return font.bold(); } - bool italic(){ + bool italic() + { QFont font = qScriptValueToValue(thisObject()); return font.italic(); } - bool underline(){ + bool underline() + { QFont font = qScriptValueToValue(thisObject()); return font.underline(); } - static QScriptValue constructorQFont(QScriptContext * context, QScriptEngine * engine) { + static QScriptValue constructorQFont(QScriptContext* context, QScriptEngine* engine) + { QFont font; switch (context->argumentCount()) { - case 5: font.setUnderline(qScriptValueToValue(context->argument(4))); - case 4: font.setBold(qScriptValueToValue(context->argument(3))); - case 3: font.setItalic(qScriptValueToValue(context->argument(2))); - case 2: font.setPointSize(qScriptValueToValue(context->argument(1))); - case 1: font.setFamily(qScriptValueToValue(context->argument(0))); - case 0: break; + case 5: + font.setUnderline(qScriptValueToValue(context->argument(4))); + case 4: + font.setBold(qScriptValueToValue(context->argument(3))); + case 3: + font.setItalic(qScriptValueToValue(context->argument(2))); + case 2: + font.setPointSize(qScriptValueToValue(context->argument(1))); + case 1: + font.setFamily(qScriptValueToValue(context->argument(0))); + case 0: + break; default: break; } @@ -610,7 +690,7 @@ public: }; #endif -} +} // namespace LimeReport #ifdef USE_QTSCRIPTENGINE Q_DECLARE_METATYPE(LimeReport::ComboBoxPrototype*) Q_DECLARE_METATYPE(QComboBox*) diff --git a/limereport/lrscriptenginemanagerintf.h b/limereport/lrscriptenginemanagerintf.h index 573f748..055e771 100644 --- a/limereport/lrscriptenginemanagerintf.h +++ b/limereport/lrscriptenginemanagerintf.h @@ -32,15 +32,15 @@ #include "qglobal.h" #if QT_VERSION >= 0x050600 - #ifndef USE_QTSCRIPTENGINE - #ifndef USE_QJSENGINE - #define USE_QJSENGINE - #endif - #endif +#ifndef USE_QTSCRIPTENGINE +#ifndef USE_QJSENGINE +#define USE_QJSENGINE +#endif +#endif #else - #ifndef USE_QTSCRIPTENGINE - #define USE_QTSCRIPTENGINE - #endif +#ifndef USE_QTSCRIPTENGINE +#define USE_QTSCRIPTENGINE +#endif #endif #ifdef USE_QJSENGINE @@ -49,38 +49,38 @@ #include #endif -namespace LimeReport{ +namespace LimeReport { #ifdef USE_QJSENGINE - typedef QJSEngine ScriptEngineType; - typedef QJSValue ScriptValueType; - template - static inline QJSValue getJSValue(QJSEngine &e, T *p) - { - QJSValue res = e.newQObject(p); - QQmlEngine::setObjectOwnership(p, QQmlEngine::CppOwnership); - return res; - } +typedef QJSEngine ScriptEngineType; +typedef QJSValue ScriptValueType; +template static inline QJSValue getJSValue(QJSEngine& e, T* p) +{ + QJSValue res = e.newQObject(p); + QQmlEngine::setObjectOwnership(p, QQmlEngine::CppOwnership); + return res; +} #else - typedef QScriptEngine ScriptEngineType; - typedef QScriptValue ScriptValueType; +typedef QScriptEngine ScriptEngineType; +typedef QScriptValue ScriptValueType; #endif -class IScriptEngineManager{ +class IScriptEngineManager { public: virtual ScriptEngineType* scriptEngine() = 0; #ifdef USE_QTSCRIPTENGINE virtual bool addFunction(const QString& name, ScriptEngineType::FunctionSignature function, - const QString& category="", const QString& description="") = 0; + const QString& category = "", const QString& description = "") + = 0; #endif - virtual bool addFunction(const QString &name, const QString& script, - const QString &category="", const QString &description="") = 0; + virtual bool addFunction(const QString& name, const QString& script, + const QString& category = "", const QString& description = "") + = 0; virtual const QString& lastError() const = 0; virtual ScriptValueType moveQObjectToScript(QObject* object, const QString objectName) = 0; - virtual ~IScriptEngineManager(){} - + virtual ~IScriptEngineManager() { } }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRSCRIPTENGINEMANAGERINTF_H diff --git a/limereport/lrsettingdialog.cpp b/limereport/lrsettingdialog.cpp index 8da15ac..e2e7332 100644 --- a/limereport/lrsettingdialog.cpp +++ b/limereport/lrsettingdialog.cpp @@ -1,34 +1,28 @@ #include "lrsettingdialog.h" #include "ui_lrsettingdialog.h" + #include "lrglobal.h" + #include #include -namespace LimeReport{ +namespace LimeReport { -SettingDialog::SettingDialog(QWidget *parent) : +SettingDialog::SettingDialog(QWidget* parent): QDialog(parent), - ui(new Ui::SettingDialog), m_settings(0) + ui(new Ui::SettingDialog), + m_settings(0) { ui->setupUi(this); ui->toolBox->setCurrentIndex(0); - ui->indentSize->setRange(0,10); + ui->indentSize->setRange(0, 10); } -SettingDialog::~SettingDialog() -{ - delete ui; -} +SettingDialog::~SettingDialog() { delete ui; } -int SettingDialog::verticalGridStep() -{ - return ui->verticalGridStep->value(); -} +int SettingDialog::verticalGridStep() { return ui->verticalGridStep->value(); } -int SettingDialog::horizontalGridStep() -{ - return ui->horizontalGridStep->value(); -} +int SettingDialog::horizontalGridStep() { return ui->horizontalGridStep->value(); } QFont SettingDialog::defaultFont() { @@ -44,15 +38,9 @@ QFont SettingDialog::scriptFont() return result; } -int SettingDialog::tabIndention() -{ - return ui->indentSize->value(); -} +int SettingDialog::tabIndention() { return ui->indentSize->value(); } -QString SettingDialog::theme() -{ - return ui->cbTheme->currentText(); -} +QString SettingDialog::theme() { return ui->cbTheme->currentText(); } bool SettingDialog::suppressAbsentFieldsAndVarsWarnings() { @@ -68,36 +56,22 @@ QLocale::Language SettingDialog::designerLanguage() return QLocale().language(); } -QString SettingDialog::reportUnits() -{ - return ui->reportUnits->currentText(); -} +QString SettingDialog::reportUnits() { return ui->reportUnits->currentText(); } -int SettingDialog::baseItemPadding() -{ - return ui->neBaseItemPadding->value(); -} +int SettingDialog::baseItemPadding() { return ui->neBaseItemPadding->value(); } -void SettingDialog::setSuppressAbsentFieldsAndVarsWarnings(bool value){ +void SettingDialog::setSuppressAbsentFieldsAndVarsWarnings(bool value) +{ ui->cbSuppressWarnings->setChecked(value); } -void SettingDialog::setBaseItemPadding(int value) -{ - ui->neBaseItemPadding->setValue(value); -} +void SettingDialog::setBaseItemPadding(int value) { ui->neBaseItemPadding->setValue(value); } -void SettingDialog::setHorizontalGridStep(int value) -{ - ui->horizontalGridStep->setValue(value); -} +void SettingDialog::setHorizontalGridStep(int value) { ui->horizontalGridStep->setValue(value); } -void SettingDialog::setVerticalGridStep(int value) -{ - ui->verticalGridStep->setValue(value); -} +void SettingDialog::setVerticalGridStep(int value) { ui->verticalGridStep->setValue(value); } -void SettingDialog::setDefaultFont(const QFont &value) +void SettingDialog::setDefaultFont(const QFont& value) { ui->defaultFont->setCurrentFont(value); ui->defaultFontSize->setValue(value.pointSize()); @@ -109,12 +83,9 @@ void SettingDialog::setScriptFont(const QFont& value) ui->scriptFontSize->setValue(value.pointSize()); } -void SettingDialog::setScritpTabIndention(int size) -{ - ui->indentSize->setValue(size); -} +void SettingDialog::setScritpTabIndention(int size) { ui->indentSize->setValue(size); } -void SettingDialog::setTheme(const QString &theme) +void SettingDialog::setTheme(const QString& theme) { #if QT_VERSION < 0x050000 ui->cbTheme->setCurrentIndex(ui->cbTheme->findText(theme)); @@ -123,7 +94,8 @@ void SettingDialog::setTheme(const QString &theme) #endif } -void SettingDialog::setDesignerLanguages(QList languages, QLocale::Language currentLanguage) +void SettingDialog::setDesignerLanguages(QList languages, + QLocale::Language currentLanguage) { m_aviableLanguages = languages; m_currentLanguage = currentLanguage; @@ -139,13 +111,14 @@ void SettingDialog::setDesignerLanguages(QList languages, QLo ui->designerLanguage->addItem(QLocale::languageToString(language)); } #if QT_VERSION < 0x050000 - ui->designerLanguage->setCurrentIndex(ui->designerLanguage->findText(QLocale::languageToString(currentLanguage))); + ui->designerLanguage->setCurrentIndex( + ui->designerLanguage->findText(QLocale::languageToString(currentLanguage))); #else ui->designerLanguage->setCurrentText(QLocale::languageToString(currentLanguage)); #endif } -void SettingDialog::setDesignerThemes(QList themes, const QString ¤tTheme) +void SettingDialog::setDesignerThemes(QList themes, const QString& currentTheme) { ui->cbTheme->clear(); ui->cbTheme->addItems(themes); @@ -167,18 +140,19 @@ void SettingDialog::setDesignerUnites(QList unitTypes, const QString cu #endif } -void SettingDialog::setSettings(QSettings* settings){ +void SettingDialog::setSettings(QSettings* settings) +{ m_settings = settings; - if (m_settings){ + if (m_settings) { m_settings->beginGroup("ScriptEditor"); QVariant fontName = m_settings->value("DefaultFontName"); - if (fontName.isValid()){ + if (fontName.isValid()) { QVariant fontSize = m_settings->value("DefaultFontSize"); - ui->scriptFont->setCurrentFont(QFont(fontName.toString(),fontSize.toInt())); + ui->scriptFont->setCurrentFont(QFont(fontName.toString(), fontSize.toInt())); ui->scriptFontSize->setValue(fontSize.toInt()); } QVariant indentSize = m_settings->value("TabIndention"); - if (indentSize.isValid()){ + if (indentSize.isValid()) { ui->indentSize->setValue(indentSize.toInt()); } else { ui->indentSize->setValue(LimeReport::Const::DEFAULT_TAB_INDENTION); @@ -189,7 +163,7 @@ void SettingDialog::setSettings(QSettings* settings){ void SettingDialog::on_bbOkCancel_accepted() { - if (m_settings){ + if (m_settings) { m_settings->beginGroup("ScriptEditor"); m_settings->setValue("DefaultFontName", ui->scriptFont->currentFont().family()); m_settings->setValue("DefaultFontSize", ui->scriptFontSize->value()); @@ -198,12 +172,10 @@ void SettingDialog::on_bbOkCancel_accepted() } } -bool SettingDialog::isFileExists(const QString &path) +bool SettingDialog::isFileExists(const QString& path) { QFileInfo check_file(path); return check_file.exists() && check_file.isFile(); } } // namespace LimeReport - - diff --git a/limereport/lrsettingdialog.h b/limereport/lrsettingdialog.h index 173cdcc..48db608 100644 --- a/limereport/lrsettingdialog.h +++ b/limereport/lrsettingdialog.h @@ -5,18 +5,17 @@ #include #include -namespace LimeReport{ +namespace LimeReport { namespace Ui { -class SettingDialog; + class SettingDialog; } -class SettingDialog : public QDialog -{ +class SettingDialog: public QDialog { Q_OBJECT public: - explicit SettingDialog(QWidget *parent = 0); + explicit SettingDialog(QWidget* parent = 0); ~SettingDialog(); int verticalGridStep(); int horizontalGridStep(); @@ -36,16 +35,19 @@ public: void setScriptFont(const QFont& value); void setScritpTabIndention(int size); void setTheme(const QString& theme); - void setDesignerLanguages(QList languages, QLocale::Language currentLanguage); + void setDesignerLanguages(QList languages, + QLocale::Language currentLanguage); void setDesignerThemes(QList themes, const QString& currentTheme); void setDesignerUnites(QList unitTypes, const QString currentUnitType); void setSettings(QSettings* settings); private slots: void on_bbOkCancel_accepted(); + private: bool isFileExists(const QString& path); + private: - Ui::SettingDialog *ui; + Ui::SettingDialog* ui; QList m_aviableLanguages; QLocale::Language m_currentLanguage; QSettings* m_settings; diff --git a/limereport/lrsimplecrypt.cpp b/limereport/lrsimplecrypt.cpp index e5de984..298094b 100644 --- a/limereport/lrsimplecrypt.cpp +++ b/limereport/lrsimplecrypt.cpp @@ -32,83 +32,89 @@ namespace LimeReport { #if defined(LP64) || defined(_LP64) || defined(__LP64__) -typedef unsigned int WORD; /* Should be 32-bit = 4 bytes */ +typedef unsigned int WORD; /* Should be 32-bit = 4 bytes */ #else typedef unsigned long int WORD; /* Should be 32-bit = 4 bytes */ #endif -const int w = 32; /* word size in bits */ -const int r = 12; /* number of rounds */ -const int b = 16; /* number of bytes in key */ -const int c = 4; /* number words in key = ceil(8*b/w)*/ -const int t = 26; /* size of table S = 2*(r+1) words */ +const int w = 32; /* word size in bits */ +const int r = 12; /* number of rounds */ +const int b = 16; /* number of bytes in key */ +const int c = 4; /* number words in key = ceil(8*b/w)*/ +const int t = 26; /* size of table S = 2*(r+1) words */ const char* passPhrase = "HjccbzHjlbyfCkjy"; WORD P = 0xb7e15163, Q = 0x9e3779b9; -#define ROTL(x,y) (((x)<<(y&(w-1))) | ((x)>>(w-(y&(w-1))))) -#define ROTR(x,y) (((x)>>(y&(w-1))) | ((x)<<(w-(y&(w-1))))) +#define ROTL(x, y) (((x) << (y & (w - 1))) | ((x) >> (w - (y & (w - 1))))) +#define ROTR(x, y) (((x) >> (y & (w - 1))) | ((x) << (w - (y & (w - 1))))) -union WTB{ - WORD word[2]; - char bytes[8]; +union WTB { + WORD word[2]; + char bytes[8]; }; -void initPt(WTB& pt, QByteArray::Iterator* it, QByteArray::Iterator end){ - for (int i = 0; i<8; i++){ - if (*it != end){ - pt.bytes[i]=**it; +void initPt(WTB& pt, QByteArray::Iterator* it, QByteArray::Iterator end) +{ + for (int i = 0; i < 8; i++) { + if (*it != end) { + pt.bytes[i] = **it; ++*it; - } else break; + } else + break; } } -class ChipperPrivate{ +class ChipperPrivate { friend class Chipper; + public: - ChipperPrivate():m_prepared(false){} - bool isPrepared(){ return m_prepared;} + ChipperPrivate(): m_prepared(false) { } + bool isPrepared() { return m_prepared; } + private: - void RC5_SETUP(const char *K); - void RC5_ENCRYPT(WORD *pt, WORD *ct); - void RC5_DECRYPT(WORD *ct, WORD *pt); - WORD S[26] = {0}; + void RC5_SETUP(const char* K); + void RC5_ENCRYPT(WORD* pt, WORD* ct); + void RC5_DECRYPT(WORD* ct, WORD* pt); + WORD S[26] = { 0 }; bool m_prepared; }; -void ChipperPrivate::RC5_SETUP(const char *K) +void ChipperPrivate::RC5_SETUP(const char* K) { - WORD i, j, k, u=w/8, A, B, L[c]; - for (i=b,L[c-1]=0; i!=0; i--) - L[(i-1)/u] = (L[(i-1)/u]<<8)+K[i-1]; - for (S[0]=P,i=1; i 3*c */ - A = S[i] = ROTL(S[i]+(A+B),3); - B = L[j] = ROTL(L[j]+(A+B),(A+B)); + WORD i, j, k, u = w / 8, A, B, L[c]; + for (i = b, L[c - 1] = 0; i != 0; i--) + L[(i - 1) / u] = (L[(i - 1) / u] << 8) + K[i - 1]; + for (S[0] = P, i = 1; i < t; i++) + S[i] = S[i - 1] + Q; + for (A = B = i = j = k = 0; k < 3 * t; k++, i = (i + 1) % t, j = (j + 1) % c) { /* 3*t > 3*c */ + A = S[i] = ROTL(S[i] + (A + B), 3); + B = L[j] = ROTL(L[j] + (A + B), (A + B)); } m_prepared = true; } -void ChipperPrivate::RC5_ENCRYPT(WORD *pt, WORD *ct) +void ChipperPrivate::RC5_ENCRYPT(WORD* pt, WORD* ct) { - WORD i, A=pt[0]+S[0], B=pt[1]+S[1]; - for (i=1; i<=r; i++) - { A = ROTL(A^B,B)+S[2*i]; - B = ROTL(B^A,A)+S[2*i+1]; - } - ct[0] = A; ct[1] = B; + WORD i, A = pt[0] + S[0], B = pt[1] + S[1]; + for (i = 1; i <= r; i++) { + A = ROTL(A ^ B, B) + S[2 * i]; + B = ROTL(B ^ A, A) + S[2 * i + 1]; + } + ct[0] = A; + ct[1] = B; } -void ChipperPrivate::RC5_DECRYPT(WORD *ct, WORD *pt) +void ChipperPrivate::RC5_DECRYPT(WORD* ct, WORD* pt) { - WORD i, B=ct[1], A=ct[0]; - for (i=r; i>0; i--) - { B = ROTR(B-S[2*i+1],A)^A; - A = ROTR(A-S[2*i],B)^B; - } - pt[1] = B-S[1]; pt[0] = A-S[0]; + WORD i, B = ct[1], A = ct[0]; + for (i = r; i > 0; i--) { + B = ROTR(B - S[2 * i + 1], A) ^ A; + A = ROTR(A - S[2 * i], B) ^ B; + } + pt[1] = B - S[1]; + pt[0] = A - S[0]; } QByteArray Chipper::cryptString(QString value) @@ -121,26 +127,26 @@ QByteArray Chipper::cryptString(QString value) if (!d->isPrepared()) d->RC5_SETUP(passPhrase); - prior.word[0]=0; - prior.word[1]=0; + prior.word[0] = 0; + prior.word[1] = 0; QByteArray::Iterator it = buff.begin(); - while (it!=buff.end()){ + while (it != buff.end()) { pt.word[0] = 0; pt.word[1] = 0; - initPt(pt,&it,buff.end()); + initPt(pt, &it, buff.end()); pt.word[0] = pt.word[0] ^ prior.word[0]; pt.word[1] = pt.word[1] ^ prior.word[1]; - d->RC5_ENCRYPT(pt.word,ct.word); + d->RC5_ENCRYPT(pt.word, ct.word); prior.word[0] = pt.word[0]; prior.word[1] = pt.word[1]; - for (int i=0;i<8;i++){ + for (int i = 0; i < 8; i++) { result += ct.bytes[i]; } } @@ -158,14 +164,14 @@ QString Chipper::decryptByteArray(QByteArray value) prior.word[1] = 0; QByteArray::Iterator it = value.begin(); - while (it!=value.end()){ + while (it != value.end()) { pt.word[0] = 0; pt.word[1] = 0; - initPt(pt,&it,value.end()); + initPt(pt, &it, value.end()); - d->RC5_DECRYPT(pt.word,ct.word); + d->RC5_DECRYPT(pt.word, ct.word); ct.word[0] = ct.word[0] ^ prior.word[0]; ct.word[1] = ct.word[1] ^ prior.word[1]; @@ -173,28 +179,23 @@ QString Chipper::decryptByteArray(QByteArray value) prior.word[0] = ct.word[0]; prior.word[1] = ct.word[1]; - for (int i=0;i<8;i++){ + for (int i = 0; i < 8; i++) { result += ct.bytes[i]; } - } return QString(result); } -Chipper::Chipper(): d(new ChipperPrivate()){} +Chipper::Chipper(): d(new ChipperPrivate()) { } Chipper::Chipper(QString passphrase): d(new ChipperPrivate()) { - if (!passphrase.trimmed().isEmpty()){ - passphrase = passphrase.leftJustified(16,'#'); + if (!passphrase.trimmed().isEmpty()) { + passphrase = passphrase.leftJustified(16, '#'); d->RC5_SETUP(passphrase.toLatin1().data()); } } -Chipper::~Chipper() -{ - delete d; -} - -} +Chipper::~Chipper() { delete d; } +} // namespace LimeReport diff --git a/limereport/lrsimplecrypt.h b/limereport/lrsimplecrypt.h index 6ba0b7e..3f0b3a5 100644 --- a/limereport/lrsimplecrypt.h +++ b/limereport/lrsimplecrypt.h @@ -30,24 +30,25 @@ #ifndef LRSIMPLECRYPT_H #define LRSIMPLECRYPT_H -#include #include #include +#include namespace LimeReport { class ChipperPrivate; -class Chipper{ +class Chipper { public: QByteArray cryptString(QString value); QString decryptByteArray(QByteArray value); Chipper(); Chipper(QString passphrase); ~Chipper(); + private: ChipperPrivate* d; }; -} +} // namespace LimeReport #endif // LRSIMPLECRYPT_H diff --git a/limereport/lrvariablesholder.cpp b/limereport/lrvariablesholder.cpp index 9cbfcd1..35e363f 100644 --- a/limereport/lrvariablesholder.cpp +++ b/limereport/lrvariablesholder.cpp @@ -28,21 +28,20 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrvariablesholder.h" -#include -#include + #include +#include -namespace LimeReport{ +#include -VariablesHolder::VariablesHolder(QObject *parent) : - QObject(parent) -{ -} +namespace LimeReport { + +VariablesHolder::VariablesHolder(QObject* parent): QObject(parent) { } VariablesHolder::~VariablesHolder() { - QMap::iterator it = m_varNames.begin(); - while(it!=m_varNames.end()){ + QMap::iterator it = m_varNames.begin(); + while (it != m_varNames.end()) { delete *it; ++it; } @@ -50,38 +49,41 @@ VariablesHolder::~VariablesHolder() m_userVariables.clear(); } -void VariablesHolder::addVariable(const QString& name, const QVariant& value, VarDesc::VarType type, RenderPass pass) +void VariablesHolder::addVariable(const QString& name, const QVariant& value, VarDesc::VarType type, + RenderPass pass) { - if (!m_varNames.contains(name)){ + if (!m_varNames.contains(name)) { VarDesc* varValue = new VarDesc; varValue->setName(name); varValue->setValue(value); varValue->setVarType(type); varValue->setRenderPass(pass); - m_varNames.insert(name,varValue); - if (type==VarDesc::Report) + m_varNames.insert(name, varValue); + if (type == VarDesc::Report) m_userVariables.append(varValue); emit variableHasBeenAdded(name); } else { - throw ReportError(tr("variable with name ")+name+tr(" already exists!")); + throw ReportError(tr("variable with name ") + name + tr(" already exists!")); } } -QVariant VariablesHolder::variable(const QString &name) +QVariant VariablesHolder::variable(const QString& name) { if (m_varNames.contains(name)) return m_varNames.value(name)->value(); - else return QVariant(); + else + return QVariant(); } -VarDesc::VarType VariablesHolder::variableType(const QString &name) +VarDesc::VarType VariablesHolder::variableType(const QString& name) { if (m_varNames.contains(name)) return m_varNames.value(name)->varType(); - else throw ReportError(tr("variable with name ")+name+tr(" does not exists!")); + else + throw ReportError(tr("variable with name ") + name + tr(" does not exists!")); } -void VariablesHolder::deleteVariable(const QString &name) +void VariablesHolder::deleteVariable(const QString& name) { if (m_varNames.contains(name)) { m_userVariables.removeOne(m_varNames.value(name)); @@ -91,73 +93,63 @@ void VariablesHolder::deleteVariable(const QString &name) } } -void VariablesHolder::changeVariable(const QString &name, const QVariant &value) +void VariablesHolder::changeVariable(const QString& name, const QVariant& value) { - if(m_varNames.contains(name)) { + if (m_varNames.contains(name)) { m_varNames.value(name)->setValue(value); emit variableHasBeenChanged(name); } else - throw ReportError(tr("variable with name ")+name+tr(" does not exists!")); + throw ReportError(tr("variable with name ") + name + tr(" does not exists!")); } void VariablesHolder::clearUserVariables() { - QMap::iterator it = m_varNames.begin(); - while (it != m_varNames.end()){ - if (it.value()->varType()==VarDesc::User || - it.value()->varType()==VarDesc::Report){ + QMap::iterator it = m_varNames.begin(); + while (it != m_varNames.end()) { + if (it.value()->varType() == VarDesc::User || it.value()->varType() == VarDesc::Report) { m_userVariables.removeAll(it.value()); delete it.value(); it = m_varNames.erase(it); } else { ++it; } - } - } -bool VariablesHolder::containsVariable(const QString &name) -{ - return m_varNames.contains(name); -} +bool VariablesHolder::containsVariable(const QString& name) { return m_varNames.contains(name); } -int VariablesHolder::variablesCount() -{ - return m_userVariables.count(); -} +int VariablesHolder::variablesCount() { return m_userVariables.count(); } VarDesc* VariablesHolder::variableByName(const QString& name) { if (m_varNames.contains(name)) return m_varNames.value(name); - else return 0; + else + return 0; } -VarDesc *VariablesHolder::variableAt(int index) -{ - return m_userVariables.at(index); -} +VarDesc* VariablesHolder::variableAt(int index) { return m_userVariables.at(index); } bool VariablesHolder::variableIsMandatory(const QString& name) { if (m_varNames.contains(name)) return m_varNames.value(name)->isMandatory(); - else return false; + else + return false; } void VariablesHolder::setVarableMandatory(const QString& name, bool value) { if (m_varNames.contains(name)) m_varNames.value(name)->setMandatory(value); - } VariableDataType VariablesHolder::variableDataType(const QString& name) { if (m_varNames.contains(name)) return m_varNames.value(name)->dataType(); - else return Enums::Undefined; + else + return Enums::Undefined; } void VariablesHolder::setVariableDataType(const QString& name, VariableDataType value) @@ -169,28 +161,23 @@ void VariablesHolder::setVariableDataType(const QString& name, VariableDataType QStringList VariablesHolder::variableNames() { QStringList result; - foreach(QString varName,m_varNames.keys()){ - result<renderPass(); - else throw ReportError(tr("variable with name ")+name+tr(" does not exists!")); + else + throw ReportError(tr("variable with name ") + name + tr(" does not exists!")); } -bool VarDesc::isMandatory() const -{ - return m_mandatory; -} +bool VarDesc::isMandatory() const { return m_mandatory; } -void VarDesc::setMandatory(bool mandatory) -{ - m_mandatory = mandatory; -} +void VarDesc::setMandatory(bool mandatory) { m_mandatory = mandatory; } void VarDesc::initFrom(VarDesc* value) { @@ -198,24 +185,12 @@ void VarDesc::initFrom(VarDesc* value) m_dataType = value->dataType(); } -VariableDataType VarDesc::dataType() const -{ - return m_dataType; -} +VariableDataType VarDesc::dataType() const { return m_dataType; } -void VarDesc::setDataType(const VariableDataType& dataType) -{ - m_dataType = dataType; -} +void VarDesc::setDataType(const VariableDataType& dataType) { m_dataType = dataType; } -int VarDesc::readDataTypeProperty() const -{ - return static_cast(m_dataType); -} +int VarDesc::readDataTypeProperty() const { return static_cast(m_dataType); } -void VarDesc::setDataTypeProperty(int value) -{ - m_dataType = static_cast(value); -} +void VarDesc::setDataTypeProperty(int value) { m_dataType = static_cast(value); } -}// namespace LimeReport +} // namespace LimeReport diff --git a/limereport/lrvariablesholder.h b/limereport/lrvariablesholder.h index c9f6ff6..6a587c2 100644 --- a/limereport/lrvariablesholder.h +++ b/limereport/lrvariablesholder.h @@ -30,54 +30,61 @@ #ifndef LRVARIABLEHOLDER_H #define LRVARIABLEHOLDER_H -#include -#include -#include -#include #include "lrglobal.h" -namespace LimeReport{ +#include +#include +#include +#include -class VarDesc : public QObject{ +namespace LimeReport { + +class VarDesc: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QVariant value READ value WRITE setValue) Q_PROPERTY(bool isMandatory READ isMandatory WRITE setMandatory) Q_PROPERTY(int dataType READ readDataTypeProperty WRITE setDataTypeProperty) public: - VarDesc() : m_dataType(Enums::Undefined), m_mandatory(false){} - enum VarType {System, User, Report}; - void setVarType(VarType value){m_varType=value;} - VarType varType(){return m_varType;} - void setRenderPass(RenderPass value){m_varPass=value;} - RenderPass renderPass(){return m_varPass;} - void setName(QString value){m_name=value;} - QString name(){return m_name;} - void setValue(QVariant value){m_value=value;} - QVariant value(){return m_value;} + VarDesc(): m_dataType(Enums::Undefined), m_mandatory(false) { } + enum VarType { + System, + User, + Report + }; + void setVarType(VarType value) { m_varType = value; } + VarType varType() { return m_varType; } + void setRenderPass(RenderPass value) { m_varPass = value; } + RenderPass renderPass() { return m_varPass; } + void setName(QString value) { m_name = value; } + QString name() { return m_name; } + void setValue(QVariant value) { m_value = value; } + QVariant value() { return m_value; } VariableDataType dataType() const; void setDataType(const VariableDataType& dataType); - int readDataTypeProperty() const; + int readDataTypeProperty() const; void setDataTypeProperty(int value); bool isMandatory() const; void setMandatory(bool isMandatory); void initFrom(VarDesc* value); + private: - VarType m_varType; - RenderPass m_varPass; - QString m_name; - QVariant m_value; + VarType m_varType; + RenderPass m_varPass; + QString m_name; + QVariant m_value; VariableDataType m_dataType; - bool m_mandatory; + bool m_mandatory; }; -class IVariablesContainer -{ +class IVariablesContainer { public: - virtual ~IVariablesContainer(){} - virtual void addVariable(const QString& name, const QVariant &value, VarDesc::VarType type=VarDesc::User, RenderPass pass=FirstPass) = 0; + virtual ~IVariablesContainer() { } + virtual void addVariable(const QString& name, const QVariant& value, + VarDesc::VarType type = VarDesc::User, RenderPass pass = FirstPass) + = 0; virtual void deleteVariable(const QString& name) = 0; - virtual void changeVariable(const QString& name, const QVariant &value) = 0; + virtual void changeVariable(const QString& name, const QVariant& value) = 0; virtual void clearUserVariables() = 0; virtual QVariant variable(const QString& name) = 0; virtual VarDesc::VarType variableType(const QString& name) = 0; @@ -90,37 +97,38 @@ public: virtual void setVariableDataType(const QString& name, VariableDataType value) = 0; }; -class VariablesHolder : public QObject, public IVariablesContainer -{ +class VariablesHolder: public QObject, public IVariablesContainer { Q_OBJECT public: - explicit VariablesHolder(QObject *parent = 0); + explicit VariablesHolder(QObject* parent = 0); ~VariablesHolder(); - void addVariable(const QString &name, const QVariant &value, VarDesc::VarType type=VarDesc::User, RenderPass pass=FirstPass); - void deleteVariable(const QString &name); - void changeVariable(const QString &name, const QVariant &value); + void addVariable(const QString& name, const QVariant& value, + VarDesc::VarType type = VarDesc::User, RenderPass pass = FirstPass); + void deleteVariable(const QString& name); + void changeVariable(const QString& name, const QVariant& value); void clearUserVariables(); - QVariant variable(const QString &name); + QVariant variable(const QString& name); VarDesc::VarType variableType(const QString& name); - RenderPass variablePass(const QString &name); - bool containsVariable(const QString &name); - QStringList variableNames(); - int variablesCount(); + RenderPass variablePass(const QString& name); + bool containsVariable(const QString& name); + QStringList variableNames(); + int variablesCount(); VarDesc* variableByName(const QString& name); VarDesc* variableAt(int index); - bool variableIsMandatory(const QString& name); - void setVarableMandatory(const QString &name, bool value); + bool variableIsMandatory(const QString& name); + void setVarableMandatory(const QString& name, bool value); VariableDataType variableDataType(const QString& name); - void setVariableDataType(const QString &name, VariableDataType value); + void setVariableDataType(const QString& name, VariableDataType value); signals: void variableHasBeenAdded(const QString& variableName); void variableHasBeenChanged(const QString& variableName); void variableHasBennDeleted(const QString& variableName); + private: - QMap m_varNames; + QMap m_varNames; QList m_userVariables; }; -}// namespace LimeReport +} // namespace LimeReport #endif // VARIABLEHOLDER_H diff --git a/limereport/objectinspector/editors/lrbuttonlineeditor.cpp b/limereport/objectinspector/editors/lrbuttonlineeditor.cpp index 294e384..801bd7f 100644 --- a/limereport/objectinspector/editors/lrbuttonlineeditor.cpp +++ b/limereport/objectinspector/editors/lrbuttonlineeditor.cpp @@ -28,23 +28,26 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrbuttonlineeditor.h" -#include -#include -#include -#include + #include +#include +#include +#include +#include #include -#if QT_VERSION < QT_VERSION_CHECK(5,12,3) +#if QT_VERSION < QT_VERSION_CHECK(5, 12, 3) #include #else #include #endif #include "lrtextitempropertyeditor.h" -namespace LimeReport{ +namespace LimeReport { -ButtonLineEditor::ButtonLineEditor(const QString &propertyName, QWidget *parent) : - QWidget(parent), m_overButton(false), m_propertyName(propertyName) +ButtonLineEditor::ButtonLineEditor(const QString& propertyName, QWidget* parent): + QWidget(parent), + m_overButton(false), + m_propertyName(propertyName) { m_lineEdit = new QLineEdit(this); m_lineEdit->installEventFilter(this); @@ -54,55 +57,53 @@ ButtonLineEditor::ButtonLineEditor(const QString &propertyName, QWidget *parent) m_buttonEdit->installEventFilter(this); m_buttonEdit->setAttribute(Qt::WA_Hover); - QHBoxLayout *layout = new QHBoxLayout(this); + QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_lineEdit); layout->addWidget(m_buttonEdit); - layout->setContentsMargins(1,1,1,1); + layout->setContentsMargins(1, 1, 1, 1); layout->setSpacing(0); setAutoFillBackground(true); - connect(m_buttonEdit,SIGNAL(clicked()),this,SLOT(editButtonClicked())); - //connect(m_lineEdit,SIGNAL(editingFinished()),this,SLOT(lineEditEditingFinished())); + connect(m_buttonEdit, SIGNAL(clicked()), this, SLOT(editButtonClicked())); + // connect(m_lineEdit,SIGNAL(editingFinished()),this,SLOT(lineEditEditingFinished())); } -ButtonLineEditor::~ButtonLineEditor(){} +ButtonLineEditor::~ButtonLineEditor() { } void ButtonLineEditor::editButtonClicked() { TextItemPropertyEditor* editor = new TextItemPropertyEditor(QApplication::activeWindow()); editor->setAttribute(Qt::WA_DeleteOnClose); -#if QT_VERSION < QT_VERSION_CHECK(5,12,3) - editor->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, editor->size(), QApplication::desktop()->availableGeometry())); +#if QT_VERSION < QT_VERSION_CHECK(5, 12, 3) + editor->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, editor->size(), + QApplication::desktop()->availableGeometry())); #else - editor->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, editor->size(), QGuiApplication::screens().first()->availableGeometry())); + editor->setGeometry( + QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, editor->size(), + QGuiApplication::screens().first()->availableGeometry())); #endif editor->setWindowTitle(m_propertyName); editor->setText(m_lineEdit->text()); - connect(editor,SIGNAL(accepted()),this,SLOT(editingByEditorFinished())); + connect(editor, SIGNAL(accepted()), this, SLOT(editingByEditorFinished())); editor->exec(); } -void ButtonLineEditor::setText(const QString &value){ - m_lineEdit->setText(value); -} +void ButtonLineEditor::setText(const QString& value) { m_lineEdit->setText(value); } -QString ButtonLineEditor::text() -{ - return m_lineEdit->text(); -} +QString ButtonLineEditor::text() { return m_lineEdit->text(); } -bool ButtonLineEditor::eventFilter(QObject *target, QEvent *event) +bool ButtonLineEditor::eventFilter(QObject* target, QEvent* event) { - if (target==m_buttonEdit) { + if (target == m_buttonEdit) { - if (event->type()==QEvent::HoverEnter){ - m_overButton=true; + if (event->type() == QEvent::HoverEnter) { + m_overButton = true; } - if (event->type()==QEvent::HoverLeave){ - m_overButton=false; + if (event->type() == QEvent::HoverLeave) { + m_overButton = false; } - if (event->type()==QEvent::FocusOut){ - if (static_cast(event)->reason()!=Qt::MouseFocusReason){ + if (event->type() == QEvent::FocusOut) { + if (static_cast(event)->reason() != Qt::MouseFocusReason) { m_lineEdit->setFocus(); } } @@ -110,29 +111,27 @@ bool ButtonLineEditor::eventFilter(QObject *target, QEvent *event) enterKeys.insert(Qt::Key_Enter); enterKeys.insert(Qt::Key_Return); - if (event->type()==QEvent::KeyPress){ - if (enterKeys.contains(static_cast(event)->key())){ + if (event->type() == QEvent::KeyPress) { + if (enterKeys.contains(static_cast(event)->key())) { m_buttonEdit->click(); return true; } } } - if (target==m_lineEdit){ - if (event->type()==QEvent::FocusOut){ - switch (static_cast(event)->reason()){ + if (target == m_lineEdit) { + if (event->type() == QEvent::FocusOut) { + switch (static_cast(event)->reason()) { case Qt::TabFocusReason: - m_overButton=true; + m_overButton = true; break; case Qt::MouseFocusReason: break; default: - m_overButton=false; + m_overButton = false; } - } } - return QWidget::eventFilter(target,event); - + return QWidget::eventFilter(target, event); } void ButtonLineEditor::editingByEditorFinished() @@ -142,4 +141,4 @@ void ButtonLineEditor::editingByEditorFinished() emit editingFinished(); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrbuttonlineeditor.h b/limereport/objectinspector/editors/lrbuttonlineeditor.h index 4757d88..0b8335d 100644 --- a/limereport/objectinspector/editors/lrbuttonlineeditor.h +++ b/limereport/objectinspector/editors/lrbuttonlineeditor.h @@ -30,41 +30,44 @@ #ifndef LRBUTTONLINEEDIT_H #define LRBUTTONLINEEDIT_H -#include +#include "lrtextitempropertyeditor.h" + +#include +#include #include #include #include -#include -#include -#include "lrtextitempropertyeditor.h" +#include -namespace LimeReport{ +namespace LimeReport { -class ButtonLineEditor : public QWidget -{ +class ButtonLineEditor: public QWidget { Q_OBJECT public: - explicit ButtonLineEditor(const QString& propertyName,QWidget *parent = 0); + explicit ButtonLineEditor(const QString& propertyName, QWidget* parent = 0); ~ButtonLineEditor(); - void setText(const QString &value); + void setText(const QString& value); QString text(); signals: void editingFinished(); public slots: virtual void editButtonClicked(); void editingByEditorFinished(); + protected: - QString propertyName(){return m_propertyName;} + QString propertyName() { return m_propertyName; } + private: QLineEdit* m_lineEdit; QToolButton* m_buttonEdit; bool m_overButton; QString m_propertyName; + private: - bool eventFilter(QObject *, QEvent *); - //QHBoxLayout* m_layout; + bool eventFilter(QObject*, QEvent*); + // QHBoxLayout* m_layout; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LRBUTTONLINEEDIT_H diff --git a/limereport/objectinspector/editors/lrcheckboxeditor.cpp b/limereport/objectinspector/editors/lrcheckboxeditor.cpp index 3911540..b4efb2b 100644 --- a/limereport/objectinspector/editors/lrcheckboxeditor.cpp +++ b/limereport/objectinspector/editors/lrcheckboxeditor.cpp @@ -28,33 +28,34 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrcheckboxeditor.h" -#include -#include -#include -#include + #include +#include +#include +#include #include +#include -namespace LimeReport{ +namespace LimeReport { -CheckBoxEditor::CheckBoxEditor(QWidget *parent) - :QWidget(parent), m_editing(false) -{ +CheckBoxEditor::CheckBoxEditor(QWidget* parent): QWidget(parent), m_editing(false) +{ m_checkBox = new QCheckBox(this); init(); } -CheckBoxEditor::CheckBoxEditor(const QString &text, QWidget *parent) - :QWidget(parent), m_editing(false) +CheckBoxEditor::CheckBoxEditor(const QString& text, QWidget* parent): + QWidget(parent), + m_editing(false) { - m_checkBox = new QCheckBox(text,this); + m_checkBox = new QCheckBox(text, this); init(); } -CheckBoxEditor::~CheckBoxEditor(){} +CheckBoxEditor::~CheckBoxEditor() { } void CheckBoxEditor::init() -{ - QVBoxLayout *layout=new QVBoxLayout(this); +{ + QVBoxLayout* layout = new QVBoxLayout(this); layout->addStretch(); layout->addWidget(m_checkBox); #ifdef HAVE_QT5 @@ -62,56 +63,45 @@ void CheckBoxEditor::init() #endif connect(m_checkBox, SIGNAL(stateChanged(int)), this, SLOT(slotStateChanged(int))); layout->addStretch(); - layout->setContentsMargins(2,1,1,1); + layout->setContentsMargins(2, 1, 1, 1); layout->setSpacing(0); setLayout(layout); setAutoFillBackground(true); - setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); } -void CheckBoxEditor::setEditing(bool value) -{ - m_editing=value; -} +void CheckBoxEditor::setEditing(bool value) { m_editing = value; } -void CheckBoxEditor::setChecked(bool value) -{ - m_checkBox->setChecked(value); -} +void CheckBoxEditor::setChecked(bool value) { m_checkBox->setChecked(value); } -bool CheckBoxEditor::isChecked() -{ - return m_checkBox->isChecked(); -} +bool CheckBoxEditor::isChecked() { return m_checkBox->isChecked(); } -void CheckBoxEditor::mousePressEvent(QMouseEvent *) +void CheckBoxEditor::mousePressEvent(QMouseEvent*) { m_checkBox->setChecked(!m_checkBox->isChecked()); emit editingFinished(); } -void CheckBoxEditor::keyPressEvent(QKeyEvent *event) +void CheckBoxEditor::keyPressEvent(QKeyEvent* event) { - if (event->key()==Qt::Key_Space) m_checkBox->setChecked(!m_checkBox->isChecked()); - if ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down)){ + if (event->key() == Qt::Key_Space) + m_checkBox->setChecked(!m_checkBox->isChecked()); + if ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down)) { emit editingFinished(); } QWidget::keyPressEvent(event); } -void CheckBoxEditor::showEvent(QShowEvent *) +void CheckBoxEditor::showEvent(QShowEvent*) { - int border = (height() - QApplication::style()->pixelMetric(QStyle::PM_IndicatorWidth))/2 + int border = (height() - QApplication::style()->pixelMetric(QStyle::PM_IndicatorWidth)) / 2 #ifdef Q_OS_MAC - +QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) + + QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) #endif - ; - layout()->setContentsMargins(border,0,0,0); + ; + layout()->setContentsMargins(border, 0, 0, 0); } -void CheckBoxEditor::slotStateChanged(int) -{ - emit editingFinished(); -} +void CheckBoxEditor::slotStateChanged(int) { emit editingFinished(); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrcheckboxeditor.h b/limereport/objectinspector/editors/lrcheckboxeditor.h index 8f558cb..d95be6e 100644 --- a/limereport/objectinspector/editors/lrcheckboxeditor.h +++ b/limereport/objectinspector/editors/lrcheckboxeditor.h @@ -32,33 +32,33 @@ #include -namespace LimeReport{ +namespace LimeReport { -class CheckBoxEditor : public QWidget -{ +class CheckBoxEditor: public QWidget { Q_OBJECT public: - CheckBoxEditor(QWidget * parent = 0); - CheckBoxEditor(const QString & text, QWidget * parent = 0); + CheckBoxEditor(QWidget* parent = 0); + CheckBoxEditor(const QString& text, QWidget* parent = 0); ~CheckBoxEditor(); void setEditing(bool value); void setChecked(bool value); bool isChecked(); + protected: - void mousePressEvent(QMouseEvent *); - void keyPressEvent(QKeyEvent *event); - void showEvent(QShowEvent *); + void mousePressEvent(QMouseEvent*); + void keyPressEvent(QKeyEvent* event); + void showEvent(QShowEvent*); signals: void editingFinished(); private slots: void slotStateChanged(int); + private: QCheckBox* m_checkBox; bool m_editing; void init(); - }; -} +} // namespace LimeReport #endif // LRCHECKBOXEDITOR_H diff --git a/limereport/objectinspector/editors/lrcoloreditor.cpp b/limereport/objectinspector/editors/lrcoloreditor.cpp index bac93a2..c9d114d 100644 --- a/limereport/objectinspector/editors/lrcoloreditor.cpp +++ b/limereport/objectinspector/editors/lrcoloreditor.cpp @@ -28,50 +28,50 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrcoloreditor.h" + #include "lrglobal.h" -#include +#include #include +#include #include #include -#include #include -namespace LimeReport{ +namespace LimeReport { -ColorEditor::ColorEditor(QWidget *parent) : - QWidget(parent), m_buttonPressed(false) +ColorEditor::ColorEditor(QWidget* parent): QWidget(parent), m_buttonPressed(false) { m_colorIndicator = new ColorIndicator(this); m_colorIndicator->setColor(m_color); m_button = new QToolButton(this); - m_button->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_button->setText("..."); m_button->installEventFilter(this); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_colorIndicator); layout->addWidget(m_button); layout->setSpacing(0); - layout->setContentsMargins(1,1,1,1); + layout->setContentsMargins(1, 1, 1, 1); setFocusProxy(m_button); setAutoFillBackground(true); setLayout(layout); setAutoFillBackground(true); - connect(m_button,SIGNAL(clicked()),this,SLOT(slotClicked())); + connect(m_button, SIGNAL(clicked()), this, SLOT(slotClicked())); } -void ColorEditor::setColor(const QColor &value) +void ColorEditor::setColor(const QColor& value) { - m_color=value; + m_color = value; m_colorIndicator->setColor(m_color); } -bool ColorEditor::eventFilter(QObject *obj, QEvent *event) +bool ColorEditor::eventFilter(QObject* obj, QEvent* event) { - if (obj == m_button){ - if (event->type() == QEvent::FocusOut && !m_buttonPressed){ + if (obj == m_button) { + if (event->type() == QEvent::FocusOut && !m_buttonPressed) { QFocusEvent* focusEvent = dynamic_cast(event); - if (focusEvent && focusEvent->reason()!=Qt::MouseFocusReason){ + if (focusEvent && focusEvent->reason() != Qt::MouseFocusReason) { setFocusToParent(); emit(editingFinished()); } @@ -81,7 +81,8 @@ bool ColorEditor::eventFilter(QObject *obj, QEvent *event) return false; } -void ColorEditor::setFocusToParent(){ +void ColorEditor::setFocusToParent() +{ if (parentWidget()) parentWidget()->setFocus(); } @@ -91,7 +92,8 @@ void ColorEditor::slotClicked() m_buttonPressed = true; QColorDialog* dialog = new QColorDialog(this); dialog->setCurrentColor(m_color); - if (dialog->exec()) m_color=dialog->currentColor(); + if (dialog->exec()) + m_color = dialog->currentColor(); delete dialog; setFocusToParent(); emit(editingFinished()); @@ -107,36 +109,27 @@ void ColorIndicator::paintEvent(QPaintEvent* event) QColor penColor = isColorDark(m_color) ? Qt::transparent : Qt::darkGray; painter.setPen(penColor); - int border = (event->rect().height() - style->pixelMetric(QStyle::PM_IndicatorWidth))/2; + int border = (event->rect().height() - style->pixelMetric(QStyle::PM_IndicatorWidth)) / 2; - QRect rect(event->rect().x()+border, event->rect().y()+border, + QRect rect(event->rect().x() + border, event->rect().y() + border, style->pixelMetric(QStyle::PM_IndicatorWidth), - style->pixelMetric(QStyle::PM_IndicatorWidth));// = option.rect.adjusted(4,4,-4,-6); + style->pixelMetric(QStyle::PM_IndicatorWidth)); // = option.rect.adjusted(4,4,-4,-6); painter.drawRect(rect); painter.restore(); } -ColorIndicator::ColorIndicator(QWidget *parent) - :QWidget(parent), m_color(Qt::white){ +ColorIndicator::ColorIndicator(QWidget* parent): QWidget(parent), m_color(Qt::white) +{ setAttribute(Qt::WA_StaticContents); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); setFocusPolicy(Qt::NoFocus); } -QColor ColorIndicator::color() const -{ - return m_color; -} +QColor ColorIndicator::color() const { return m_color; } -void ColorIndicator::setColor(const QColor &color) -{ - m_color = color; -} +void ColorIndicator::setColor(const QColor& color) { m_color = color; } -QSize ColorIndicator::sizeHint() const -{ - return QSize(20,20); -} +QSize ColorIndicator::sizeHint() const { return QSize(20, 20); } } // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrcoloreditor.h b/limereport/objectinspector/editors/lrcoloreditor.h index c8227e9..c28f8e6 100644 --- a/limereport/objectinspector/editors/lrcoloreditor.h +++ b/limereport/objectinspector/editors/lrcoloreditor.h @@ -30,45 +30,49 @@ #ifndef LRCOLOREDITOR_H #define LRCOLOREDITOR_H -#include #include #include +#include -namespace LimeReport{ +namespace LimeReport { -class ColorIndicator : public QWidget{ +class ColorIndicator: public QWidget { Q_OBJECT public: ColorIndicator(QWidget* parent = 0); QColor color() const; - void setColor(const QColor &color); + void setColor(const QColor& color); QSize sizeHint() const; + protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent* event); + private: QColor m_color; }; -class ColorEditor : public QWidget -{ +class ColorEditor: public QWidget { Q_OBJECT public: - explicit ColorEditor(QWidget *parent = 0); - QColor color(){return m_color;} + explicit ColorEditor(QWidget* parent = 0); + QColor color() { return m_color; } void setColor(const QColor& value); + protected: - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject* obj, QEvent* event); + private: void setFocusToParent(); signals: - void editingFinished(); + void editingFinished(); private slots: - void slotClicked(); + void slotClicked(); + private: - QColor m_color; - QToolButton* m_button; - ColorIndicator* m_colorIndicator; - bool m_buttonPressed; + QColor m_color; + QToolButton* m_button; + ColorIndicator* m_colorIndicator; + bool m_buttonPressed; }; } // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrcomboboxeditor.cpp b/limereport/objectinspector/editors/lrcomboboxeditor.cpp index 3a4748a..9f25a51 100644 --- a/limereport/objectinspector/editors/lrcomboboxeditor.cpp +++ b/limereport/objectinspector/editors/lrcomboboxeditor.cpp @@ -27,19 +27,20 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include +#include "lrcomboboxeditor.h" + #include -#include #include #include #include +#include #include -#include "lrcomboboxeditor.h" +#include +#include -namespace LimeReport{ +namespace LimeReport { -ComboBoxEditor::ComboBoxEditor(QWidget *parent, bool clearable) : +ComboBoxEditor::ComboBoxEditor(QWidget* parent, bool clearable): QWidget(parent), m_comboBox(new InternalComboBox(this)), m_buttonClear(0), @@ -51,37 +52,41 @@ ComboBoxEditor::ComboBoxEditor(QWidget *parent, bool clearable) : m_buttonClear = new QToolButton(this); m_buttonClear->setIcon(QIcon(":/items/clear.png")); m_buttonClear->installEventFilter(this); - m_buttonClear->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Expanding); + m_buttonClear->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); m_buttonClear->setMaximumHeight(QWIDGETSIZE_MAX); - connect(m_buttonClear,SIGNAL(clicked()),this,SLOT(slotClearButtonClicked())); + connect(m_buttonClear, SIGNAL(clicked()), this, SLOT(slotClearButtonClicked())); } -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - connect(m_comboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(slotCurrentIndexChanged(QString))); +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + connect(m_comboBox, SIGNAL(currentTextChanged(QString)), this, + SLOT(slotCurrentIndexChanged(QString))); #else - connect(m_comboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotCurrentIndexChanged(QString))); + connect(m_comboBox, SIGNAL(currentIndexChanged(QString)), this, + SLOT(slotCurrentIndexChanged(QString))); #endif m_comboBox->installEventFilter(this); - QHBoxLayout *layout = new QHBoxLayout(this); + QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_comboBox); if (clearable) layout->addWidget(m_buttonClear); - layout->setContentsMargins(0,0,0,0); + layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(2); setLayout(layout); setAutoFillBackground(true); } -void ComboBoxEditor::addItems(const QStringList &values){ +void ComboBoxEditor::addItems(const QStringList& values) +{ m_settingValues = true; m_comboBox->addItems(values); m_settingValues = false; } -void ComboBoxEditor::setTextValue(const QString &value){ +void ComboBoxEditor::setTextValue(const QString& value) +{ m_settingValues = true; - if (m_comboBox->findText(value)>0){ + if (m_comboBox->findText(value) > 0) { m_comboBox->setCurrentIndex(m_comboBox->findText(value)); } else { m_comboBox->setEditText(value); @@ -89,20 +94,16 @@ void ComboBoxEditor::setTextValue(const QString &value){ m_settingValues = false; } -void ComboBoxEditor::slotClearButtonClicked(){ - m_comboBox->setCurrentIndex(-1); -} +void ComboBoxEditor::slotClearButtonClicked() { m_comboBox->setCurrentIndex(-1); } void ComboBoxEditor::slotCurrentIndexChanged(const QString& value) { - if (!m_settingValues){ + if (!m_settingValues) { emit currentIndexChanged(value); } } -QString ComboBoxEditor::text(){ - return m_comboBox->currentText(); -} +QString ComboBoxEditor::text() { return m_comboBox->currentText(); } void ComboBoxEditor::setEditable(bool value) { @@ -111,10 +112,11 @@ void ComboBoxEditor::setEditable(bool value) } } -bool ComboBoxEditor::eventFilter(QObject *target, QEvent *event){ - if (target == m_buttonClear){ - if (event->type()==QEvent::FocusOut){ - if (static_cast(event)->reason()!=Qt::MouseFocusReason){ +bool ComboBoxEditor::eventFilter(QObject* target, QEvent* event) +{ + if (target == m_buttonClear) { + if (event->type() == QEvent::FocusOut) { + if (static_cast(event)->reason() != Qt::MouseFocusReason) { m_comboBox->setFocus(); } } @@ -122,28 +124,27 @@ bool ComboBoxEditor::eventFilter(QObject *target, QEvent *event){ enterKeys.insert(Qt::Key_Enter); enterKeys.insert(Qt::Key_Return); - if (event->type()==QEvent::KeyPress){ - if (enterKeys.contains(static_cast(event)->key())){ + if (event->type() == QEvent::KeyPress) { + if (enterKeys.contains(static_cast(event)->key())) { m_buttonClear->click(); return true; } } } - if (target == m_comboBox){ - if (event->type() == QEvent::FocusOut){ + if (target == m_comboBox) { + if (event->type() == QEvent::FocusOut) { if (!m_comboBox->isPopup() || (m_buttonClear && m_buttonClear->hasFocus())) emit editingFinished(); } } - return QWidget::eventFilter(target,event); + return QWidget::eventFilter(target, event); } - -void ComboBoxEditor::resizeEvent(QResizeEvent *e) +void ComboBoxEditor::resizeEvent(QResizeEvent* e) { if (m_buttonClear) - m_buttonClear->setMinimumHeight(e->size().height()-4); + m_buttonClear->setMinimumHeight(e->size().height() - 4); } } // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrcomboboxeditor.h b/limereport/objectinspector/editors/lrcomboboxeditor.h index a752579..1c45f94 100644 --- a/limereport/objectinspector/editors/lrcomboboxeditor.h +++ b/limereport/objectinspector/editors/lrcomboboxeditor.h @@ -30,32 +30,39 @@ #ifndef LRCOMBOBOXEDITOR_H #define LRCOMBOBOXEDITOR_H -#include #include +#include //#include class QToolButton; -namespace LimeReport{ +namespace LimeReport { -class InternalComboBox :public QComboBox{ +class InternalComboBox: public QComboBox { Q_OBJECT public: - InternalComboBox(QWidget* parent=0):QComboBox(parent),m_popup(false){} - void showPopup(){m_popup = true;QComboBox::showPopup();} - void hidePopup(){QComboBox::hidePopup(); m_popup = false;} - bool isPopup(){return m_popup;} + InternalComboBox(QWidget* parent = 0): QComboBox(parent), m_popup(false) { } + void showPopup() + { + m_popup = true; + QComboBox::showPopup(); + } + void hidePopup() + { + QComboBox::hidePopup(); + m_popup = false; + } + bool isPopup() { return m_popup; } + private: bool m_popup; - }; -class ComboBoxEditor : public QWidget -{ +class ComboBoxEditor: public QWidget { Q_OBJECT public: - //explicit ComboBoxEditor(QWidget *parent = 0); - ComboBoxEditor(QWidget *parent=0, bool clearable=false); + // explicit ComboBoxEditor(QWidget *parent = 0); + ComboBoxEditor(QWidget* parent = 0, bool clearable = false); void addItems(const QStringList& values); void setTextValue(const QString& value); QString text(); @@ -63,13 +70,15 @@ public: signals: void editingFinished(); void currentIndexChanged(const QString&); + protected: - void resizeEvent(QResizeEvent *e); + void resizeEvent(QResizeEvent* e); private slots: void slotClearButtonClicked(); void slotCurrentIndexChanged(const QString& value); + private: - bool eventFilter(QObject *target, QEvent *event); + bool eventFilter(QObject* target, QEvent* event); InternalComboBox* m_comboBox; QToolButton* m_buttonClear; bool m_settingValues; diff --git a/limereport/objectinspector/editors/lrfonteditor.cpp b/limereport/objectinspector/editors/lrfonteditor.cpp index 55e6230..1d0de50 100644 --- a/limereport/objectinspector/editors/lrfonteditor.cpp +++ b/limereport/objectinspector/editors/lrfonteditor.cpp @@ -28,58 +28,57 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrfonteditor.h" -#include -#include + #include +#include +#include -namespace LimeReport{ +namespace LimeReport { -FontEditor::FontEditor(QWidget *parent) : - QWidget(parent) +FontEditor::FontEditor(QWidget* parent): QWidget(parent) { - //m_button = new QPushButton(this); + // m_button = new QPushButton(this); m_button = new QToolButton(this); - m_button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); + m_button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_button); layout->setSpacing(0); - layout->setContentsMargins(1,1,1,1); + layout->setContentsMargins(1, 1, 1, 1); setFocusProxy(m_button); setLayout(layout); setAutoFillBackground(true); - connect(m_button,SIGNAL(clicked()),this,SLOT(slotButtonCliked())); + connect(m_button, SIGNAL(clicked()), this, SLOT(slotButtonCliked())); } -FontEditor::~FontEditor() -{} +FontEditor::~FontEditor() { } -void FontEditor::setFontValue(const QFont &font) +void FontEditor::setFontValue(const QFont& font) { - m_font=font; + m_font = font; m_button->setText(toString(font)); } -QFont FontEditor::fontValue() -{ - return m_font; -} +QFont FontEditor::fontValue() { return m_font; } void FontEditor::slotButtonCliked() { QFontDialog* dialog = new QFontDialog(this); dialog->setCurrentFont(m_font); - if (dialog->exec()) m_font=dialog->currentFont(); + if (dialog->exec()) + m_font = dialog->currentFont(); delete dialog; emit(editingFinished()); } -QString FontEditor::toString(const QFont &value) const +QString FontEditor::toString(const QFont& value) const { - QString attribs="["; - if (value.bold()) (attribs=="[") ? attribs+="b":attribs+=",b"; - if (value.italic()) (attribs=="[") ? attribs+="i":attribs+=",i"; - attribs+="]"; - return value.family()+" "+QString::number(value.pointSize())+" "+attribs; + QString attribs = "["; + if (value.bold()) + (attribs == "[") ? attribs += "b" : attribs += ",b"; + if (value.italic()) + (attribs == "[") ? attribs += "i" : attribs += ",i"; + attribs += "]"; + return value.family() + " " + QString::number(value.pointSize()) + " " + attribs; } } // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrfonteditor.h b/limereport/objectinspector/editors/lrfonteditor.h index d5fa17a..438b8b5 100644 --- a/limereport/objectinspector/editors/lrfonteditor.h +++ b/limereport/objectinspector/editors/lrfonteditor.h @@ -30,28 +30,29 @@ #ifndef LRFONTEDITOR_H #define LRFONTEDITOR_H -#include #include #include +#include -namespace LimeReport{ +namespace LimeReport { -class FontEditor : public QWidget -{ +class FontEditor: public QWidget { Q_OBJECT public: - explicit FontEditor(QWidget *parent = 0); + explicit FontEditor(QWidget* parent = 0); ~FontEditor(); - void setFontValue(const QFont &font); + void setFontValue(const QFont& font); QFont fontValue(); signals: void editingFinished(); public slots: void slotButtonCliked(); + private: QString toString(const QFont& value) const; + private: - //QPushButton* m_button; + // QPushButton* m_button; QToolButton* m_button; QFont m_font; }; diff --git a/limereport/objectinspector/editors/lrimageeditor.cpp b/limereport/objectinspector/editors/lrimageeditor.cpp index 4066116..63cdce9 100644 --- a/limereport/objectinspector/editors/lrimageeditor.cpp +++ b/limereport/objectinspector/editors/lrimageeditor.cpp @@ -27,14 +27,14 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include #include "lrimageeditor.h" -namespace LimeReport{ +#include +#include -ImageEditor::ImageEditor(QWidget* parent) - :QWidget(parent) +namespace LimeReport { + +ImageEditor::ImageEditor(QWidget* parent): QWidget(parent) { m_button.setIcon(QIcon(":items/ImageItem")); m_clearButton.setIcon(QIcon(":items/clear.png")); @@ -42,18 +42,15 @@ ImageEditor::ImageEditor(QWidget* parent) layout->addWidget(&m_button); layout->addWidget(&m_clearButton); layout->setSpacing(1); - layout->setContentsMargins(1,0,1,1); + layout->setContentsMargins(1, 0, 1, 1); setLayout(layout); setFocusProxy(&m_button); setAutoFillBackground(true); - connect(&m_button,SIGNAL(clicked()),this,SLOT(slotButtonClicked())); - connect(&m_clearButton,SIGNAL(clicked()),this,SLOT(slotClearButtonClicked())); + connect(&m_button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); + connect(&m_clearButton, SIGNAL(clicked()), this, SLOT(slotClearButtonClicked())); } -QImage ImageEditor::image() -{ - return m_image; -} +QImage ImageEditor::image() { return m_image; } void ImageEditor::slotButtonClicked() { @@ -67,4 +64,4 @@ void ImageEditor::slotClearButtonClicked() emit editingFinished(); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrimageeditor.h b/limereport/objectinspector/editors/lrimageeditor.h index 999032b..9eac700 100644 --- a/limereport/objectinspector/editors/lrimageeditor.h +++ b/limereport/objectinspector/editors/lrimageeditor.h @@ -29,24 +29,24 @@ ****************************************************************************/ #ifndef LRIMAGEEDITOR_H #define LRIMAGEEDITOR_H -#include #include +#include -namespace LimeReport{ +namespace LimeReport { -class ImageEditor : public QWidget -{ +class ImageEditor: public QWidget { Q_OBJECT public: - ImageEditor(QWidget *parent=0); + ImageEditor(QWidget* parent = 0); QImage image(); - void setImage(const QImage& image){m_image=image;} + void setImage(const QImage& image) { m_image = image; } signals: void editingFinished(); private slots: void slotButtonClicked(); void slotClearButtonClicked(); + private: QPushButton m_button; QPushButton m_clearButton; diff --git a/limereport/objectinspector/editors/lrsvgeditor.cpp b/limereport/objectinspector/editors/lrsvgeditor.cpp index f394f8f..9d3373e 100644 --- a/limereport/objectinspector/editors/lrsvgeditor.cpp +++ b/limereport/objectinspector/editors/lrsvgeditor.cpp @@ -1,12 +1,13 @@ #include "lrsvgeditor.h" -#include -#include + #include "lrimageeditor.h" -namespace LimeReport{ +#include +#include -SvgEditor::SvgEditor(QWidget* parent) - :QWidget(parent) +namespace LimeReport { + +SvgEditor::SvgEditor(QWidget* parent): QWidget(parent) { m_button.setIcon(QIcon(":items/ImageItem")); m_clearButton.setIcon(QIcon(":items/clear.png")); @@ -14,25 +15,23 @@ SvgEditor::SvgEditor(QWidget* parent) layout->addWidget(&m_button); layout->addWidget(&m_clearButton); layout->setSpacing(1); - layout->setContentsMargins(1,0,1,1); + layout->setContentsMargins(1, 0, 1, 1); setLayout(layout); setFocusProxy(&m_button); setAutoFillBackground(true); - connect(&m_button,SIGNAL(clicked()),this,SLOT(slotButtonClicked())); - connect(&m_clearButton,SIGNAL(clicked()),this,SLOT(slotClearButtonClicked())); + connect(&m_button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); + connect(&m_clearButton, SIGNAL(clicked()), this, SLOT(slotClearButtonClicked())); } -QByteArray SvgEditor::image() -{ - return m_image; -} +QByteArray SvgEditor::image() { return m_image; } void SvgEditor::slotButtonClicked() { - QString fileName = QFileDialog::getOpenFileName(this, tr("Select image file"), "", "SVG (*.svg)"); - if (!fileName.isEmpty()){ + QString fileName + = QFileDialog::getOpenFileName(this, tr("Select image file"), "", "SVG (*.svg)"); + if (!fileName.isEmpty()) { QFile file(fileName); - if (file.open(QIODevice::ReadOnly)){ + if (file.open(QIODevice::ReadOnly)) { m_image = file.readAll(); } } @@ -45,4 +44,4 @@ void SvgEditor::slotClearButtonClicked() emit editingFinished(); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrsvgeditor.h b/limereport/objectinspector/editors/lrsvgeditor.h index 6ba0649..730405d 100644 --- a/limereport/objectinspector/editors/lrsvgeditor.h +++ b/limereport/objectinspector/editors/lrsvgeditor.h @@ -1,27 +1,27 @@ #ifndef SVGEDITOR_H #define SVGEDITOR_H -#include #include +#include -namespace LimeReport{ +namespace LimeReport { -class SvgEditor : public QWidget -{ +class SvgEditor: public QWidget { Q_OBJECT public: - SvgEditor(QWidget *parent=0); + SvgEditor(QWidget* parent = 0); QByteArray image(); - void setImage(const QByteArray& image){m_image=image;} + void setImage(const QByteArray& image) { m_image = image; } signals: void editingFinished(); private slots: void slotButtonClicked(); void slotClearButtonClicked(); + private: QPushButton m_button; QPushButton m_clearButton; - QByteArray m_image; + QByteArray m_image; }; } // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrtextitempropertyeditor.cpp b/limereport/objectinspector/editors/lrtextitempropertyeditor.cpp index e5a036d..cb3aaaa 100644 --- a/limereport/objectinspector/editors/lrtextitempropertyeditor.cpp +++ b/limereport/objectinspector/editors/lrtextitempropertyeditor.cpp @@ -29,11 +29,12 @@ ****************************************************************************/ #include "lrtextitempropertyeditor.h" #include "ui_ltextitempropertyeditor.h" + #include -namespace LimeReport{ +namespace LimeReport { -TextItemPropertyEditor::TextItemPropertyEditor(QWidget *parent) : +TextItemPropertyEditor::TextItemPropertyEditor(QWidget* parent): QDialog(parent), ui(new Ui::TextItemPropertyEditor) { @@ -41,19 +42,10 @@ TextItemPropertyEditor::TextItemPropertyEditor(QWidget *parent) : ui->textEdit->setAcceptRichText(false); } -TextItemPropertyEditor::~TextItemPropertyEditor() -{ - delete ui; -} +TextItemPropertyEditor::~TextItemPropertyEditor() { delete ui; } -void TextItemPropertyEditor::setText(const QString &value) -{ - ui->textEdit->setPlainText(value); -} +void TextItemPropertyEditor::setText(const QString& value) { ui->textEdit->setPlainText(value); } -QString TextItemPropertyEditor::text() -{ - return ui->textEdit->toPlainText(); -} +QString TextItemPropertyEditor::text() { return ui->textEdit->toPlainText(); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectinspector/editors/lrtextitempropertyeditor.h b/limereport/objectinspector/editors/lrtextitempropertyeditor.h index 22e14de..28c1c4e 100644 --- a/limereport/objectinspector/editors/lrtextitempropertyeditor.h +++ b/limereport/objectinspector/editors/lrtextitempropertyeditor.h @@ -33,28 +33,28 @@ #include #include -namespace LimeReport{ +namespace LimeReport { namespace Ui { class TextItemPropertyEditor; } -class TextItemPropertyEditor : public QDialog -{ +class TextItemPropertyEditor: public QDialog { Q_OBJECT public: - explicit TextItemPropertyEditor(QWidget *parent = 0); + explicit TextItemPropertyEditor(QWidget* parent = 0); ~TextItemPropertyEditor(); - void setText(const QString &value); + void setText(const QString& value); QString text(); public slots: - void pbSaveCliked(){ emit editingFinished();} + void pbSaveCliked() { emit editingFinished(); } signals: void editingFinished(); + private: - Ui::TextItemPropertyEditor *ui; + Ui::TextItemPropertyEditor* ui; }; -} //namespace LimeReport +} // namespace LimeReport #endif // ATEXTITEMPROPERTYEDITOR_H diff --git a/limereport/objectinspector/lrbasedesignobjectmodel.cpp b/limereport/objectinspector/lrbasedesignobjectmodel.cpp index b83904c..267b575 100644 --- a/limereport/objectinspector/lrbasedesignobjectmodel.cpp +++ b/limereport/objectinspector/lrbasedesignobjectmodel.cpp @@ -28,24 +28,21 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrbasedesignobjectmodel.h" + #include "lrbasedesignintf.h" -namespace LimeReport{ +namespace LimeReport { -BaseDesignPropertyModel::BaseDesignPropertyModel(QObject *parent) - : QObjectPropertyModel(parent) -{} +BaseDesignPropertyModel::BaseDesignPropertyModel(QObject* parent): QObjectPropertyModel(parent) { } -void BaseDesignPropertyModel::setObject(QObject *object) +void BaseDesignPropertyModel::setObject(QObject* object) { BaseDesignIntf* reportItem = dynamic_cast(object); - if (reportItem){ - connect(reportItem,SIGNAL(propertyChanged(QString,QVariant,QVariant)),this,SLOT(slotPropertyChanged(QString,QVariant,QVariant))); - + if (reportItem) { + connect(reportItem, SIGNAL(propertyChanged(QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QVariant, QVariant))); } QObjectPropertyModel::setObject(object); } -} - - +} // namespace LimeReport diff --git a/limereport/objectinspector/lrbasedesignobjectmodel.h b/limereport/objectinspector/lrbasedesignobjectmodel.h index 4d50a78..a64ec3d 100644 --- a/limereport/objectinspector/lrbasedesignobjectmodel.h +++ b/limereport/objectinspector/lrbasedesignobjectmodel.h @@ -31,13 +31,13 @@ #define LRBASEDESIGNOBJECTSMODEL_H #include "lrobjectitemmodel.h" + #include -namespace LimeReport{ -class BaseDesignPropertyModel : public QObjectPropertyModel -{ +namespace LimeReport { +class BaseDesignPropertyModel: public QObjectPropertyModel { public: - explicit BaseDesignPropertyModel(QObject* parent=0); - virtual void setObject(QObject *object); + explicit BaseDesignPropertyModel(QObject* parent = 0); + virtual void setObject(QObject* object); }; -} +} // namespace LimeReport #endif // LRBASEDESIGNOBJECTSMODEL_H diff --git a/limereport/objectinspector/lrobjectinspectorwidget.cpp b/limereport/objectinspector/lrobjectinspectorwidget.cpp index 2baa105..51c6ec5 100644 --- a/limereport/objectinspector/lrobjectinspectorwidget.cpp +++ b/limereport/objectinspector/lrobjectinspectorwidget.cpp @@ -27,86 +27,88 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include +#include "lrobjectinspectorwidget.h" #include "lrglobal.h" -#include "lrobjectinspectorwidget.h" #include "lrobjectitemmodel.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include +#include +#include -ObjectInspectorTreeView::ObjectInspectorTreeView(QWidget *parent) - :QTreeView(parent), m_propertyDelegate(0) +namespace LimeReport { + +ObjectInspectorTreeView::ObjectInspectorTreeView(QWidget* parent): + QTreeView(parent), + m_propertyDelegate(0) { setRootIsDecorated(false); initColorMap(); - setEditTriggers( - QAbstractItemView::DoubleClicked | - QAbstractItemView::SelectedClicked | - QAbstractItemView::EditKeyPressed - ); + setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked + | QAbstractItemView::EditKeyPressed); m_propertyDelegate = new PropertyDelegate(this); setItemDelegate(m_propertyDelegate); QPalette p = palette(); - p.setColor(QPalette::AlternateBase,QColor(229,255,214)); + p.setColor(QPalette::AlternateBase, QColor(229, 255, 214)); setPalette(p); } -ObjectInspectorTreeView::~ObjectInspectorTreeView(){} +ObjectInspectorTreeView::~ObjectInspectorTreeView() { } -void ObjectInspectorTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const +void ObjectInspectorTreeView::drawRow(QPainter* painter, const QStyleOptionViewItem& options, + const QModelIndex& index) const { - ObjectPropItem *node = nodeFromIndex(index); + ObjectPropItem* node = nodeFromIndex(index); StyleOptionViewItem so = options; bool alternate = so.features & StyleOptionViewItem::Alternate; - if (node){ - if ((!node->isHaveValue())){ + if (node) { + if ((!node->isHaveValue())) { const QColor c = options.palette.color(QPalette::Dark); - painter->fillRect(options.rect,c); - so.palette.setColor(QPalette::AlternateBase,c); + painter->fillRect(options.rect, c); + so.palette.setColor(QPalette::AlternateBase, c); } else { - if ( index.isValid()&&(nodeFromIndex(index)->colorIndex()!=-1) ){ - QColor fillColor(getColor(nodeFromIndex(index)->colorIndex()%m_colors.count())); - so.palette.setColor(QPalette::AlternateBase,fillColor.lighter(115)); - if (!alternate){ - painter->fillRect(options.rect,fillColor); + if (index.isValid() && (nodeFromIndex(index)->colorIndex() != -1)) { + QColor fillColor(getColor(nodeFromIndex(index)->colorIndex() % m_colors.count())); + so.palette.setColor(QPalette::AlternateBase, fillColor.lighter(115)); + if (!alternate) { + painter->fillRect(options.rect, fillColor); } } } } - QTreeView::drawRow(painter,so,index); + QTreeView::drawRow(painter, so, index); painter->save(); - QColor gridLineColor = static_cast(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor,&so)); + QColor gridLineColor + = static_cast(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &so)); painter->setPen(gridLineColor); - painter->drawLine(so.rect.x(),so.rect.bottom(),so.rect.right(),so.rect.bottom()); + painter->drawLine(so.rect.x(), so.rect.bottom(), so.rect.right(), so.rect.bottom()); painter->restore(); } -void ObjectInspectorTreeView::mousePressEvent(QMouseEvent *event) +void ObjectInspectorTreeView::mousePressEvent(QMouseEvent* event) { - if ((event->button()==Qt::LeftButton)){ - QModelIndex index=indexAt(event->pos()); - if (index.isValid()){ + if ((event->button() == Qt::LeftButton)) { + QModelIndex index = indexAt(event->pos()); + if (index.isValid()) { if (event->pos().x() < indentation()) { if (!nodeFromIndex(index)->isHaveValue()) - setExpanded(index,!isExpanded(index)); + setExpanded(index, !isExpanded(index)); } else { - if ((index.column()==1)&&(!nodeFromIndex(index)->isHaveChildren())) { + if ((index.column() == 1) && (!nodeFromIndex(index)->isHaveChildren())) { setCurrentIndex(index); Qt::ItemFlags flags = index.model()->flags(index); - if ( !(((flags & Qt::ItemIsEditable) == 0) || ((flags & Qt::ItemIsEnabled) == 0)) ) + if (!(((flags & Qt::ItemIsEditable) == 0) + || ((flags & Qt::ItemIsEnabled) == 0))) edit(index); - return ; + return; } } } @@ -118,56 +120,56 @@ void ObjectInspectorTreeView::mousePressEvent(QMouseEvent *event) void ObjectInspectorTreeView::initColorMap() { m_colors.reserve(6); - m_colors.push_back(QColor(255,230,191)); - m_colors.push_back(QColor(255,255,191)); - m_colors.push_back(QColor(191,255,191)); - m_colors.push_back(QColor(199,255,255)); - m_colors.push_back(QColor(234,191,255)); - m_colors.push_back(QColor(255,191,239)); + m_colors.push_back(QColor(255, 230, 191)); + m_colors.push_back(QColor(255, 255, 191)); + m_colors.push_back(QColor(191, 255, 191)); + m_colors.push_back(QColor(199, 255, 255)); + m_colors.push_back(QColor(234, 191, 255)); + m_colors.push_back(QColor(255, 191, 239)); } -QColor ObjectInspectorTreeView::getColor(const int index) const -{ - return m_colors[index]; -} +QColor ObjectInspectorTreeView::getColor(const int index) const { return m_colors[index]; } void ObjectInspectorTreeView::reset() { QTreeView::reset(); - for (int i=0;irowCount();i++){ - if (!nodeFromIndex(model()->index(i,0))->isHaveValue()){ - setFirstColumnSpanned(i,model()->index(i,0).parent(),true); + for (int i = 0; i < model()->rowCount(); i++) { + if (!nodeFromIndex(model()->index(i, 0))->isHaveValue()) { + setFirstColumnSpanned(i, model()->index(i, 0).parent(), true); } } } -ObjectPropItem * ObjectInspectorTreeView::nodeFromIndex(QModelIndex index) const +ObjectPropItem* ObjectInspectorTreeView::nodeFromIndex(QModelIndex index) const { return qvariant_cast(index.data(Qt::UserRole)); } -void ObjectInspectorTreeView::keyPressEvent(QKeyEvent *event) +void ObjectInspectorTreeView::keyPressEvent(QKeyEvent* event) { - if (event->key()==Qt::Key_Return){ - if(!m_propertyDelegate->isEditing()){ - QModelIndex index = currentIndex().model()->index(currentIndex().row(), - 1,currentIndex().parent()); + if (event->key() == Qt::Key_Return) { + if (!m_propertyDelegate->isEditing()) { + QModelIndex index + = currentIndex().model()->index(currentIndex().row(), 1, currentIndex().parent()); edit(index); event->accept(); } - } else QTreeView::keyPressEvent(event); + } else + QTreeView::keyPressEvent(event); } -void ObjectInspectorTreeView::commitActiveEditorData(){ - if (state()==QAbstractItemView::EditingState){ +void ObjectInspectorTreeView::commitActiveEditorData() +{ + if (state() == QAbstractItemView::EditingState) { commitData(indexWidget(currentIndex())); } } -bool PropertyFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool PropertyFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); - if (sourceParent.isValid()) return true; + if (sourceParent.isValid()) + return true; #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) return sourceModel()->data(index).toString().contains(filterRegExp()); #else @@ -175,8 +177,7 @@ bool PropertyFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sou #endif } -ObjectInspectorWidget::ObjectInspectorWidget(QWidget *parent) - :QWidget(parent), m_filterModel(0) +ObjectInspectorWidget::ObjectInspectorWidget(QWidget* parent): QWidget(parent), m_filterModel(0) { m_objectInspectorView = new ObjectInspectorTreeView(this); m_propertyModel = new BaseDesignPropertyModel(this); @@ -185,17 +186,19 @@ ObjectInspectorWidget::ObjectInspectorWidget(QWidget *parent) #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) m_filterModel->setFilterRegExp(QRegExp("", Qt::CaseInsensitive, QRegExp::FixedString)); #else - m_filterModel->setFilterRegularExpression(QRegularExpression("", QRegularExpression::CaseInsensitiveOption)); + m_filterModel->setFilterRegularExpression( + QRegularExpression("", QRegularExpression::CaseInsensitiveOption)); #endif m_objectInspectorView->setModel(m_filterModel); QVBoxLayout* l = new QVBoxLayout(); QLineEdit* le = new QLineEdit(this); - QToolButton * pbClear = new QToolButton(this); + QToolButton* pbClear = new QToolButton(this); pbClear->setToolTip(tr("Clear")); pbClear->setIcon(QIcon(":/items/clear.png")); connect(pbClear, SIGNAL(clicked()), le, SLOT(clear())); le->setPlaceholderText(tr("Filter")); - connect(le, SIGNAL(textChanged(const QString&)), this, SLOT(slotFilterTextChanged(const QString&))); + connect(le, SIGNAL(textChanged(const QString&)), this, + SLOT(slotFilterTextChanged(const QString&))); QToolButton* settingButton = new QToolButton(this); settingButton->setIcon(QIcon(":/items/images/settings.png")); @@ -204,8 +207,8 @@ ObjectInspectorWidget::ObjectInspectorWidget(QWidget *parent) m_translateProperties->setCheckable(true); m_translateProperties->setChecked(translateProperties()); - connect(m_translateProperties, SIGNAL(toggled(bool)), - this, SLOT(slotTranslatePropertiesChecked(bool))); + connect(m_translateProperties, SIGNAL(toggled(bool)), this, + SLOT(slotTranslatePropertiesChecked(bool))); settingButton->setMenu(settingMenu); settingButton->setPopupMode(QToolButton::InstantPopup); @@ -223,11 +226,10 @@ ObjectInspectorWidget::ObjectInspectorWidget(QWidget *parent) this->setLayout(l); } -void ObjectInspectorWidget::setModel(QAbstractItemModel *model) +void ObjectInspectorWidget::setModel(QAbstractItemModel* model) { m_filterModel->setSourceModel(model); - } void ObjectInspectorWidget::setAlternatingRowColors(bool value) @@ -260,15 +262,12 @@ void ObjectInspectorWidget::commitActiveEditorData() m_objectInspectorView->commitActiveEditorData(); } -void ObjectInspectorWidget::setValidator(ValidatorIntf *validator) +void ObjectInspectorWidget::setValidator(ValidatorIntf* validator) { m_propertyModel->setValidator(validator); } -bool ObjectInspectorWidget::subclassesAsLevel() -{ - return m_propertyModel->subclassesAsLevel(); -} +bool ObjectInspectorWidget::subclassesAsLevel() { return m_propertyModel->subclassesAsLevel(); } void ObjectInspectorWidget::setSubclassesAsLevel(bool value) { @@ -287,37 +286,30 @@ void ObjectInspectorWidget::setTranslateProperties(bool value) update(); } -const QObject *ObjectInspectorWidget::object(){ - return m_propertyModel->currentObject(); -} +const QObject* ObjectInspectorWidget::object() { return m_propertyModel->currentObject(); } -void ObjectInspectorWidget::setObject(QObject *object) -{ - m_propertyModel->setObject(object); -} +void ObjectInspectorWidget::setObject(QObject* object) { m_propertyModel->setObject(object); } -void ObjectInspectorWidget::setMultiObjects(QList *list) +void ObjectInspectorWidget::setMultiObjects(QList* list) { m_propertyModel->setMultiObjects(list); } -void ObjectInspectorWidget::clearObjectsList() -{ - m_propertyModel->clearObjectsList(); -} +void ObjectInspectorWidget::clearObjectsList() { m_propertyModel->clearObjectsList(); } -void ObjectInspectorWidget::updateProperty(const QString &propertyName) +void ObjectInspectorWidget::updateProperty(const QString& propertyName) { m_propertyModel->updateProperty(propertyName); } -void ObjectInspectorWidget::slotFilterTextChanged(const QString &filter) +void ObjectInspectorWidget::slotFilterTextChanged(const QString& filter) { if (m_filterModel) #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) m_filterModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::FixedString)); #else - m_filterModel->setFilterRegularExpression(QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption)); + m_filterModel->setFilterRegularExpression( + QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption)); #endif } @@ -326,4 +318,4 @@ void ObjectInspectorWidget::slotTranslatePropertiesChecked(bool value) setTranslateProperties(value); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectinspector/lrobjectinspectorwidget.h b/limereport/objectinspector/lrobjectinspectorwidget.h index 2244887..c41984a 100644 --- a/limereport/objectinspector/lrobjectinspectorwidget.h +++ b/limereport/objectinspector/lrobjectinspectorwidget.h @@ -30,46 +30,49 @@ #ifndef LROBJECTINSPECTORWIDGET_H #define LROBJECTINSPECTORWIDGET_H -#include -#include -#include - -#include "lrobjectitemmodel.h" #include "lrbasedesignobjectmodel.h" +#include "lrobjectitemmodel.h" #include "lrpropertydelegate.h" -namespace LimeReport{ +#include +#include +#include -class ObjectInspectorTreeView : public QTreeView -{ +namespace LimeReport { + +class ObjectInspectorTreeView: public QTreeView { Q_OBJECT public: - ObjectInspectorTreeView(QWidget * parent=0); + ObjectInspectorTreeView(QWidget* parent = 0); ~ObjectInspectorTreeView(); QColor getColor(const int index) const; virtual void reset(); virtual void commitActiveEditorData(); + protected: - void mousePressEvent(QMouseEvent *event); - void drawRow(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const; - void keyPressEvent(QKeyEvent *event); + void mousePressEvent(QMouseEvent* event); + void drawRow(QPainter* painter, const QStyleOptionViewItem& options, + const QModelIndex& index) const; + void keyPressEvent(QKeyEvent* event); + private: void initColorMap(); LimeReport::ObjectPropItem* nodeFromIndex(QModelIndex index) const; private: QVector m_colors; - PropertyDelegate *m_propertyDelegate; + PropertyDelegate* m_propertyDelegate; }; -class PropertyFilterModel: public QSortFilterProxyModel{ +class PropertyFilterModel: public QSortFilterProxyModel { public: - PropertyFilterModel(QObject* parent = 0): QSortFilterProxyModel(parent){} + PropertyFilterModel(QObject* parent = 0): QSortFilterProxyModel(parent) { } + protected: - bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const; + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const; }; -class ObjectInspectorWidget: public QWidget{ +class ObjectInspectorWidget: public QWidget { Q_OBJECT public: ObjectInspectorWidget(QWidget* parent = 0); @@ -77,30 +80,30 @@ public: void setAlternatingRowColors(bool value); void setRootIsDecorated(bool value); void setColumnWidth(int column, int width); - int columnWidth(int column); + int columnWidth(int column); void expandToDepth(int depth); void commitActiveEditorData(); - void setValidator(ValidatorIntf *validator); + void setValidator(ValidatorIntf* validator); bool subclassesAsLevel(); void setSubclassesAsLevel(bool value); bool translateProperties(); void setTranslateProperties(bool value); void setObject(QObject* setObject); const QObject* object(); - void setMultiObjects(QList* list); + void setMultiObjects(QList* list); void clearObjectsList(); - void updateProperty(const QString &propertyName); + void updateProperty(const QString& propertyName); private slots: void slotFilterTextChanged(const QString& filter); void slotTranslatePropertiesChecked(bool value); + private: ObjectInspectorTreeView* m_objectInspectorView; QSortFilterProxyModel* m_filterModel; BaseDesignPropertyModel* m_propertyModel; QAction* m_translateProperties; - }; -} //namespace LimeReport +} // namespace LimeReport #endif // LROBJECTINSPECTORWIDGET_H diff --git a/limereport/objectinspector/lrobjectitemmodel.cpp b/limereport/objectinspector/lrobjectitemmodel.cpp index 1f768d9..138ef7d 100644 --- a/limereport/objectinspector/lrobjectitemmodel.cpp +++ b/limereport/objectinspector/lrobjectitemmodel.cpp @@ -28,10 +28,11 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrobjectitemmodel.h" -#include -#include + #include #include +#include +#include namespace LimeReport { @@ -178,48 +179,48 @@ void QObjectPropertyModel::translatePropertyName() tr("borderStyle"); } -void QObjectPropertyModel::clearObjectsList() +void QObjectPropertyModel::clearObjectsList() { m_objects.clear(); } + +QObjectPropertyModel::QObjectPropertyModel(QObject* parent /*=0*/): + QAbstractItemModel(parent), + m_rootNode(0), + m_object(0), + m_dataChanging(false), + m_subclassesAsLevel(true), + m_validator(0), + m_translateProperties(true) { - m_objects.clear(); } -QObjectPropertyModel::QObjectPropertyModel(QObject *parent/*=0*/) - :QAbstractItemModel(parent),m_rootNode(0), m_object(0), m_dataChanging(false), - m_subclassesAsLevel(true), m_validator(0), m_translateProperties(true) -{} - -QObjectPropertyModel::~QObjectPropertyModel() -{ - delete m_rootNode; -} +QObjectPropertyModel::~QObjectPropertyModel() { delete m_rootNode; } void QObjectPropertyModel::initModel() { beginResetModel(); delete m_rootNode; - m_rootNode=0; + m_rootNode = 0; if (m_object) { - connect(m_object,SIGNAL(destroyed(QObject*)),this,SLOT(slotObjectDestroyed(QObject*))); - m_rootNode=new ObjectPropItem(0,0,"root","root",QVariant(),0); + connect(m_object, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*))); + m_rootNode = new ObjectPropItem(0, 0, "root", "root", QVariant(), 0); m_rootNode->setModel(this); - foreach(QObject* item, m_objects) - connect(item,SIGNAL(destroyed(QObject*)),this,SLOT(slotObjectDestroyed(QObject*))); + foreach (QObject* item, m_objects) + connect(item, SIGNAL(destroyed(QObject*)), this, SLOT(slotObjectDestroyed(QObject*))); addObjectProperties(m_object->metaObject(), m_object, &m_objects); } endResetModel(); } -void QObjectPropertyModel::setObject(QObject *object) +void QObjectPropertyModel::setObject(QObject* object) { m_objects.clear(); - if (m_object!=object){ + if (m_object != object) { submit(); - m_object=object; + m_object = object; initModel(); } } -void QObjectPropertyModel::setMultiObjects(QList* list) +void QObjectPropertyModel::setMultiObjects(QList* list) { m_objects.clear(); submit(); @@ -228,28 +229,29 @@ void QObjectPropertyModel::setMultiObjects(QList* list) return; } - if (!list->contains(m_object)){ - m_object=list->at(0); + if (!list->contains(m_object)) { + m_object = list->at(0); list->removeAt(0); } else { list->removeOne(m_object); } - foreach(QObject* item, *list) + foreach (QObject* item, *list) m_objects.append(item); - //initModel(); + // initModel(); } -void QObjectPropertyModel::slotObjectDestroyed(QObject *obj) +void QObjectPropertyModel::slotObjectDestroyed(QObject* obj) { m_objects.removeOne(obj); - if (m_object == obj){ - m_object=0; - initModel(); + if (m_object == obj) { + m_object = 0; + initModel(); } } -void QObjectPropertyModel::slotPropertyChanged(const QString &propertyName, const QVariant& oldValue, const QVariant& newValue) +void QObjectPropertyModel::slotPropertyChanged(const QString& propertyName, + const QVariant& oldValue, const QVariant& newValue) { Q_UNUSED(oldValue); Q_UNUSED(newValue); @@ -257,7 +259,8 @@ void QObjectPropertyModel::slotPropertyChanged(const QString &propertyName, cons updateProperty(propertyName); } -void QObjectPropertyModel::slotPropertyObjectNameChanged(const QString &oldName, const QString &newName) +void QObjectPropertyModel::slotPropertyObjectNameChanged(const QString& oldName, + const QString& newName) { Q_UNUSED(oldName) Q_UNUSED(newName) @@ -265,45 +268,43 @@ void QObjectPropertyModel::slotPropertyObjectNameChanged(const QString &oldName, updateProperty("objectName"); } - -int QObjectPropertyModel::columnCount(const QModelIndex &/*parent*/) const -{ - return 2; -} +int QObjectPropertyModel::columnCount(const QModelIndex& /*parent*/) const { return 2; } QVariant QObjectPropertyModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation==Qt::Horizontal&&role==Qt::DisplayRole){ - if (section==0) return tr("Property Name"); - else return tr("Property value"); - } else return QVariant(); + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { + if (section == 0) + return tr("Property Name"); + else + return tr("Property value"); + } else + return QVariant(); } -ObjectPropItem * QObjectPropertyModel::nodeFromIndex(const QModelIndex &index) const +ObjectPropItem* QObjectPropertyModel::nodeFromIndex(const QModelIndex& index) const { - if(index.isValid()){ + if (index.isValid()) { return static_cast(index.internalPointer()); - } else return m_rootNode; + } else + return m_rootNode; } -void QObjectPropertyModel::updateProperty(const QString &propertyName) +void QObjectPropertyModel::updateProperty(const QString& propertyName) { - if (!m_dataChanging&&m_rootNode){ + if (!m_dataChanging && m_rootNode) { ObjectPropItem* propItem = m_rootNode->findPropertyItem(propertyName); if (propItem) - propItem->updatePropertyValue(); + propItem->updatePropertyValue(); } } -void QObjectPropertyModel::setSubclassesAsLevel(bool value) -{ - m_subclassesAsLevel = value; -} +void QObjectPropertyModel::setSubclassesAsLevel(bool value) { m_subclassesAsLevel = value; } -int QObjectPropertyModel::rowCount(const QModelIndex &parent) const +int QObjectPropertyModel::rowCount(const QModelIndex& parent) const { - if (!m_rootNode) return 0; - ObjectPropItem *parentNode; + if (!m_rootNode) + return 0; + ObjectPropItem* parentNode; if (parent.isValid()) parentNode = nodeFromIndex(parent); else @@ -311,23 +312,26 @@ int QObjectPropertyModel::rowCount(const QModelIndex &parent) const return parentNode->childCount(); } -QVariant QObjectPropertyModel::data(const QModelIndex &index, int role) const +QVariant QObjectPropertyModel::data(const QModelIndex& index, int role) const { - ObjectPropItem *node = nodeFromIndex(index); + ObjectPropItem* node = nodeFromIndex(index); switch (role) { case Qt::DisplayRole: - if (!node) return QVariant(); + if (!node) + return QVariant(); node->setTranslateProperty(isTranslateProperties()); - if (index.column()==0){ + if (index.column() == 0) { return node->displayName(); } else { return node->displayValue(); } - case Qt::DecorationRole : - if (!node) return QIcon(); - if (index.column()==1){ + case Qt::DecorationRole: + if (!node) + return QIcon(); + if (index.column() == 1) { return node->iconValue(); - } else return QIcon(); + } else + return QIcon(); case Qt::UserRole: return QVariant::fromValue(node); default: @@ -335,184 +339,179 @@ QVariant QObjectPropertyModel::data(const QModelIndex &index, int role) const } } -QModelIndex QObjectPropertyModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex QObjectPropertyModel::index(int row, int column, const QModelIndex& parent) const { - if(!m_rootNode) + if (!m_rootNode) return QModelIndex(); if (!hasIndex(row, column, parent)) return QModelIndex(); - ObjectPropItem *parentNode; + ObjectPropItem* parentNode; if (parent.isValid()) parentNode = nodeFromIndex(parent); else parentNode = m_rootNode; - ObjectPropItem *childItem=parentNode->child(row); + ObjectPropItem* childItem = parentNode->child(row); - if (childItem){ - QModelIndex modelIndex=createIndex(row,column,childItem); - if (column==1){ - if (childItem->modelIndex()!=modelIndex){ + if (childItem) { + QModelIndex modelIndex = createIndex(row, column, childItem); + if (column == 1) { + if (childItem->modelIndex() != modelIndex) { childItem->setModelIndex(modelIndex); } } return modelIndex; - } - else return QModelIndex(); + } else + return QModelIndex(); } -QModelIndex QObjectPropertyModel::parent(const QModelIndex &child) const -{ - if (!child.isValid()) return QModelIndex(); - - ObjectPropItem *childNode = nodeFromIndex(child); - if (!childNode) return QModelIndex(); - - ObjectPropItem *parentNode = childNode->parent(); - if ((parentNode == m_rootNode) || (!parentNode)) return QModelIndex(); - - return createIndex(parentNode->row(),0,parentNode); -} - - -Qt::ItemFlags QObjectPropertyModel::flags(const QModelIndex &index) const +QModelIndex QObjectPropertyModel::parent(const QModelIndex& child) const { - if ((index.column() == 1) && (!nodeFromIndex(index)->isValueReadonly())) return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable; - else return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + if (!child.isValid()) + return QModelIndex(); + + ObjectPropItem* childNode = nodeFromIndex(child); + if (!childNode) + return QModelIndex(); + + ObjectPropItem* parentNode = childNode->parent(); + if ((parentNode == m_rootNode) || (!parentNode)) + return QModelIndex(); + + return createIndex(parentNode->row(), 0, parentNode); +} + +Qt::ItemFlags QObjectPropertyModel::flags(const QModelIndex& index) const +{ + if ((index.column() == 1) && (!nodeFromIndex(index)->isValueReadonly())) + return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable; + else + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } CreatePropItem QObjectPropertyModel::propertyItemCreator(QMetaProperty prop) { CreatePropItem creator = 0; - creator = ObjectPropFactory::instance().objectCreator(APropIdent(prop.name(),prop.enclosingMetaObject()->className())); - if (!creator){ - if (prop.isFlagType()){ - creator=ObjectPropFactory::instance().objectCreator(APropIdent("flags","")); - if (creator){ - return creator; - } else { - qDebug()<<"flags prop editor not found"; - return 0; - } - } - if (prop.isEnumType()){ - creator=ObjectPropFactory::instance().objectCreator(APropIdent("enum","")); - if (creator){ + creator = ObjectPropFactory::instance().objectCreator( + APropIdent(prop.name(), prop.enclosingMetaObject()->className())); + if (!creator) { + if (prop.isFlagType()) { + creator = ObjectPropFactory::instance().objectCreator(APropIdent("flags", "")); + if (creator) { return creator; } else { - qDebug()<<"enum prop editor not found"; + qDebug() << "flags prop editor not found"; return 0; } } - creator = ObjectPropFactory::instance().objectCreator(APropIdent(prop.typeName(),"")); - if (!creator) {qDebug()<<"Editor for propperty name = \""<property(prop.name()), - parent, - !(prop.isWritable() && prop.isDesignable()) - ); + propertyItem = creator(object, objects, QString(prop.name()), QString(tr(prop.name())), + object->property(prop.name()), parent, + !(prop.isWritable() && prop.isDesignable())); } else { - propertyItem=new ObjectPropItem( - 0, - 0, - QString(prop.name()), - QString(tr(prop.name())), - object->property(prop.name()), - parent - ); + propertyItem = new ObjectPropItem(0, 0, QString(prop.name()), QString(tr(prop.name())), + object->property(prop.name()), parent); } return propertyItem; } -bool QObjectPropertyModel::isTranslateProperties() const -{ - return m_translateProperties; -} +bool QObjectPropertyModel::isTranslateProperties() const { return m_translateProperties; } void QObjectPropertyModel::setTranslateProperties(bool translateProperties) { m_translateProperties = translateProperties; } -ValidatorIntf *QObjectPropertyModel::validator() const -{ - return m_validator; -} +ValidatorIntf* QObjectPropertyModel::validator() const { return m_validator; } -void QObjectPropertyModel::setValidator(ValidatorIntf *validator) -{ - m_validator = validator; -} +void QObjectPropertyModel::setValidator(ValidatorIntf* validator) { m_validator = validator; } -void QObjectPropertyModel::addObjectProperties(const QMetaObject *metaObject, QObject *object, ObjectPropItem::ObjectsList *objects, int level) +void QObjectPropertyModel::addObjectProperties(const QMetaObject* metaObject, QObject* object, + ObjectPropItem::ObjectsList* objects, int level) { - if (metaObject->propertyCount()>metaObject->propertyOffset()){ + if (metaObject->propertyCount() > metaObject->propertyOffset()) { ObjectPropItem* objectNode; - if (m_subclassesAsLevel){ - objectNode=new ObjectPropItem(0,0,metaObject->className(),metaObject->className(),m_rootNode,true); + if (m_subclassesAsLevel) { + objectNode = new ObjectPropItem(0, 0, metaObject->className(), metaObject->className(), + m_rootNode, true); m_rootNode->appendItem(objectNode); } else { objectNode = m_rootNode; } - for (int i=metaObject->propertyOffset();ipropertyCount();i++){ - if (metaObject->property(i).isDesignable()){ - ObjectPropItem* prop=createPropertyItem(metaObject->property(i),object,objects,objectNode); + for (int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); i++) { + if (metaObject->property(i).isDesignable()) { + ObjectPropItem* prop + = createPropertyItem(metaObject->property(i), object, objects, objectNode); objectNode->appendItem(prop); } } - if (m_subclassesAsLevel){ + if (m_subclassesAsLevel) { objectNode->setColorIndex(level); objectNode->sortItem(); level++; } } - if (metaObject->superClass()) addObjectProperties(metaObject->superClass(),object,objects,level); + if (metaObject->superClass()) + addObjectProperties(metaObject->superClass(), object, objects, level); m_rootNode->sortItem(); } -bool QObjectPropertyModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool QObjectPropertyModel::setData(const QModelIndex& index, const QVariant& value, int role) { - if (index.isValid()&&role==Qt::EditRole){ - m_dataChanging=true; - ObjectPropItem * propItem = nodeFromIndex(index); - if (propItem->propertyValue()!=value){ + if (index.isValid() && role == Qt::EditRole) { + m_dataChanging = true; + ObjectPropItem* propItem = nodeFromIndex(index); + if (propItem->propertyValue() != value) { QString msg; - if (validator() && !validator()->validate(propItem->propertyName(),value.toString(),m_object,msg)){ - QMessageBox::information(0,tr("Warning"),msg); + if (validator() + && !validator()->validate(propItem->propertyName(), value.toString(), m_object, + msg)) { + QMessageBox::information(0, tr("Warning"), msg); return true; } - QVariant oldValue=propItem->propertyValue(); + QVariant oldValue = propItem->propertyValue(); propItem->setPropertyValue(value); - emit dataChanged(index,index); - emit objectPropetyChanged(propItem->propertyName(),oldValue,propItem->propertyValue()); + emit dataChanged(index, index); + emit objectPropetyChanged(propItem->propertyName(), oldValue, + propItem->propertyValue()); } - m_dataChanging=false; + m_dataChanging = false; return true; } return false; } -void QObjectPropertyModel::itemDataChanged(const QModelIndex &index) +void QObjectPropertyModel::itemDataChanged(const QModelIndex& index) { - emit dataChanged(index,index); -} - + emit dataChanged(index, index); } +} // namespace LimeReport diff --git a/limereport/objectinspector/lrobjectitemmodel.h b/limereport/objectinspector/lrobjectitemmodel.h index 2beb0dd..67df368 100644 --- a/limereport/objectinspector/lrobjectitemmodel.h +++ b/limereport/objectinspector/lrobjectitemmodel.h @@ -30,70 +30,77 @@ #ifndef LROBJECTITEMMODEL_H #define LROBJECTITEMMODEL_H -#include -#include -#include #include "lrobjectpropitem.h" -namespace LimeReport{ +#include +#include +#include +namespace LimeReport { class ValidatorIntf { public: - virtual bool validate(const QString& propName, const QVariant& propValue, QObject* object, QString& msg) = 0; - virtual ~ValidatorIntf(){} + virtual bool validate(const QString& propName, const QVariant& propValue, QObject* object, + QString& msg) + = 0; + virtual ~ValidatorIntf() { } }; -class QObjectPropertyModel : public QAbstractItemModel -{ +class QObjectPropertyModel: public QAbstractItemModel { Q_OBJECT public: - QObjectPropertyModel(QObject *parent=0); + QObjectPropertyModel(QObject* parent = 0); ~QObjectPropertyModel(); - virtual void setObject(QObject *object); - virtual void setMultiObjects(QList* list); - virtual QModelIndex index(int row, int column, const QModelIndex &parent) const; - virtual QModelIndex parent(const QModelIndex &child) const; - virtual int columnCount(const QModelIndex &parent) const; - virtual int rowCount(const QModelIndex &parent) const; - virtual QVariant data(const QModelIndex &index, int role) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; - virtual Qt::ItemFlags flags(const QModelIndex &index) const; - virtual bool setData(const QModelIndex &index, const QVariant &value, int role); - void itemDataChanged(const QModelIndex &index); - void initModel(); - const QObject* currentObject(){return m_object;} - LimeReport::ObjectPropItem* nodeFromIndex(const QModelIndex &index) const; - LimeReport::ObjectPropItem* rootNode(){return m_rootNode;} - void updateProperty(const QString& propertyName); - void setSubclassesAsLevel(bool value); - bool subclassesAsLevel(){return m_subclassesAsLevel;} - ValidatorIntf* validator() const; - void setValidator(ValidatorIntf* validator); - void translatePropertyName(); - void clearObjectsList(); - bool isTranslateProperties() const; - void setTranslateProperties(bool isTranslateProperties); + virtual void setObject(QObject* object); + virtual void setMultiObjects(QList* list); + virtual QModelIndex index(int row, int column, const QModelIndex& parent) const; + virtual QModelIndex parent(const QModelIndex& child) const; + virtual int columnCount(const QModelIndex& parent) const; + virtual int rowCount(const QModelIndex& parent) const; + virtual QVariant data(const QModelIndex& index, int role) const; + virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; + virtual Qt::ItemFlags flags(const QModelIndex& index) const; + virtual bool setData(const QModelIndex& index, const QVariant& value, int role); + void itemDataChanged(const QModelIndex& index); + void initModel(); + const QObject* currentObject() { return m_object; } + LimeReport::ObjectPropItem* nodeFromIndex(const QModelIndex& index) const; + LimeReport::ObjectPropItem* rootNode() { return m_rootNode; } + void updateProperty(const QString& propertyName); + void setSubclassesAsLevel(bool value); + bool subclassesAsLevel() { return m_subclassesAsLevel; } + ValidatorIntf* validator() const; + void setValidator(ValidatorIntf* validator); + void translatePropertyName(); + void clearObjectsList(); + bool isTranslateProperties() const; + void setTranslateProperties(bool isTranslateProperties); signals: - void objectPropetyChanged(const QString& , const QVariant&, const QVariant&); + void objectPropetyChanged(const QString&, const QVariant&, const QVariant&); private slots: void slotObjectDestroyed(QObject* obj); - void slotPropertyChanged(const QString& propertyName, const QVariant &oldValue, const QVariant &newValue); + void slotPropertyChanged(const QString& propertyName, const QVariant& oldValue, + const QVariant& newValue); void slotPropertyObjectNameChanged(const QString& oldName, const QString& newName); + private: - void addObjectProperties(const QMetaObject *metaObject, QObject *object, ObjectPropItem::ObjectsList* objects, int level=0); - LimeReport::CreatePropItem propertyItemCreator(QMetaProperty prop); - LimeReport::ObjectPropItem* createPropertyItem(QMetaProperty prop, QObject *object, ObjectPropItem::ObjectsList* objects, ObjectPropItem* parent); + void addObjectProperties(const QMetaObject* metaObject, QObject* object, + ObjectPropItem::ObjectsList* objects, int level = 0); + LimeReport::CreatePropItem propertyItemCreator(QMetaProperty prop); + LimeReport::ObjectPropItem* createPropertyItem(QMetaProperty prop, QObject* object, + ObjectPropItem::ObjectsList* objects, + ObjectPropItem* parent); + private: - LimeReport::ObjectPropItem* m_rootNode; - QObject* m_object; - QList m_objects; - bool m_dataChanging; - bool m_subclassesAsLevel; - ValidatorIntf* m_validator; - bool m_translateProperties; + LimeReport::ObjectPropItem* m_rootNode; + QObject* m_object; + QList m_objects; + bool m_dataChanging; + bool m_subclassesAsLevel; + ValidatorIntf* m_validator; + bool m_translateProperties; }; -} +} // namespace LimeReport #endif // LROBJECTITEMMODEL_H diff --git a/limereport/objectinspector/lrobjectpropitem.cpp b/limereport/objectinspector/lrobjectpropitem.cpp index 638dd4c..d455753 100644 --- a/limereport/objectinspector/lrobjectpropitem.cpp +++ b/limereport/objectinspector/lrobjectpropitem.cpp @@ -28,6 +28,7 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrobjectpropitem.h" + #include "lrobjectitemmodel.h" #ifdef INSPECT_BASEDESIGN #include "lrbasedesignintf.h" @@ -36,175 +37,193 @@ namespace LimeReport { -bool lesThen(ObjectPropItem* v1, ObjectPropItem* v2){ - return v1->displayName().compare(v2->displayName())<0; +bool lesThen(ObjectPropItem* v1, ObjectPropItem* v2) +{ + return v1->displayName().compare(v2->displayName()) < 0; } -ObjectPropItem::ObjectPropItem(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, ObjectPropItem *parent, bool isClass) - :m_object(object), m_name(name), m_displayName(displayName), m_haveValue(false), m_parent(parent), m_colorIndex(-1), - m_readonly(true), m_model(0), m_isClass(isClass), m_changingValue(false), - m_translatePropperty(true) +ObjectPropItem::ObjectPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, ObjectPropItem* parent, bool isClass): + m_object(object), + m_name(name), + m_displayName(displayName), + m_haveValue(false), + m_parent(parent), + m_colorIndex(-1), + m_readonly(true), + m_model(0), + m_isClass(isClass), + m_changingValue(false), + m_translatePropperty(true) { - if (parent) setModel(parent->model()); - m_index=QModelIndex(); - //if (objects) foreach(QObject* item, *objects) m_objects.append(item); + if (parent) + setModel(parent->model()); + m_index = QModelIndex(); + // if (objects) foreach(QObject* item, *objects) m_objects.append(item); m_objects = objects; #ifdef INSPECT_BASEDESIGN - BaseDesignIntf * item = dynamic_cast(object); - if (item){ - connect(item,SIGNAL(propertyChanged(QString,QVariant,QVariant)),this,SLOT(slotPropertyChanged(QString,QVariant,QVariant))); - connect(item,SIGNAL(propertyObjectNameChanged(QString,QString)),this,SLOT(slotPropertyObjectName(QString,QString))); + BaseDesignIntf* item = dynamic_cast(object); + if (item) { + connect(item, SIGNAL(propertyChanged(QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QVariant, QVariant))); + connect(item, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPropertyObjectName(QString, QString))); } #endif } -ObjectPropItem::ObjectPropItem(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly) - :m_object(object), m_name(name), m_displayName(displayName), m_value(value), - m_haveValue(true), m_parent(parent), m_colorIndex(-1), - m_readonly(readonly), m_model(0), m_isClass(false), m_changingValue(false), - m_translatePropperty(true) +ObjectPropItem::ObjectPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + m_object(object), + m_name(name), + m_displayName(displayName), + m_value(value), + m_haveValue(true), + m_parent(parent), + m_colorIndex(-1), + m_readonly(readonly), + m_model(0), + m_isClass(false), + m_changingValue(false), + m_translatePropperty(true) { - if (parent) setModel(parent->model()); - m_index=QModelIndex(); - //if (objects) foreach(QObject* item, *objects) m_objects.append(item); + if (parent) + setModel(parent->model()); + m_index = QModelIndex(); + // if (objects) foreach(QObject* item, *objects) m_objects.append(item); m_objects = objects; #ifdef INSPECT_BASEDESIGN - BaseDesignIntf * item = dynamic_cast(object); - if (item){ - connect(item,SIGNAL(propertyChanged(QString,QVariant,QVariant)),this,SLOT(slotPropertyChanged(QString,QVariant,QVariant))); - connect(item,SIGNAL(propertyObjectNameChanged(QString,QString)),this,SLOT(slotPropertyObjectName(QString,QString))); + BaseDesignIntf* item = dynamic_cast(object); + if (item) { + connect(item, SIGNAL(propertyChanged(QString, QVariant, QVariant)), this, + SLOT(slotPropertyChanged(QString, QVariant, QVariant))); + connect(item, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPropertyObjectName(QString, QString))); } #endif } -ObjectPropItem::~ObjectPropItem(){ - qDeleteAll(m_childItems); -} +ObjectPropItem::~ObjectPropItem() { qDeleteAll(m_childItems); } +int ObjectPropItem::childCount() { return m_childItems.count(); } -int ObjectPropItem::childCount(){ - return m_childItems.count(); -} - -void ObjectPropItem::appendItem(ObjectPropItem *item){ - m_childItems.append(item); - if (m_parent && (!item->isClass())) m_parent->m_globalPropList.append(item); -} - -void ObjectPropItem::sortItem() +void ObjectPropItem::appendItem(ObjectPropItem* item) { - std::sort(m_childItems.begin(), m_childItems.end(), lesThen); + m_childItems.append(item); + if (m_parent && (!item->isClass())) + m_parent->m_globalPropList.append(item); } -QVariant ObjectPropItem::propertyValue() const { - return m_value; -} +void ObjectPropItem::sortItem() { std::sort(m_childItems.begin(), m_childItems.end(), lesThen); } -void ObjectPropItem::setPropertyValue(QVariant value){ - m_value=value; - LimeReport::QObjectPropertyModel *itemModel=dynamic_cast(model()); - if (itemModel){ +QVariant ObjectPropItem::propertyValue() const { return m_value; } + +void ObjectPropItem::setPropertyValue(QVariant value) +{ + m_value = value; + LimeReport::QObjectPropertyModel* itemModel + = dynamic_cast(model()); + if (itemModel) { itemModel->itemDataChanged(modelIndex()); - foreach(ObjectPropItem*item, children()){ - if (item->modelIndex().isValid()) itemModel->itemDataChanged(item->modelIndex()); + foreach (ObjectPropItem* item, children()) { + if (item->modelIndex().isValid()) + itemModel->itemDataChanged(item->modelIndex()); } } } -QString ObjectPropItem::displayName() const { +QString ObjectPropItem::displayName() const +{ return isTranslateProperty() ? m_displayName : propertyName(); } -int ObjectPropItem::row(){ +int ObjectPropItem::row() +{ if (m_parent) return m_parent->m_childItems.indexOf(const_cast(this)); return 0; } -ObjectPropItem * ObjectPropItem::child(int row){ - return m_childItems[row]; -} +ObjectPropItem* ObjectPropItem::child(int row) { return m_childItems[row]; } void ObjectPropItem::setColorIndex(int value) { - m_colorIndex=value; - for (int i=0;isetColorIndex(value); } } #ifdef INSPECT_BASEDESIGN -void ObjectPropItem::slotPropertyChanged(const QString &name, QVariant, QVariant newValue) +void ObjectPropItem::slotPropertyChanged(const QString& name, QVariant, QVariant newValue) { - if (name.compare(propertyName(),Qt::CaseInsensitive)==0 && !isValueChanging()){ + if (name.compare(propertyName(), Qt::CaseInsensitive) == 0 && !isValueChanging()) { setPropertyValue(newValue); } } -void ObjectPropItem::slotPropertyObjectName(const QString &oldValue, const QString &newValue) +void ObjectPropItem::slotPropertyObjectName(const QString& oldValue, const QString& newValue) { Q_UNUSED(oldValue) - if (propertyName().compare("objectName",Qt::CaseInsensitive)==0 && !isValueChanging()){ + if (propertyName().compare("objectName", Qt::CaseInsensitive) == 0 && !isValueChanging()) { setPropertyValue(newValue); } } #endif -void ObjectPropItem::setValueToObject(const QString &propertyName, QVariant propertyValue) +void ObjectPropItem::setValueToObject(const QString& propertyName, QVariant propertyValue) { - object()->setProperty(propertyName.toLatin1(),propertyValue); - if (objects()){ + object()->setProperty(propertyName.toLatin1(), propertyValue); + if (objects()) { foreach (QObject* item, *objects()) { - if (item->metaObject()->indexOfProperty(propertyName.toLatin1())!=-1) + if (item->metaObject()->indexOfProperty(propertyName.toLatin1()) != -1) item->setProperty(propertyName.toLatin1(), propertyValue); } } } -bool ObjectPropItem::isTranslateProperty() const -{ - return m_translatePropperty; -} +bool ObjectPropItem::isTranslateProperty() const { return m_translatePropperty; } void ObjectPropItem::setTranslateProperty(bool translatePropperty) { m_translatePropperty = translatePropperty; } -ObjectPropItem * ObjectPropItem::findChild(const QString &name) +ObjectPropItem* ObjectPropItem::findChild(const QString& name) { - foreach(ObjectPropItem* item,m_childItems){ - if (item->propertyName()==name) return item; + foreach (ObjectPropItem* item, m_childItems) { + if (item->propertyName() == name) + return item; } return 0; } -ObjectPropItem *ObjectPropItem::findPropertyItem(const QString &propertyName) +ObjectPropItem* ObjectPropItem::findPropertyItem(const QString& propertyName) { - foreach(ObjectPropItem* item,m_globalPropList){ - if (item->propertyName()==propertyName) return item; + foreach (ObjectPropItem* item, m_globalPropList) { + if (item->propertyName() == propertyName) + return item; } return 0; } -void ObjectPropItem::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const +void ObjectPropItem::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, + const QModelIndex&) const { editor->setGeometry(option.rect); } void ObjectPropItem::updatePropertyValue() { - m_model->setData(m_index,m_object->property(m_name.toLatin1())); + m_model->setData(m_index, m_object->property(m_name.toLatin1())); } -bool ObjectPropItem::paint(QPainter *, const StyleOptionViewItem &, const QModelIndex &) +bool ObjectPropItem::paint(QPainter*, const StyleOptionViewItem&, const QModelIndex&) { return false; } -QString ObjectPropItem::displayValue() const -{ - return m_value.toString(); -} +QString ObjectPropItem::displayValue() const { return m_value.toString(); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/lrobjectpropitem.h b/limereport/objectinspector/lrobjectpropitem.h index d557cd7..650ca24 100644 --- a/limereport/objectinspector/lrobjectpropitem.h +++ b/limereport/objectinspector/lrobjectpropitem.h @@ -30,116 +30,135 @@ #ifndef LROBJECTPROPITEM_H #define LROBJECTPROPITEM_H -#include -#include -#include -#include -#include -#include - #include "lrattribsabstractfactory.h" #include "lrsingleton.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include - class ObjectPropItem : public QObject +namespace LimeReport { + +class ObjectPropItem: public QObject { + Q_OBJECT + +public: + typedef QList ObjectsList; + ObjectPropItem() { invalidate(); } + ObjectPropItem(QObject* object, ObjectsList* objects, const QString& propertyName, + const QString& displayName, const QVariant& propertyValue, + ObjectPropItem* parent, bool readonly = true); + ObjectPropItem(QObject* object, ObjectsList* objects, const QString& propertyName, + const QString& displayName, ObjectPropItem* parent, bool isClass = false); + ~ObjectPropItem(); + + virtual QVariant propertyValue() const; + virtual void setPropertyValue(QVariant value); + virtual QString propertyName() const { return m_name; } + virtual QString displayName() const; + virtual QString displayValue() const; + virtual QIcon iconValue() const { return QIcon(); } + virtual bool isHaveChildren() const { return m_childItems.count() > 0; } + virtual bool isHaveValue() const { return m_haveValue; } + virtual bool isValueReadonly() const { return m_readonly; } + void setValueReadOnly(bool value) { m_readonly = value; } + virtual bool isValueModified() const { return false; } + virtual QWidget* createProperyEditor(QWidget* /*parent*/) const { return 0; } + virtual void setPropertyEditorData(QWidget*, const QModelIndex&) const { } + virtual void setModelData(QWidget* /*editor*/, QAbstractItemModel* /*model*/, + const QModelIndex& /*index*/) { - Q_OBJECT + } + virtual void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, + const QModelIndex& /*index*/) const; + virtual void updatePropertyValue(); + virtual bool paint(QPainter*, const StyleOptionViewItem&, const QModelIndex&); - public: - typedef QList< QObject* > ObjectsList; - ObjectPropItem(){invalidate();} - ObjectPropItem(QObject *object, ObjectsList* objects, const QString& propertyName, const QString& displayName, const QVariant& propertyValue, ObjectPropItem* parent, bool readonly=true); - ObjectPropItem(QObject *object, ObjectsList* objects, const QString& propertyName, const QString& displayName, ObjectPropItem *parent, bool isClass = false); - ~ObjectPropItem(); - - virtual QVariant propertyValue() const; - virtual void setPropertyValue(QVariant value); - virtual QString propertyName() const {return m_name;} - virtual QString displayName() const; - virtual QString displayValue() const; - virtual QIcon iconValue() const{return QIcon();} - virtual bool isHaveChildren() const {return m_childItems.count()>0;} - virtual bool isHaveValue() const {return m_haveValue;} - virtual bool isValueReadonly() const {return m_readonly;} - void setValueReadOnly(bool value){m_readonly=value;} - virtual bool isValueModified() const {return false;} - virtual QWidget* createProperyEditor(QWidget * /*parent*/) const {return 0;} - virtual void setPropertyEditorData(QWidget *, const QModelIndex &) const{} - virtual void setModelData(QWidget * /*editor*/, QAbstractItemModel * /*model*/, const QModelIndex &/*index*/){} - virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const; - virtual void updatePropertyValue(); - virtual bool paint(QPainter *, const StyleOptionViewItem &, const QModelIndex &); - - ObjectPropItem* parent() const{ return m_parent;} - QObject* object() const{return m_object;} - ObjectsList* objects() {return m_objects;} - ObjectPropItem* child(int row); - QList children(){return m_childItems;} - ObjectPropItem* findChild(const QString& propertyName); - ObjectPropItem* findPropertyItem(const QString& propertyName); - int childCount(); - void appendItem(ObjectPropItem* item); - void sortItem(); - int row(); - bool isValid(){return m_valid;} - int colorIndex(){return m_colorIndex;} - void setColorIndex(int propertyValue); - void setModel(QAbstractItemModel* model){m_model=model;} - QAbstractItemModel* model(){return m_model;} - void setModelIndex(const QModelIndex& index){m_index=index;} - QModelIndex modelIndex(){return m_index;} - bool isClass(){return m_isClass;} - bool isTranslateProperty() const; - void setTranslateProperty(bool translatePropperty); + ObjectPropItem* parent() const { return m_parent; } + QObject* object() const { return m_object; } + ObjectsList* objects() { return m_objects; } + ObjectPropItem* child(int row); + QList children() { return m_childItems; } + ObjectPropItem* findChild(const QString& propertyName); + ObjectPropItem* findPropertyItem(const QString& propertyName); + int childCount(); + void appendItem(ObjectPropItem* item); + void sortItem(); + int row(); + bool isValid() { return m_valid; } + int colorIndex() { return m_colorIndex; } + void setColorIndex(int propertyValue); + void setModel(QAbstractItemModel* model) { m_model = model; } + QAbstractItemModel* model() { return m_model; } + void setModelIndex(const QModelIndex& index) { m_index = index; } + QModelIndex modelIndex() { return m_index; } + bool isClass() { return m_isClass; } + bool isTranslateProperty() const; + void setTranslateProperty(bool translatePropperty); #ifdef INSPECT_BASEDESIGN - private slots: - void slotPropertyChanged(const QString& name, QVariant, QVariant newValue); - void slotPropertyObjectName(const QString& oldValue, const QString& newValue); +private slots: + void slotPropertyChanged(const QString& name, QVariant, QVariant newValue); + void slotPropertyObjectName(const QString& oldValue, const QString& newValue); #endif - private: - bool m_valid; - void invalidate(){m_object=0; m_objects=0; m_valid = false; m_name = ""; m_value=QVariant(); m_isClass=false;} - - protected: - void beginChangeValue(){ m_changingValue = true; } - void endChangeValue(){ m_changingValue = false; } - bool isValueChanging(){ return m_changingValue; } - void setValueToObject(const QString& propertyName, QVariant propertyValue); - private: - QObject* m_object; - ObjectsList* m_objects; - QString m_name; - QString m_displayName; - QVariant m_value; - bool m_haveValue; - ObjectPropItem* m_parent; - QList m_childItems; - QList m_globalPropList; - int m_colorIndex; - bool m_readonly; - QAbstractItemModel* m_model; - QModelIndex m_index; - bool m_isClass; - bool m_changingValue; - bool m_translatePropperty; - }; - - typedef QPair APropIdent; - typedef ObjectPropItem* (*CreatePropItem)(QObject *object, ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly); - - class ObjectPropFactory : public AttribsAbstractFactory +private: + bool m_valid; + void invalidate() { - private: - friend class Singleton; - private: - ObjectPropFactory(){} - ~ObjectPropFactory(){} - ObjectPropFactory(const ObjectPropFactory&){} - ObjectPropFactory& operator = (const ObjectPropFactory&){return *this;} - }; + m_object = 0; + m_objects = 0; + m_valid = false; + m_name = ""; + m_value = QVariant(); + m_isClass = false; + } -} +protected: + void beginChangeValue() { m_changingValue = true; } + void endChangeValue() { m_changingValue = false; } + bool isValueChanging() { return m_changingValue; } + void setValueToObject(const QString& propertyName, QVariant propertyValue); + +private: + QObject* m_object; + ObjectsList* m_objects; + QString m_name; + QString m_displayName; + QVariant m_value; + bool m_haveValue; + ObjectPropItem* m_parent; + QList m_childItems; + QList m_globalPropList; + int m_colorIndex; + bool m_readonly; + QAbstractItemModel* m_model; + QModelIndex m_index; + bool m_isClass; + bool m_changingValue; + bool m_translatePropperty; +}; + +typedef QPair APropIdent; +typedef ObjectPropItem* (*CreatePropItem)(QObject* object, ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& value, ObjectPropItem* parent, + bool readonly); + +class ObjectPropFactory: + public AttribsAbstractFactory { +private: + friend class Singleton; + +private: + ObjectPropFactory() { } + ~ObjectPropFactory() { } + ObjectPropFactory(const ObjectPropFactory&) { } + ObjectPropFactory& operator=(const ObjectPropFactory&) { return *this; } +}; + +} // namespace LimeReport Q_DECLARE_METATYPE(LimeReport::ObjectPropItem*) diff --git a/limereport/objectinspector/lrpropertydelegate.cpp b/limereport/objectinspector/lrpropertydelegate.cpp index cb5fa39..51a1a45 100644 --- a/limereport/objectinspector/lrpropertydelegate.cpp +++ b/limereport/objectinspector/lrpropertydelegate.cpp @@ -28,20 +28,28 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrpropertydelegate.h" -#include "lrobjectitemmodel.h" -#include "lrobjectinspectorwidget.h" -#include -#include -#include + #include "lrglobal.h" +#include "lrobjectinspectorwidget.h" +#include "lrobjectitemmodel.h" -LimeReport::PropertyDelegate::PropertyDelegate(QObject *parent) - :QStyledItemDelegate(parent), m_objectInspector(NULL), m_editingItem(0), m_isEditing(false) -{} +#include +#include +#include -void LimeReport::PropertyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +LimeReport::PropertyDelegate::PropertyDelegate(QObject* parent): + QStyledItemDelegate(parent), + m_objectInspector(NULL), + m_editingItem(0), + m_isEditing(false) { - if (!index.isValid()) return; +} + +void LimeReport::PropertyDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + if (!index.isValid()) + return; #if QT_VERSION >= 0x050000 QStyleOptionViewItem opt = option; @@ -49,147 +57,146 @@ void LimeReport::PropertyDelegate::paint(QPainter *painter, const QStyleOptionVi QStyleOptionViewItemV4 opt = option; #endif - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); + QStyle* style = opt.widget ? opt.widget->style() : QApplication::style(); - LimeReport::ObjectPropItem *node = qvariant_cast(index.data(Qt::UserRole)); - if (node){ - if (!node->isHaveValue()){ - if (index.column()==0) { + LimeReport::ObjectPropItem* node + = qvariant_cast(index.data(Qt::UserRole)); + if (node) { + if (!node->isHaveValue()) { + if (index.column() == 0) { StyleOptionViewItem cellOpt = option; - QTreeView const *tree = dynamic_cast(cellOpt.widget); + QTreeView const* tree = dynamic_cast(cellOpt.widget); QStyleOptionViewItem primitiveOpt = cellOpt; primitiveOpt.rect.setWidth(tree->indentation()); painter->save(); painter->setPen(option.palette.color(QPalette::HighlightedText)); painter->setBackground(QBrush(option.palette.color(QPalette::Highlight))); - cellOpt.widget->style()->drawPrimitive(QStyle::PE_IndicatorBranch,&primitiveOpt,painter); - cellOpt.rect.adjust(primitiveOpt.rect.width(),0,0,0); + cellOpt.widget->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &primitiveOpt, + painter); + cellOpt.rect.adjust(primitiveOpt.rect.width(), 0, 0, 0); cellOpt.font.setBold(true); - cellOpt.palette.setColor(QPalette::Text,cellOpt.palette.color(QPalette::BrightText)); + cellOpt.palette.setColor(QPalette::Text, + cellOpt.palette.color(QPalette::BrightText)); cellOpt.text = LimeReport::extractClassName(node->propertyName()); style->drawControl(QStyle::CE_ItemViewItem, &cellOpt, painter, cellOpt.widget); painter->restore(); } - } else { + } else { - StyleOptionViewItem so = option; - if ((node->isValueReadonly())&&(!node->isHaveChildren())) { - so.palette.setColor(QPalette::Text,so.palette.color(QPalette::Dark)); - } + StyleOptionViewItem so = option; + if ((node->isValueReadonly()) && (!node->isHaveChildren())) { + so.palette.setColor(QPalette::Text, so.palette.color(QPalette::Dark)); + } - QColor backgroundColor = (so.features & StyleOptionViewItem::Alternate) ? - so.palette.alternateBase().color() : - so.palette.base().color(); + QColor backgroundColor = (so.features & StyleOptionViewItem::Alternate) + ? so.palette.alternateBase().color() + : so.palette.base().color(); - qreal luma = 0.2126 * backgroundColor.red() + - 0.7152 * backgroundColor.green() + - 0.0722 * backgroundColor.blue(); + qreal luma = 0.2126 * backgroundColor.red() + 0.7152 * backgroundColor.green() + + 0.0722 * backgroundColor.blue(); - if (luma<128) - so.palette.setColor(QPalette::Text,Qt::white); - else - so.palette.setColor(QPalette::Text,Qt::black); + if (luma < 128) + so.palette.setColor(QPalette::Text, Qt::white); + else + so.palette.setColor(QPalette::Text, Qt::black); - opt.text = ""; - opt.rect.setHeight(opt.rect.height()-1); - style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); + opt.text = ""; + opt.rect.setHeight(opt.rect.height() - 1); + style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); - if (!node->paint(painter,so,index)){ - so.state &= ~QStyle::State_HasFocus; - so.rect.adjust(0,0,0,-1); - QStyledItemDelegate::paint(painter, so, index); - } + if (!node->paint(painter, so, index)) { + so.state &= ~QStyle::State_HasFocus; + so.rect.adjust(0, 0, 0, -1); + QStyledItemDelegate::paint(painter, so, index); + } - if (index.column()==0){ - QPointF start( - option.rect.x()+option.rect.width()-1, - option.rect.y() - ); - QPointF end( - option.rect.x()+option.rect.width()-1, - option.rect.y()+option.rect.height() - ); - painter->save(); - QColor color = static_cast(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &option)); - painter->setPen(color); - painter->drawLine(start,end); - painter->restore(); - } - - - } + if (index.column() == 0) { + QPointF start(option.rect.x() + option.rect.width() - 1, option.rect.y()); + QPointF end(option.rect.x() + option.rect.width() - 1, + option.rect.y() + option.rect.height()); + painter->save(); + QColor color = static_cast( + QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &option)); + painter->setPen(color); + painter->drawLine(start, end); + painter->restore(); + } + } } } -QSize LimeReport::PropertyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +QSize LimeReport::PropertyDelegate::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { - QSize size=option.rect.size(); - size.setHeight(option.fontMetrics.height()+ - QApplication::style()->pixelMetric(QStyle::PM_ButtonMargin) + QSize size = option.rect.size(); + size.setHeight(option.fontMetrics.height() + + QApplication::style()->pixelMetric(QStyle::PM_ButtonMargin) #ifdef Q_OS_MAC - +QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) + + QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) #endif - +4); - //return size; + + 4); + // return size; QSize defaultSize = QStyledItemDelegate::sizeHint(option, index); return size.height() > defaultSize.height() ? size : defaultSize; } -QWidget * LimeReport::PropertyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const +QWidget* LimeReport::PropertyDelegate::createEditor(QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { m_editingItem = qvariant_cast(index.data(Qt::UserRole)); - connect(m_editingItem,SIGNAL(destroyed(QObject*)), this, SLOT(slotItemDeleted(QObject*))); - QWidget *editor=m_editingItem->createProperyEditor(parent); - if (editor){ + connect(m_editingItem, SIGNAL(destroyed(QObject*)), this, SLOT(slotItemDeleted(QObject*))); + QWidget* editor = m_editingItem->createProperyEditor(parent); + if (editor) { m_isEditing = true; - editor->setMaximumHeight(option.rect.height()-1); + editor->setMaximumHeight(option.rect.height() - 1); editor->setGeometry(option.rect); - if (editor->metaObject()->indexOfSignal("editingFinished()")!=-1) - connect(editor,SIGNAL(editingFinished()),this,SLOT(commitAndCloseEditor())); - connect(editor,SIGNAL(destroyed()),this,SLOT(slotEditorDeleted())); + if (editor->metaObject()->indexOfSignal("editingFinished()") != -1) + connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor())); + connect(editor, SIGNAL(destroyed()), this, SLOT(slotEditorDeleted())); } return editor; } -void LimeReport::PropertyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +void LimeReport::PropertyDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { - if (m_editingItem) m_editingItem->setPropertyEditorData(editor,index); + if (m_editingItem) + m_editingItem->setPropertyEditorData(editor, index); } void LimeReport::PropertyDelegate::commitAndCloseEditor() { - QWidget *editor = qobject_cast(sender()); + QWidget* editor = qobject_cast(sender()); emit commitData(editor); emit closeEditor(editor); } -void LimeReport::PropertyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void LimeReport::PropertyDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, + const QModelIndex& index) const { - if (m_editingItem) m_editingItem->setModelData(editor,model,index); + if (m_editingItem) + m_editingItem->setModelData(editor, model, index); } -void LimeReport::PropertyDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const +void LimeReport::PropertyDelegate::updateEditorGeometry(QWidget* editor, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { - if (m_editingItem) m_editingItem->updateEditorGeometry(editor,option,index); + if (m_editingItem) + m_editingItem->updateEditorGeometry(editor, option, index); } void LimeReport::PropertyDelegate::setObjectInspector(ObjectInspectorTreeView* objectInspector) { - m_objectInspector=objectInspector; + m_objectInspector = objectInspector; } -void LimeReport::PropertyDelegate::slotEditorDeleted() +void LimeReport::PropertyDelegate::slotEditorDeleted() { m_isEditing = false; } + +void LimeReport::PropertyDelegate::slotItemDeleted(QObject* item) { - m_isEditing=false; -} - -void LimeReport::PropertyDelegate::slotItemDeleted(QObject *item) -{ - if (item == m_editingItem) m_editingItem = 0; -} - -LimeReport::ObjectPropItem* LimeReport::PropertyDelegate::editingItem() -{ - return m_editingItem; + if (item == m_editingItem) + m_editingItem = 0; } +LimeReport::ObjectPropItem* LimeReport::PropertyDelegate::editingItem() { return m_editingItem; } diff --git a/limereport/objectinspector/lrpropertydelegate.h b/limereport/objectinspector/lrpropertydelegate.h index f21c692..72d5b78 100644 --- a/limereport/objectinspector/lrpropertydelegate.h +++ b/limereport/objectinspector/lrpropertydelegate.h @@ -30,39 +30,42 @@ #ifndef LRPROPERTYDELEGATE_H #define LRPROPERTYDELEGATE_H -#include -#include -#include -#include - #include "lrobjectitemmodel.h" -namespace LimeReport{ +#include +#include +#include +#include + +namespace LimeReport { class ObjectInspectorTreeView; -//class PropertyDelegate : public QItemDelegate -class PropertyDelegate : public QStyledItemDelegate -{ +// class PropertyDelegate : public QItemDelegate +class PropertyDelegate: public QStyledItemDelegate { Q_OBJECT public: - PropertyDelegate(QObject *parent=0); + PropertyDelegate(QObject* parent = 0); void setObjectInspector(ObjectInspectorTreeView* objectInspector); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; + QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, + const QModelIndex& index) const; + void setEditorData(QWidget* editor, const QModelIndex& index) const; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const; + void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, + const QModelIndex& index) const; LimeReport::ObjectPropItem* editingItem(); - bool isEditing(){return m_isEditing;} + bool isEditing() { return m_isEditing; } private slots: void commitAndCloseEditor(); void slotEditorDeleted(); void slotItemDeleted(QObject* item); + private: LimeReport::ObjectInspectorTreeView* m_objectInspector; mutable LimeReport::ObjectPropItem* m_editingItem; mutable bool m_isEditing; }; -} +} // namespace LimeReport #endif // LRPROPERTYDELEGATE_H diff --git a/limereport/objectinspector/propertyItems/lraxispropitem.cpp b/limereport/objectinspector/propertyItems/lraxispropitem.cpp index 40466c4..a9f277b 100644 --- a/limereport/objectinspector/propertyItems/lraxispropitem.cpp +++ b/limereport/objectinspector/propertyItems/lraxispropitem.cpp @@ -7,45 +7,59 @@ #include namespace { -LimeReport::ObjectPropItem * createYAxisPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +LimeReport::ObjectPropItem* createYAxisPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { - return new LimeReport::AxisPropItem(object, objects, name, displayName, data, parent, readonly, false); + return new LimeReport::AxisPropItem(object, objects, name, displayName, data, parent, readonly, + false); } -LimeReport::ObjectPropItem * createXAxisPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +LimeReport::ObjectPropItem* createXAxisPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { - return new LimeReport::AxisPropItem(object, objects, name, displayName, data, parent, readonly, true); -} -bool VARIABLE_IS_NOT_USED registredXAxisProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("xAxisSettings", "LimeReport::ChartItem"), QObject::tr("X axis"), createXAxisPropItem); -bool VARIABLE_IS_NOT_USED registredYAxisProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("yAxisSettings", "LimeReport::ChartItem"), QObject::tr("Y axis"), createYAxisPropItem); + return new LimeReport::AxisPropItem(object, objects, name, displayName, data, parent, readonly, + true); } +bool VARIABLE_IS_NOT_USED registredXAxisProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("xAxisSettings", "LimeReport::ChartItem"), QObject::tr("X axis"), + createXAxisPropItem); +bool VARIABLE_IS_NOT_USED registredYAxisProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("yAxisSettings", "LimeReport::ChartItem"), QObject::tr("Y axis"), + createYAxisPropItem); +} // namespace namespace LimeReport { -QWidget *AxisPropItem::createProperyEditor(QWidget *parent) const +QWidget* AxisPropItem::createProperyEditor(QWidget* parent) const { return new AxisPropEditor(qobject_cast(object()), m_isXAxis, parent); } -QString AxisPropItem::displayValue() const -{ - return QObject::tr("Axis"); -} +QString AxisPropItem::displayValue() const { return QObject::tr("Axis"); } -AxisPropEditor::AxisPropEditor(ChartItem *chart, bool isXAxis, QWidget *parent) - : QWidget(parent), m_button(new QPushButton(this)), m_chart(chart), m_isXAxis(isXAxis) +AxisPropEditor::AxisPropEditor(ChartItem* chart, bool isXAxis, QWidget* parent): + QWidget(parent), + m_button(new QPushButton(this)), + m_chart(chart), + m_isXAxis(isXAxis) { m_button->setText("..."); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_button); layout->setSpacing(1); - layout->setContentsMargins(1,0,1,1); + layout->setContentsMargins(1, 0, 1, 1); setLayout(layout); setFocusProxy(m_button); setAutoFillBackground(true); - connect(m_button,SIGNAL(clicked()),this,SLOT(slotButtonClicked())); + connect(m_button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); } void AxisPropEditor::slotButtonClicked() @@ -54,4 +68,4 @@ void AxisPropEditor::slotButtonClicked() emit editingFinished(); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lraxispropitem.h b/limereport/objectinspector/propertyItems/lraxispropitem.h index 93fc08d..98dc28a 100644 --- a/limereport/objectinspector/propertyItems/lraxispropitem.h +++ b/limereport/objectinspector/propertyItems/lraxispropitem.h @@ -1,37 +1,41 @@ #ifndef AXISPROPITEM_H #define AXISPROPITEM_H -#include #include -#include -#include +#include +#include +#include namespace LimeReport { -class AxisPropEditor : public QWidget -{ +class AxisPropEditor: public QWidget { Q_OBJECT public: - AxisPropEditor(ChartItem* chart, bool isXAxis, QWidget *parent = 0); + AxisPropEditor(ChartItem* chart, bool isXAxis, QWidget* parent = 0); signals: void editingFinished(); private slots: void slotButtonClicked(); + private: QPushButton* m_button; ChartItem* m_chart; bool m_isXAxis; }; -class AxisPropItem: public LimeReport::ObjectPropItem -{ +class AxisPropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - AxisPropItem():ObjectPropItem(){} - AxisPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly, bool isXAxis) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly), m_isXAxis(isXAxis){} - QWidget* createProperyEditor(QWidget *parent) const; + AxisPropItem(): ObjectPropItem() { } + AxisPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly, bool isXAxis): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly), + m_isXAxis(isXAxis) + { + } + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; private: diff --git a/limereport/objectinspector/propertyItems/lrboolpropitem.cpp b/limereport/objectinspector/propertyItems/lrboolpropitem.cpp index 0529453..578a809 100644 --- a/limereport/objectinspector/propertyItems/lrboolpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrboolpropitem.cpp @@ -28,46 +28,53 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrboolpropitem.h" -#include "lrobjectpropitem.h" -#include -#include -#include -#include #include "../editors/lrcheckboxeditor.h" +#include "lrobjectpropitem.h" -namespace{ - LimeReport::ObjectPropItem * createBoolPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::BoolPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("bool",""),QObject::tr("bool"),createBoolPropItem); +#include +#include +#include +#include + +namespace { +LimeReport::ObjectPropItem* createBoolPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::BoolPropItem(object, objects, name, displayName, data, parent, readonly); +} +bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("bool", ""), QObject::tr("bool"), createBoolPropItem); } // namespace namespace LimeReport { -QWidget *BoolPropItem::createProperyEditor(QWidget *parent) const +QWidget* BoolPropItem::createProperyEditor(QWidget* parent) const { - CheckBoxEditor *editor= new CheckBoxEditor(parent); + CheckBoxEditor* editor = new CheckBoxEditor(parent); return editor; } -void BoolPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void BoolPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - CheckBoxEditor *editor =qobject_cast(propertyEditor); + CheckBoxEditor* editor = qobject_cast(propertyEditor); editor->setEditing(true); editor->setChecked(propertyValue().toBool()); editor->setEditing(false); } -void BoolPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void BoolPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->isChecked()); - setValueToObject(propertyName(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->isChecked()); + setValueToObject(propertyName(), propertyValue()); } -QPixmap BoolPropItem::getIndicatorImage(const StyleOptionViewItem &option){ +QPixmap BoolPropItem::getIndicatorImage(const StyleOptionViewItem& option) +{ QStyleOptionButton so; so.state = option.state; if (!isValueReadonly()) @@ -75,34 +82,35 @@ QPixmap BoolPropItem::getIndicatorImage(const StyleOptionViewItem &option){ else so.state &= ~QStyle::State_Enabled; so.state |= propertyValue().toBool() ? QStyle::State_On : QStyle::State_Off; - so.rect = QRect(0,0, - QApplication::style()->pixelMetric(QStyle::PM_IndicatorWidth), + so.rect = QRect(0, 0, QApplication::style()->pixelMetric(QStyle::PM_IndicatorWidth), QApplication::style()->pixelMetric(QStyle::PM_IndicatorHeight)); - QPixmap pixmap(so.rect.width(),so.rect.height()); + QPixmap pixmap(so.rect.width(), so.rect.height()); pixmap.fill(Qt::transparent); QPainter p(&pixmap); - option.widget->style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck,&so, &p); + option.widget->style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck, &so, &p); return pixmap; } -bool BoolPropItem::paint(QPainter *painter, const StyleOptionViewItem &option, const QModelIndex &index) +bool BoolPropItem::paint(QPainter* painter, const StyleOptionViewItem& option, + const QModelIndex& index) { QStyle* style = option.widget ? option.widget->style() : QApplication::style(); - if (index.column()==1){ - int border = (option.rect.height() - style->pixelMetric(QStyle::PM_IndicatorWidth))/2; -// QStyleOptionButton so; -// so.rect = option.rect.adjusted(border,border,0,-border); -// so.rect.setWidth(style->pixelMetric(QStyle::PM_IndicatorWidth)); -// so.rect.setHeight(style->pixelMetric(QStyle::PM_IndicatorHeight)); -// so.state |= propertyValue().toBool() ? QStyle::State_On : QStyle::State_Off; -// style->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck,&so,painter); - painter->drawPixmap(option.rect.x()+border,option.rect.y()+border, getIndicatorImage(option)); + if (index.column() == 1) { + int border = (option.rect.height() - style->pixelMetric(QStyle::PM_IndicatorWidth)) / 2; + // QStyleOptionButton so; + // so.rect = option.rect.adjusted(border,border,0,-border); + // so.rect.setWidth(style->pixelMetric(QStyle::PM_IndicatorWidth)); + // so.rect.setHeight(style->pixelMetric(QStyle::PM_IndicatorHeight)); + // so.state |= propertyValue().toBool() ? QStyle::State_On : QStyle::State_Off; + // style->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck,&so,painter); + painter->drawPixmap(option.rect.x() + border, option.rect.y() + border, + getIndicatorImage(option)); return true; - } else return false; + } else + return false; } } // namespace LimeReport - diff --git a/limereport/objectinspector/propertyItems/lrboolpropitem.h b/limereport/objectinspector/propertyItems/lrboolpropitem.h index fec0c83..f64269d 100644 --- a/limereport/objectinspector/propertyItems/lrboolpropitem.h +++ b/limereport/objectinspector/propertyItems/lrboolpropitem.h @@ -33,20 +33,25 @@ #include "lrobjectpropitem.h" namespace LimeReport { -class BoolPropItem : public ObjectPropItem -{ +class BoolPropItem: public ObjectPropItem { Q_OBJECT public: - BoolPropItem():ObjectPropItem(){} - BoolPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - virtual QString displayValue() const {return "";} - virtual QWidget* createProperyEditor(QWidget *parent) const; - virtual void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - virtual void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); - bool paint(QPainter *painter, const StyleOptionViewItem &option, const QModelIndex &index); + BoolPropItem(): ObjectPropItem() { } + BoolPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + virtual QString displayValue() const { return ""; } + virtual QWidget* createProperyEditor(QWidget* parent) const; + virtual void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + virtual void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index); + bool paint(QPainter* painter, const StyleOptionViewItem& option, const QModelIndex& index); + protected: - QPixmap getIndicatorImage(const StyleOptionViewItem &option); + QPixmap getIndicatorImage(const StyleOptionViewItem& option); }; } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrcolorpropitem.cpp b/limereport/objectinspector/propertyItems/lrcolorpropitem.cpp index 96e9e5b..0aaf868 100644 --- a/limereport/objectinspector/propertyItems/lrcolorpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrcolorpropitem.cpp @@ -28,60 +28,72 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrcolorpropitem.h" -#include "lrglobal.h" + #include "editors/lrcoloreditor.h" -#include +#include "lrglobal.h" + #include +#include -namespace{ - LimeReport::ObjectPropItem * createColorPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::ColorPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredColorProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QColor",""),QObject::tr("QColor"),createColorPropItem); -} - -namespace LimeReport{ - -void ColorPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +namespace { +LimeReport::ObjectPropItem* createColorPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { - ColorEditor *editor =qobject_cast(propertyEditor); + return new LimeReport::ColorPropItem(object, objects, name, displayName, data, parent, + readonly); +} +bool VARIABLE_IS_NOT_USED registredColorProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QColor", ""), QObject::tr("QColor"), createColorPropItem); +} // namespace + +namespace LimeReport { + +void ColorPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const +{ + ColorEditor* editor = qobject_cast(propertyEditor); editor->setColor(propertyValue().value()); } -void ColorPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void ColorPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->color()); - setValueToObject(propertyName(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->color()); + setValueToObject(propertyName(), propertyValue()); } -bool ColorPropItem::paint(QPainter *painter, const StyleOptionViewItem &option, const QModelIndex &index) +bool ColorPropItem::paint(QPainter* painter, const StyleOptionViewItem& option, + const QModelIndex& index) { - if (index.column()==1){ + if (index.column() == 1) { painter->save(); QStyle* style = option.widget ? option.widget->style() : QApplication::style(); QPen pen; - QColor penColor = isColorDark(propertyValue().value()) ? Qt::transparent : Qt::darkGray; + QColor penColor + = isColorDark(propertyValue().value()) ? Qt::transparent : Qt::darkGray; pen.setColor(penColor); painter->setPen(pen); painter->setBrush(propertyValue().value()); - int border = (option.rect.height() - style->pixelMetric(QStyle::PM_IndicatorWidth))/2; + int border = (option.rect.height() - style->pixelMetric(QStyle::PM_IndicatorWidth)) / 2; - QRect rect(option.rect.x()+border,option.rect.y()+border, + QRect rect(option.rect.x() + border, option.rect.y() + border, style->pixelMetric(QStyle::PM_IndicatorWidth), style->pixelMetric(QStyle::PM_IndicatorWidth)); painter->drawRect(rect); painter->restore(); return true; - } else return false; + } else + return false; } -QWidget *ColorPropItem::createProperyEditor(QWidget *parent) const +QWidget* ColorPropItem::createProperyEditor(QWidget* parent) const { return new ColorEditor(parent); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrcolorpropitem.h b/limereport/objectinspector/propertyItems/lrcolorpropitem.h index b30f697..b4206b9 100644 --- a/limereport/objectinspector/propertyItems/lrcolorpropitem.h +++ b/limereport/objectinspector/propertyItems/lrcolorpropitem.h @@ -32,20 +32,23 @@ #include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class ColorPropItem : public ObjectPropItem -{ +class ColorPropItem: public ObjectPropItem { Q_OBJECT public: - ColorPropItem():ObjectPropItem(){} - ColorPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index); - bool paint(QPainter *painter, const StyleOptionViewItem &option, const QModelIndex &index); + ColorPropItem(): ObjectPropItem() { } + ColorPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); + bool paint(QPainter* painter, const StyleOptionViewItem& option, const QModelIndex& index); }; -} +} // namespace LimeReport #endif // LRCOLORPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrcontentpropitem.cpp b/limereport/objectinspector/propertyItems/lrcontentpropitem.cpp index cc50ced..043e953 100644 --- a/limereport/objectinspector/propertyItems/lrcontentpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrcontentpropitem.cpp @@ -1,38 +1,47 @@ #include "lrcontentpropitem.h" -#include "lrtextitem.h" + #include "editors/lrbuttonlineeditor.h" #include "items/lrtextitemeditor.h" +#include "lrtextitem.h" + #include -namespace{ - LimeReport::ObjectPropItem * createContentPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::ContentPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredContentProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("content","LimeReport::TextItem"),QObject::tr("content"),createContentPropItem); +namespace { +LimeReport::ObjectPropItem* createContentPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::ContentPropItem(object, objects, name, displayName, data, parent, + readonly); +} +bool VARIABLE_IS_NOT_USED registredContentProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("content", "LimeReport::TextItem"), QObject::tr("content"), + createContentPropItem); } // namespace namespace LimeReport { -QWidget *ContentPropItem::createProperyEditor(QWidget *parent) const +QWidget* ContentPropItem::createProperyEditor(QWidget* parent) const { - return new ContentEditor(object(), object()->objectName()+"."+displayName(), parent); + return new ContentEditor(object(), object()->objectName() + "." + displayName(), parent); } void ContentEditor::editButtonClicked() { QDialog* dialog = new QDialog(QApplication::activeWindow()); dialog->setLayout(new QVBoxLayout()); - dialog->layout()->setContentsMargins(1,1,1,1); + dialog->layout()->setContentsMargins(1, 1, 1, 1); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setWindowTitle(propertyName()); QWidget* editor = dynamic_cast(m_object)->defaultEditor(); dialog->layout()->addWidget(editor); dialog->resize(editor->size()); - connect(editor,SIGNAL(destroyed()),dialog,SLOT(close())); - connect(editor,SIGNAL(destroyed()),this,SIGNAL(editingFinished())); + connect(editor, SIGNAL(destroyed()), dialog, SLOT(close())); + connect(editor, SIGNAL(destroyed()), this, SIGNAL(editingFinished())); dialog->exec(); } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrcontentpropitem.h b/limereport/objectinspector/propertyItems/lrcontentpropitem.h index 3c91b27..845e219 100644 --- a/limereport/objectinspector/propertyItems/lrcontentpropitem.h +++ b/limereport/objectinspector/propertyItems/lrcontentpropitem.h @@ -6,24 +6,32 @@ namespace LimeReport { -class ContentEditor : public ButtonLineEditor{ +class ContentEditor: public ButtonLineEditor { Q_OBJECT public: - explicit ContentEditor(QObject* object, const QString& propertyName,QWidget *parent = 0) - :ButtonLineEditor(propertyName,parent), m_object(object){} + explicit ContentEditor(QObject* object, const QString& propertyName, QWidget* parent = 0): + ButtonLineEditor(propertyName, parent), + m_object(object) + { + } public slots: void editButtonClicked(); + private: QObject* m_object; }; -class ContentPropItem : public StringPropItem{ +class ContentPropItem: public StringPropItem { Q_OBJECT public: - ContentPropItem():StringPropItem(){} - ContentPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly) - :StringPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; + ContentPropItem(): StringPropItem() { } + ContentPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + StringPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; }; } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrdatasourcepropitem.cpp b/limereport/objectinspector/propertyItems/lrdatasourcepropitem.cpp index 15da9fb..3be6b40 100644 --- a/limereport/objectinspector/propertyItems/lrdatasourcepropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrdatasourcepropitem.cpp @@ -28,98 +28,125 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrdatasourcepropitem.h" -#include "lrobjectpropitem.h" -#include "lrbasedesignintf.h" -#include "lrreportengine_p.h" + #include "../editors/lrcomboboxeditor.h" +#include "lrbasedesignintf.h" +#include "lrobjectpropitem.h" +#include "lrreportengine_p.h" + #include -namespace{ - LimeReport::ObjectPropItem * createDatasourcePropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::DatasourcePropItem(object, objects, name, displayName, data, parent, readonly); - } - - LimeReport::ObjectPropItem* createFieldPropItem(QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly){ - return new LimeReport::FieldPropItem(object, objects, name, displayName, data, parent, readonly); - } - - bool VARIABLE_IS_NOT_USED registredDatasouceProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::DataBandDesignIntf"),QObject::tr("datasource"),createDatasourcePropItem - ); - - bool VARIABLE_IS_NOT_USED registredImageDatasouceProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::ImageItem"),QObject::tr("datasource"),createDatasourcePropItem - ); - - bool VARIABLE_IS_NOT_USED registredImageFieldProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("field","LimeReport::ImageItem"),QObject::tr("field"),createFieldPropItem - ); - - bool VARIABLE_IS_NOT_USED registredChartDatasouceProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::ChartItem"),QObject::tr("datasource"),createDatasourcePropItem - ); - - bool VARIABLE_IS_NOT_USED registredBarcodeDatasouceProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::BarcodeItem"),QObject::tr("datasource"),createDatasourcePropItem - ); - - bool VARIABLE_IS_NOT_USED registredBarcodeFieldProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("field","LimeReport::BarcodeItem"),QObject::tr("field"),createFieldPropItem - ); - - bool VARIABLE_IS_NOT_USED registredSVGItemDatasouceProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("datasource","LimeReport::SVGItem"),QObject::tr("datasource"),createDatasourcePropItem - ); - - bool VARIABLE_IS_NOT_USED registredSVGFieldProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("field","LimeReport::SVGItem"),QObject::tr("field"),createFieldPropItem - ); +namespace { +LimeReport::ObjectPropItem* +createDatasourcePropItem(QObject* object, LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::DatasourcePropItem(object, objects, name, displayName, data, parent, + readonly); } -QWidget* LimeReport::DatasourcePropItem::createProperyEditor(QWidget *parent) const{ - ComboBoxEditor *editor = new ComboBoxEditor(parent,true); +LimeReport::ObjectPropItem* createFieldPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::FieldPropItem(object, objects, name, displayName, data, parent, + readonly); +} + +bool VARIABLE_IS_NOT_USED registredDatasouceProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("datasource", "LimeReport::DataBandDesignIntf"), + QObject::tr("datasource"), createDatasourcePropItem); + +bool VARIABLE_IS_NOT_USED registredImageDatasouceProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("datasource", "LimeReport::ImageItem"), QObject::tr("datasource"), + createDatasourcePropItem); + +bool VARIABLE_IS_NOT_USED registredImageFieldProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("field", "LimeReport::ImageItem"), QObject::tr("field"), + createFieldPropItem); + +bool VARIABLE_IS_NOT_USED registredChartDatasouceProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("datasource", "LimeReport::ChartItem"), QObject::tr("datasource"), + createDatasourcePropItem); + +bool VARIABLE_IS_NOT_USED registredBarcodeDatasouceProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("datasource", "LimeReport::BarcodeItem"), QObject::tr("datasource"), + createDatasourcePropItem); + +bool VARIABLE_IS_NOT_USED registredBarcodeFieldProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("field", "LimeReport::BarcodeItem"), QObject::tr("field"), + createFieldPropItem); + +bool VARIABLE_IS_NOT_USED registredSVGItemDatasouceProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("datasource", "LimeReport::SVGItem"), QObject::tr("datasource"), + createDatasourcePropItem); + +bool VARIABLE_IS_NOT_USED registredSVGFieldProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("field", "LimeReport::SVGItem"), QObject::tr("field"), + createFieldPropItem); +} // namespace + +QWidget* LimeReport::DatasourcePropItem::createProperyEditor(QWidget* parent) const +{ + ComboBoxEditor* editor = new ComboBoxEditor(parent, true); editor->setEditable(true); - LimeReport::BaseDesignIntf *item=dynamic_cast(object()); - if (item){ - editor->addItems(item->reportEditor()->dataManager()->dataSourceNames()); + LimeReport::BaseDesignIntf* item = dynamic_cast(object()); + if (item) { + editor->addItems(item->reportEditor()->dataManager()->dataSourceNames()); } return editor; } -void LimeReport::DatasourcePropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const{ - ComboBoxEditor *editor=qobject_cast(propertyEditor); +void LimeReport::DatasourcePropItem::setPropertyEditorData(QWidget* propertyEditor, + const QModelIndex&) const +{ + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(propertyValue().toString()); } -void LimeReport::DatasourcePropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index){ - model->setData(index,qobject_cast(propertyEditor)->text()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); +void LimeReport::DatasourcePropItem::setModelData(QWidget* propertyEditor, + QAbstractItemModel* model, + const QModelIndex& index) +{ + model->setData(index, qobject_cast(propertyEditor)->text()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } - -QWidget *LimeReport::FieldPropItem::createProperyEditor(QWidget *parent) const +QWidget* LimeReport::FieldPropItem::createProperyEditor(QWidget* parent) const { - ComboBoxEditor *editor = new ComboBoxEditor(parent); + ComboBoxEditor* editor = new ComboBoxEditor(parent); editor->setEditable(true); - LimeReport::BaseDesignIntf *item=dynamic_cast(object()); + LimeReport::BaseDesignIntf* item = dynamic_cast(object()); int propertyIndex = object()->metaObject()->indexOfProperty("datasource"); - if (item && propertyIndex>0){ - editor->addItems(item->reportEditor()->dataManager()->fieldNames(object()->property("datasource").toString())); + if (item && propertyIndex > 0) { + editor->addItems(item->reportEditor()->dataManager()->fieldNames( + object()->property("datasource").toString())); } return editor; } -void LimeReport::FieldPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void LimeReport::FieldPropItem::setPropertyEditorData(QWidget* propertyEditor, + const QModelIndex&) const { - ComboBoxEditor *editor=qobject_cast(propertyEditor); + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(propertyValue().toString()); } -void LimeReport::FieldPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void LimeReport::FieldPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->text()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->text()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } diff --git a/limereport/objectinspector/propertyItems/lrdatasourcepropitem.h b/limereport/objectinspector/propertyItems/lrdatasourcepropitem.h index 7149325..80799bd 100644 --- a/limereport/objectinspector/propertyItems/lrdatasourcepropitem.h +++ b/limereport/objectinspector/propertyItems/lrdatasourcepropitem.h @@ -31,31 +31,37 @@ #define LRDATASOURCEPROPITEM_H #include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class DatasourcePropItem : public LimeReport::ObjectPropItem -{ +class DatasourcePropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - DatasourcePropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget *, const QModelIndex &) const; - void setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &); + DatasourcePropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget*, const QModelIndex&) const; + void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&); }; -class FieldPropItem : public LimeReport::ObjectPropItem -{ +class FieldPropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - FieldPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *, const QModelIndex &index); + FieldPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel*, const QModelIndex& index); }; -} +} // namespace LimeReport #endif // LRDATASOURCEPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrenumpropitem.cpp b/limereport/objectinspector/propertyItems/lrenumpropitem.cpp index 9addfd2..76f0af9 100644 --- a/limereport/objectinspector/propertyItems/lrenumpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrenumpropitem.cpp @@ -28,35 +28,43 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrenumpropitem.h" + #include "../editors/lrcomboboxeditor.h" #include "lrbanddesignintf.h" namespace { -LimeReport::ObjectPropItem * createEnumPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +LimeReport::ObjectPropItem* createEnumPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { return new LimeReport::EnumPropItem(object, objects, name, displayName, data, parent, readonly); } bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("enum",""),QObject::tr("enum"),createEnumPropItem -); + LimeReport::APropIdent("enum", ""), QObject::tr("enum"), createEnumPropItem); -} +} // namespace namespace LimeReport { -QWidget *EnumPropItem::createProperyEditor(QWidget *parent) const +QWidget* EnumPropItem::createProperyEditor(QWidget* parent) const { - ComboBoxEditor *editor = new ComboBoxEditor(parent,false); - connect(editor,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotEnumChanged(QString))); + ComboBoxEditor* editor = new ComboBoxEditor(parent, false); + connect(editor, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotEnumChanged(QString))); QStringList enumValues; - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); - for (int i=0;imetaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); + for (int i = 0; i < propEnum.keyCount(); i++) { + if (m_acceptableValues.isEmpty()) + enumValues.append(tr(propEnum.key(i))); else { - if (m_acceptableValues.contains(propEnum.value(i))){ + if (m_acceptableValues.contains(propEnum.value(i))) { enumValues.append(tr(propEnum.key(i))); } } @@ -65,20 +73,24 @@ QWidget *EnumPropItem::createProperyEditor(QWidget *parent) const return editor; } -void EnumPropItem::slotEnumChanged(const QString &text) +void EnumPropItem::slotEnumChanged(const QString& text) { - if ( nameByType(object()->property(propertyName().toLatin1()).toInt())!=text){ + if (nameByType(object()->property(propertyName().toLatin1()).toInt()) != text) { beginChangeValue(); setPropertyValue(typeByName(text)); - setValueToObject(propertyName(),typeByName(text)); + setValueToObject(propertyName(), typeByName(text)); endChangeValue(); } } void EnumPropItem::initTranslation() { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); - for (int i=0;imetaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); + for (int i = 0; i < propEnum.keyCount(); i++) { m_translation.insert(QString(tr(propEnum.key(i))), QString(propEnum.key(i))); } } @@ -168,36 +180,42 @@ void EnumPropItem::translateEnumItemName() tr("DashDotLine"); tr("DashDotDotLine"); tr("CustomDashLine"); - } -void EnumPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void EnumPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - ComboBoxEditor *editor=qobject_cast(propertyEditor); + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(nameByType(propertyValue().toInt())); } -void EnumPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void EnumPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - setValueToObject(propertyName(),typeByName(qobject_cast(propertyEditor)->text())); - model->setData(index,object()->property(propertyName().toLatin1())); + setValueToObject(propertyName(), + typeByName(qobject_cast(propertyEditor)->text())); + model->setData(index, object()->property(propertyName().toLatin1())); } QString EnumPropItem::nameByType(int value) const { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); + QMetaEnum propEnum + = object() + ->metaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); return isTranslateProperty() ? tr(propEnum.valueToKey(value)) : propEnum.valueToKey(value); } -int EnumPropItem::typeByName(const QString &value) const +int EnumPropItem::typeByName(const QString& value) const { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); + QMetaEnum propEnum + = object() + ->metaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); return propEnum.keyToValue(m_translation.value(value).toLatin1()); } -QString EnumPropItem::displayValue() const -{ - return nameByType((propertyValue().toInt())); -} +QString EnumPropItem::displayValue() const { return nameByType((propertyValue().toInt())); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrenumpropitem.h b/limereport/objectinspector/propertyItems/lrenumpropitem.h index b610e20..106f69c 100644 --- a/limereport/objectinspector/propertyItems/lrenumpropitem.h +++ b/limereport/objectinspector/propertyItems/lrenumpropitem.h @@ -31,35 +31,51 @@ #define LRENUMPROPITEM_H #include "lrobjectpropitem.h" + #include -namespace LimeReport{ -class EnumPropItem : public ObjectPropItem -{ +namespace LimeReport { +class EnumPropItem: public ObjectPropItem { Q_OBJECT public: - EnumPropItem():ObjectPropItem(), m_settingValue(false){initTranslation();} - EnumPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly),m_settingValue(false){initTranslation();} - EnumPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly, QVector acceptableValues) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly),m_acceptableValues(acceptableValues),m_settingValue(false){initTranslation();} - QWidget* createProperyEditor(QWidget *parent) const; - QString displayValue() const; - void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); - QVector acceptableValues() const {return m_acceptableValues;} + EnumPropItem(): ObjectPropItem(), m_settingValue(false) { initTranslation(); } + EnumPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly), + m_settingValue(false) + { + initTranslation(); + } + EnumPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly, QVector acceptableValues): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly), + m_acceptableValues(acceptableValues), + m_settingValue(false) + { + initTranslation(); + } + QWidget* createProperyEditor(QWidget* parent) const; + QString displayValue() const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); + QVector acceptableValues() const { return m_acceptableValues; } + protected: QString nameByType(int propertyValue) const; - int typeByName(const QString& propertyValue) const; + int typeByName(const QString& propertyValue) const; private slots: void slotEnumChanged(const QString& text); + private: void initTranslation(); void translateEnumItemName(); + private: QVector m_acceptableValues; bool m_settingValue; QMap m_translation; }; -} +} // namespace LimeReport #endif // LRENUMPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrflagspropitem.cpp b/limereport/objectinspector/propertyItems/lrflagspropitem.cpp index d932144..261a19a 100644 --- a/limereport/objectinspector/propertyItems/lrflagspropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrflagspropitem.cpp @@ -28,10 +28,12 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrflagspropitem.h" -#include "lrenumpropitem.h" -#include "lrboolpropitem.h" + #include "../editors/lrcheckboxeditor.h" +#include "lrboolpropitem.h" +#include "lrenumpropitem.h" #include "lrobjectitemmodel.h" + #include #include #include @@ -40,14 +42,17 @@ namespace { -LimeReport::ObjectPropItem * createFlagsPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +LimeReport::ObjectPropItem* createFlagsPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { - return new LimeReport::FlagsPropItem(object, objects, name, displayName, data, parent, readonly); + return new LimeReport::FlagsPropItem(object, objects, name, displayName, data, parent, + readonly); } bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("flags",""),QObject::tr("flags"),createFlagsPropItem -); + LimeReport::APropIdent("flags", ""), QObject::tr("flags"), createFlagsPropItem); } // namespace @@ -55,52 +60,73 @@ namespace LimeReport { void FlagsPropItem::createChildren() { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); - for (int i=0;imetaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); + for (int i = 0; i < propEnum.keyCount(); i++) { + if (propEnum.keyToValue(propEnum.key(i)) != 0) { this->appendItem(new LimeReport::FlagPropItem( - object(), objects(), QString(propEnum.key(i)), tr(propEnum.key(i)), - bool((propertyValue().toInt() & propEnum.keyToValue(propEnum.key(i)))==propEnum.keyToValue(propEnum.key(i))), - this, false - ) - ); + object(), objects(), QString(propEnum.key(i)), tr(propEnum.key(i)), + bool((propertyValue().toInt() & propEnum.keyToValue(propEnum.key(i))) + == propEnum.keyToValue(propEnum.key(i))), + this, false)); } } } void FlagsPropItem::updateChildren() { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); - for (int i=0;imetaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); + for (int i = 0; i < propEnum.keyCount(); i++) { ObjectPropItem* property = findChild(QString(propEnum.key(i))); if (property) - property->setPropertyValue(bool((propertyValue().toInt() & propEnum.keyToValue(propEnum.key(i)))==propEnum.keyToValue(propEnum.key(i)))); + property->setPropertyValue( + bool((propertyValue().toInt() & propEnum.keyToValue(propEnum.key(i))) + == propEnum.keyToValue(propEnum.key(i)))); } } -FlagsPropItem::FlagsPropItem(QObject *object, ObjectPropItem::ObjectsList *objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly) +FlagsPropItem::FlagsPropItem(QObject* object, ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) { createChildren(); } -FlagsPropItem::FlagsPropItem(QObject *object, ObjectPropItem::ObjectsList *objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly, QSet acceptableValues) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly),m_acceptableValues(acceptableValues){} +FlagsPropItem::FlagsPropItem(QObject* object, ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly, QSet acceptableValues): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly), + m_acceptableValues(acceptableValues) +{ +} QString FlagsPropItem::displayValue() const { QString result; - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())).enumerator(); - for (int i=0;imetaObject() + ->property(object()->metaObject()->indexOfProperty(propertyName().toLatin1())) + .enumerator(); + for (int i = 0; i < propEnum.keyCount(); i++) { + if ((propEnum.keyToValue(propEnum.key(i)) == 0) + ? propertyValue().toInt() == 0 + : (propertyValue().toInt() & propEnum.keyToValue(propEnum.key(i))) + == propEnum.keyToValue(propEnum.key(i))) { + if (result.isEmpty()) + result += isTranslateProperty() ? tr(propEnum.key(i)) : propEnum.key(i); + else + result = result + " | " + + (isTranslateProperty() ? tr(propEnum.key(i)) : propEnum.key(i)); } - } return result; } @@ -111,9 +137,7 @@ void FlagsPropItem::setPropertyValue(QVariant value) updateChildren(); } -void FlagsPropItem::slotEnumChanged(QString /*text*/) -{ -} +void FlagsPropItem::slotEnumChanged(QString /*text*/) { } void FlagsPropItem::translateFlagsItem() { @@ -125,34 +149,42 @@ void FlagsPropItem::translateFlagsItem() tr("AllLines"); } -FlagPropItem::FlagPropItem(QObject* object, ObjectsList* objects, const QString &propName, const QString &displayName, const QVariant &value, ObjectPropItem* parent, bool readonly) - :BoolPropItem(object, objects, propName,displayName,value,parent,readonly) +FlagPropItem::FlagPropItem(QObject* object, ObjectsList* objects, const QString& propName, + const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + BoolPropItem(object, objects, propName, displayName, value, parent, readonly) { } -void FlagPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &/*index*/) const +void FlagPropItem::setPropertyEditorData(QWidget* propertyEditor, + const QModelIndex& /*index*/) const { - CheckBoxEditor *editor = qobject_cast(propertyEditor); + CheckBoxEditor* editor = qobject_cast(propertyEditor); editor->setChecked(propertyValue().toBool()); } -void FlagPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void FlagPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { bool value = qobject_cast(propertyEditor)->isChecked(); - model->setData(index,value); + model->setData(index, value); int flags = object()->property(parent()->propertyName().toLatin1()).toInt(); - if (value) flags = flags | valueByName(propertyName()); - else if (flags & valueByName(propertyName())) flags = flags ^ valueByName(propertyName()); - setValueToObject(parent()->propertyName(),flags); + if (value) + flags = flags | valueByName(propertyName()); + else if (flags & valueByName(propertyName())) + flags = flags ^ valueByName(propertyName()); + setValueToObject(parent()->propertyName(), flags); parent()->setPropertyValue(flags); } int FlagPropItem::valueByName(const QString& typeName) { - QMetaEnum propEnum = object()->metaObject()->property(object()->metaObject()->indexOfProperty(parent()->propertyName().toLatin1())).enumerator(); + QMetaEnum propEnum = object() + ->metaObject() + ->property(object()->metaObject()->indexOfProperty( + parent()->propertyName().toLatin1())) + .enumerator(); return propEnum.keyToValue(typeName.toLatin1()); } } // namespace LimeReport - - diff --git a/limereport/objectinspector/propertyItems/lrflagspropitem.h b/limereport/objectinspector/propertyItems/lrflagspropitem.h index dae5e96..a939265 100644 --- a/limereport/objectinspector/propertyItems/lrflagspropitem.h +++ b/limereport/objectinspector/propertyItems/lrflagspropitem.h @@ -30,43 +30,50 @@ #ifndef LRFLAGSPROPEDITOR_H #define LRFLAGSPROPEDITOR_H -#include "lrobjectpropitem.h" #include "lrboolpropitem.h" +#include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class FlagsPropItem : public ObjectPropItem -{ +class FlagsPropItem: public ObjectPropItem { Q_OBJECT public: - FlagsPropItem():ObjectPropItem(){} - FlagsPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly); - FlagsPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly, QSet acceptableValues); + FlagsPropItem(): ObjectPropItem() { } + FlagsPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly); + FlagsPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly, QSet acceptableValues); virtual QString displayValue() const; - virtual void setPropertyValue(QVariant propertyValue); + virtual void setPropertyValue(QVariant propertyValue); private slots: void slotEnumChanged(QString); + private: void translateFlagsItem(); + private: QSet m_acceptableValues; QString nameByType(int propertyValue) const; - int typeByName(QString propertyValue) const; + int typeByName(QString propertyValue) const; void createChildren(); void updateChildren(); }; -class FlagPropItem : public BoolPropItem{ +class FlagPropItem: public BoolPropItem { public: - FlagPropItem():BoolPropItem(){} - FlagPropItem(QObject* object, ObjectsList* objects, const QString& propName, const QString& displayName, const QVariant& propertyValue, ObjectPropItem* parent, bool readonly); - virtual void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex & ) const; - virtual void setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &); - virtual QString displayValue() const{return "";} -private: - int valueByName(const QString &typeName); -}; + FlagPropItem(): BoolPropItem() { } + FlagPropItem(QObject* object, ObjectsList* objects, const QString& propName, + const QString& displayName, const QVariant& propertyValue, ObjectPropItem* parent, + bool readonly); + virtual void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + virtual void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&); + virtual QString displayValue() const { return ""; } +private: + int valueByName(const QString& typeName); +}; } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrfontpropitem.cpp b/limereport/objectinspector/propertyItems/lrfontpropitem.cpp index 58f26fe..dbea345 100644 --- a/limereport/objectinspector/propertyItems/lrfontpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrfontpropitem.cpp @@ -27,35 +27,48 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include - #include "lrfontpropitem.h" + #include "editors/lrbuttonlineeditor.h" -#include "editors/lrfonteditor.h" #include "editors/lrcheckboxeditor.h" +#include "editors/lrfonteditor.h" #include "lrobjectitemmodel.h" -namespace{ - LimeReport::ObjectPropItem * createFontPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::FontPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredFontProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QFont",""),QObject::tr("QFont"),createFontPropItem); +#include + +namespace { +LimeReport::ObjectPropItem* createFontPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::FontPropItem(object, objects, name, displayName, data, parent, readonly); } +bool VARIABLE_IS_NOT_USED registredFontProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QFont", ""), QObject::tr("QFont"), createFontPropItem); +} // namespace +namespace LimeReport { -namespace LimeReport{ - -FontPropItem::FontPropItem(QObject *object, ObjectPropItem::ObjectsList *objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly) +FontPropItem::FontPropItem(QObject* object, ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) { - m_bold = new FontAttribPropItem(object,objects,"bold",tr("bold"),propertyValue().value().bold(),this,false); - m_italic = new FontAttribPropItem(object,objects,"italic",tr("italic"),propertyValue().value().italic(),this,false); - m_underline = new FontAttribPropItem(object,objects,"underline",tr("underline"),propertyValue().value().underline(),this,false); - m_pointSize = new FontPointSizePropItem(object,0,"pointSize",tr("size"),propertyValue().value().pointSize(),this,false); - m_family = new FontFamilyPropItem(object,0,"family",tr("family"),propertyValue().value(),this,false); + m_bold = new FontAttribPropItem(object, objects, "bold", tr("bold"), + propertyValue().value().bold(), this, false); + m_italic = new FontAttribPropItem(object, objects, "italic", tr("italic"), + propertyValue().value().italic(), this, false); + m_underline = new FontAttribPropItem(object, objects, "underline", tr("underline"), + propertyValue().value().underline(), this, false); + m_pointSize + = new FontPointSizePropItem(object, 0, "pointSize", tr("size"), + propertyValue().value().pointSize(), this, false); + m_family = new FontFamilyPropItem(object, 0, "family", tr("family"), + propertyValue().value(), this, false); this->appendItem(m_family); this->appendItem(m_pointSize); @@ -64,23 +77,24 @@ FontPropItem::FontPropItem(QObject *object, ObjectPropItem::ObjectsList *objects this->appendItem(m_underline); } -QWidget *FontPropItem::createProperyEditor(QWidget *parent) const -{ - return new FontEditor(parent); -} +QWidget* FontPropItem::createProperyEditor(QWidget* parent) const { return new FontEditor(parent); } QString FontPropItem::displayValue() const { - return toString(propertyValue().value());//propertyValue().toString();//toString(propertyValue().value()); + return toString( + propertyValue() + .value< + QFont>()); // propertyValue().toString();//toString(propertyValue().value()); } -void FontPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex &) const +void FontPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - FontEditor *editor =qobject_cast(propertyEditor); + FontEditor* editor = qobject_cast(propertyEditor); editor->setFontValue(propertyValue().value()); } -void FontPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex &index) +void FontPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { QFont tmpFont = qobject_cast(propertyEditor)->fontValue(); @@ -89,8 +103,8 @@ void FontPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* mod font.setPointSize(tmpFont.pointSize()); font.setItalic(tmpFont.italic()); font.setUnderline(tmpFont.underline()); - model->setData(index,font); - setValueToObject(propertyName(),propertyValue()); + model->setData(index, font); + setValueToObject(propertyName(), propertyValue()); } void FontPropItem::setPropertyValue(QVariant value) @@ -105,11 +119,14 @@ void FontPropItem::setPropertyValue(QVariant value) QString FontPropItem::toString(QFont value) const { - QString attribs=""; - if (value.bold()) (attribs=="") ? attribs+="b":attribs+=",b"; - if (value.italic()) (attribs=="") ? attribs+="i":attribs+=",i"; - if (attribs!="") attribs="["+attribs+"]"; - return "\""+ value.family()+"\" "+QString::number(value.pointSize())+" "+attribs; + QString attribs = ""; + if (value.bold()) + (attribs == "") ? attribs += "b" : attribs += ",b"; + if (value.italic()) + (attribs == "") ? attribs += "i" : attribs += ",i"; + if (attribs != "") + attribs = "[" + attribs + "]"; + return "\"" + value.family() + "\" " + QString::number(value.pointSize()) + " " + attribs; } QString FontFamilyPropItem::displayValue() const @@ -118,71 +135,70 @@ QString FontFamilyPropItem::displayValue() const return font.family(); } -QWidget *FontFamilyPropItem::createProperyEditor(QWidget *parent) const +QWidget* FontFamilyPropItem::createProperyEditor(QWidget* parent) const { FontFamilyEditor* editor = new FontFamilyEditor(parent); -// QFontComboBox* editor = new QFontComboBox(parent); + // QFontComboBox* editor = new QFontComboBox(parent); editor->setAutoFillBackground(true); editor->setFont(propertyValue().value()); return editor; } -void FontFamilyPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void FontFamilyPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { FontFamilyEditor* editor = qobject_cast(propertyEditor); -// QFontComboBox* editor = qobject_cast(propertyEditor); + // QFontComboBox* editor = qobject_cast(propertyEditor); editor->setFont(propertyValue().value()); } -void FontFamilyPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void FontFamilyPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { QFont font = object()->property(parent()->propertyName().toLatin1()).value(); -// font.setFamily(qobject_cast(propertyEditor)->currentFont().family()); + // font.setFamily(qobject_cast(propertyEditor)->currentFont().family()); font.setFamily(qobject_cast(propertyEditor)->currentFont().family()); - model->setData(index,font); - setValueToObject(parent()->propertyName(),font); + model->setData(index, font); + setValueToObject(parent()->propertyName(), font); } -void FontAttribPropItem::setModelData(QWidget *propertyEditor , QAbstractItemModel *model, const QModelIndex &index) +void FontAttribPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->isChecked()); + model->setData(index, qobject_cast(propertyEditor)->isChecked()); QFont font = object()->property(parent()->propertyName().toLatin1()).value(); - if (propertyName()=="bold"){ + if (propertyName() == "bold") { font.setBold(propertyValue().toBool()); } - if (propertyName()=="italic"){ + if (propertyName() == "italic") { font.setItalic(propertyValue().toBool()); } - if (propertyName()=="underline"){ + if (propertyName() == "underline") { font.setUnderline(propertyValue().toBool()); } - setValueToObject(parent()->propertyName(),font); + setValueToObject(parent()->propertyName(), font); } -void FontPointSizePropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void FontPointSizePropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->value()); + model->setData(index, qobject_cast(propertyEditor)->value()); QFont font = object()->property(parent()->propertyName().toLatin1()).value(); font.setPointSize(propertyValue().toInt()); - setValueToObject(parent()->propertyName(),font); + setValueToObject(parent()->propertyName(), font); } -FontFamilyEditor::FontFamilyEditor(QWidget *parent) - :QWidget(parent) +FontFamilyEditor::FontFamilyEditor(QWidget* parent): QWidget(parent) { m_valueEditor = new QFontComboBox(this); setFocusProxy(m_valueEditor); QHBoxLayout* hLayout = new QHBoxLayout(this); hLayout->addWidget(m_valueEditor); - hLayout->setContentsMargins(1,1,1,1); + hLayout->setContentsMargins(1, 1, 1, 1); hLayout->setSpacing(0); setAutoFillBackground(true); } -QFont FontFamilyEditor::currentFont() -{ - return m_valueEditor->currentFont(); -} +QFont FontFamilyEditor::currentFont() { return m_valueEditor->currentFont(); } void FontFamilyEditor::setFont(QFont font) { @@ -190,4 +206,4 @@ void FontFamilyEditor::setFont(QFont font) m_valueEditor->setFont(font); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrfontpropitem.h b/limereport/objectinspector/propertyItems/lrfontpropitem.h index 654ba8a..31abd0d 100644 --- a/limereport/objectinspector/propertyItems/lrfontpropitem.h +++ b/limereport/objectinspector/propertyItems/lrfontpropitem.h @@ -30,15 +30,15 @@ #ifndef LRFONTPROPITEM_H #define LRFONTPROPITEM_H -#include - -#include "lrobjectpropitem.h" #include "lrboolpropitem.h" #include "lrintpropitem.h" +#include "lrobjectpropitem.h" -namespace LimeReport{ +#include -class FontFamilyEditor : public QWidget{ +namespace LimeReport { + +class FontFamilyEditor: public QWidget { Q_OBJECT public: FontFamilyEditor(QWidget* parent); @@ -46,62 +46,82 @@ public: void setFont(QFont font); signals: void editingFinished(); + private: QFontComboBox* m_valueEditor; }; -class FontFamilyPropItem : public ObjectPropItem -{ +class FontFamilyPropItem: public ObjectPropItem { Q_OBJECT public: - FontFamilyPropItem():ObjectPropItem(){} - FontFamilyPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly=true) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} + FontFamilyPropItem(): ObjectPropItem() { } + FontFamilyPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } QString displayValue() const; - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor , QAbstractItemModel *model, const QModelIndex &index); + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; -class FontPointSizePropItem : public IntPropItem -{ +class FontPointSizePropItem: public IntPropItem { Q_OBJECT public: - FontPointSizePropItem():IntPropItem(){} - FontPointSizePropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly=true) - :IntPropItem(object, objects, name, displayName, value, parent, readonly){} - void setModelData(QWidget *propertyEditor , QAbstractItemModel *model, const QModelIndex &index); + FontPointSizePropItem(): IntPropItem() { } + FontPointSizePropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true): + IntPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; -class FontAttribPropItem : public BoolPropItem -{ +class FontAttribPropItem: public BoolPropItem { Q_OBJECT public: - FontAttribPropItem():BoolPropItem(){} - FontAttribPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly=true) - :BoolPropItem(object, objects, name, displayName, value, parent, readonly){} - void setModelData(QWidget *propertyEditor , QAbstractItemModel *model, const QModelIndex &index); + FontAttribPropItem(): BoolPropItem() { } + FontAttribPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true): + BoolPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; -class FontPropItem : public ObjectPropItem -{ +class FontPropItem: public ObjectPropItem { Q_OBJECT public: - FontPropItem():ObjectPropItem(), m_pointSize(NULL), m_bold(NULL), m_italic(NULL), m_underline(NULL), m_family(NULL) {} - FontPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly); - QWidget* createProperyEditor(QWidget *parent) const; + FontPropItem(): + ObjectPropItem(), + m_pointSize(NULL), + m_bold(NULL), + m_italic(NULL), + m_underline(NULL), + m_family(NULL) + { + } + FontPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly); + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index); + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); void setPropertyValue(QVariant value); + protected: QString toString(QFont value) const; FontPointSizePropItem* m_pointSize; - FontAttribPropItem *m_bold; - FontAttribPropItem *m_italic; - FontAttribPropItem *m_underline; - FontFamilyPropItem *m_family; + FontAttribPropItem* m_bold; + FontAttribPropItem* m_italic; + FontAttribPropItem* m_underline; + FontFamilyPropItem* m_family; }; -} +} // namespace LimeReport #endif // LRFONTPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.cpp b/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.cpp index 86dda68..d406777 100644 --- a/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.cpp @@ -28,55 +28,66 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrgroupfieldpropitem.h" + #include "../editors/lrcomboboxeditor.h" #include "lrgroupbands.h" #include "lrreportengine_p.h" -namespace { - LimeReport::ObjectPropItem* createFieldPropItem(QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly){ - return new LimeReport::GroupFieldPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredGroupFieldProp = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("groupFieldName","LimeReport::GroupBandHeader"),QObject::tr("field"),createFieldPropItem - ); +namespace { +LimeReport::ObjectPropItem* createFieldPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::GroupFieldPropItem(object, objects, name, displayName, data, parent, + readonly); } +bool VARIABLE_IS_NOT_USED registredGroupFieldProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("groupFieldName", "LimeReport::GroupBandHeader"), + QObject::tr("field"), createFieldPropItem); +} // namespace namespace LimeReport { - -QString findDatasourceName(BandDesignIntf* band){ - if (!band) return ""; - if (!band->datasourceName().isEmpty()) return band->datasourceName(); - else return findDatasourceName(band->parentBand()); +QString findDatasourceName(BandDesignIntf* band) +{ + if (!band) + return ""; + if (!band->datasourceName().isEmpty()) + return band->datasourceName(); + else + return findDatasourceName(band->parentBand()); } -QWidget *GroupFieldPropItem::createProperyEditor(QWidget *parent) const +QWidget* GroupFieldPropItem::createProperyEditor(QWidget* parent) const { - ComboBoxEditor *editor = new ComboBoxEditor(parent,true); + ComboBoxEditor* editor = new ComboBoxEditor(parent, true); editor->setEditable(true); - GroupBandHeader *item=dynamic_cast(object()); - if (item){ + GroupBandHeader* item = dynamic_cast(object()); + if (item) { BandDesignIntf* dataBand = dynamic_cast(item->parentBand()); - if (dataBand){ + if (dataBand) { QString datasourceName = findDatasourceName(dataBand); - if (!datasourceName.isEmpty()){ - editor->addItems(item->reportEditor()->dataManager()->fieldNames(datasourceName)); + if (!datasourceName.isEmpty()) { + editor->addItems(item->reportEditor()->dataManager()->fieldNames(datasourceName)); } } } return editor; } -void GroupFieldPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void GroupFieldPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - ComboBoxEditor *editor=qobject_cast(propertyEditor); + ComboBoxEditor* editor = qobject_cast(propertyEditor); editor->setTextValue(propertyValue().toString()); } -void GroupFieldPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void GroupFieldPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->text()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); -} - + model->setData(index, qobject_cast(propertyEditor)->text()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.h b/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.h index e51f297..fba8dcf 100644 --- a/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.h +++ b/limereport/objectinspector/propertyItems/lrgroupfieldpropitem.h @@ -31,19 +31,21 @@ #define LRGROUPFIELDPROPITEM_H #include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class GroupFieldPropItem : public ObjectPropItem -{ +class GroupFieldPropItem: public ObjectPropItem { public: - GroupFieldPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index); + GroupFieldPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; -} - +} // namespace LimeReport #endif // LRGROUPFIELDPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrimagepropitem.cpp b/limereport/objectinspector/propertyItems/lrimagepropitem.cpp index 31c37fd..441f68a 100644 --- a/limereport/objectinspector/propertyItems/lrimagepropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrimagepropitem.cpp @@ -28,20 +28,27 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrimagepropitem.h" + #include "editors/lrimageeditor.h" -namespace{ - LimeReport::ObjectPropItem * createImagePropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::ImagePropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredImageProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QImage",""),QObject::tr("QImage"),createImagePropItem); +namespace { +LimeReport::ObjectPropItem* createImagePropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::ImagePropItem(object, objects, name, displayName, data, parent, + readonly); } +bool VARIABLE_IS_NOT_USED registredImageProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QImage", ""), QObject::tr("QImage"), createImagePropItem); +} // namespace -namespace LimeReport{ +namespace LimeReport { -QWidget* ImagePropItem::createProperyEditor(QWidget *parent) const +QWidget* ImagePropItem::createProperyEditor(QWidget* parent) const { return new ImageEditor(parent); } @@ -51,16 +58,17 @@ QString ImagePropItem::displayValue() const return (propertyValue().isNull()) ? "" : QObject::tr("image"); } -void ImagePropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void ImagePropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - ImageEditor *editor = qobject_cast(propertyEditor); + ImageEditor* editor = qobject_cast(propertyEditor); editor->setImage(propertyValue().value()); } -void ImagePropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void ImagePropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->image()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->image()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } QIcon ImagePropItem::iconValue() const @@ -68,4 +76,4 @@ QIcon ImagePropItem::iconValue() const return QIcon(QPixmap::fromImage(propertyValue().value())); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrimagepropitem.h b/limereport/objectinspector/propertyItems/lrimagepropitem.h index ab97f05..19c6981 100644 --- a/limereport/objectinspector/propertyItems/lrimagepropitem.h +++ b/limereport/objectinspector/propertyItems/lrimagepropitem.h @@ -31,21 +31,24 @@ #define LRIMAGEPROPITEM_H #include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class ImagePropItem : public ObjectPropItem -{ +class ImagePropItem: public ObjectPropItem { Q_OBJECT public: - ImagePropItem():ObjectPropItem(){} - ImagePropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; + ImagePropItem(): ObjectPropItem() { } + ImagePropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index); + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); virtual QIcon iconValue() const; }; -} +} // namespace LimeReport #endif // LRIMAGEPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrintpropitem.cpp b/limereport/objectinspector/propertyItems/lrintpropitem.cpp index 172c40e..2556303 100644 --- a/limereport/objectinspector/propertyItems/lrintpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrintpropitem.cpp @@ -28,56 +28,62 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrintpropitem.h" -#include + #include #include -namespace{ - LimeReport::ObjectPropItem * createIntPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::IntPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("int",""),QObject::tr("int"),createIntPropItem); +#include + +namespace { +LimeReport::ObjectPropItem* createIntPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::IntPropItem(object, objects, name, displayName, data, parent, readonly); +} +bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("int", ""), QObject::tr("int"), createIntPropItem); } // namespace -namespace LimeReport{ +namespace LimeReport { -QWidget *IntPropItem::createProperyEditor(QWidget *parent) const +QWidget* IntPropItem::createProperyEditor(QWidget* parent) const { -// QWidget* base = new QWidget(parent); -// QHBoxLayout* layout = new QHBoxLayout(); -// base->setLayout(layout); + // QWidget* base = new QWidget(parent); + // QHBoxLayout* layout = new QHBoxLayout(); + // base->setLayout(layout); -// QSpinBox *editor = new QSpinBox(parent); -// editor->setMaximum(std::numeric_limits::max()); -// editor->setMinimum(std::numeric_limits::min()); + // QSpinBox *editor = new QSpinBox(parent); + // editor->setMaximum(std::numeric_limits::max()); + // editor->setMinimum(std::numeric_limits::min()); -// layout->addWidget(editor); + // layout->addWidget(editor); return new SpinBoxEditor(parent); } -void IntPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void IntPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - SpinBoxEditor *editor =qobject_cast(propertyEditor); + SpinBoxEditor* editor = qobject_cast(propertyEditor); editor->setValue(propertyValue().toInt()); } -void IntPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void IntPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->value()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); - if (objects()){ - foreach(QObject* item, *objects()){ - if (item->metaObject()->indexOfProperty(propertyName().toLatin1())!=-1){ - item->setProperty(propertyName().toLatin1(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->value()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); + if (objects()) { + foreach (QObject* item, *objects()) { + if (item->metaObject()->indexOfProperty(propertyName().toLatin1()) != -1) { + item->setProperty(propertyName().toLatin1(), propertyValue()); } } } } -SpinBoxEditor::SpinBoxEditor(QWidget *parent) - :QWidget(parent) +SpinBoxEditor::SpinBoxEditor(QWidget* parent): QWidget(parent) { m_valueEditor = new QSpinBox(this); m_valueEditor->setMinimum(std::numeric_limits::min()); @@ -85,20 +91,14 @@ SpinBoxEditor::SpinBoxEditor(QWidget *parent) setFocusProxy(m_valueEditor); QHBoxLayout* hLayout = new QHBoxLayout(this); hLayout->addWidget(m_valueEditor); - hLayout->setContentsMargins(1,1,1,1); + hLayout->setContentsMargins(1, 1, 1, 1); hLayout->setSpacing(0); setAutoFillBackground(true); connect(m_valueEditor, SIGNAL(editingFinished()), this, SIGNAL(editingFinished())); } -int SpinBoxEditor::value() -{ - return m_valueEditor->value(); -} +int SpinBoxEditor::value() { return m_valueEditor->value(); } -void SpinBoxEditor::setValue(int value) -{ - m_valueEditor->setValue(value); -} +void SpinBoxEditor::setValue(int value) { m_valueEditor->setValue(value); } } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrintpropitem.h b/limereport/objectinspector/propertyItems/lrintpropitem.h index d9a2fbb..13f49ca 100644 --- a/limereport/objectinspector/propertyItems/lrintpropitem.h +++ b/limereport/objectinspector/propertyItems/lrintpropitem.h @@ -31,11 +31,12 @@ #define LRINTPROPITEM_H #include "lrobjectpropitem.h" + #include namespace LimeReport { -class SpinBoxEditor : public QWidget{ +class SpinBoxEditor: public QWidget { Q_OBJECT public: SpinBoxEditor(QWidget* parent); @@ -43,20 +44,24 @@ public: void setValue(int value); signals: void editingFinished(); + private: QSpinBox* m_valueEditor; }; -class IntPropItem : public ObjectPropItem -{ +class IntPropItem: public ObjectPropItem { Q_OBJECT public: - IntPropItem():ObjectPropItem(){} - IntPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); + IntPropItem(): ObjectPropItem() { } + IntPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrmarginpropitem.cpp b/limereport/objectinspector/propertyItems/lrmarginpropitem.cpp index 469cfda..3dae0cc 100644 --- a/limereport/objectinspector/propertyItems/lrmarginpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrmarginpropitem.cpp @@ -1,68 +1,77 @@ #include "lrmarginpropitem.h" -#include -#include + #include "lrbasedesignintf.h" -namespace { - LimeReport::ObjectPropItem * createMarginPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::MarginPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredTopMargin = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("topMargin","LimeReport::PageItemDesignIntf"), - QObject::tr("margin"),createMarginPropItem - ); - bool VARIABLE_IS_NOT_USED registredRightMargin = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("rightMargin","LimeReport::PageItemDesignIntf"), - QObject::tr("margin"),createMarginPropItem - ); - bool VARIABLE_IS_NOT_USED registredBottomMargin = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("bottomMargin","LimeReport::PageItemDesignIntf"), - QObject::tr("margin"),createMarginPropItem - ); - bool VARIABLE_IS_NOT_USED registredLeftMargin = LimeReport::ObjectPropFactory::instance().registerCreator( - LimeReport::APropIdent("leftMargin","LimeReport::PageItemDesignIntf"), - QObject::tr("margin"),createMarginPropItem - ); +#include + +#include + +namespace { +LimeReport::ObjectPropItem* createMarginPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::MarginPropItem(object, objects, name, displayName, data, parent, + readonly); } +bool VARIABLE_IS_NOT_USED registredTopMargin + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("topMargin", "LimeReport::PageItemDesignIntf"), + QObject::tr("margin"), createMarginPropItem); +bool VARIABLE_IS_NOT_USED registredRightMargin + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("rightMargin", "LimeReport::PageItemDesignIntf"), + QObject::tr("margin"), createMarginPropItem); +bool VARIABLE_IS_NOT_USED registredBottomMargin + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("bottomMargin", "LimeReport::PageItemDesignIntf"), + QObject::tr("margin"), createMarginPropItem); +bool VARIABLE_IS_NOT_USED registredLeftMargin + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("leftMargin", "LimeReport::PageItemDesignIntf"), + QObject::tr("margin"), createMarginPropItem); +} // namespace -namespace LimeReport{ - +namespace LimeReport { QString MarginPropItem::displayValue() const { - LimeReport::BaseDesignIntf * item = dynamic_cast(object()); + LimeReport::BaseDesignIntf* item = dynamic_cast(object()); switch (item->unitType()) { case LimeReport::BaseDesignIntf::Millimeters: - return QString("%1 %2").arg(propertyValue().toDouble(), 0, 'f', 2) - .arg(QObject::tr("mm")); + return QString("%1 %2").arg(propertyValue().toDouble(), 0, 'f', 2).arg(QObject::tr("mm")); case LimeReport::BaseDesignIntf::Inches: - return QString("%1 %2").arg((propertyValue().toDouble() * Const::mmFACTOR) / (item->unitFactor() * 10), 0, 'f', 2) - .arg(QObject::tr("''")); + return QString("%1 %2") + .arg((propertyValue().toDouble() * Const::mmFACTOR) / (item->unitFactor() * 10), 0, 'f', + 2) + .arg(QObject::tr("''")); } return QString(); } -QWidget *MarginPropItem::createProperyEditor(QWidget *parent) const +QWidget* MarginPropItem::createProperyEditor(QWidget* parent) const { - QDoubleSpinBox *editor= new QDoubleSpinBox(parent); + QDoubleSpinBox* editor = new QDoubleSpinBox(parent); editor->setMaximum(std::numeric_limits::max()); - editor->setMinimum(std::numeric_limits::max()*-1); - editor->setSuffix(" "+unitShortName()); + editor->setMinimum(std::numeric_limits::max() * -1); + editor->setSuffix(" " + unitShortName()); return editor; } -void MarginPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void MarginPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - QDoubleSpinBox *editor =qobject_cast(propertyEditor); + QDoubleSpinBox* editor = qobject_cast(propertyEditor); editor->setValue(valueInUnits(propertyValue().toReal())); } -void MarginPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void MarginPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index, valueInReportUnits(qobject_cast(propertyEditor)->value())); + model->setData(index, + valueInReportUnits(qobject_cast(propertyEditor)->value())); setValueToObject(propertyName(), propertyValue()); } diff --git a/limereport/objectinspector/propertyItems/lrmarginpropitem.h b/limereport/objectinspector/propertyItems/lrmarginpropitem.h index f511ce1..d5c1efd 100644 --- a/limereport/objectinspector/propertyItems/lrmarginpropitem.h +++ b/limereport/objectinspector/propertyItems/lrmarginpropitem.h @@ -5,17 +5,21 @@ namespace LimeReport { -class MarginPropItem : public ObjectPropItem -{ +class MarginPropItem: public ObjectPropItem { Q_OBJECT public: - MarginPropItem():ObjectPropItem(){} - MarginPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} + MarginPropItem(): ObjectPropItem() { } + MarginPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } QString displayValue() const; - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); + private: qreal valueInUnits(qreal value) const; qreal valueInReportUnits(qreal value) const; @@ -24,5 +28,4 @@ private: } // namespace LimeReport - #endif // LRMARGINPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrqrealpropitem.cpp b/limereport/objectinspector/propertyItems/lrqrealpropitem.cpp index 5e4dd66..686807a 100644 --- a/limereport/objectinspector/propertyItems/lrqrealpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrqrealpropitem.cpp @@ -30,39 +30,48 @@ #include "lrqrealpropitem.h" #include + #include -namespace{ - LimeReport::ObjectPropItem * createQRealPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::QRealPropItem(object, objects, name, displayName, data, parent, readonly); - } - - bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("qreal",""),QObject::tr("qreal"),createQRealPropItem); - bool VARIABLE_IS_NOT_USED registredDouble = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("double",""),QObject::tr("qreal"),createQRealPropItem); +namespace { +LimeReport::ObjectPropItem* createQRealPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::QRealPropItem(object, objects, name, displayName, data, parent, + readonly); } -namespace LimeReport{ +bool VARIABLE_IS_NOT_USED registred = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("qreal", ""), QObject::tr("qreal"), createQRealPropItem); +bool VARIABLE_IS_NOT_USED registredDouble + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("double", ""), QObject::tr("qreal"), createQRealPropItem); +} // namespace -QWidget *QRealPropItem::createProperyEditor(QWidget *parent) const +namespace LimeReport { + +QWidget* QRealPropItem::createProperyEditor(QWidget* parent) const { - QDoubleSpinBox *editor= new QDoubleSpinBox(parent); + QDoubleSpinBox* editor = new QDoubleSpinBox(parent); editor->setMaximum(std::numeric_limits::max()); - editor->setMinimum(std::numeric_limits::max()*-1); + editor->setMinimum(std::numeric_limits::max() * -1); return editor; } -void QRealPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void QRealPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - QDoubleSpinBox *editor =qobject_cast(propertyEditor); + QDoubleSpinBox* editor = qobject_cast(propertyEditor); editor->setValue(propertyValue().toDouble()); } -void QRealPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void QRealPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->value()); - setValueToObject(propertyName(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->value()); + setValueToObject(propertyName(), propertyValue()); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrqrealpropitem.h b/limereport/objectinspector/propertyItems/lrqrealpropitem.h index 1767395..d16c4a9 100644 --- a/limereport/objectinspector/propertyItems/lrqrealpropitem.h +++ b/limereport/objectinspector/propertyItems/lrqrealpropitem.h @@ -34,17 +34,20 @@ namespace LimeReport { -class QRealPropItem : public ObjectPropItem -{ +class QRealPropItem: public ObjectPropItem { Q_OBJECT public: - QRealPropItem():ObjectPropItem(){} - QRealPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; - void setPropertyEditorData(QWidget * propertyEditor, const QModelIndex &) const; - void setModelData(QWidget * propertyEditor, QAbstractItemModel * model, const QModelIndex & index); + QRealPropItem(): ObjectPropItem() { } + QRealPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); }; -} +} // namespace LimeReport #endif // LRQREALPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrrectproptem.cpp b/limereport/objectinspector/propertyItems/lrrectproptem.cpp index d95e487..65dc410 100644 --- a/limereport/objectinspector/propertyItems/lrrectproptem.cpp +++ b/limereport/objectinspector/propertyItems/lrrectproptem.cpp @@ -28,150 +28,213 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrrectproptem.h" -#include "lrobjectpropitem.h" + #include "lrbanddesignintf.h" -#include "lrpageitemdesignintf.h" #include "lrglobal.h" #include "lrobjectitemmodel.h" +#include "lrobjectpropitem.h" +#include "lrpageitemdesignintf.h" #include -#include -#include #include +#include +#include -namespace{ - LimeReport::ObjectPropItem * createReqtItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly - ){ - return new LimeReport::RectPropItem(object, objects, name, displayName, data, parent, readonly); - } - LimeReport::ObjectPropItem * createReqtUnitItem( - QObject*object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly - ){ - return new LimeReport::RectUnitPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredRectProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QRect",""),QObject::tr("QRect"),createReqtItem); - bool VARIABLE_IS_NOT_USED registredRectFProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QRectF",""),QObject::tr("QRectF"),createReqtItem); - bool VARIABLE_IS_NOT_USED registredRectMMProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("geometry","LimeReport::BaseDesignIntf"),QObject::tr("geometry"),createReqtUnitItem); -} - -namespace LimeReport{ - -template QString rectToString(T rect) +namespace { +LimeReport::ObjectPropItem* createReqtItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, LimeReport::ObjectPropItem* parent, + bool readonly) { - return QString("[%1,%2] %3x%4").arg(rect.x()).arg(rect.y()).arg(rect.width()).arg(rect.height()); + return new LimeReport::RectPropItem(object, objects, name, displayName, data, parent, readonly); +} +LimeReport::ObjectPropItem* createReqtUnitItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::RectUnitPropItem(object, objects, name, displayName, data, parent, + readonly); +} +bool VARIABLE_IS_NOT_USED registredRectProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QRect", ""), QObject::tr("QRect"), createReqtItem); +bool VARIABLE_IS_NOT_USED registredRectFProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QRectF", ""), QObject::tr("QRectF"), createReqtItem); +bool VARIABLE_IS_NOT_USED registredRectMMProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("geometry", "LimeReport::BaseDesignIntf"), QObject::tr("geometry"), + createReqtUnitItem); +} // namespace + +namespace LimeReport { + +template QString rectToString(T rect) +{ + return QString("[%1,%2] %3x%4") + .arg(rect.x()) + .arg(rect.y()) + .arg(rect.width()) + .arg(rect.height()); } -QRectF modifyRect(QRectF rect, const QString& name, qreal itemValue){ - if (name=="x"){qreal width=rect.width(); rect.setX(itemValue); rect.setWidth(width);} - if (name=="y"){qreal heigh=rect.height(); rect.setY(itemValue); rect.setHeight(heigh);} - if (name=="height"){rect.setHeight(itemValue);} - if (name=="width"){rect.setWidth(itemValue);} +QRectF modifyRect(QRectF rect, const QString& name, qreal itemValue) +{ + if (name == "x") { + qreal width = rect.width(); + rect.setX(itemValue); + rect.setWidth(width); + } + if (name == "y") { + qreal heigh = rect.height(); + rect.setY(itemValue); + rect.setHeight(heigh); + } + if (name == "height") { + rect.setHeight(itemValue); + } + if (name == "width") { + rect.setWidth(itemValue); + } return rect; } -} +} // namespace LimeReport -LimeReport::RectPropItem::RectPropItem(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly): - ObjectPropItem(object, objects, name, displayName, value,parent,readonly) +LimeReport::RectPropItem::RectPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, + ObjectPropItem* parent, bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) { - QRect rect=value.toRect(); - this->appendItem(new ObjectPropItem(object, objects, "x","x", rect.x(),this)); - this->appendItem(new ObjectPropItem(object, objects, "y","x", rect.y(),this)); - this->appendItem(new ObjectPropItem(object, objects, "width",tr("width"), rect.width(),this)); - this->appendItem(new ObjectPropItem(object, objects, "heigh",tr("height"),rect.height(),this)); + QRect rect = value.toRect(); + this->appendItem(new ObjectPropItem(object, objects, "x", "x", rect.x(), this)); + this->appendItem(new ObjectPropItem(object, objects, "y", "x", rect.y(), this)); + this->appendItem(new ObjectPropItem(object, objects, "width", tr("width"), rect.width(), this)); + this->appendItem( + new ObjectPropItem(object, objects, "heigh", tr("height"), rect.height(), this)); } QString LimeReport::RectPropItem::displayValue() const { - //TODO: Migrate to QMetaType + // TODO: Migrate to QMetaType #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - switch(propertyValue().typeId()){ - case QMetaType::QRect: - return rectToString(propertyValue().toRect()); - case QMetaType::QRectF: - return rectToString(propertyValue().toRect()); - default : - return ObjectPropItem::displayValue(); + switch (propertyValue().typeId()) { + case QMetaType::QRect: + return rectToString(propertyValue().toRect()); + case QMetaType::QRectF: + return rectToString(propertyValue().toRect()); + default: + return ObjectPropItem::displayValue(); } #else - switch(propertyValue().type()){ - case QVariant::Rect: - return rectToString(propertyValue().toRect()); - case QVariant::RectF: - return rectToString(propertyValue().toRect()); - default : - return ObjectPropItem::displayValue(); + switch (propertyValue().type()) { + case QVariant::Rect: + return rectToString(propertyValue().toRect()); + case QVariant::RectF: + return rectToString(propertyValue().toRect()); + default: + return ObjectPropItem::displayValue(); } #endif } -LimeReport::RectUnitPropItem::RectUnitPropItem(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool /*readonly*/): - ObjectPropItem(object, objects, name, displayName, value,parent) +LimeReport::RectUnitPropItem::RectUnitPropItem(QObject* object, ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& value, ObjectPropItem* parent, + bool /*readonly*/): + ObjectPropItem(object, objects, name, displayName, value, parent) { - QRectF rect= value.toRect(); + QRectF rect = value.toRect(); LimeReport::BandDesignIntf* band = dynamic_cast(object); LimeReport::PageItemDesignIntf* page = dynamic_cast(object); LimeReport::BaseDesignIntf* item = dynamic_cast(object); - if (band){ - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "x", "x", rect.x(), this, true)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "y", "y", rect.y(), this, true)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "width", tr("width"), rect.width(), this, true)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "height", tr("height"), rect.height(), this, false)); - } else if (page){ - this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0, "x", "x", rect.x(), this, true)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0, "y", "y",rect.y(), this, true)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0,"width", tr("width"), rect.width(), this, false)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0, "height", tr("height"), rect.height(), this, false)); + if (band) { + this->appendItem( + new LimeReport::RectUnitValuePropItem(object, objects, "x", "x", rect.x(), this, true)); + this->appendItem( + new LimeReport::RectUnitValuePropItem(object, objects, "y", "y", rect.y(), this, true)); + this->appendItem(new LimeReport::RectUnitValuePropItem( + object, objects, "width", tr("width"), rect.width(), this, true)); + this->appendItem(new LimeReport::RectUnitValuePropItem( + object, objects, "height", tr("height"), rect.height(), this, false)); + } else if (page) { + this->appendItem( + new LimeReport::RectUnitValuePropItem(object, 0, "x", "x", rect.x(), this, true)); + this->appendItem( + new LimeReport::RectUnitValuePropItem(object, 0, "y", "y", rect.y(), this, true)); + this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0, "width", tr("width"), + rect.width(), this, false)); + this->appendItem(new LimeReport::RectUnitValuePropItem(object, 0, "height", tr("height"), + rect.height(), this, false)); } else { - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "x", "x", rect.x(), this, false)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "y", "y", rect.y(), this, false)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "width", tr("width"), rect.width(), this, false)); - this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "height", tr("height"), rect.height(), this, false)); + this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "x", "x", rect.x(), + this, false)); + this->appendItem(new LimeReport::RectUnitValuePropItem(object, objects, "y", "y", rect.y(), + this, false)); + this->appendItem(new LimeReport::RectUnitValuePropItem( + object, objects, "width", tr("width"), rect.width(), this, false)); + this->appendItem(new LimeReport::RectUnitValuePropItem( + object, objects, "height", tr("height"), rect.height(), this, false)); } - if (item){ - connect(item,SIGNAL(geometryChanged(QObject*,QRectF,QRectF)),this,SLOT(itemGeometryChanged(QObject*,QRectF,QRectF))); - connect(item,SIGNAL(posChanged(QObject*,QPointF,QPointF)),this,SLOT(itemPosChanged(QObject*,QPointF,QPointF))); - connect(item,SIGNAL(posChanging(QObject*,QPointF,QPointF)),this,SLOT(itemPosChanged(QObject*,QPointF,QPointF))); + if (item) { + connect(item, SIGNAL(geometryChanged(QObject*, QRectF, QRectF)), this, + SLOT(itemGeometryChanged(QObject*, QRectF, QRectF))); + connect(item, SIGNAL(posChanged(QObject*, QPointF, QPointF)), this, + SLOT(itemPosChanged(QObject*, QPointF, QPointF))); + connect(item, SIGNAL(posChanging(QObject*, QPointF, QPointF)), this, + SLOT(itemPosChanged(QObject*, QPointF, QPointF))); } - } QString LimeReport::RectUnitPropItem::displayValue() const { QRectF rect = rectInUnits(propertyValue().toRectF()); return QString("[%1,%2] %3x%4 %5") - .arg(rect.x(), 0, 'f', 2) - .arg(rect.y(), 0,'f', 2) - .arg(rect.width(), 0, 'f', 2) - .arg(rect.height(), 0, 'f', 2) - .arg(unitShortName()); + .arg(rect.x(), 0, 'f', 2) + .arg(rect.y(), 0, 'f', 2) + .arg(rect.width(), 0, 'f', 2) + .arg(rect.height(), 0, 'f', 2) + .arg(unitShortName()); } -LimeReport::RectUnitValuePropItem::RectUnitValuePropItem(QObject *object, ObjectsList* objects, const QString &name, const QString &displayName, const QVariant &value, ObjectPropItem *parent, bool readonly -):ObjectPropItem(object, objects, name, displayName, value,parent,readonly){} - -QWidget * LimeReport::RectUnitValuePropItem::createProperyEditor(QWidget *parent) const +LimeReport::RectUnitValuePropItem::RectUnitValuePropItem(QObject* object, ObjectsList* objects, + const QString& name, + const QString& displayName, + const QVariant& value, + ObjectPropItem* parent, bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) { - QDoubleSpinBox *editor= new QDoubleSpinBox(parent); +} + +QWidget* LimeReport::RectUnitValuePropItem::createProperyEditor(QWidget* parent) const +{ + QDoubleSpinBox* editor = new QDoubleSpinBox(parent); editor->setMaximum(100000); - editor->setSuffix(" "+unitShortName()); + editor->setSuffix(" " + unitShortName()); return editor; } -void LimeReport::RectUnitValuePropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void LimeReport::RectUnitValuePropItem::setPropertyEditorData(QWidget* propertyEditor, + const QModelIndex&) const { - QDoubleSpinBox *editor = qobject_cast(propertyEditor); + QDoubleSpinBox* editor = qobject_cast(propertyEditor); editor->setValue(valueInUnits(propertyValue().toReal())); } -void LimeReport::RectUnitValuePropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void LimeReport::RectUnitValuePropItem::setModelData(QWidget* propertyEditor, + QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,valueInReportUnits(qobject_cast(propertyEditor)->value())); - QRectF rect=object()->property(parent()->propertyName().toLatin1()).toRectF(); - object()->setProperty(parent()->propertyName().toLatin1(), modifyRect(rect, propertyName(), propertyValue().toReal())); + model->setData(index, + valueInReportUnits(qobject_cast(propertyEditor)->value())); + QRectF rect = object()->property(parent()->propertyName().toLatin1()).toRectF(); + object()->setProperty(parent()->propertyName().toLatin1(), + modifyRect(rect, propertyName(), propertyValue().toReal())); } qreal LimeReport::RectUnitValuePropItem::valueInUnits(qreal value) const @@ -212,43 +275,48 @@ QString LimeReport::RectUnitValuePropItem::unitShortName() const QString LimeReport::RectUnitValuePropItem::displayValue() const { - return QString("%1 %2").arg(valueInUnits(propertyValue().toReal()), 0, 'f', 2).arg(unitShortName()); + return QString("%1 %2") + .arg(valueInUnits(propertyValue().toReal()), 0, 'f', 2) + .arg(unitShortName()); } -void LimeReport::RectUnitPropItem::itemPosChanged(QObject* /*object*/, QPointF newPos, QPointF oldPos) +void LimeReport::RectUnitPropItem::itemPosChanged(QObject* /*object*/, QPointF newPos, + QPointF oldPos) { - if (newPos.x() != oldPos.x()){ + if (newPos.x() != oldPos.x()) { setValue("x", newPos.x()); } - if (newPos.y() != oldPos.y()){ + if (newPos.y() != oldPos.y()) { setValue("y", newPos.y()); } } -void LimeReport::RectUnitPropItem::itemGeometryChanged(QObject * /*object*/, QRectF newGeometry, QRectF oldGeometry) +void LimeReport::RectUnitPropItem::itemGeometryChanged(QObject* /*object*/, QRectF newGeometry, + QRectF oldGeometry) { - if (newGeometry.x() != oldGeometry.x()){ + if (newGeometry.x() != oldGeometry.x()) { setValue("x", newGeometry.x()); } - if (newGeometry.y() != oldGeometry.y()){ + if (newGeometry.y() != oldGeometry.y()) { setValue("y", newGeometry.y()); } - if (newGeometry.width() != oldGeometry.width()){ + if (newGeometry.width() != oldGeometry.width()) { setValue("width", newGeometry.width()); } - if (newGeometry.height() != oldGeometry.height()){ + if (newGeometry.height() != oldGeometry.height()) { setValue("height", newGeometry.height()); } } -void LimeReport::RectUnitPropItem::setValue(const QString &name, qreal value) +void LimeReport::RectUnitPropItem::setValue(const QString& name, qreal value) { - if (name != ""){ + if (name != "") { LimeReport::ObjectPropItem* propItem = findChild(name); if (propItem) { propItem->setPropertyValue(value); setPropertyValue(LimeReport::modifyRect(propertyValue().toRectF(), name, value)); - LimeReport::QObjectPropertyModel *itemModel = dynamic_cast(model()); + LimeReport::QObjectPropertyModel* itemModel + = dynamic_cast(model()); if (itemModel) { itemModel->itemDataChanged(modelIndex()); if (propItem->modelIndex().isValid()) @@ -263,13 +331,10 @@ QRectF LimeReport::RectUnitPropItem::rectInUnits(QRectF rect) const BaseDesignIntf* item = dynamic_cast(object()); switch (item->unitType()) { case LimeReport::BaseDesignIntf::Millimeters: - return QRectF(rect.x() / item->unitFactor(), - rect.y() / item->unitFactor(), - rect.width() / item->unitFactor(), - rect.height() / item->unitFactor()); + return QRectF(rect.x() / item->unitFactor(), rect.y() / item->unitFactor(), + rect.width() / item->unitFactor(), rect.height() / item->unitFactor()); case LimeReport::BaseDesignIntf::Inches: - return QRectF(rect.x() / (item->unitFactor() * 10), - rect.y() / (item->unitFactor() * 10), + return QRectF(rect.x() / (item->unitFactor() * 10), rect.y() / (item->unitFactor() * 10), rect.width() / (item->unitFactor() * 10), rect.height() / (item->unitFactor() * 10)); } diff --git a/limereport/objectinspector/propertyItems/lrrectproptem.h b/limereport/objectinspector/propertyItems/lrrectproptem.h index c7ce569..cb35b59 100644 --- a/limereport/objectinspector/propertyItems/lrrectproptem.h +++ b/limereport/objectinspector/propertyItems/lrrectproptem.h @@ -30,49 +30,57 @@ #ifndef LRRECTPROPTEM_H #define LRRECTPROPTEM_H #include "lrobjectpropitem.h" -#include + #include +#include -namespace LimeReport{ +namespace LimeReport { -class RectPropItem : public ObjectPropItem{ +class RectPropItem: public ObjectPropItem { Q_OBJECT public: - RectPropItem():ObjectPropItem(){} - RectPropItem(QObject *object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly=true); + RectPropItem(): ObjectPropItem() { } + RectPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true); QString displayValue() const; }; -class RectUnitPropItem : public ObjectPropItem{ +class RectUnitPropItem: public ObjectPropItem { Q_OBJECT public: - RectUnitPropItem():ObjectPropItem(){} - RectUnitPropItem(QObject *object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly=true); + RectUnitPropItem(): ObjectPropItem() { } + RectUnitPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly = true); QString displayValue() const; public slots: void itemPosChanged(QObject* /*object*/, QPointF newPos, QPointF oldPos); void itemGeometryChanged(QObject* object, QRectF newGeometry, QRectF oldGeometry); + private: - void setValue(const QString& propertyName, qreal propertyValue); - QRectF rectInUnits(QRectF rect) const; + void setValue(const QString& propertyName, qreal propertyValue); + QRectF rectInUnits(QRectF rect) const; QString unitShortName() const; }; -class RectUnitValuePropItem : public ObjectPropItem{ +class RectUnitValuePropItem: public ObjectPropItem { Q_OBJECT public: - RectUnitValuePropItem():ObjectPropItem(){} - RectUnitValuePropItem(QObject *object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly ); + RectUnitValuePropItem(): ObjectPropItem() { } + RectUnitValuePropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly); QString displayValue() const; - QWidget* createProperyEditor(QWidget *) const; - void setPropertyEditorData(QWidget *, const QModelIndex &) const; - void setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &); + QWidget* createProperyEditor(QWidget*) const; + void setPropertyEditorData(QWidget*, const QModelIndex&) const; + void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&); + private: qreal valueInUnits(qreal value) const; qreal valueInReportUnits(qreal value) const; QString unitShortName() const; - }; -} +} // namespace LimeReport #endif // LRRECTPROPTEM_H diff --git a/limereport/objectinspector/propertyItems/lrseriespropitem.cpp b/limereport/objectinspector/propertyItems/lrseriespropitem.cpp index 3e5b6eb..b327538 100644 --- a/limereport/objectinspector/propertyItems/lrseriespropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrseriespropitem.cpp @@ -6,39 +6,45 @@ #include #include -namespace{ -LimeReport::ObjectPropItem * createSeriesPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +namespace { +LimeReport::ObjectPropItem* createSeriesPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { - return new LimeReport::SeriesPropItem(object, objects, name, displayName, data, parent, readonly); -} -bool VARIABLE_IS_NOT_USED registredSeriesProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("series", "LimeReport::ChartItem"), QObject::tr("series"), createSeriesPropItem); + return new LimeReport::SeriesPropItem(object, objects, name, displayName, data, parent, + readonly); } +bool VARIABLE_IS_NOT_USED registredSeriesProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("series", "LimeReport::ChartItem"), QObject::tr("series"), + createSeriesPropItem); +} // namespace namespace LimeReport { -QWidget *SeriesPropItem::createProperyEditor(QWidget *parent) const +QWidget* SeriesPropItem::createProperyEditor(QWidget* parent) const { return new SeriesPropEditor(qobject_cast(object()), parent); } -QString SeriesPropItem::displayValue() const -{ - return QObject::tr("Series"); -} +QString SeriesPropItem::displayValue() const { return QObject::tr("Series"); } -SeriesPropEditor::SeriesPropEditor(ChartItem *chart, QWidget *parent) - : QWidget(parent), m_button(new QPushButton(this)), m_chart(chart) +SeriesPropEditor::SeriesPropEditor(ChartItem* chart, QWidget* parent): + QWidget(parent), + m_button(new QPushButton(this)), + m_chart(chart) { m_button->setText("..."); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(m_button); layout->setSpacing(1); - layout->setContentsMargins(1,0,1,1); + layout->setContentsMargins(1, 0, 1, 1); setLayout(layout); setFocusProxy(m_button); setAutoFillBackground(true); - connect(m_button,SIGNAL(clicked()),this,SLOT(slotButtonClicked())); + connect(m_button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); } void SeriesPropEditor::slotButtonClicked() @@ -47,5 +53,4 @@ void SeriesPropEditor::slotButtonClicked() emit editingFinished(); } - -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrseriespropitem.h b/limereport/objectinspector/propertyItems/lrseriespropitem.h index b7cdb1e..5f5feb3 100644 --- a/limereport/objectinspector/propertyItems/lrseriespropitem.h +++ b/limereport/objectinspector/propertyItems/lrseriespropitem.h @@ -1,41 +1,42 @@ #ifndef SERIESPROPITEM_H #define SERIESPROPITEM_H -#include #include -#include +#include + #include +#include namespace LimeReport { -class SeriesPropEditor : public QWidget -{ +class SeriesPropEditor: public QWidget { Q_OBJECT public: - SeriesPropEditor(ChartItem* chart, QWidget *parent = 0); + SeriesPropEditor(ChartItem* chart, QWidget* parent = 0); signals: void editingFinished(); private slots: void slotButtonClicked(); + private: QPushButton* m_button; ChartItem* m_chart; }; -class SeriesPropItem : public LimeReport::ObjectPropItem{ +class SeriesPropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - SeriesPropItem():ObjectPropItem(){} - SeriesPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; + SeriesPropItem(): ObjectPropItem() { } + SeriesPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; }; } // namespace LimeReport - - - - #endif // SERIESPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrstringpropitem.cpp b/limereport/objectinspector/propertyItems/lrstringpropitem.cpp index b594d35..2dc4379 100644 --- a/limereport/objectinspector/propertyItems/lrstringpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrstringpropitem.cpp @@ -27,46 +27,50 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include -#include -#include - #include "lrstringpropitem.h" + #include "lrobjectpropitem.h" #include "objectinspector/editors/lrbuttonlineeditor.h" -namespace{ - LimeReport::ObjectPropItem * createStringPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) - { - return new LimeReport::StringPropItem(object, objects, name, displayName, data, parent, readonly); - } - bool VARIABLE_IS_NOT_USED registredStringProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("QString",""),QObject::tr("QString"),createStringPropItem); +#include +#include +#include + +namespace { +LimeReport::ObjectPropItem* createStringPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) +{ + return new LimeReport::StringPropItem(object, objects, name, displayName, data, parent, + readonly); +} +bool VARIABLE_IS_NOT_USED registredStringProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("QString", ""), QObject::tr("QString"), createStringPropItem); } // namespace -namespace LimeReport{ +namespace LimeReport { - -QWidget * StringPropItem::createProperyEditor(QWidget *parent) const +QWidget* StringPropItem::createProperyEditor(QWidget* parent) const { - return new ButtonLineEditor(object()->objectName()+"."+displayName(),parent); + return new ButtonLineEditor(object()->objectName() + "." + displayName(), parent); } -void StringPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void StringPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - ButtonLineEditor *editor = qobject_cast(propertyEditor); + ButtonLineEditor* editor = qobject_cast(propertyEditor); editor->setText(propertyValue().toString()); } -void StringPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void StringPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->text()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->text()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } -QString StringPropItem::displayValue() const -{ - return propertyValue().toString().simplified(); -} +QString StringPropItem::displayValue() const { return propertyValue().toString().simplified(); } } // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrstringpropitem.h b/limereport/objectinspector/propertyItems/lrstringpropitem.h index 60bc722..b350a3c 100644 --- a/limereport/objectinspector/propertyItems/lrstringpropitem.h +++ b/limereport/objectinspector/propertyItems/lrstringpropitem.h @@ -31,17 +31,21 @@ #define LRSTRINGPROPITEM_H #include "lrobjectpropitem.h" -namespace LimeReport{ -class StringPropItem : public LimeReport::ObjectPropItem{ +namespace LimeReport { +class StringPropItem: public LimeReport::ObjectPropItem { Q_OBJECT public: - StringPropItem():ObjectPropItem(){} - StringPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value, ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; + StringPropItem(): ObjectPropItem() { } + StringPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; - void setPropertyEditorData(QWidget *, const QModelIndex &) const; - void setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &); + void setPropertyEditorData(QWidget*, const QModelIndex&) const; + void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&); }; } // namespace LimeReport #endif // LRSTRINGPROPITEM_H diff --git a/limereport/objectinspector/propertyItems/lrsvgpropitem.cpp b/limereport/objectinspector/propertyItems/lrsvgpropitem.cpp index 2d702f0..ff94f48 100644 --- a/limereport/objectinspector/propertyItems/lrsvgpropitem.cpp +++ b/limereport/objectinspector/propertyItems/lrsvgpropitem.cpp @@ -1,37 +1,42 @@ #include "lrsvgpropitem.h" + #include "editors/lrsvgeditor.h" -namespace{ -LimeReport::ObjectPropItem * createSvgPropItem( - QObject *object, LimeReport::ObjectPropItem::ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& data, LimeReport::ObjectPropItem* parent, bool readonly) +namespace { +LimeReport::ObjectPropItem* createSvgPropItem(QObject* object, + LimeReport::ObjectPropItem::ObjectsList* objects, + const QString& name, const QString& displayName, + const QVariant& data, + LimeReport::ObjectPropItem* parent, bool readonly) { return new LimeReport::SvgPropItem(object, objects, name, displayName, data, parent, readonly); } -bool VARIABLE_IS_NOT_USED registredImageProp = LimeReport::ObjectPropFactory::instance().registerCreator(LimeReport::APropIdent("image","LimeReport::SVGItem"),QObject::tr("image"),createSvgPropItem); -} +bool VARIABLE_IS_NOT_USED registredImageProp + = LimeReport::ObjectPropFactory::instance().registerCreator( + LimeReport::APropIdent("image", "LimeReport::SVGItem"), QObject::tr("image"), + createSvgPropItem); +} // namespace -namespace LimeReport{ +namespace LimeReport { -QWidget* SvgPropItem::createProperyEditor(QWidget *parent) const -{ - return new SvgEditor(parent); -} +QWidget* SvgPropItem::createProperyEditor(QWidget* parent) const { return new SvgEditor(parent); } QString SvgPropItem::displayValue() const { return (propertyValue().isNull()) ? "" : QObject::tr("image"); } -void SvgPropItem::setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const +void SvgPropItem::setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const { - SvgEditor *editor = qobject_cast(propertyEditor); + SvgEditor* editor = qobject_cast(propertyEditor); editor->setImage(propertyValue().value()); } -void SvgPropItem::setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index) +void SvgPropItem::setModelData(QWidget* propertyEditor, QAbstractItemModel* model, + const QModelIndex& index) { - model->setData(index,qobject_cast(propertyEditor)->image()); - object()->setProperty(propertyName().toLatin1(),propertyValue()); + model->setData(index, qobject_cast(propertyEditor)->image()); + object()->setProperty(propertyName().toLatin1(), propertyValue()); } QIcon SvgPropItem::iconValue() const @@ -39,4 +44,4 @@ QIcon SvgPropItem::iconValue() const return QIcon(QPixmap::fromImage(propertyValue().value())); } -} +} // namespace LimeReport diff --git a/limereport/objectinspector/propertyItems/lrsvgpropitem.h b/limereport/objectinspector/propertyItems/lrsvgpropitem.h index ee28331..8b75d43 100644 --- a/limereport/objectinspector/propertyItems/lrsvgpropitem.h +++ b/limereport/objectinspector/propertyItems/lrsvgpropitem.h @@ -2,19 +2,22 @@ #define SVGPROPITEM_H #include "lrobjectpropitem.h" -namespace LimeReport{ +namespace LimeReport { -class SvgPropItem : public ObjectPropItem -{ +class SvgPropItem: public ObjectPropItem { Q_OBJECT public: - SvgPropItem():ObjectPropItem(){} - SvgPropItem(QObject* object, ObjectsList* objects, const QString& name, const QString& displayName, const QVariant& value,ObjectPropItem* parent, bool readonly) - :ObjectPropItem(object, objects, name, displayName, value, parent, readonly){} - QWidget* createProperyEditor(QWidget *parent) const; + SvgPropItem(): ObjectPropItem() { } + SvgPropItem(QObject* object, ObjectsList* objects, const QString& name, + const QString& displayName, const QVariant& value, ObjectPropItem* parent, + bool readonly): + ObjectPropItem(object, objects, name, displayName, value, parent, readonly) + { + } + QWidget* createProperyEditor(QWidget* parent) const; QString displayValue() const; - void setPropertyEditorData(QWidget *propertyEditor, const QModelIndex &) const; - void setModelData(QWidget *propertyEditor, QAbstractItemModel *model, const QModelIndex &index); + void setPropertyEditorData(QWidget* propertyEditor, const QModelIndex&) const; + void setModelData(QWidget* propertyEditor, QAbstractItemModel* model, const QModelIndex& index); virtual QIcon iconValue() const; }; diff --git a/limereport/objectsbrowser/lrobjectbrowser.cpp b/limereport/objectsbrowser/lrobjectbrowser.cpp index dd2177e..74f9a8f 100644 --- a/limereport/objectsbrowser/lrobjectbrowser.cpp +++ b/limereport/objectsbrowser/lrobjectbrowser.cpp @@ -28,202 +28,200 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrobjectbrowser.h" -#include "lritemdesignintf.h" + #include "lrbanddesignintf.h" +#include "lritemdesignintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -ObjectBrowser::ObjectBrowser(QWidget *parent) - :QWidget(parent), m_designerWidget(NULL), m_mainWindow(NULL), - m_changingItemSelection(false), m_movingItem(false) +ObjectBrowser::ObjectBrowser(QWidget* parent): + QWidget(parent), + m_designerWidget(NULL), + m_mainWindow(NULL), + m_changingItemSelection(false), + m_movingItem(false) { - QVBoxLayout *layout = new QVBoxLayout(this); + QVBoxLayout* layout = new QVBoxLayout(this); setLayout(layout); int margin = Const::DOCKWIDGET_MARGINS; layout->setContentsMargins(margin, margin, margin, margin); m_treeView = new QTreeWidget(this); layout->addWidget(m_treeView); - m_treeView->headerItem()->setText(0,tr("Objects")); + m_treeView->headerItem()->setText(0, tr("Objects")); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); } -void ObjectBrowser::setReportEditor(ReportDesignWidget *designerWidget) +void ObjectBrowser::setReportEditor(ReportDesignWidget* designerWidget) { - m_designerWidget=designerWidget; - connect(m_designerWidget,SIGNAL(cleared()),this,SLOT(slotClear())); + m_designerWidget = designerWidget; + connect(m_designerWidget, SIGNAL(cleared()), this, SLOT(slotClear())); connect(m_designerWidget, SIGNAL(loadFinished()), this, SLOT(slotReportLoaded())); connect(m_designerWidget, SIGNAL(activePageChanged()), this, SLOT(slotActivePageChanged())); - connect(m_designerWidget,SIGNAL(itemAdded(LimeReport::PageDesignIntf*,LimeReport::BaseDesignIntf*)), - this, SLOT(slotItemAdded(LimeReport::PageDesignIntf*,LimeReport::BaseDesignIntf*))); - connect(m_designerWidget, SIGNAL(itemDeleted(LimeReport::PageDesignIntf*,LimeReport::BaseDesignIntf*)), - this, SLOT(slotItemDeleted(LimeReport::PageDesignIntf*,LimeReport::BaseDesignIntf*))); - connect(m_designerWidget, SIGNAL(bandAdded(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*)), - this, SLOT(slotBandAdded(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*))); - connect(m_designerWidget, SIGNAL(bandDeleted(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*)), - this, SLOT(slotBandDeleted(LimeReport::PageDesignIntf*,LimeReport::BandDesignIntf*))); - connect(m_treeView, SIGNAL(itemSelectionChanged()), - this, SLOT(slotObjectTreeItemSelectionChanged()) ); - connect(m_designerWidget, SIGNAL(itemSelected(LimeReport::BaseDesignIntf*)), - this, SLOT(slotItemSelected(LimeReport::BaseDesignIntf*))); - connect(m_designerWidget, SIGNAL(multiItemSelected()), - this, SLOT(slotMultiItemSelected()) ); - connect(m_designerWidget, SIGNAL(activePageUpdated(LimeReport::PageDesignIntf*)), - this, SLOT(slotActivePageUpdated(LimeReport::PageDesignIntf*))); - connect(m_treeView, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), - this, SLOT(slotItemDoubleClicked(QTreeWidgetItem*,int))); + connect(m_designerWidget, + SIGNAL(itemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*)), this, + SLOT(slotItemAdded(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*))); + connect(m_designerWidget, + SIGNAL(itemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*)), this, + SLOT(slotItemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*))); + connect(m_designerWidget, + SIGNAL(bandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, + SLOT(slotBandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); + connect(m_designerWidget, + SIGNAL(bandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*)), this, + SLOT(slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*))); + connect(m_treeView, SIGNAL(itemSelectionChanged()), this, + SLOT(slotObjectTreeItemSelectionChanged())); + connect(m_designerWidget, SIGNAL(itemSelected(LimeReport::BaseDesignIntf*)), this, + SLOT(slotItemSelected(LimeReport::BaseDesignIntf*))); + connect(m_designerWidget, SIGNAL(multiItemSelected()), this, SLOT(slotMultiItemSelected())); + connect(m_designerWidget, SIGNAL(activePageUpdated(LimeReport::PageDesignIntf*)), this, + SLOT(slotActivePageUpdated(LimeReport::PageDesignIntf*))); + connect(m_treeView, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, + SLOT(slotItemDoubleClicked(QTreeWidgetItem*, int))); buildTree(); } -void ObjectBrowser::setMainWindow(QMainWindow *mainWindow) +void ObjectBrowser::setMainWindow(QMainWindow* mainWindow) { m_mainWindow = mainWindow; } + +void ObjectBrowser::slotClear() { } + +void ObjectBrowser::fillNode(QTreeWidgetItem* parentNode, BaseDesignIntf* reportItem, + BaseDesignIntf* ignoredItem) { - m_mainWindow=mainWindow; -} - -void ObjectBrowser::slotClear() -{ - -} - -void ObjectBrowser::fillNode(QTreeWidgetItem* parentNode, BaseDesignIntf* reportItem, BaseDesignIntf *ignoredItem){ foreach (BaseDesignIntf* item, reportItem->childBaseItems()) { - if (item != ignoredItem){ + if (item != ignoredItem) { ObjectBrowserNode* treeItem = new ObjectBrowserNode(/*parentNode*/); - treeItem->setText(0,item->objectName()); + treeItem->setText(0, item->objectName()); treeItem->setObject(item); - treeItem->setIcon(0,QIcon(":/items/"+extractClassName(item->metaObject()->className()))); - connect(item, SIGNAL(propertyObjectNameChanged(QString,QString)), - this, SLOT(slotPropertyObjectNameChanged(QString,QString)), Qt::UniqueConnection); + treeItem->setIcon( + 0, QIcon(":/items/" + extractClassName(item->metaObject()->className()))); + connect(item, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPropertyObjectNameChanged(QString, QString)), Qt::UniqueConnection); ItemDesignIntf* i = dynamic_cast(item); - if (i){ - connect(i, SIGNAL(itemLocationChanged(BaseDesignIntf*,BaseDesignIntf*)), - this, SLOT(slotItemParentChanged(BaseDesignIntf*,BaseDesignIntf*)), Qt::UniqueConnection); + if (i) { + connect(i, SIGNAL(itemLocationChanged(BaseDesignIntf*, BaseDesignIntf*)), this, + SLOT(slotItemParentChanged(BaseDesignIntf*, BaseDesignIntf*)), + Qt::UniqueConnection); } - m_itemsMap.insert(item,treeItem); + m_itemsMap.insert(item, treeItem); BandDesignIntf* band = dynamic_cast(item); QSet subBands; - subBands << BandDesignIntf::SubDetailBand << - BandDesignIntf::SubDetailHeader << - BandDesignIntf::SubDetailFooter; + subBands << BandDesignIntf::SubDetailBand << BandDesignIntf::SubDetailHeader + << BandDesignIntf::SubDetailFooter; - if (band && subBands.contains(band->bandType())){ + if (band && subBands.contains(band->bandType())) { ObjectBrowserNode* parentBandNode = 0; - if (band->bandType() == BandDesignIntf::SubDetailBand){ + if (band->bandType() == BandDesignIntf::SubDetailBand) { parentBandNode = m_itemsMap.value(band->parentBand()); } else { parentBandNode = m_itemsMap.value(band->parentBand()->parentBand()); } - if(parentBandNode) + if (parentBandNode) parentBandNode->addChild(treeItem); } else { parentNode->addChild(treeItem); } if (!item->childBaseItems().isEmpty()) - fillNode(treeItem,item, ignoredItem); + fillNode(treeItem, item, ignoredItem); } } } -void ObjectBrowser::buildTree(BaseDesignIntf* ignoredItem){ +void ObjectBrowser::buildTree(BaseDesignIntf* ignoredItem) +{ m_treeView->clear(); m_itemsMap.clear(); - if (!m_designerWidget->activePage()) return; + if (!m_designerWidget->activePage()) + return; - ObjectBrowserNode *topLevelItem=new ObjectBrowserNode(m_treeView); - topLevelItem->setText(0,m_designerWidget->activePage()->objectName()); + ObjectBrowserNode* topLevelItem = new ObjectBrowserNode(m_treeView); + topLevelItem->setText(0, m_designerWidget->activePage()->objectName()); topLevelItem->setObject(m_designerWidget->activePage()); - m_itemsMap.insert(m_designerWidget->activePage(),topLevelItem); + m_itemsMap.insert(m_designerWidget->activePage(), topLevelItem); m_treeView->addTopLevelItem(topLevelItem); QList itemsList = m_designerWidget->activePage()->items(); foreach (QGraphicsItem* item, itemsList) { - if (item != ignoredItem){ + if (item != ignoredItem) { BaseDesignIntf* reportItem = dynamic_cast(item); - if (reportItem && reportItem->parentItem()==0){ + if (reportItem && reportItem->parentItem() == 0) { ObjectBrowserNode* tItem = new ObjectBrowserNode(topLevelItem); - tItem->setText(0,reportItem->objectName()); + tItem->setText(0, reportItem->objectName()); tItem->setObject(reportItem); - tItem->setIcon(0,QIcon(":/items/"+extractClassName(reportItem->metaObject()->className()))); - connect(reportItem, SIGNAL(propertyObjectNameChanged(QString,QString)), - this, SLOT(slotPropertyObjectNameChanged(QString,QString))); - m_itemsMap.insert(reportItem,tItem); - fillNode(tItem,reportItem, ignoredItem); + tItem->setIcon( + 0, QIcon(":/items/" + extractClassName(reportItem->metaObject()->className()))); + connect(reportItem, SIGNAL(propertyObjectNameChanged(QString, QString)), this, + SLOT(slotPropertyObjectNameChanged(QString, QString))); + m_itemsMap.insert(reportItem, tItem); + fillNode(tItem, reportItem, ignoredItem); topLevelItem->addChild(tItem); } } } - m_treeView->sortItems(0,Qt::AscendingOrder); + m_treeView->sortItems(0, Qt::AscendingOrder); m_treeView->expandAll(); } -void ObjectBrowser::findAndRemove(QTreeWidgetItem* node, BaseDesignIntf* item){ +void ObjectBrowser::findAndRemove(QTreeWidgetItem* node, BaseDesignIntf* item) +{ - for (int i=0;ichildCount();i++){ + for (int i = 0; i < node->childCount(); i++) { QTreeWidgetItem* treeItem = node->child(i); - if (treeItem->text(0)==item->objectName()){ + if (treeItem->text(0) == item->objectName()) { node->removeChild(treeItem); break; } else { - if (treeItem->childCount()>0) findAndRemove(treeItem, item); + if (treeItem->childCount() > 0) + findAndRemove(treeItem, item); } } - } -void ObjectBrowser::slotPropertyObjectNameChanged(const QString &oldName, const QString &newName) +void ObjectBrowser::slotPropertyObjectNameChanged(const QString& oldName, const QString& newName) { Q_UNUSED(oldName) - if (m_itemsMap.contains(sender())){ - m_itemsMap.value(sender())->setText(0,newName); + if (m_itemsMap.contains(sender())) { + m_itemsMap.value(sender())->setText(0, newName); } } -//void ObjectBrowser::slotObjectNameChanged(const QString &objectName) +// void ObjectBrowser::slotObjectNameChanged(const QString &objectName) //{ // if (m_itemsMap.contains(sender())){ // m_itemsMap.value(sender())->setText(0,objectName); // } //} -void ObjectBrowser::removeItem(BaseDesignIntf *item) +void ObjectBrowser::removeItem(BaseDesignIntf* item) { - findAndRemove(m_treeView->topLevelItem(0),item); + findAndRemove(m_treeView->topLevelItem(0), item); } -void ObjectBrowser::slotReportLoaded() +void ObjectBrowser::slotReportLoaded() { buildTree(); } + +void ObjectBrowser::slotActivePageChanged() { buildTree(); } + +void ObjectBrowser::slotBandAdded(LimeReport::PageDesignIntf*, BandDesignIntf*) { buildTree(); } + +void ObjectBrowser::slotBandDeleted(PageDesignIntf*, BandDesignIntf* item) { buildTree(item); } + +void ObjectBrowser::slotItemAdded(PageDesignIntf* page, BaseDesignIntf*) { - buildTree(); + if (!page->isUpdating()) + buildTree(); } -void ObjectBrowser::slotActivePageChanged() +void ObjectBrowser::slotItemDeleted(PageDesignIntf*, BaseDesignIntf* item) { - buildTree(); -} - -void ObjectBrowser::slotBandAdded(LimeReport::PageDesignIntf *, BandDesignIntf *) -{ - buildTree(); -} - -void ObjectBrowser::slotBandDeleted(PageDesignIntf *, BandDesignIntf * item) -{ - buildTree(item); -} - -void ObjectBrowser::slotItemAdded(PageDesignIntf *page, BaseDesignIntf *) -{ - if (!page->isUpdating()) buildTree(); -} - -void ObjectBrowser::slotItemDeleted(PageDesignIntf *, BaseDesignIntf *item) -{ - if (dynamic_cast(item)){ + if (dynamic_cast(item)) { buildTree(item); } else { removeItem(item); @@ -232,12 +230,12 @@ void ObjectBrowser::slotItemDeleted(PageDesignIntf *, BaseDesignIntf *item) void ObjectBrowser::slotObjectTreeItemSelectionChanged() { - if (!m_changingItemSelection && m_designerWidget->activePage()){ + if (!m_changingItemSelection && m_designerWidget->activePage()) { m_changingItemSelection = true; m_designerWidget->activePage()->clearSelection(); - foreach(QTreeWidgetItem* item, m_treeView->selectedItems()){ + foreach (QTreeWidgetItem* item, m_treeView->selectedItems()) { ObjectBrowserNode* tn = dynamic_cast(item); - if (tn){ + if (tn) { BaseDesignIntf* si = dynamic_cast(tn->object()); if (si) { m_designerWidget->activePage()->animateItem(si); @@ -253,14 +251,14 @@ void ObjectBrowser::slotObjectTreeItemSelectionChanged() } } -void ObjectBrowser::slotItemSelected(LimeReport::BaseDesignIntf *item) +void ObjectBrowser::slotItemSelected(LimeReport::BaseDesignIntf* item) { - if (!m_changingItemSelection){ + if (!m_changingItemSelection) { m_changingItemSelection = true; m_treeView->selectionModel()->clear(); BaseDesignIntf* bg = dynamic_cast(item); - if (bg){ + if (bg) { if (m_itemsMap.value(bg)) m_itemsMap.value(bg)->setSelected(true); } @@ -271,17 +269,17 @@ void ObjectBrowser::slotItemSelected(LimeReport::BaseDesignIntf *item) void ObjectBrowser::slotMultiItemSelected() { - if (!m_changingItemSelection){ + if (!m_changingItemSelection) { m_changingItemSelection = true; m_treeView->selectionModel()->clear(); - foreach(QGraphicsItem* item, m_designerWidget->activePage()->selectedItems()){ + foreach (QGraphicsItem* item, m_designerWidget->activePage()->selectedItems()) { BaseDesignIntf* bg = dynamic_cast(item); - if (bg){ + if (bg) { ObjectBrowserNode* node = m_itemsMap.value(bg); if (node) - node->setSelected(true); + node->setSelected(true); } } @@ -289,10 +287,10 @@ void ObjectBrowser::slotMultiItemSelected() } } -void ObjectBrowser::slotItemDoubleClicked(QTreeWidgetItem *item, int) +void ObjectBrowser::slotItemDoubleClicked(QTreeWidgetItem* item, int) { ObjectBrowserNode* node = dynamic_cast(item); - if (node){ + if (node) { BaseDesignIntf* baseItem = dynamic_cast(node->object()); if (baseItem) { baseItem->showEditorDialog(); @@ -300,16 +298,11 @@ void ObjectBrowser::slotItemDoubleClicked(QTreeWidgetItem *item, int) } } -void ObjectBrowser::slotActivePageUpdated(LimeReport::PageDesignIntf *) -{ - buildTree(); -} - - +void ObjectBrowser::slotActivePageUpdated(LimeReport::PageDesignIntf*) { buildTree(); } void ObjectBrowser::moveItemNode(BaseDesignIntf* item, BaseDesignIntf* parent) { - if (m_itemsMap.contains(item) && m_itemsMap.contains(parent)){ + if (m_itemsMap.contains(item) && m_itemsMap.contains(parent)) { m_itemsMap.value(item)->parent()->removeChild(m_itemsMap.value(item)); m_itemsMap.value(parent)->addChild(m_itemsMap.value(item)); m_changingItemSelection = true; @@ -321,11 +314,11 @@ void ObjectBrowser::moveItemNode(BaseDesignIntf* item, BaseDesignIntf* parent) void ObjectBrowser::slotItemParentChanged(BaseDesignIntf* item, BaseDesignIntf* parent) { - if (!m_movingItem){ + if (!m_movingItem) { m_movingItem = true; moveItemNode(item, parent); m_movingItem = false; - foreach(QObject* di, m_defferedItems){ + foreach (QObject* di, m_defferedItems) { BaseDesignIntf* b = dynamic_cast(di); if (b) moveItemNode(b, parent); @@ -337,28 +330,24 @@ void ObjectBrowser::slotItemParentChanged(BaseDesignIntf* item, BaseDesignIntf* } } -void ObjectBrowserNode::setObject(QObject *value) +void ObjectBrowserNode::setObject(QObject* value) { m_object = value; } + +QObject* ObjectBrowserNode::object() const { return m_object; } + +ObjectBrowserNode::ObjectBrowserNode(QTreeWidget* view): QTreeWidgetItem(view), m_object(0) { } + +ObjectBrowserNode::ObjectBrowserNode(QTreeWidgetItem* parent): QTreeWidgetItem(parent), m_object(0) { - m_object = value; } -QObject *ObjectBrowserNode::object() const -{ - return m_object; -} - -ObjectBrowserNode::ObjectBrowserNode(QTreeWidget *view) - :QTreeWidgetItem(view), m_object(0){} - -ObjectBrowserNode::ObjectBrowserNode(QTreeWidgetItem *parent) - :QTreeWidgetItem(parent), m_object(0){} - -bool ObjectBrowserNode::operator <(const QTreeWidgetItem &other) const +bool ObjectBrowserNode::operator<(const QTreeWidgetItem& other) const { BandDesignIntf* band1 = dynamic_cast(m_object); - BandDesignIntf* band2 = dynamic_cast(dynamic_cast(other).object()); - if (band1 && band2) return band1->bandIndex()bandIndex(); + BandDesignIntf* band2 + = dynamic_cast(dynamic_cast(other).object()); + if (band1 && band2) + return band1->bandIndex() < band2->bandIndex(); return false; } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/objectsbrowser/lrobjectbrowser.h b/limereport/objectsbrowser/lrobjectbrowser.h index 8008e1c..fee27f1 100644 --- a/limereport/objectsbrowser/lrobjectbrowser.h +++ b/limereport/objectsbrowser/lrobjectbrowser.h @@ -30,62 +30,66 @@ #ifndef LROBJECTBROWSER_H #define LROBJECTBROWSER_H -#include -#include -#include "lrreportdesignwidget.h" #include "lrbasedesignintf.h" +#include "lrreportdesignwidget.h" -namespace LimeReport{ +#include +#include -class ObjectBrowserNode :public QTreeWidgetItem{ +namespace LimeReport { + +class ObjectBrowserNode: public QTreeWidgetItem { public: void setObject(QObject* value); QObject* object() const; - explicit ObjectBrowserNode(QTreeWidget *view); - explicit ObjectBrowserNode(QTreeWidgetItem *parent = 0); - bool operator <(const QTreeWidgetItem& other) const; + explicit ObjectBrowserNode(QTreeWidget* view); + explicit ObjectBrowserNode(QTreeWidgetItem* parent = 0); + bool operator<(const QTreeWidgetItem& other) const; + private: QObject* m_object; }; -class ObjectBrowser :public QWidget -{ +class ObjectBrowser: public QWidget { Q_OBJECT public: - ObjectBrowser(QWidget *parent=0); + ObjectBrowser(QWidget* parent = 0); void setReportEditor(LimeReport::ReportDesignWidget* designerWidget); void setMainWindow(QMainWindow* mainWindow); + protected: - void fillNode(QTreeWidgetItem *parentNode, BaseDesignIntf *reportItem, BaseDesignIntf* ignoredItem = 0); - void buildTree(BaseDesignIntf *ignoredItem = 0); + void fillNode(QTreeWidgetItem* parentNode, BaseDesignIntf* reportItem, + BaseDesignIntf* ignoredItem = 0); + void buildTree(BaseDesignIntf* ignoredItem = 0); void removeItem(BaseDesignIntf* item); - void findAndRemove(QTreeWidgetItem *node, BaseDesignIntf *item); + void findAndRemove(QTreeWidgetItem* node, BaseDesignIntf* item); void moveItemNode(BaseDesignIntf* item, BaseDesignIntf* parent); private slots: -// void slotObjectNameChanged(const QString& objectName); + // void slotObjectNameChanged(const QString& objectName); void slotPropertyObjectNameChanged(const QString& oldName, const QString& newName); void slotClear(); void slotReportLoaded(); void slotActivePageChanged(); void slotBandAdded(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*); - void slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf*item); - void slotItemAdded(LimeReport::PageDesignIntf*page, LimeReport::BaseDesignIntf*); - void slotItemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf*item); + void slotBandDeleted(LimeReport::PageDesignIntf*, LimeReport::BandDesignIntf* item); + void slotItemAdded(LimeReport::PageDesignIntf* page, LimeReport::BaseDesignIntf*); + void slotItemDeleted(LimeReport::PageDesignIntf*, LimeReport::BaseDesignIntf* item); void slotObjectTreeItemSelectionChanged(); void slotItemSelected(LimeReport::BaseDesignIntf* item); void slotMultiItemSelected(); - void slotItemDoubleClicked(QTreeWidgetItem* item,int); + void slotItemDoubleClicked(QTreeWidgetItem* item, int); void slotActivePageUpdated(LimeReport::PageDesignIntf*); void slotItemParentChanged(BaseDesignIntf* item, BaseDesignIntf* parent); + private: ReportDesignWidget* m_designerWidget; - QMainWindow* m_mainWindow; - QTreeWidget* m_treeView; + QMainWindow* m_mainWindow; + QTreeWidget* m_treeView; QMap m_itemsMap; bool m_changingItemSelection; bool m_movingItem; QList m_defferedItems; }; -} //namespace LimeReport +} // namespace LimeReport #endif // LROBJECTBROWSER_H diff --git a/limereport/scriptbrowser/lrscriptbrowser.cpp b/limereport/scriptbrowser/lrscriptbrowser.cpp index ae8ddc5..3f81ab5 100644 --- a/limereport/scriptbrowser/lrscriptbrowser.cpp +++ b/limereport/scriptbrowser/lrscriptbrowser.cpp @@ -36,11 +36,9 @@ #endif #include -namespace LimeReport{ +namespace LimeReport { -ScriptBrowser::ScriptBrowser(QWidget *parent) : - QWidget(parent), - ui(new Ui::ScriptBrowser) +ScriptBrowser::ScriptBrowser(QWidget* parent): QWidget(parent), ui(new Ui::ScriptBrowser) { ui->setupUi(this); int margin = Const::DOCKWIDGET_MARGINS; @@ -51,18 +49,16 @@ ScriptBrowser::ScriptBrowser(QWidget *parent) : #endif } -ScriptBrowser::~ScriptBrowser() -{ - delete ui; -} +ScriptBrowser::~ScriptBrowser() { delete ui; } void ScriptBrowser::setReportEditor(ReportDesignWidget* designerWidget) { - m_designerWidget=designerWidget; - connect(m_designerWidget,SIGNAL(cleared()),this,SLOT(slotClear())); - connect(m_designerWidget,SIGNAL(loadFinished()),this,SLOT(slotUpdate())); + m_designerWidget = designerWidget; + connect(m_designerWidget, SIGNAL(cleared()), this, SLOT(slotClear())); + connect(m_designerWidget, SIGNAL(loadFinished()), this, SLOT(slotUpdate())); #ifdef HAVE_UI_LOADER - connect(m_designerWidget->scriptContext(), SIGNAL(dialogAdded(QString)), this, SLOT(slotDialogAdded(QString))); + connect(m_designerWidget->scriptContext(), SIGNAL(dialogAdded(QString)), this, + SLOT(slotDialogAdded(QString))); #endif updateFunctionTree(); } @@ -71,61 +67,64 @@ void ScriptBrowser::updateFunctionTree() { ui->twFunctions->clear(); ScriptEngineManager* sm = reportEditor()->scriptManager(); - QMap categ; - foreach(ScriptFunctionDesc fd, sm->functionsDescribers()){ - QString functionCategory = (fd.category!="") ? fd.category : tr("NO CATEGORY"); - if (categ.contains(functionCategory)){ - QTreeWidgetItem* item = new QTreeWidgetItem(categ.value(fd.category),QStringList(fd.name)); - item->setIcon(0,QIcon(":/report/images/function")); + QMap categ; + foreach (ScriptFunctionDesc fd, sm->functionsDescribers()) { + QString functionCategory = (fd.category != "") ? fd.category : tr("NO CATEGORY"); + if (categ.contains(functionCategory)) { + QTreeWidgetItem* item + = new QTreeWidgetItem(categ.value(fd.category), QStringList(fd.name)); + item->setIcon(0, QIcon(":/report/images/function")); } else { - QTreeWidgetItem* categItem = new QTreeWidgetItem(ui->twFunctions,QStringList(functionCategory)); - categItem->setIcon(0,QIcon(":/report/images/folder")); - categ.insert(functionCategory,categItem); - QTreeWidgetItem* item = new QTreeWidgetItem(categItem,QStringList(fd.name)); - item->setIcon(0,QIcon(":/report/images/function")); + QTreeWidgetItem* categItem + = new QTreeWidgetItem(ui->twFunctions, QStringList(functionCategory)); + categItem->setIcon(0, QIcon(":/report/images/folder")); + categ.insert(functionCategory, categItem); + QTreeWidgetItem* item = new QTreeWidgetItem(categItem, QStringList(fd.name)); + item->setIcon(0, QIcon(":/report/images/function")); } } } #ifdef HAVE_UI_LOADER -void ScriptBrowser::fillProperties(QTreeWidgetItem* objectItem, QObject* item){ - for(int i=0; imetaObject()->propertyCount(); ++i){ +void ScriptBrowser::fillProperties(QTreeWidgetItem* objectItem, QObject* item) +{ + for (int i = 0; i < item->metaObject()->propertyCount(); ++i) { QStringList row; - row<metaObject()->property(i).typeName()<metaObject()->property(i).name(); - /*QTreeWidgetItem* propItem = */new QTreeWidgetItem(objectItem,row); + row << item->metaObject()->property(i).typeName() << item->metaObject()->property(i).name(); + /*QTreeWidgetItem* propItem = */ new QTreeWidgetItem(objectItem, row); } } -void ScriptBrowser::fillDialog(QTreeWidgetItem* dialogItem,const QString& description){ +void ScriptBrowser::fillDialog(QTreeWidgetItem* dialogItem, const QString& description) +{ QUiLoader loader; QByteArray baDesc = description.toUtf8(); QBuffer buff(&baDesc); buff.open(QIODevice::ReadOnly); QDialog* dialog = dynamic_cast(loader.load(&buff)); - if (dialog){ + if (dialog) { foreach (QObject* child, dialog->children()) { - if (!child->objectName().isEmpty()){ + if (!child->objectName().isEmpty()) { QStringList row; - row<metaObject()->className()<objectName(); - QTreeWidgetItem* item = new QTreeWidgetItem(dialogItem,row); - item->setIcon(0,QIcon(":/scriptbrowser/images/item")); - fillProperties(item,child); + row << child->metaObject()->className() << child->objectName(); + QTreeWidgetItem* item = new QTreeWidgetItem(dialogItem, row); + item->setIcon(0, QIcon(":/scriptbrowser/images/item")); + fillProperties(item, child); } } delete dialog; } - } void ScriptBrowser::updateDialogsTree() { ui->twDialogs->clear(); ScriptEngineContext* sc = reportEditor()->scriptContext(); - foreach(DialogDescriber::Ptr dc, sc->dialogDescribers()){ - QTreeWidgetItem* dialogItem = new QTreeWidgetItem(ui->twDialogs,QStringList(dc->name())); - dialogItem->setIcon(0,QIcon(":/scriptbrowser/images/dialog")); - fillDialog(dialogItem,dc->description()); + foreach (DialogDescriber::Ptr dc, sc->dialogDescribers()) { + QTreeWidgetItem* dialogItem = new QTreeWidgetItem(ui->twDialogs, QStringList(dc->name())); + dialogItem->setIcon(0, QIcon(":/scriptbrowser/images/dialog")); + fillDialog(dialogItem, dc->description()); } } #endif @@ -145,40 +144,45 @@ void ScriptBrowser::slotUpdate() #ifdef HAVE_UI_LOADER -void ScriptBrowser::slotDialogAdded(QString) -{ - updateDialogsTree(); -} +void ScriptBrowser::slotDialogAdded(QString) { updateDialogsTree(); } void ScriptBrowser::on_tbAddDialog_clicked() { QFileDialog fileDialog(this); - if (fileDialog.exec()==QDialog::Accepted){ + if (fileDialog.exec() == QDialog::Accepted) { QStringList fileNames = fileDialog.selectedFiles(); QUiLoader loader; - if (!fileNames.isEmpty()){ + if (!fileNames.isEmpty()) { foreach (QString fileName, fileNames) { QFile file(fileName); file.open(QIODevice::ReadOnly); - if (file.isOpen()){ + if (file.isOpen()) { QWidget* widget = loader.load(&file); QDialog* dialog = dynamic_cast(widget); - if (dialog){ - if (!m_designerWidget->scriptContext()->containsDialog(dialog->objectName())){ + if (dialog) { + if (!m_designerWidget->scriptContext()->containsDialog( + dialog->objectName())) { file.seek(0); - m_designerWidget->scriptContext()->addDialog(dialog->objectName(),file.readAll()); - //updateDialogsTree(); + m_designerWidget->scriptContext()->addDialog(dialog->objectName(), + file.readAll()); + // updateDialogsTree(); } else { - QMessageBox::critical(this,tr("Error"),tr("Dialog with name: %1 already exists").arg(dialog->objectName())); + QMessageBox::critical(this, tr("Error"), + tr("Dialog with name: %1 already exists") + .arg(dialog->objectName())); } } else { if (widget) - QMessageBox::critical(this,tr("Error"),tr("ui file must cointain QDialog instead QWidget or QMainWindow")); + QMessageBox::critical( + this, tr("Error"), + tr("ui file must cointain QDialog instead QWidget or " + "QMainWindow")); else - QMessageBox::critical(this,tr("Error"),tr("wrong file format")); + QMessageBox::critical(this, tr("Error"), tr("wrong file format")); } - if (widget) delete widget; + if (widget) + delete widget; } } } @@ -187,14 +191,14 @@ void ScriptBrowser::on_tbAddDialog_clicked() void ScriptBrowser::on_tbRunDialog_clicked() { - if (ui->twDialogs->currentItem()&& ui->twDialogs->currentItem()->parent()==0){ + if (ui->twDialogs->currentItem() && ui->twDialogs->currentItem()->parent() == 0) { m_designerWidget->scriptContext()->previewDialog(ui->twDialogs->currentItem()->text(0)); } } void ScriptBrowser::on_tbDeleteDialog_clicked() { - if (ui->twDialogs->currentItem()&& ui->twDialogs->currentItem()->parent()==0){ + if (ui->twDialogs->currentItem() && ui->twDialogs->currentItem()->parent() == 0) { m_designerWidget->scriptContext()->deleteDialog(ui->twDialogs->currentItem()->text(0)); updateDialogsTree(); } @@ -202,6 +206,4 @@ void ScriptBrowser::on_tbDeleteDialog_clicked() #endif -} //namespace LimeReport - - +} // namespace LimeReport diff --git a/limereport/scriptbrowser/lrscriptbrowser.h b/limereport/scriptbrowser/lrscriptbrowser.h index 5ac96da..4b69b0b 100644 --- a/limereport/scriptbrowser/lrscriptbrowser.h +++ b/limereport/scriptbrowser/lrscriptbrowser.h @@ -30,34 +30,34 @@ #ifndef LRSCRIPTBROWSER_H #define LRSCRIPTBROWSER_H -#include -#include -#include #include "lrreportdesignwidget.h" -namespace LimeReport{ +#include +#include +#include + +namespace LimeReport { namespace Ui { -class ScriptBrowser; + class ScriptBrowser; } -class ScriptBrowser : public QWidget -{ +class ScriptBrowser: public QWidget { Q_OBJECT - + public: - explicit ScriptBrowser(QWidget *parent = 0); + explicit ScriptBrowser(QWidget* parent = 0); ~ScriptBrowser(); void setReportEditor(LimeReport::ReportDesignWidget* designerWidget); - inline ReportDesignWidget* reportEditor(){return m_designerWidget;} + inline ReportDesignWidget* reportEditor() { return m_designerWidget; } void updateFunctionTree(); #ifdef HAVE_UI_LOADER void updateDialogsTree(); #endif protected: #ifdef HAVE_UI_LOADER - void fillDialog(QTreeWidgetItem *dialogItem, const QString &description); - void fillProperties(QTreeWidgetItem *objectItem, QObject *item); + void fillDialog(QTreeWidgetItem* dialogItem, const QString& description); + void fillProperties(QTreeWidgetItem* objectItem, QObject* item); #endif private slots: void slotClear(); @@ -70,8 +70,8 @@ private slots: #endif private: - Ui::ScriptBrowser *ui; - ReportDesignWidget* m_designerWidget; + Ui::ScriptBrowser* ui; + ReportDesignWidget* m_designerWidget; }; } // namespace LimeReport diff --git a/limereport/scripteditor/lrcodeeditor.cpp b/limereport/scripteditor/lrcodeeditor.cpp index c70c20b..6295cc8 100644 --- a/limereport/scripteditor/lrcodeeditor.cpp +++ b/limereport/scripteditor/lrcodeeditor.cpp @@ -1,45 +1,45 @@ #include "lrcodeeditor.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#include "lrscripthighlighter.h" #include "lrglobal.h" +#include "lrscripthighlighter.h" -namespace LimeReport{ +#include +#include +#include +#include +#include +#include +#include +#include -CodeEditor::CodeEditor(QWidget *parent) - : QPlainTextEdit(parent), m_completer(0) +namespace LimeReport { + +CodeEditor::CodeEditor(QWidget* parent): QPlainTextEdit(parent), m_completer(0) { lineNumberArea = new LineNumberArea(this); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); - connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); + connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(updateLineNumberArea(QRect, int))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); updateLineNumberAreaWidth(0); highlightCurrentLine(); new ScriptHighlighter(document()); - connect(this, SIGNAL(cursorPositionChanged()), - this, SLOT(matchParentheses())); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(matchParentheses())); } -void CodeEditor::setCompleter(QCompleter *value) +void CodeEditor::setCompleter(QCompleter* value) { - if (value) disconnect(value,0,this,0); + if (value) + disconnect(value, 0, this, 0); m_completer = value; - if (!m_completer) return; + if (!m_completer) + return; m_completer->setWidget(this); m_completer->setCompletionMode(QCompleter::PopupCompletion); m_completer->setCaseSensitivity(Qt::CaseInsensitive); - connect(m_completer,SIGNAL(activated(QString)),this,SLOT(insertCompletion(QString))); + connect(m_completer, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent* event) @@ -47,14 +47,14 @@ void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent* event) QPainter painter(lineNumberArea); QStyleOption option; option.initFrom(this); - //painter.fillRect(event->rect(), QPalette().window().color()); + // painter.fillRect(event->rect(), QPalette().window().color()); QColor bg = option.palette.window().color().darker(150); painter.fillRect(event->rect(), bg); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); - int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); - int bottom = top + (int) blockBoundingRect(block).height(); + int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top(); + int bottom = top + (int)blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { @@ -66,7 +66,7 @@ void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent* event) block = block.next(); top = bottom; - bottom = top + (int) blockBoundingRect(block).height(); + bottom = top + (int)blockBoundingRect(block).height(); ++blockNumber; } } @@ -80,12 +80,13 @@ int CodeEditor::lineNumberAreaWidth() ++digits; } - int space = fontMetrics().boundingRect(QLatin1Char('9')).width()*2 + fontMetrics().boundingRect(QLatin1Char('9')).width() * digits; + int space = fontMetrics().boundingRect(QLatin1Char('9')).width() * 2 + + fontMetrics().boundingRect(QLatin1Char('9')).width() * digits; return space; } -void CodeEditor::keyPressEvent(QKeyEvent *e) +void CodeEditor::keyPressEvent(QKeyEvent* e) { if (m_completer && m_completer->popup()->isVisible()) { switch (e->key()) { @@ -106,7 +107,8 @@ void CodeEditor::keyPressEvent(QKeyEvent *e) } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); - if (!m_completer || !isShortcut) QPlainTextEdit::keyPressEvent(e); + if (!m_completer || !isShortcut) + QPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!m_completer || (ctrlOrShift && e->text().isEmpty())) @@ -116,10 +118,9 @@ void CodeEditor::keyPressEvent(QKeyEvent *e) QString completionPrefix = textUnderCursor(); - if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 - || Const::EOW.contains(e->text().right(1))) - ) - { + if (!isShortcut + && (hasModifier || e->text().isEmpty() || completionPrefix.length() < 3 + || Const::EOW.contains(e->text().right(1)))) { m_completer->popup()->hide(); return; } @@ -129,8 +130,9 @@ void CodeEditor::keyPressEvent(QKeyEvent *e) m_completer->popup()->setCurrentIndex(m_completer->completionModel()->index(0, 0)); } - QModelIndex ci = m_completer->completionModel()->index(0,0); - if (ci.isValid() && m_completer->completionModel()->data(ci).toString().compare(completionPrefix) == 0){ + QModelIndex ci = m_completer->completionModel()->index(0, 0); + if (ci.isValid() + && m_completer->completionModel()->data(ci).toString().compare(completionPrefix) == 0) { m_completer->popup()->hide(); return; } @@ -140,16 +142,15 @@ void CodeEditor::keyPressEvent(QKeyEvent *e) + m_completer->popup()->verticalScrollBar()->sizeHint().width()); m_completer->complete(cr); - if (!completionPrefix.isEmpty() && - completionPrefix.at(completionPrefix.length()-1) == '.') - { + if (!completionPrefix.isEmpty() && completionPrefix.at(completionPrefix.length() - 1) == '.') { m_completer->popup(); } } -void CodeEditor::focusInEvent(QFocusEvent *e) +void CodeEditor::focusInEvent(QFocusEvent* e) { - if (m_completer) m_completer->setWidget(this); + if (m_completer) + m_completer->setWidget(this); QPlainTextEdit::focusInEvent(e); } @@ -164,39 +165,40 @@ QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); QString currentText; - tc.movePosition(QTextCursor::StartOfBlock,QTextCursor::KeepAnchor); + tc.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); QString blockText = tc.selectedText(); - for(int i = blockText.length(); i>0; --i){ - if (!Const::EOW.contains(blockText.at(i-1))) - currentText = blockText.at(i-1) + currentText; - else break; + for (int i = blockText.length(); i > 0; --i) { + if (!Const::EOW.contains(blockText.at(i - 1))) + currentText = blockText.at(i - 1) + currentText; + else + break; } return currentText.trimmed(); } -bool CodeEditor::matchLeftParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, int numLeftParentheses) +bool CodeEditor::matchLeftParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, + int numLeftParentheses) { - TextBlockData *data = static_cast(currentBlock.userData()); - if (data){ - QVector infos = data->parentheses(); + TextBlockData* data = static_cast(currentBlock.userData()); + if (data) { + QVector infos = data->parentheses(); int docPos = currentBlock.position(); for (; i < infos.size(); ++i) { - ParenthesisInfo *info = infos.at(i); + ParenthesisInfo* info = infos.at(i); if (info->character == parenthesisType) { ++numLeftParentheses; continue; } - if (info->character == getParenthesisReverceChar(parenthesisType)){ + if (info->character == getParenthesisReverceChar(parenthesisType)) { if (numLeftParentheses == 0) { createParenthesisSelection(docPos + info->position); return true; } else --numLeftParentheses; } - } } @@ -207,20 +209,22 @@ bool CodeEditor::matchLeftParenthesis(QTextBlock currentBlock, QChar parenthesis return false; } -bool CodeEditor::matchRightParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, int numRightParentheses) +bool CodeEditor::matchRightParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, + int numRightParentheses) { - TextBlockData *data = static_cast(currentBlock.userData()); - if (data){ - QVector parentheses = data->parentheses(); + TextBlockData* data = static_cast(currentBlock.userData()); + if (data) { + QVector parentheses = data->parentheses(); int docPos = currentBlock.position(); - if (i == -2) i = parentheses.size()-1; + if (i == -2) + i = parentheses.size() - 1; for (; i > -1 && parentheses.size() > 0; --i) { - ParenthesisInfo *info = parentheses.at(i); + ParenthesisInfo* info = parentheses.at(i); if (info->character == parenthesisType) { ++numRightParentheses; continue; } - if (info->character == getParenthesisReverceChar(parenthesisType)){ + if (info->character == getParenthesisReverceChar(parenthesisType)) { if (numRightParentheses == 0) { createParenthesisSelection(docPos + info->position); return true; @@ -259,7 +263,7 @@ void CodeEditor::createParenthesisSelection(int pos) bool CodeEditor::charIsParenthesis(QChar character, ParenthesisType type) { - for (int i = 0; i < PARENHEIS_COUNT; ++i){ + for (int i = 0; i < PARENHEIS_COUNT; ++i) { if (character == parenthesisCharacters[type][i]) return true; } @@ -268,27 +272,27 @@ bool CodeEditor::charIsParenthesis(QChar character, ParenthesisType type) QChar CodeEditor::getParenthesisReverceChar(QChar parenthesisChar) { - for (int i = 0; i < PARENHEIS_COUNT; ++i){ - if ( parenthesisCharacters[RightParenthesis][i] == parenthesisChar) + for (int i = 0; i < PARENHEIS_COUNT; ++i) { + if (parenthesisCharacters[RightParenthesis][i] == parenthesisChar) return parenthesisCharacters[LeftParenthesis][i]; - if ( parenthesisCharacters[LeftParenthesis][i] == parenthesisChar) + if (parenthesisCharacters[LeftParenthesis][i] == parenthesisChar) return parenthesisCharacters[RightParenthesis][i]; } return ' '; } -void CodeEditor::insertCompletion(const QString &completion) +void CodeEditor::insertCompletion(const QString& completion) { if (m_completer->widget() != this) - return; + return; QTextCursor tc = textCursor(); -// QString prefix = m_completer->completionPrefix(); -// int extra = completion.length() - prefix.length(); - for (int i=0; i < m_completer->completionPrefix().length(); ++i ) { + // QString prefix = m_completer->completionPrefix(); + // int extra = completion.length() - prefix.length(); + for (int i = 0; i < m_completer->completionPrefix().length(); ++i) { tc.deletePreviousChar(); } tc.insertText(completion); -// tc.insertText(completion.right(extra)); + // tc.insertText(completion.right(extra)); setTextCursor(tc); } @@ -332,27 +336,28 @@ void CodeEditor::matchParentheses() QList selections; setExtraSelections(selections); - TextBlockData *data = static_cast(textCursor().block().userData()); + TextBlockData* data = static_cast(textCursor().block().userData()); if (data) { - QVector infos = data->parentheses(); + QVector infos = data->parentheses(); int pos = textCursor().block().position(); for (int i = 0; i < infos.size(); ++i) { - ParenthesisInfo *info = infos.at(i); + ParenthesisInfo* info = infos.at(i); int curPos = textCursor().position() - textCursor().block().position(); - if ( (info->position == (curPos - 1)) && charIsParenthesis(info->character, LeftParenthesis)) - { + if ((info->position == (curPos - 1)) + && charIsParenthesis(info->character, LeftParenthesis)) { if (matchLeftParenthesis(textCursor().block(), info->character, i + 1, 0)) createParenthesisSelection(pos + info->position); - } else if ( (info->position == (curPos - 1)) && charIsParenthesis(info->character, RightParenthesis)) { + } else if ((info->position == (curPos - 1)) + && charIsParenthesis(info->character, RightParenthesis)) { if (matchRightParenthesis(textCursor().block(), info->character, i - 1, 0)) createParenthesisSelection(pos + info->position); } - } + } } } -} //namespace LimeReport +} // namespace LimeReport diff --git a/limereport/scripteditor/lrcodeeditor.h b/limereport/scripteditor/lrcodeeditor.h index 9a638b3..2bbe7b3 100644 --- a/limereport/scripteditor/lrcodeeditor.h +++ b/limereport/scripteditor/lrcodeeditor.h @@ -1,9 +1,10 @@ #ifndef LRCODEEDITOR_H #define LRCODEEDITOR_H +#include "lrscripthighlighter.h" + #include #include -#include "lrscripthighlighter.h" QT_BEGIN_NAMESPACE class QWidget; @@ -12,58 +13,54 @@ class QKeyEvent; class QScrollBar; QT_END_NAMESPACE -namespace LimeReport{ +namespace LimeReport { -class CodeEditor :public QPlainTextEdit -{ +class CodeEditor: public QPlainTextEdit { Q_OBJECT public: - CodeEditor(QWidget* parent=0); + CodeEditor(QWidget* parent = 0); void setCompleter(QCompleter* value); - QCompleter* compleater() const{ return m_completer;} - void lineNumberAreaPaintEvent(QPaintEvent *event); + QCompleter* compleater() const { return m_completer; } + void lineNumberAreaPaintEvent(QPaintEvent* event); int lineNumberAreaWidth(); + protected: - void keyPressEvent(QKeyEvent *e); - void focusInEvent(QFocusEvent *e); - void resizeEvent(QResizeEvent *event); + void keyPressEvent(QKeyEvent* e); + void focusInEvent(QFocusEvent* e); + void resizeEvent(QResizeEvent* event); + private: QString textUnderCursor() const; - bool matchLeftParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, int numLeftParentheses); - bool matchRightParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, int numRightParentheses); - void createParenthesisSelection(int pos); - bool charIsParenthesis(QChar character, ParenthesisType type); - QChar getParenthesisReverceChar(QChar parenthesisChar); + bool matchLeftParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, + int numLeftParentheses); + bool matchRightParenthesis(QTextBlock currentBlock, QChar parenthesisType, int i, + int numRightParentheses); + void createParenthesisSelection(int pos); + bool charIsParenthesis(QChar character, ParenthesisType type); + QChar getParenthesisReverceChar(QChar parenthesisChar); private slots: void insertCompletion(const QString& completion); void updateLineNumberAreaWidth(int newBlockCount); void highlightCurrentLine(); - void updateLineNumberArea(const QRect &rect, int dy); + void updateLineNumberArea(const QRect& rect, int dy); void matchParentheses(); + private: QCompleter* m_completer; - QWidget *lineNumberArea; + QWidget* lineNumberArea; }; - -class LineNumberArea : public QWidget -{ +class LineNumberArea: public QWidget { public: - LineNumberArea(CodeEditor *editor) : QWidget(editor) { - codeEditor = editor; - } + LineNumberArea(CodeEditor* editor): QWidget(editor) { codeEditor = editor; } - QSize sizeHint() const { - return QSize(codeEditor->lineNumberAreaWidth(), 0); - } + QSize sizeHint() const { return QSize(codeEditor->lineNumberAreaWidth(), 0); } protected: - void paintEvent(QPaintEvent *event) { - codeEditor->lineNumberAreaPaintEvent(event); - } + void paintEvent(QPaintEvent* event) { codeEditor->lineNumberAreaPaintEvent(event); } private: - CodeEditor *codeEditor; + CodeEditor* codeEditor; }; } // namespace LimeReport diff --git a/limereport/scripteditor/lrcompletermodel.cpp b/limereport/scripteditor/lrcompletermodel.cpp index 70299f6..367aba4 100644 --- a/limereport/scripteditor/lrcompletermodel.cpp +++ b/limereport/scripteditor/lrcompletermodel.cpp @@ -1,74 +1,78 @@ #include "lrcompletermodel.h" + #include -CompleterModel::CompleterModel(QObject *parent) : QAbstractItemModel(parent){m_root.setModel(this);} - -QModelIndex CompleterModel::index(int row, int column, const QModelIndex &parent) const +CompleterModel::CompleterModel(QObject* parent): QAbstractItemModel(parent) { - CompleterItem const *parentItem; + m_root.setModel(this); +} + +QModelIndex CompleterModel::index(int row, int column, const QModelIndex& parent) const +{ + CompleterItem const* parentItem; if (!parent.isValid()) parentItem = &m_root; else parentItem = static_cast(parent.internalPointer()); - if ((parentItem == nullptr) - || (row < 0) - || (column < 0) - || (row >= parentItem->rowCount()) - || (column >= 1)) - { + if ((parentItem == nullptr) || (row < 0) || (column < 0) || (row >= parentItem->rowCount()) + || (column >= 1)) { return QModelIndex(); } return createIndex(row, column, parentItem->child(row)); } -QModelIndex CompleterModel::parent(const QModelIndex &child) const { - if(child.isValid()) { - if(CompleterItem *childItem = static_cast(child.internalPointer()); - childItem) { - CompleterItem *parentItem = childItem->parent(); - if(parentItem != &m_root) { - return indexFromItem(parentItem); - } +QModelIndex CompleterModel::parent(const QModelIndex& child) const +{ + if (child.isValid()) { + if (CompleterItem* childItem = static_cast(child.internalPointer()); + childItem) { + CompleterItem* parentItem = childItem->parent(); + if (parentItem != &m_root) { + return indexFromItem(parentItem); + } + } } - } - return QModelIndex(); + return QModelIndex(); } -int CompleterModel::rowCount(const QModelIndex &parent) const +int CompleterModel::rowCount(const QModelIndex& parent) const { - if (parent.isValid()){ - CompleterItem *parentItem = static_cast(parent.internalPointer()); + if (parent.isValid()) { + CompleterItem* parentItem = static_cast(parent.internalPointer()); return parentItem->rowCount(); } return m_root.rowCount(); } -int CompleterModel::columnCount(const QModelIndex &parent) const +int CompleterModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent) return 1; } -QVariant CompleterModel::data(const QModelIndex &index, int role) const +QVariant CompleterModel::data(const QModelIndex& index, int role) const { - if (index.isValid()){ + if (index.isValid()) { CompleterItem* item = static_cast(index.internalPointer()); switch (role) { case Qt::DisplayRole: case Qt::EditRole: - if (!item) return QVariant(); + if (!item) + return QVariant(); - if (index.column()==0){ + if (index.column() == 0) { return item->text(); } else { return ""; } - case Qt::DecorationRole : - if (!item) return QIcon(); - if (index.column()==0){ + case Qt::DecorationRole: + if (!item) + return QIcon(); + if (index.column() == 0) { return item->icon(); - } else return QIcon(); + } else + return QIcon(); default: return QVariant(); } @@ -76,10 +80,11 @@ QVariant CompleterModel::data(const QModelIndex &index, int role) const return QVariant(); } -QList CompleterModel::findItems(const QString &text, Qt::MatchFlags flags, int column) const +QList CompleterModel::findItems(const QString& text, Qt::MatchFlags flags, + int column) const { - QModelIndexList indexes = match(index(0, column, QModelIndex()), - Qt::DisplayRole, text, -1, flags); + QModelIndexList indexes + = match(index(0, column, QModelIndex()), Qt::DisplayRole, text, -1, flags); QList items; const int numIndexes = indexes.size(); items.reserve(numIndexes); @@ -95,49 +100,45 @@ void CompleterModel::clear() endResetModel(); } -CompleterItem *CompleterModel::itemFromIndex(const QModelIndex index) const +CompleterItem* CompleterModel::itemFromIndex(const QModelIndex index) const { if ((index.row() < 0) || (index.column() < 0) || (index.model() != this)) - return nullptr; - CompleterItem *parent = static_cast(index.internalPointer()); + return nullptr; + CompleterItem* parent = static_cast(index.internalPointer()); if (parent == nullptr) - return nullptr; - CompleterItem *item = parent->child(index.row()); + return nullptr; + CompleterItem* item = parent->child(index.row()); return item; } -QModelIndex CompleterModel::indexFromItem(CompleterItem *item) const +QModelIndex CompleterModel::indexFromItem(CompleterItem* item) const { - if (item && item->parent()){ + if (item && item->parent()) { return createIndex(item->row(), 0, item); } return QModelIndex(); } -CompleterItem::~CompleterItem(){} +CompleterItem::~CompleterItem() { } -void CompleterItem::setIcon(const QIcon &newIcon) +void CompleterItem::setIcon(const QIcon& newIcon) { m_icon = newIcon; } + +void CompleterItem::setText(const QString& newText) { m_text = newText; } + +void CompleterItem::appendRow(CompleterItem* child) { - m_icon = newIcon; -} - -void CompleterItem::setText(const QString &newText) -{ - m_text = newText; -} - -void CompleterItem::appendRow(CompleterItem *child){ child->m_parent = this; child->m_model = this->m_model; m_children.append(QSharedPointer(child)); - if (m_model){ + if (m_model) { QModelIndex start = m_model->indexFromItem(child); emit m_model->dataChanged(start, start); } } -void CompleterItem::appendRows(const QList &children){ - foreach(CompleterItem* item, children){ +void CompleterItem::appendRows(const QList& children) +{ + foreach (CompleterItem* item, children) { appendRow(item); } } diff --git a/limereport/scripteditor/lrcompletermodel.h b/limereport/scripteditor/lrcompletermodel.h index 8f218e8..162eff1 100644 --- a/limereport/scripteditor/lrcompletermodel.h +++ b/limereport/scripteditor/lrcompletermodel.h @@ -8,66 +8,70 @@ class CompleterModel; class CompleterItem { public: - CompleterItem():m_parent(0), m_model(0){} - CompleterItem(QString text, QIcon icon):m_parent(0), m_text(text), m_icon(icon), m_model(0){} + CompleterItem(): m_parent(0), m_model(0) { } + CompleterItem(QString text, QIcon icon): m_parent(0), m_text(text), m_icon(icon), m_model(0) { } ~CompleterItem(); - int rowCount() const {return m_children.count();} - CompleterItem *child(int row) const { - return m_children.count() > row ? m_children.at(row).data() : nullptr; + int rowCount() const { return m_children.count(); } + CompleterItem* child(int row) const + { + return m_children.count() > row ? m_children.at(row).data() : nullptr; } - CompleterItem* parent() const {return m_parent;} - int row() const{ - if (m_parent){ - for(int i=0; i < m_parent->m_children.count(); ++i){ + CompleterItem* parent() const { return m_parent; } + int row() const + { + if (m_parent) { + for (int i = 0; i < m_parent->m_children.count(); ++i) { CompleterItem* c = m_parent->m_children.at(i).data(); - if (c == this) return i; + if (c == this) + return i; } } return -1; } - QString text(){return m_text;} - QIcon icon() {return m_icon;} + QString text() { return m_text; } + QIcon icon() { return m_icon; } - void setIcon(const QIcon &newIcon); - void setText(const QString &newText); - void setModel(CompleterModel* model){m_model=model;} - void clear(){m_children.clear();} + void setIcon(const QIcon& newIcon); + void setText(const QString& newText); + void setModel(CompleterModel* model) { m_model = model; } + void clear() { m_children.clear(); } void appendRow(CompleterItem* child); - void appendRows(const QList &children); + void appendRows(const QList& children); + private: - CompleterItem* m_parent{nullptr}; - QVector > m_children; + CompleterItem* m_parent { nullptr }; + QVector> m_children; QString m_text; QIcon m_icon; CompleterModel* m_model; }; - -class CompleterModel : public QAbstractItemModel -{ +class CompleterModel: public QAbstractItemModel { friend CompleterItem; + public: - explicit CompleterModel(QObject *parent = nullptr); + explicit CompleterModel(QObject* parent = nullptr); // QAbstractItemModel interface public: - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - CompleterItem* invisibleRootItem(){return &m_root;} - QList findItems(const QString &text, - Qt::MatchFlags flags = Qt::MatchExactly, + QModelIndex index(int row, int column, const QModelIndex& parent) const; + QModelIndex parent(const QModelIndex& child) const; + int rowCount(const QModelIndex& parent) const; + int columnCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& index, int role) const; + CompleterItem* invisibleRootItem() { return &m_root; } + QList findItems(const QString& text, Qt::MatchFlags flags = Qt::MatchExactly, int column = 0) const; void clear(); + private: - CompleterItem *itemFromIndex(const QModelIndex index) const; - QModelIndex indexFromItem(CompleterItem *item) const; + CompleterItem* itemFromIndex(const QModelIndex index) const; + QModelIndex indexFromItem(CompleterItem* item) const; + private: CompleterItem m_root; -public: +public: }; #endif // COMPLETERMODEL_H diff --git a/limereport/scripteditor/lrscripteditor.cpp b/limereport/scripteditor/lrscripteditor.cpp index 916739e..3476e94 100644 --- a/limereport/scripteditor/lrscripteditor.cpp +++ b/limereport/scripteditor/lrscripteditor.cpp @@ -5,34 +5,36 @@ #include #endif -#include "lrdatasourcemanager.h" -#include "lrscriptenginemanager.h" #include "lrdatadesignintf.h" +#include "lrdatasourcemanager.h" #include "lrreportengine_p.h" +#include "lrscriptenginemanager.h" -namespace LimeReport{ +namespace LimeReport { -ScriptEditor::ScriptEditor(QWidget *parent) : +ScriptEditor::ScriptEditor(QWidget* parent): QWidget(parent), - ui(new Ui::ScriptEditor), m_reportEngine(0), m_page(0), m_tabIndention(4) + ui(new Ui::ScriptEditor), + m_reportEngine(0), + m_page(0), + m_tabIndention(4) { ui->setupUi(this); setFocusProxy(ui->textEdit); m_completer = new ReportStructureCompleater(this); ui->textEdit->setCompleter(m_completer); -#if QT_VERSION < QT_VERSION_CHECK(5,12,3) - ui->textEdit->setTabStopWidth(ui->textEdit->fontMetrics().boundingRect("0").width()*m_tabIndention); +#if QT_VERSION < QT_VERSION_CHECK(5, 12, 3) + ui->textEdit->setTabStopWidth(ui->textEdit->fontMetrics().boundingRect("0").width() + * m_tabIndention); #else - ui->textEdit->setTabStopDistance(ui->textEdit->fontMetrics().boundingRect("0").width()*m_tabIndention); + ui->textEdit->setTabStopDistance(ui->textEdit->fontMetrics().boundingRect("0").width() + * m_tabIndention); #endif - connect(ui->splitter, SIGNAL(splitterMoved(int,int)), this, SIGNAL(splitterMoved(int,int))); + connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SIGNAL(splitterMoved(int, int))); connect(ui->textEdit, SIGNAL(textChanged()), this, SIGNAL(textChanged())); } -ScriptEditor::~ScriptEditor() -{ - delete ui; -} +ScriptEditor::~ScriptEditor() { delete ui; } void ScriptEditor::initEditor(DataSourceManager* dm) { @@ -41,16 +43,17 @@ void ScriptEditor::initEditor(DataSourceManager* dm) initCompleter(); - if (dm){ + if (dm) { if (dm->isNeedUpdateDatasourceModel()) - dm->updateDatasourceModel(); + dm->updateDatasourceModel(); ui->twData->setModel(dm->datasourcesModel()); ui->twScriptEngine->setModel(se.model()); } - if (ui->twScriptEngine->selectionModel()){ - connect(ui->twScriptEngine->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), - this, SLOT(slotOnCurrentChanged(QModelIndex,QModelIndex))); + if (ui->twScriptEngine->selectionModel()) { + connect(ui->twScriptEngine->selectionModel(), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, + SLOT(slotOnCurrentChanged(QModelIndex, QModelIndex))); } } @@ -58,29 +61,29 @@ void ScriptEditor::setReportEngine(ReportEnginePrivateInterface* reportEngine) { m_reportEngine = reportEngine; DataSourceManager* dm = m_reportEngine->dataManager(); - if (dm) initEditor(dm); - else ui->tabWidget->setVisible(false); + if (dm) + initEditor(dm); + else + ui->tabWidget->setVisible(false); } void ScriptEditor::setReportPage(PageDesignIntf* page) { m_page = page; DataSourceManager* dm = page->datasourceManager(); - if (dm) initEditor(dm); - else ui->tabWidget->setVisible(false); + if (dm) + initEditor(dm); + else + ui->tabWidget->setVisible(false); } void ScriptEditor::setPageBand(BandDesignIntf* band) { - if (band && ui->twData->model() && !band->datasourceName().isEmpty()){ - QModelIndexList nodes = ui->twData->model()->match( - ui->twData->model()->index(0,0), - Qt::DisplayRole, - band->datasourceName(), - 2, - Qt::MatchRecursive - ); - if (!nodes.isEmpty()){ + if (band && ui->twData->model() && !band->datasourceName().isEmpty()) { + QModelIndexList nodes + = ui->twData->model()->match(ui->twData->model()->index(0, 0), Qt::DisplayRole, + band->datasourceName(), 2, Qt::MatchRecursive); + if (!nodes.isEmpty()) { ui->twData->expand(nodes.at(0).parent()); ui->twData->expand(nodes.at(0)); } @@ -89,11 +92,13 @@ void ScriptEditor::setPageBand(BandDesignIntf* band) void ScriptEditor::setTabIndention(int charCount) { - if (m_tabIndention != charCount){ -#if QT_VERSION < QT_VERSION_CHECK(5,12,3) - ui->textEdit->setTabStopWidth(ui->textEdit->fontMetrics().boundingRect("W").width()*charCount); + if (m_tabIndention != charCount) { +#if QT_VERSION < QT_VERSION_CHECK(5, 12, 3) + ui->textEdit->setTabStopWidth(ui->textEdit->fontMetrics().boundingRect("W").width() + * charCount); #else - ui->textEdit->setTabStopDistance(ui->textEdit->fontMetrics().boundingRect("W").width()*charCount); + ui->textEdit->setTabStopDistance(ui->textEdit->fontMetrics().boundingRect("W").width() + * charCount); #endif m_tabIndention = charCount; } @@ -107,68 +112,55 @@ void ScriptEditor::initCompleter() m_completer->updateCompleaterModel(m_page->datasourceManager()); } -QByteArray ScriptEditor::saveState() -{ - return ui->splitter->saveState(); -} +QByteArray ScriptEditor::saveState() { return ui->splitter->saveState(); } -void ScriptEditor::restoreState(QByteArray state) -{ - ui->splitter->restoreState(state); -} +void ScriptEditor::restoreState(QByteArray state) { ui->splitter->restoreState(state); } -void ScriptEditor::setPlainText(const QString& text) -{ - ui->textEdit->setPlainText(text); -} +void ScriptEditor::setPlainText(const QString& text) { ui->textEdit->setPlainText(text); } -void ScriptEditor::setEditorFont(QFont font) -{ - ui->textEdit->setFont(font); -} +void ScriptEditor::setEditorFont(QFont font) { ui->textEdit->setFont(font); } -QFont ScriptEditor::editorFont() -{ - return ui->textEdit->font(); -} +QFont ScriptEditor::editorFont() { return ui->textEdit->font(); } -QString ScriptEditor::toPlainText() -{ - return ui->textEdit->toPlainText(); -} +QString ScriptEditor::toPlainText() { return ui->textEdit->toPlainText(); } -void ScriptEditor::on_twData_doubleClicked(const QModelIndex &index) +void ScriptEditor::on_twData_doubleClicked(const QModelIndex& index) { - if (!index.isValid()) return; + if (!index.isValid()) + return; LimeReport::DataNode* node = static_cast(index.internalPointer()); - if (node->type()==LimeReport::DataNode::Field){ - ui->textEdit->insertPlainText(QString("$D{%1.%2}").arg(node->parent()->name()).arg(node->name())); + if (node->type() == LimeReport::DataNode::Field) { + ui->textEdit->insertPlainText( + QString("$D{%1.%2}").arg(node->parent()->name()).arg(node->name())); } - if (node->type()==LimeReport::DataNode::Variable){ + if (node->type() == LimeReport::DataNode::Variable) { ui->textEdit->insertPlainText(QString("$V{%1}").arg(node->name())); } ui->textEdit->setFocus(); } -void ScriptEditor::on_twScriptEngine_doubleClicked(const QModelIndex &index) +void ScriptEditor::on_twScriptEngine_doubleClicked(const QModelIndex& index) { - if (!index.isValid()) return; - LimeReport::ScriptEngineNode* node = static_cast(index.internalPointer()); - if (node->type()==LimeReport::ScriptEngineNode::Function){ - ui->textEdit->insertPlainText(node->name()+"()"); + if (!index.isValid()) + return; + LimeReport::ScriptEngineNode* node + = static_cast(index.internalPointer()); + if (node->type() == LimeReport::ScriptEngineNode::Function) { + ui->textEdit->insertPlainText(node->name() + "()"); } ui->textEdit->setFocus(); } -void ScriptEditor::slotOnCurrentChanged(const QModelIndex &to, const QModelIndex &) +void ScriptEditor::slotOnCurrentChanged(const QModelIndex& to, const QModelIndex&) { - LimeReport::ScriptEngineNode* node = static_cast(to.internalPointer()); - if (node->type()==LimeReport::ScriptEngineNode::Function){ - ui->lblDescription->setText(node->description()); + LimeReport::ScriptEngineNode* node + = static_cast(to.internalPointer()); + if (node->type() == LimeReport::ScriptEngineNode::Function) { + ui->lblDescription->setText(node->description()); } } -QString ReportStructureCompleater::pathFromIndex(const QModelIndex &index) const +QString ReportStructureCompleater::pathFromIndex(const QModelIndex& index) const { QStringList dataList; for (QModelIndex i = index; i.isValid(); i = i.parent()) { @@ -177,18 +169,20 @@ QString ReportStructureCompleater::pathFromIndex(const QModelIndex &index) const return dataList.join("."); } -QStringList ReportStructureCompleater::splitPath(const QString &path) const +QStringList ReportStructureCompleater::splitPath(const QString& path) const { return path.split("."); } -void ReportStructureCompleater::addAdditionalDatawords(CompleterModel* model, DataSourceManager* dataManager){ +void ReportStructureCompleater::addAdditionalDatawords(CompleterModel* model, + DataSourceManager* dataManager) +{ - foreach(const QString &dsName,dataManager->dataSourceNames()){ + foreach (const QString& dsName, dataManager->dataSourceNames()) { CompleterItem* dsNode = new CompleterItem; dsNode->setText(dsName); model->invisibleRootItem()->appendRow(dsNode); - foreach(const QString &field, dataManager->fieldNames(dsName)){ + foreach (const QString& field, dataManager->fieldNames(dsName)) { CompleterItem* fieldNode = new CompleterItem; fieldNode->setText(field); dsNode->appendRow(fieldNode); @@ -205,29 +199,32 @@ void ReportStructureCompleater::addAdditionalDatawords(CompleterModel* model, Da ScriptEngineManager& se = LimeReport::ScriptEngineManager::instance(); QJSValue globalObject = se.scriptEngine()->globalObject(); QJSValueIterator it(globalObject); - while (it.hasNext()){ + while (it.hasNext()) { it.next(); - if (it.value().isCallable() ){ + if (it.value().isCallable()) { CompleterItem* itemNode = new CompleterItem; - itemNode->setText(it.name()+"()"); + itemNode->setText(it.name() + "()"); model->invisibleRootItem()->appendRow(itemNode); } - if (it.value().isQObject()){ - if (it.value().toQObject()){ - if (model->findItems(it.name()).isEmpty()){ + if (it.value().isQObject()) { + if (it.value().toQObject()) { + if (model->findItems(it.name()).isEmpty()) { CompleterItem* objectNode = new CompleterItem; objectNode->setText(it.name()); objectNode->setIcon(QIcon(":/report/images/object")); - for (int i = 0; i< it.value().toQObject()->metaObject()->methodCount();++i){ - if (it.value().toQObject()->metaObject()->method(i).methodType() == QMetaMethod::Method){ + for (int i = 0; i < it.value().toQObject()->metaObject()->methodCount(); ++i) { + if (it.value().toQObject()->metaObject()->method(i).methodType() + == QMetaMethod::Method) { CompleterItem* methodNode = new CompleterItem; QMetaMethod m = it.value().toQObject()->metaObject()->method(i); QString methodSignature = m.name() + "("; bool isFirst = true; - for (int j = 0; j < m.parameterCount(); ++j){ - methodSignature += (isFirst ? "" : ",") + m.parameterTypes()[j]+" "+m.parameterNames()[j]; - if (isFirst) isFirst = false; + for (int j = 0; j < m.parameterCount(); ++j) { + methodSignature += (isFirst ? "" : ",") + m.parameterTypes()[j] + + " " + m.parameterNames()[j]; + if (isFirst) + isFirst = false; } methodSignature += ")"; methodNode->setText(methodSignature); @@ -240,18 +237,17 @@ void ReportStructureCompleater::addAdditionalDatawords(CompleterModel* model, Da } } #endif - } void ReportStructureCompleater::updateCompleaterModel(ReportEnginePrivateInterface* report) { - if (report){ + if (report) { m_newModel.clear(); QIcon signalIcon(":/report/images/signal"); QIcon propertyIcon(":/report/images/property"); - for ( int i = 0; i < report->pageCount(); ++i){ + for (int i = 0; i < report->pageCount(); ++i) { PageDesignIntf* page = report->pageAt(i); CompleterItem* itemNode = new CompleterItem; @@ -259,21 +255,21 @@ void ReportStructureCompleater::updateCompleaterModel(ReportEnginePrivateInterfa itemNode->setIcon(QIcon(":/report/images/object")); QStringList items = extractSignalNames(page->pageItem()); - foreach(QString slotName, items){ + foreach (QString slotName, items) { CompleterItem* slotItem = new CompleterItem; slotItem->setText(slotName); slotItem->setIcon(signalIcon); itemNode->appendRow(slotItem); } items = extractProperties(page->pageItem()); - foreach(QString propertyName, items){ + foreach (QString propertyName, items) { CompleterItem* properyItem = new CompleterItem; properyItem->setText(propertyName); properyItem->setIcon(propertyIcon); itemNode->appendRow(properyItem); } - foreach (BaseDesignIntf* item, page->pageItem()->childBaseItems()){ + foreach (BaseDesignIntf* item, page->pageItem()->childBaseItems()) { addChildItem(item, itemNode->text(), m_newModel.invisibleRootItem()); } @@ -285,20 +281,20 @@ void ReportStructureCompleater::updateCompleaterModel(ReportEnginePrivateInterfa } } -void ReportStructureCompleater::updateCompleaterModel(DataSourceManager *dataManager) +void ReportStructureCompleater::updateCompleaterModel(DataSourceManager* dataManager) { m_newModel.clear(); addAdditionalDatawords(&m_newModel, dataManager); } -QStringList ReportStructureCompleater::extractSignalNames(BaseDesignIntf *item) +QStringList ReportStructureCompleater::extractSignalNames(BaseDesignIntf* item) { QStringList result; - if (!item) return result; - QMetaObject const * mo = item->metaObject(); - while (mo){ - for(int i = mo->methodOffset(); i < mo->methodCount(); ++i) - { + if (!item) + return result; + QMetaObject const* mo = item->metaObject(); + while (mo) { + for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) { if (mo->method(i).methodType() == QMetaMethod::Signal) { #ifndef HAVE_QT4 result.append(QString::fromLatin1(mo->method(i).name())); @@ -313,15 +309,15 @@ QStringList ReportStructureCompleater::extractSignalNames(BaseDesignIntf *item) return result; } -QStringList ReportStructureCompleater::extractProperties(BaseDesignIntf *item) +QStringList ReportStructureCompleater::extractProperties(BaseDesignIntf* item) { QStringList result; - if (!item) return result; - QMetaObject const * mo = item->metaObject(); - while (mo){ - for(int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) - { - result.append(QString::fromLatin1(mo->property(i).name())); + if (!item) + return result; + QMetaObject const* mo = item->metaObject(); + while (mo) { + for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) { + result.append(QString::fromLatin1(mo->property(i).name())); } mo = mo->superClass(); } @@ -329,74 +325,70 @@ QStringList ReportStructureCompleater::extractProperties(BaseDesignIntf *item) return result; } -void ReportStructureCompleater::addChildItem(BaseDesignIntf *item, const QString &pageName, CompleterItem *parent) +void ReportStructureCompleater::addChildItem(BaseDesignIntf* item, const QString& pageName, + CompleterItem* parent) { - if (!item) return; + if (!item) + return; QIcon signalIcon(":/report/images/signal"); QIcon propertyIcon(":/report/images/property"); CompleterItem* itemNode = new CompleterItem; - itemNode->setText(pageName+"_"+item->objectName()); + itemNode->setText(pageName + "_" + item->objectName()); itemNode->setIcon(QIcon(":/report/images/object")); parent->appendRow(itemNode); -// if (m_cache.contains(item->metaObject()->className())){ + // if (m_cache.contains(item->metaObject()->className())){ -// QSharedPointer cacheItem = m_cache.value(item->metaObject()->className()); -// itemNode->appendRows(cacheItem->slotsItems); -// itemNode->appendRows(cacheItem->propsItems); + // QSharedPointer cacheItem = + // m_cache.value(item->metaObject()->className()); + // itemNode->appendRows(cacheItem->slotsItems); + // itemNode->appendRows(cacheItem->propsItems); -// } else { + // } else { -// QSharedPointer cacheItem = QSharedPointer(new CacheItem); + // QSharedPointer cacheItem = QSharedPointer(new CacheItem); - QStringList items; - if (!m_signals.contains(item->metaObject()->className())){ - items = extractSignalNames(item); - m_signals.insert(item->metaObject()->className(),items); - } else { - items = m_signals.value(item->metaObject()->className()); - } + QStringList items; + if (!m_signals.contains(item->metaObject()->className())) { + items = extractSignalNames(item); + m_signals.insert(item->metaObject()->className(), items); + } else { + items = m_signals.value(item->metaObject()->className()); + } - foreach(QString slotName, items){ - CompleterItem* slotItem = new CompleterItem; - slotItem->setText(slotName); - slotItem->setIcon(signalIcon); - //cacheItem->slotsItems.append(QSharedPointer(slotItem)); - itemNode->appendRow(slotItem); + foreach (QString slotName, items) { + CompleterItem* slotItem = new CompleterItem; + slotItem->setText(slotName); + slotItem->setIcon(signalIcon); + // cacheItem->slotsItems.append(QSharedPointer(slotItem)); + itemNode->appendRow(slotItem); + } - } + if (!m_properties.contains(item->metaObject()->className())) { + items = extractProperties(item); + m_properties.insert(item->metaObject()->className(), items); + } else { + items = m_properties.value(item->metaObject()->className()); + } - if (!m_properties.contains(item->metaObject()->className())){ - items = extractProperties(item); - m_properties.insert(item->metaObject()->className(),items); - } else { - items = m_properties.value(item->metaObject()->className()); - } + foreach (QString propertyName, items) { + CompleterItem* properyItem = new CompleterItem; + properyItem->setText(propertyName); + properyItem->setIcon(propertyIcon); + itemNode->appendRow(properyItem); + // cacheItem->propsItems.append(QSharedPointer(properyItem)); + } - foreach(QString propertyName, items){ - CompleterItem* properyItem = new CompleterItem; - properyItem->setText(propertyName); - properyItem->setIcon(propertyIcon); - itemNode->appendRow(properyItem); - //cacheItem->propsItems.append(QSharedPointer(properyItem)); - } - - //m_cache.insert(item->metaObject()->className(), cacheItem); - //itemNode->appendRows(cacheItem->slotsItems); - //itemNode->appendRows(cacheItem->propsItems); + // m_cache.insert(item->metaObject()->className(), cacheItem); + // itemNode->appendRows(cacheItem->slotsItems); + // itemNode->appendRows(cacheItem->propsItems); //} - foreach (BaseDesignIntf* child, item->childBaseItems()){ + foreach (BaseDesignIntf* child, item->childBaseItems()) { addChildItem(child, pageName, parent); } } } // namespace LimeReport - - - - - - diff --git a/limereport/scripteditor/lrscripteditor.h b/limereport/scripteditor/lrscripteditor.h index ea0a433..df0a4c8 100644 --- a/limereport/scripteditor/lrscripteditor.h +++ b/limereport/scripteditor/lrscripteditor.h @@ -1,15 +1,16 @@ #ifndef LRSCRIPTEDITOR_H #define LRSCRIPTEDITOR_H -#include +#include "lrcompletermodel.h" + #include -#include #include #include #include -#include "lrcompletermodel.h" +#include +#include -namespace LimeReport{ +namespace LimeReport { class ReportEnginePrivateInterface; class BaseDesignIntf; @@ -18,7 +19,7 @@ class BandDesignIntf; class DataSourceManager; namespace Ui { -class ScriptEditor; + class ScriptEditor; } struct CacheItem { @@ -26,34 +27,42 @@ struct CacheItem { QList> slotsItems; }; -class ReportStructureCompleater : public QCompleter{ +class ReportStructureCompleater: public QCompleter { Q_OBJECT public: - explicit ReportStructureCompleater(QObject* parent = 0): QCompleter(parent){ setModel(&m_newModel);} - explicit ReportStructureCompleater(QAbstractItemModel* model, QObject* parent = 0) - :QCompleter(model, parent){ setModel(&m_newModel);} + explicit ReportStructureCompleater(QObject* parent = 0): QCompleter(parent) + { + setModel(&m_newModel); + } + explicit ReportStructureCompleater(QAbstractItemModel* model, QObject* parent = 0): + QCompleter(model, parent) + { + setModel(&m_newModel); + } + public: // QCompleter interface QString pathFromIndex(const QModelIndex& index) const; QStringList splitPath(const QString& path) const; void updateCompleaterModel(ReportEnginePrivateInterface* report); void updateCompleaterModel(DataSourceManager* dataManager); + protected: QStringList extractSignalNames(BaseDesignIntf* item); QStringList extractProperties(BaseDesignIntf* item); - void addChildItem(BaseDesignIntf *item, const QString &pageName, CompleterItem *parent); - void addAdditionalDatawords(CompleterModel *model, DataSourceManager *dataManager); + void addChildItem(BaseDesignIntf* item, const QString& pageName, CompleterItem* parent); + void addAdditionalDatawords(CompleterModel* model, DataSourceManager* dataManager); + private: CompleterModel m_newModel; QMap m_properties; QMap m_signals; }; -class ScriptEditor : public QWidget -{ +class ScriptEditor: public QWidget { Q_OBJECT public: - explicit ScriptEditor(QWidget *parent = 0); + explicit ScriptEditor(QWidget* parent = 0); ~ScriptEditor(); void setReportEngine(LimeReport::ReportEnginePrivateInterface* reportEngine); void setReportPage(PageDesignIntf* page); @@ -62,7 +71,7 @@ public: void initCompleter(); QByteArray saveState(); void restoreState(QByteArray state); - void setPlainText(const QString &text); + void setPlainText(const QString& text); void setEditorFont(QFont font); QFont editorFont(); QString toPlainText(); @@ -71,16 +80,17 @@ public: signals: void splitterMoved(int, int); void textChanged(); + protected: void initEditor(DataSourceManager* dm); private slots: - void on_twData_doubleClicked(const QModelIndex &index); - void on_twScriptEngine_doubleClicked(const QModelIndex &index); + void on_twData_doubleClicked(const QModelIndex& index); + void on_twScriptEngine_doubleClicked(const QModelIndex& index); void slotOnCurrentChanged(const QModelIndex& to, const QModelIndex&); private: - Ui::ScriptEditor *ui; + Ui::ScriptEditor* ui; ReportEnginePrivateInterface* m_reportEngine; PageDesignIntf* m_page; ReportStructureCompleater* m_completer; diff --git a/limereport/scripteditor/lrscripthighlighter.cpp b/limereport/scripteditor/lrscripthighlighter.cpp index 37771fd..9592527 100644 --- a/limereport/scripteditor/lrscripthighlighter.cpp +++ b/limereport/scripteditor/lrscripthighlighter.cpp @@ -1,21 +1,25 @@ #include "lrscripthighlighter.h" + #include "lrglobal.h" + #include #include -namespace LimeReport{ +namespace LimeReport { #define KEYWORDS_COUNT 60 -static const char *const keywords[KEYWORDS_COUNT] = { - "do","if","in","for","int","new","try","var","byte","case","char","else","enum", - "goto","long","null","this","true","void","with","break","catch","class","const", - "false","final","float","short","super","throw","while","delete","double","export", - "import","native","public","return","static","switch","throws","typeof","boolean", - "default","extends","finally","package","private","abstract","continue","debugger", - "function","volatile","interface","protected","transient","implements","instanceof", - "synchronized","let" -}; +static const char* const keywords[KEYWORDS_COUNT] + = { "do", "if", "in", "for", "int", "new", + "try", "var", "byte", "case", "char", "else", + "enum", "goto", "long", "null", "this", "true", + "void", "with", "break", "catch", "class", "const", + "false", "final", "float", "short", "super", "throw", + "while", "delete", "double", "export", "import", "native", + "public", "return", "static", "switch", "throws", "typeof", + "boolean", "default", "extends", "finally", "package", "private", + "abstract", "continue", "debugger", "function", "volatile", "interface", + "protected", "transient", "implements", "instanceof", "synchronized", "let" }; enum LiteralsType { SpaceFound, @@ -50,11 +54,12 @@ enum States { StatesCount }; -void ScriptHighlighter::createParentheisisInfo(const char& literal, TextBlockData *data, const QString& text) +void ScriptHighlighter::createParentheisisInfo(const char& literal, TextBlockData* data, + const QString& text) { int pos = text.indexOf(literal); while (pos != -1) { - ParenthesisInfo *info = new ParenthesisInfo; + ParenthesisInfo* info = new ParenthesisInfo; info->character = literal; info->position = pos; data->insert(info); @@ -70,73 +75,97 @@ void ScriptHighlighter::highlightBlock(const QString& text) States state = prevState != Undefined ? (States)prevState : Start; States oldState = Undefined; const States stateMaschine[StatesCount][LiteralsCount] = { -// Space Alpahabet Number Hash Slash Asterix, Bracket, Quotation, Apostrophe, Apostrophe2 Separator, Back Slash - {Separator, MayBeKeyWord, MayBeNumber, Separator, MayBeComment, Separator, Separator, String, String2, String3, Separator, Separator}, - {Separator, MayBeKeyWord, Code, Separator, MayBeComment, Separator, Separator, String, String2, String3, Separator, Separator}, - {Separator, Code, Code, Separator, Separator, Separator, Separator, String, String2, String3, Separator, Separator}, - {Separator, Code, MayBeNumber, Code, Comment, Comment2, Code, String, String2, String3, Separator, Code}, - {Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment}, - {Comment2, Comment2, Comment2, Comment2, Comment2, MayBeComment2End, Comment2, Comment2, Comment2, Comment2, Comment2, Comment2}, - {Comment2, Comment2, Comment2, Comment2, Separator, Comment2, Comment2, Comment2, Comment2, Comment2, Comment2, Comment2}, - {String, String, String, String, String, String, String, Separator, String, String, String, String}, - {String2, String2, String2, String2, String2, String2, String2, String2, Separator, String2, String2, String2}, - {String3, String3, String3, String3, String3, String3, String3, String3, String3, Separator, String3, String3}, - {Separator, Code, MayBeNumber, Separator, MayBeComment, Separator, Separator, String, String2, String3, Separator, Code}, - {Separator, MayBeKeyWord, MayBeNumber, Separator, MayBeComment, Separator, Separator, String, String2, String3, Separator, Separator}, + // Space Alpahabet Number Hash Slash Asterix, + // Bracket, Quotation, Apostrophe, Apostrophe2 Separator, Back Slash + { Separator, MayBeKeyWord, MayBeNumber, Separator, MayBeComment, Separator, Separator, + String, String2, String3, Separator, Separator }, + { Separator, MayBeKeyWord, Code, Separator, MayBeComment, Separator, Separator, String, + String2, String3, Separator, Separator }, + { Separator, Code, Code, Separator, Separator, Separator, Separator, String, String2, + String3, Separator, Separator }, + { Separator, Code, MayBeNumber, Code, Comment, Comment2, Code, String, String2, String3, + Separator, Code }, + { Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, Comment, + Comment, Comment }, + { Comment2, Comment2, Comment2, Comment2, Comment2, MayBeComment2End, Comment2, Comment2, + Comment2, Comment2, Comment2, Comment2 }, + { Comment2, Comment2, Comment2, Comment2, Separator, Comment2, Comment2, Comment2, Comment2, + Comment2, Comment2, Comment2 }, + { String, String, String, String, String, String, String, Separator, String, String, String, + String }, + { String2, String2, String2, String2, String2, String2, String2, String2, Separator, + String2, String2, String2 }, + { String3, String3, String3, String3, String3, String3, String3, String3, String3, + Separator, String3, String3 }, + { Separator, Code, MayBeNumber, Separator, MayBeComment, Separator, Separator, String, + String2, String3, Separator, Code }, + { Separator, MayBeKeyWord, MayBeNumber, Separator, MayBeComment, Separator, Separator, + String, String2, String3, Separator, Separator }, }; QString buffer; setCurrentBlockState(Undefined); - if (text.isEmpty()) - { + if (text.isEmpty()) { if (prevState == Comment2) setCurrentBlockState(Comment2); return; } int i = 0; - for (;;){ + for (;;) { QChar currentChar = text.at(i); - switch(currentChar.toLatin1()){ - case ' ': - literal = SpaceFound; - break; - case '/': - literal = SlashFound; - break; - case '*': - literal = AsterixFound; - break; - case '#': - literal = HashFound; - break; - case '\'': - literal = ApostropheFound; - break; - case '\\': - literal = BackSlashFound; - break; - case '"': - literal = QuotationFound; - break; - case '`': - literal = Apostrophe2Found; - break; - case '{': case '[': case '(': - case '}': case ']': case ')': - literal = BracketFound; - break; - case '1': case '2': case '3': case '4': case '5': - case '6': case '7': case '8': case '9': case '0': - literal = NumberFound; - break; - default: - if (currentChar.isLetter()) - literal = AlpahabetFound; - else - literal = SeparatorFound; + switch (currentChar.toLatin1()) { + case ' ': + literal = SpaceFound; + break; + case '/': + literal = SlashFound; + break; + case '*': + literal = AsterixFound; + break; + case '#': + literal = HashFound; + break; + case '\'': + literal = ApostropheFound; + break; + case '\\': + literal = BackSlashFound; + break; + case '"': + literal = QuotationFound; + break; + case '`': + literal = Apostrophe2Found; + break; + case '{': + case '[': + case '(': + case '}': + case ']': + case ')': + literal = BracketFound; + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '0': + literal = NumberFound; + break; + default: + if (currentChar.isLetter()) + literal = AlpahabetFound; + else + literal = SeparatorFound; }; lastWasBackSlash = !lastWasBackSlash && currentChar == QLatin1Char('\\'); @@ -147,85 +176,83 @@ void ScriptHighlighter::highlightBlock(const QString& text) buffer += currentChar; if (oldState != state) { - switch( state ){ - case MayBeComment: - if (oldState == MayBeNumber){ - setFormat(i-(buffer.length()-1), buffer.length()-1, m_formats[NumberFormat]); + switch (state) { + case MayBeComment: + if (oldState == MayBeNumber) { + setFormat(i - (buffer.length() - 1), buffer.length() - 1, + m_formats[NumberFormat]); + } + buffer.clear(); + buffer += currentChar; + break; + case String: + case String2: + case String3: + buffer.clear(); + buffer += currentChar; + break; + case MayBeKeyWord: + case MayBeNumber: + buffer.clear(); + buffer += currentChar; + break; + case Comment2: + setCurrentBlockState(Comment2); + case Separator: + switch (oldState) { + case MayBeComment2End: + setFormat(i - (buffer.length() - 1), buffer.length(), m_formats[CommentFormat]); + setCurrentBlockState(Undefined); + buffer.clear(); + break; + case MayBeKeyWord: + if (isKeyWord(buffer.left(buffer.length() - 1))) { + setFormat(i - (buffer.length() - 1), buffer.length() - 1, + m_formats[KeywordFormat]); } buffer.clear(); - buffer += currentChar; break; + case MayBeNumber: + setFormat(i - (buffer.length() - 1), buffer.length() - 1, + m_formats[NumberFormat]); + buffer.clear(); case String: case String2: case String3: + setFormat(i - (buffer.length() - 1), buffer.length(), m_formats[StringFormat]); buffer.clear(); - buffer += currentChar; - break; - case MayBeKeyWord: - case MayBeNumber: - buffer.clear(); - buffer += currentChar; - break; - case Comment2: - setCurrentBlockState(Comment2); - case Separator: - switch(oldState){ - case MayBeComment2End: - setFormat(i-(buffer.length()-1), buffer.length(), m_formats[CommentFormat]); - setCurrentBlockState(Undefined); - buffer.clear(); - break; - case MayBeKeyWord: - if (isKeyWord(buffer.left(buffer.length()-1))){ - setFormat(i-(buffer.length()-1), buffer.length()-1, m_formats[KeywordFormat]); - } - buffer.clear(); - break; - case MayBeNumber: - setFormat(i-(buffer.length()-1), buffer.length()-1, m_formats[NumberFormat]); - buffer.clear(); - case String: - case String2: - case String3: - setFormat(i-(buffer.length()-1), buffer.length(), m_formats[StringFormat]); - buffer.clear(); - break; - } - default: break; + } + default: + break; } - } - else if (state == Comment2) - { + } else if (state == Comment2) { setCurrentBlockState(Comment2); } - if ( state == Comment || state == Comment2 ){ - setFormat(i-(buffer.length()-1), buffer.length(), m_formats[CommentFormat]); + if (state == Comment || state == Comment2) { + setFormat(i - (buffer.length() - 1), buffer.length(), m_formats[CommentFormat]); } - if ( state == String || state == String2 || state == String3 ){ - setFormat(i-(buffer.length()-1), buffer.length(), m_formats[StringFormat]); + if (state == String || state == String2 || state == String3) { + setFormat(i - (buffer.length() - 1), buffer.length(), m_formats[StringFormat]); } i++; - if ( i>= text.length()) break; + if (i >= text.length()) + break; } - if (buffer.length()) - { - if (state == MayBeKeyWord) - { + if (buffer.length()) { + if (state == MayBeKeyWord) { if (isKeyWord(buffer)) - setFormat(i - buffer.length(), buffer.length(), m_formats[KeywordFormat]); - } - else if (state == MayBeNumber) - { + setFormat(i - buffer.length(), buffer.length(), m_formats[KeywordFormat]); + } else if (state == MayBeNumber) { setFormat(i - buffer.length(), buffer.length(), m_formats[NumberFormat]); } } - TextBlockData *data = new TextBlockData; + TextBlockData* data = new TextBlockData; for (int i = 0; i < PARENHEIS_COUNT; ++i) { createParentheisisInfo(parenthesisCharacters[LeftParenthesis][i].toLatin1(), data, text); @@ -235,19 +262,15 @@ void ScriptHighlighter::highlightBlock(const QString& text) setCurrentBlockUserData(data); } -bool ScriptHighlighter::isKeyWord(const QString& word) -{ - return m_keywords.contains(word); -} +bool ScriptHighlighter::isKeyWord(const QString& word) { return m_keywords.contains(word); } -ScriptHighlighter::ScriptHighlighter(QTextDocument* parent): - QSyntaxHighlighter(parent) +ScriptHighlighter::ScriptHighlighter(QTextDocument* parent): QSyntaxHighlighter(parent) { - for(int i=0; i TextBlockData::parentheses() -{ - return m_parentheses; -} +QVector TextBlockData::parentheses() { return m_parentheses; } void TextBlockData::insert(ParenthesisInfo* info) { int i = 0; - while (i < m_parentheses.size() && - info->position > m_parentheses.at(i)->position) + while (i < m_parentheses.size() && info->position > m_parentheses.at(i)->position) ++i; m_parentheses.insert(i, info); diff --git a/limereport/scripteditor/lrscripthighlighter.h b/limereport/scripteditor/lrscripthighlighter.h index 86bee85..678b86d 100644 --- a/limereport/scripteditor/lrscripthighlighter.h +++ b/limereport/scripteditor/lrscripthighlighter.h @@ -1,53 +1,57 @@ #ifndef LRSCRIPTHIGHLIGHTER_H #define LRSCRIPTHIGHLIGHTER_H -#include #include +#include -namespace LimeReport{ +namespace LimeReport { -enum ParenthesisType {LeftParenthesis, RightParenthesis, ParenthesisTypeCount}; - -#define PARENHEIS_COUNT 3 -const QChar parenthesisCharacters[ParenthesisTypeCount][PARENHEIS_COUNT] = { - {'(', '{', '['}, - {')', '}', ']'} +enum ParenthesisType { + LeftParenthesis, + RightParenthesis, + ParenthesisTypeCount }; -struct ParenthesisInfo -{ +#define PARENHEIS_COUNT 3 +const QChar parenthesisCharacters[ParenthesisTypeCount][PARENHEIS_COUNT] + = { { '(', '{', '[' }, { ')', '}', ']' } }; + +struct ParenthesisInfo { char character; int position; }; -class TextBlockData : public QTextBlockUserData -{ +class TextBlockData: public QTextBlockUserData { public: - TextBlockData(){} + TextBlockData() { } ~TextBlockData(); - QVector parentheses(); - void insert(ParenthesisInfo *info); + QVector parentheses(); + void insert(ParenthesisInfo* info); private: - QVector m_parentheses; + QVector m_parentheses; }; -class ScriptHighlighter : QSyntaxHighlighter{ +class ScriptHighlighter: QSyntaxHighlighter { public: ScriptHighlighter(QTextDocument* parent); + protected: void highlightBlock(const QString& text); enum ScriptFormats { - NumberFormat, StringFormat, KeywordFormat, - CommentFormat, FormatsCount + NumberFormat, + StringFormat, + KeywordFormat, + CommentFormat, + FormatsCount }; QTextCharFormat m_formats[FormatsCount]; bool isKeyWord(const QString& word); - void createParentheisisInfo(const char& literal, TextBlockData *data, const QString& text); + void createParentheisisInfo(const char& literal, TextBlockData* data, const QString& text); + private: QSet m_keywords; }; - -} +} // namespace LimeReport #endif // LRSCRIPTHIGHLIGHTER_H diff --git a/limereport/serializators/lrserializatorintf.h b/limereport/serializators/lrserializatorintf.h index 452922e..9e1ab3f 100644 --- a/limereport/serializators/lrserializatorintf.h +++ b/limereport/serializators/lrserializatorintf.h @@ -32,19 +32,17 @@ #include namespace LimeReport { -class SerializatorIntf -{ +class SerializatorIntf { public: virtual QVariant loadValue() = 0; - virtual void save(const QVariant& value,QString name) = 0; - virtual ~SerializatorIntf(){} + virtual void save(const QVariant& value, QString name) = 0; + virtual ~SerializatorIntf() { } }; -class CryptedSerializator : public virtual SerializatorIntf -{ +class CryptedSerializator: public virtual SerializatorIntf { public: virtual void setPassPhrase(const QString& passPhrase) = 0; }; -} +} // namespace LimeReport #endif // LRSERIALIZATORINTF_H diff --git a/limereport/serializators/lrstorageintf.h b/limereport/serializators/lrstorageintf.h index c178bd2..842062a 100644 --- a/limereport/serializators/lrstorageintf.h +++ b/limereport/serializators/lrstorageintf.h @@ -31,33 +31,32 @@ #define LRSTORAGEINTF_H #include "lrglobal.h" + #include class QString; class QObject; -namespace LimeReport{ +namespace LimeReport { -class LIMEREPORT_EXPORT ObjectLoadingStateIntf{ +class LIMEREPORT_EXPORT ObjectLoadingStateIntf { public: virtual bool isLoading() = 0; virtual void objectLoadStarted() = 0; virtual void objectLoadFinished() = 0; }; -class LIMEREPORT_EXPORT ItemsWriterIntf -{ +class LIMEREPORT_EXPORT ItemsWriterIntf { public: virtual void putItem(QObject* item) = 0; virtual bool saveToFile(QString fileName) = 0; virtual QString saveToString() = 0; virtual QByteArray saveToByteArray() = 0; virtual void setPassPhrase(const QString& passPhrase) = 0; - virtual ~ItemsWriterIntf(){} + virtual ~ItemsWriterIntf() { } }; -class LIMEREPORT_EXPORT ItemsReaderIntf -{ +class LIMEREPORT_EXPORT ItemsReaderIntf { public: typedef QSharedPointer Ptr; virtual bool first() = 0; @@ -65,12 +64,12 @@ public: virtual bool prior() = 0; virtual QString itemType() = 0; virtual QString itemClassName() = 0; - virtual bool readItem(QObject *item) = 0; + virtual bool readItem(QObject* item) = 0; virtual int firstLevelItemsCount() = 0; virtual QString lastError() = 0; virtual void setPassPhrase(const QString& passPhrase) = 0; - virtual ~ItemsReaderIntf(){} + virtual ~ItemsReaderIntf() { } }; -} +} // namespace LimeReport #endif // LRSTORAGEINTF_H diff --git a/limereport/serializators/lrxmlbasetypesserializators.cpp b/limereport/serializators/lrxmlbasetypesserializators.cpp index 38feed3..885bf13 100644 --- a/limereport/serializators/lrxmlbasetypesserializators.cpp +++ b/limereport/serializators/lrxmlbasetypesserializators.cpp @@ -28,91 +28,129 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrxmlbasetypesserializators.h" -#include "serializators/lrxmlserializatorsfactory.h" + #include "lrsimplecrypt.h" +#include "serializators/lrxmlserializatorsfactory.h" + +#include #include #include -#include -namespace{ +namespace { -LimeReport::SerializatorIntf * createIntSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlIntSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createQRealSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQRealSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createQStringSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQStringSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createEnumAndFlagsSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlEnumAndFlagsSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createBoolSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlBoolSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createFontSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlFontSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createQSizeFSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQSizeFSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createQImageSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQImageSerializator(doc,node); -} - -LimeReport::SerializatorIntf * createQColorSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlColorSerializator(doc,node); -} - -LimeReport::SerializatorIntf* createQByteArraySerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQByteArraySerializator(doc,node); -} - -LimeReport::SerializatorIntf* createQVariantSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XmlQVariantSerializator(doc,node); -} - -bool VARIABLE_IS_NOT_USED registredQString = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QString", createQStringSerializator); -bool VARIABLE_IS_NOT_USED registredInt = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("int", createIntSerializator); -bool VARIABLE_IS_NOT_USED registredEnumAndFlags = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("enumAndFlags",createEnumAndFlagsSerializator); -bool VARIABLE_IS_NOT_USED registredBool = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("bool", createBoolSerializator); -bool VARIABLE_IS_NOT_USED registredQFont = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QFont", createFontSerializator); -bool VARIABLE_IS_NOT_USED registredQSizeF = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QSizeF", createQSizeFSerializator); -bool VARIABLE_IS_NOT_USED registredQImage = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QImage", createQImageSerializator); -bool VARIABLE_IS_NOT_USED registredQReal = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("qreal", createQRealSerializator); -bool VARIABLE_IS_NOT_USED registerDouble = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("double", createQRealSerializator); -bool VARIABLE_IS_NOT_USED registerQColor = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QColor", createQColorSerializator); -bool VARIABLE_IS_NOT_USED registerQByteArray = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QByteArray", createQByteArraySerializator); -bool VARIABLE_IS_NOT_USED registerQVariant = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QVariant", createQVariantSerializator); - -} - - -namespace LimeReport{ - -void XmlBaseSerializator::saveBool(QDomElement node,QString name, bool value) +LimeReport::SerializatorIntf* createIntSerializator(QDomDocument* doc, QDomElement* node) { - if (value) node.setAttribute(name,1); - else node.setAttribute(name,0); + return new LimeReport::XmlIntSerializator(doc, node); } -void XmlQStringSerializator::save(const QVariant &value, QString name) +LimeReport::SerializatorIntf* createQRealSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQRealSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQStringSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQStringSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createEnumAndFlagsSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlEnumAndFlagsSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createBoolSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlBoolSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createFontSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlFontSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQSizeFSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQSizeFSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQImageSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQImageSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQColorSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlColorSerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQByteArraySerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQByteArraySerializator(doc, node); +} + +LimeReport::SerializatorIntf* createQVariantSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XmlQVariantSerializator(doc, node); +} + +bool VARIABLE_IS_NOT_USED registredQString + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QString", createQStringSerializator); +bool VARIABLE_IS_NOT_USED registredInt + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("int", + createIntSerializator); +bool VARIABLE_IS_NOT_USED registredEnumAndFlags + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "enumAndFlags", createEnumAndFlagsSerializator); +bool VARIABLE_IS_NOT_USED registredBool + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "bool", createBoolSerializator); +bool VARIABLE_IS_NOT_USED registredQFont + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QFont", createFontSerializator); +bool VARIABLE_IS_NOT_USED registredQSizeF + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QSizeF", createQSizeFSerializator); +bool VARIABLE_IS_NOT_USED registredQImage + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QImage", createQImageSerializator); +bool VARIABLE_IS_NOT_USED registredQReal + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "qreal", createQRealSerializator); +bool VARIABLE_IS_NOT_USED registerDouble + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "double", createQRealSerializator); +bool VARIABLE_IS_NOT_USED registerQColor + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QColor", createQColorSerializator); +bool VARIABLE_IS_NOT_USED registerQByteArray + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QByteArray", createQByteArraySerializator); +bool VARIABLE_IS_NOT_USED registerQVariant + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QVariant", createQVariantSerializator); + +} // namespace + +namespace LimeReport { + +void XmlBaseSerializator::saveBool(QDomElement node, QString name, bool value) +{ + if (value) + node.setAttribute(name, 1); + else + node.setAttribute(name, 0); +} + +void XmlQStringSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QString"); - if (name.compare("password")==0){ + _node.setAttribute("Type", "QString"); + if (name.compare("password") == 0) { Chipper chipper(passPhrase()); QByteArray ba = chipper.cryptString(value.toString()); - //ba.append(); - _node.setAttribute("Value",QString(ba.toBase64())); + // ba.append(); + _node.setAttribute("Value", QString(ba.toBase64())); } else { _node.appendChild(doc()->createTextNode(value.toString())); } @@ -121,7 +159,7 @@ void XmlQStringSerializator::save(const QVariant &value, QString name) QVariant XmlQStringSerializator::loadValue() { - if (node()->tagName().compare("password")==0){ + if (node()->tagName().compare("password") == 0) { QByteArray ba; Chipper chipper(passPhrase()); ba.append(node()->attribute("Value").toLatin1()); @@ -130,62 +168,54 @@ QVariant XmlQStringSerializator::loadValue() return node()->text(); } -void XmlIntSerializator::save(const QVariant &value, QString name) +void XmlIntSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","int"); - _node.setAttribute("Value",value.toInt()); + _node.setAttribute("Type", "int"); + _node.setAttribute("Value", value.toInt()); node()->appendChild(_node); } -QVariant XmlIntSerializator::loadValue() -{ - return node()->attribute("Value").toInt(); -} +QVariant XmlIntSerializator::loadValue() { return node()->attribute("Value").toInt(); } -void XmlEnumAndFlagsSerializator::save(const QVariant &value, QString name) +void XmlEnumAndFlagsSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","enumAndFlags"); - _node.setAttribute("Value",value.toInt()); + _node.setAttribute("Type", "enumAndFlags"); + _node.setAttribute("Value", value.toInt()); node()->appendChild(_node); } -QVariant XmlEnumAndFlagsSerializator::loadValue() -{ - return node()->attribute("Value").toInt(); -} +QVariant XmlEnumAndFlagsSerializator::loadValue() { return node()->attribute("Value").toInt(); } -void XmlBoolSerializator::save(const QVariant &value, QString name) +void XmlBoolSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","bool"); + _node.setAttribute("Type", "bool"); if (value.toBool()) - _node.setAttribute("Value",1); - else _node.setAttribute("Value",0); + _node.setAttribute("Value", 1); + else + _node.setAttribute("Value", 0); node()->appendChild(_node); } -QVariant XmlBoolSerializator::loadValue() -{ - return node()->attribute("Value").toInt(); -} +QVariant XmlBoolSerializator::loadValue() { return node()->attribute("Value").toInt(); } -void XmlFontSerializator::save(const QVariant &value, QString name) +void XmlFontSerializator::save(const QVariant& value, QString name) { QFont font = value.value(); QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QFont"); - _node.setAttribute("family",font.family()); - _node.setAttribute("pointSize",font.pointSize()); -//#if QT_VERSION>0x040800 -// _node.setAttribute("stylename",font.styleName()); -//#endif - _node.setAttribute("weight",font.weight()); - //saveBool(_node,"bold",font.bold()); - saveBool(_node,"italic",font.italic()); - saveBool(_node,"underline",font.underline()); + _node.setAttribute("Type", "QFont"); + _node.setAttribute("family", font.family()); + _node.setAttribute("pointSize", font.pointSize()); + //#if QT_VERSION>0x040800 + // _node.setAttribute("stylename",font.styleName()); + //#endif + _node.setAttribute("weight", font.weight()); + // saveBool(_node,"bold",font.bold()); + saveBool(_node, "italic", font.italic()); + saveBool(_node, "underline", font.underline()); node()->appendChild(_node); } @@ -194,25 +224,25 @@ QVariant XmlFontSerializator::loadValue() QFont font; font.setFamily(node()->attribute("family")); font.setPointSize(node()->attribute("pointSize").toInt()); -//#if QT_VERSION>0x040800 -// font.setStyleName(node()->attribute("stylename")); -//#endif + //#if QT_VERSION>0x040800 + // font.setStyleName(node()->attribute("stylename")); + //#endif if (node()->attribute("weight").toInt() > 0) font.setWeight(static_cast(node()->attribute("weight").toInt())); if (!node()->attribute("bold").isEmpty()) - font.setBold(node()->attribute("bold").toInt()); + font.setBold(node()->attribute("bold").toInt()); font.setItalic(node()->attribute("italic").toInt()); font.setUnderline(node()->attribute("underline").toInt()); return font; } -void XmlQSizeFSerializator::save(const QVariant &value, QString name) +void XmlQSizeFSerializator::save(const QVariant& value, QString name) { QSizeF size = value.toSizeF(); QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QSizeF"); - _node.setAttribute("width",QString::number(size.width())); - _node.setAttribute("height",QString::number(size.height())); + _node.setAttribute("Type", "QSizeF"); + _node.setAttribute("width", QString::number(size.width())); + _node.setAttribute("height", QString::number(size.height())); node()->appendChild(_node); } @@ -224,15 +254,15 @@ QVariant XmlQSizeFSerializator::loadValue() return size; } -void XmlQImageSerializator::save(const QVariant &value, QString name) +void XmlQImageSerializator::save(const QVariant& value, QString name) { - QImage image=value.value(); + QImage image = value.value(); QByteArray ba; QBuffer buff(&ba); buff.open(QIODevice::WriteOnly); - image.save(&buff,"PNG"); + image.save(&buff, "PNG"); QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QImage"); + _node.setAttribute("Type", "QImage"); _node.appendChild(doc()->createTextNode(ba.toHex())); node()->appendChild(_node); } @@ -240,41 +270,35 @@ void XmlQImageSerializator::save(const QVariant &value, QString name) QVariant XmlQImageSerializator::loadValue() { QImage img; - img.loadFromData(QByteArray::fromHex(node()->text().toLatin1()),"PNG"); + img.loadFromData(QByteArray::fromHex(node()->text().toLatin1()), "PNG"); return img; } -void XmlQRealSerializator::save(const QVariant &value, QString name) +void XmlQRealSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","qreal"); - _node.setAttribute("Value",QString::number(value.toDouble())); + _node.setAttribute("Type", "qreal"); + _node.setAttribute("Value", QString::number(value.toDouble())); node()->appendChild(_node); } -QVariant XmlQRealSerializator::loadValue() -{ - return node()->attribute("Value").toDouble(); -} +QVariant XmlQRealSerializator::loadValue() { return node()->attribute("Value").toDouble(); } -void XmlColorSerializator::save(const QVariant &value, QString name) +void XmlColorSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QColor"); - _node.setAttribute("Value",value.value().name()); + _node.setAttribute("Type", "QColor"); + _node.setAttribute("Value", value.value().name()); node()->appendChild(_node); } -QVariant XmlColorSerializator::loadValue() -{ - return QColor(node()->attribute("Value")); -} +QVariant XmlColorSerializator::loadValue() { return QColor(node()->attribute("Value")); } -void XmlQByteArraySerializator::save(const QVariant &value, QString name) +void XmlQByteArraySerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QByteArray"); - _node.setAttribute("Value",QString(value.toByteArray().toBase64())); + _node.setAttribute("Type", "QByteArray"); + _node.setAttribute("Value", QString(value.toByteArray().toBase64())); node()->appendChild(_node); } @@ -285,11 +309,11 @@ QVariant XmlQByteArraySerializator::loadValue() return QByteArray::fromBase64(ba); } -void XmlQVariantSerializator::save(const QVariant &value, QString name) +void XmlQVariantSerializator::save(const QVariant& value, QString name) { QDomElement _node = doc()->createElement(name); - _node.setAttribute("Type","QVariant"); - _node.setAttribute("Value",QString(value.toByteArray().toBase64())); + _node.setAttribute("Type", "QVariant"); + _node.setAttribute("Value", QString(value.toByteArray().toBase64())); node()->appendChild(_node); } @@ -300,9 +324,4 @@ QVariant XmlQVariantSerializator::loadValue() return QByteArray::fromBase64(ba); } - - -} - - - +} // namespace LimeReport diff --git a/limereport/serializators/lrxmlbasetypesserializators.h b/limereport/serializators/lrxmlbasetypesserializators.h index 8662503..0814a77 100644 --- a/limereport/serializators/lrxmlbasetypesserializators.h +++ b/limereport/serializators/lrxmlbasetypesserializators.h @@ -31,131 +31,149 @@ #define LRXMLBASETYPESSERIALIZATORS_H #include "lrserializatorintf.h" -#include + #include +#include -namespace LimeReport{ +namespace LimeReport { -class XmlBaseSerializator : public virtual SerializatorIntf{ +class XmlBaseSerializator: public virtual SerializatorIntf { public: - XmlBaseSerializator(QDomDocument *doc, QDomElement *node):m_doc(doc),m_node(node){} + XmlBaseSerializator(QDomDocument* doc, QDomElement* node): m_doc(doc), m_node(node) { } + protected: - QDomDocument* doc() {return m_doc;} - QDomElement* node() {if (!m_node) qDebug()< #include -namespace{ +namespace { -LimeReport::SerializatorIntf * createQRectSerializator(QDomDocument *doc, QDomElement *node){ - return new LimeReport::XMLQRectSerializator(doc,node); +LimeReport::SerializatorIntf* createQRectSerializator(QDomDocument* doc, QDomElement* node) +{ + return new LimeReport::XMLQRectSerializator(doc, node); } -//LimeReport::SerializatorIntf * createQRectFSerializator(QDomDocument *doc, QDomElement *node){ +// LimeReport::SerializatorIntf * createQRectFSerializator(QDomDocument *doc, QDomElement +// *node){ // return new LimeReport::XMLQRectFSerializator(doc,node); //} -bool VARIABLE_IS_NOT_USED registredQRect = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QRect", createQRectSerializator); -bool VARIABLE_IS_NOT_USED registredQRectF = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator("QRectF", createQRectSerializator); +bool VARIABLE_IS_NOT_USED registredQRect + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QRect", createQRectSerializator); +bool VARIABLE_IS_NOT_USED registredQRectF + = LimeReport::XMLAbstractSerializatorFactory::instance().registerCreator( + "QRectF", createQRectSerializator); -} +} // namespace QVariant LimeReport::XMLQRectSerializator::loadValue() { QRect rect; - //QDomElement geometryNode = m_node->firstChildElement(name); - //if (!geometryNode.isNull()){ - rect = QRect( - m_node->attribute("x").toInt(), - m_node->attribute("y").toInt(), - m_node->attribute("width").toInt(), - m_node->attribute("height").toInt() - ); + // QDomElement geometryNode = m_node->firstChildElement(name); + // if (!geometryNode.isNull()){ + rect = QRect(m_node->attribute("x").toInt(), m_node->attribute("y").toInt(), + m_node->attribute("width").toInt(), m_node->attribute("height").toInt()); //} return rect; } -void LimeReport::XMLQRectSerializator::save(const QVariant &value, QString name) +void LimeReport::XMLQRectSerializator::save(const QVariant& value, QString name) { QDomElement geometryNode = m_doc->createElement(name); - geometryNode.setAttribute("Type","QRect"); - geometryNode.setAttribute("x",value.toRect().x()); - geometryNode.setAttribute("x",value.toRect().x()); - geometryNode.setAttribute("y",value.toRect().y()); - geometryNode.setAttribute("width",value.toRect().width()); - geometryNode.setAttribute("height",value.toRect().height()); + geometryNode.setAttribute("Type", "QRect"); + geometryNode.setAttribute("x", value.toRect().x()); + geometryNode.setAttribute("x", value.toRect().x()); + geometryNode.setAttribute("y", value.toRect().y()); + geometryNode.setAttribute("width", value.toRect().width()); + geometryNode.setAttribute("height", value.toRect().height()); m_node->appendChild(geometryNode); } -void LimeReport::XMLQRectFSerializator::save(const QVariant &value, QString name) +void LimeReport::XMLQRectFSerializator::save(const QVariant& value, QString name) { QDomElement geometryNode = m_doc->createElement(name); - geometryNode.setAttribute("Type","QRectF"); - geometryNode.setAttribute("x",value.toRect().x()); - geometryNode.setAttribute("y",value.toRect().y()); - geometryNode.setAttribute("width",value.toRect().width()); - geometryNode.setAttribute("height",value.toRect().height()); + geometryNode.setAttribute("Type", "QRectF"); + geometryNode.setAttribute("x", value.toRect().x()); + geometryNode.setAttribute("y", value.toRect().y()); + geometryNode.setAttribute("width", value.toRect().width()); + geometryNode.setAttribute("height", value.toRect().height()); m_node->appendChild(geometryNode); } QVariant LimeReport::XMLQRectFSerializator::loadValue() { QRectF rect; - //QDomElement geometryNode = m_node->firstChildElement(name); - //if (!geometryNode.isNull()){ - rect = QRect( - m_node->attribute("x").toDouble(), - m_node->attribute("y").toDouble(), - m_node->attribute("width").toDouble(), - m_node->attribute("height").toDouble() - ); + // QDomElement geometryNode = m_node->firstChildElement(name); + // if (!geometryNode.isNull()){ + rect = QRect(m_node->attribute("x").toDouble(), m_node->attribute("y").toDouble(), + m_node->attribute("width").toDouble(), m_node->attribute("height").toDouble()); //} return rect; diff --git a/limereport/serializators/lrxmlqrectserializator.h b/limereport/serializators/lrxmlqrectserializator.h index b41dc93..8902ce8 100644 --- a/limereport/serializators/lrxmlqrectserializator.h +++ b/limereport/serializators/lrxmlqrectserializator.h @@ -31,31 +31,32 @@ #define LRXMLQRECTSERIALIZATOR_H #include "lrserializatorintf.h" + #include -namespace LimeReport{ +namespace LimeReport { -class XMLQRectSerializator : public SerializatorIntf -{ +class XMLQRectSerializator: public SerializatorIntf { public: - XMLQRectSerializator(QDomDocument *doc, QDomElement *node):m_doc(doc),m_node(node){} - virtual void save(const QVariant &value,QString name); + XMLQRectSerializator(QDomDocument* doc, QDomElement* node): m_doc(doc), m_node(node) { } + virtual void save(const QVariant& value, QString name); virtual QVariant loadValue(); + private: - QDomDocument *m_doc; - QDomElement *m_node; + QDomDocument* m_doc; + QDomElement* m_node; }; -class XMLQRectFSerializator : public SerializatorIntf -{ +class XMLQRectFSerializator: public SerializatorIntf { public: - XMLQRectFSerializator(QDomDocument *doc, QDomElement *node):m_doc(doc),m_node(node){} - virtual void save(const QVariant &value, QString name); + XMLQRectFSerializator(QDomDocument* doc, QDomElement* node): m_doc(doc), m_node(node) { } + virtual void save(const QVariant& value, QString name); virtual QVariant loadValue(); + private: - QDomDocument *m_doc; - QDomElement *m_node; + QDomDocument* m_doc; + QDomElement* m_node; }; -} +} // namespace LimeReport #endif // LRXMLQRECTSERIALIZATOR_H diff --git a/limereport/serializators/lrxmlreader.cpp b/limereport/serializators/lrxmlreader.cpp index 3925128..d038bd6 100644 --- a/limereport/serializators/lrxmlreader.cpp +++ b/limereport/serializators/lrxmlreader.cpp @@ -27,52 +27,51 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ -#include "stdexcept" - #include "lrxmlreader.h" + #include "lrbasedesignintf.h" -#include "lrdesignelementsfactory.h" #include "lrcollection.h" +#include "lrdesignelementsfactory.h" #include "lrreporttranslation.h" +#include "stdexcept" #include #ifdef BUILD_WITH_EASY_PROFILER #include "easy/profiler.h" #else -# define EASY_BLOCK(...) -# define EASY_END_BLOCK +#define EASY_BLOCK(...) +#define EASY_END_BLOCK #endif -namespace LimeReport{ +namespace LimeReport { -XMLReader::XMLReader() - : m_doc(new QDomDocument){} -XMLReader::XMLReader(QSharedPointer doc) - : m_doc(doc){} +XMLReader::XMLReader(): m_doc(new QDomDocument) { } +XMLReader::XMLReader(QSharedPointer doc): m_doc(doc) { } bool XMLReader::prepareReader(QDomDocument* doc) { Q_UNUSED(doc); - m_error=QLatin1String("Context not initialized"); + m_error = QLatin1String("Context not initialized"); return false; } int XMLReader::firstLevelItemsCount() { - if (m_firstNode.childNodes().count()==0) return 0; + if (m_firstNode.childNodes().count() == 0) + return 0; QDomElement tmpNode = m_firstNode; - int res=0; - while (!tmpNode.isNull()){ + int res = 0; + while (!tmpNode.isNull()) { res++; - tmpNode=tmpNode.nextSiblingElement(); + tmpNode = tmpNode.nextSiblingElement(); } return res; } bool XMLReader::first() { - if (extractFirstNode()){ + if (extractFirstNode()) { m_curNode = m_firstNode; return !m_curNode.isNull(); } @@ -91,98 +90,88 @@ bool XMLReader::prior() return !m_curNode.isNull(); } -QString XMLReader::itemType() -{ - return m_curNode.attribute("Type"); -} +QString XMLReader::itemType() { return m_curNode.attribute("Type"); } -QString XMLReader::itemClassName() -{ - return m_curNode.attribute("ClassName"); -} +QString XMLReader::itemClassName() { return m_curNode.attribute("ClassName"); } -bool XMLReader::readItem(QObject *item) +bool XMLReader::readItem(QObject* item) { - if (!m_curNode.isNull()){ - readItemFromNode(item,&m_curNode); + if (!m_curNode.isNull()) { + readItemFromNode(item, &m_curNode); } else { - m_error=QString("Object %1 not founded").arg(item->objectName()); + m_error = QString("Object %1 not founded").arg(item->objectName()); return false; } return true; } -void XMLReader::readItemFromNode(QObject* item,QDomElement *node) +void XMLReader::readItemFromNode(QObject* item, QDomElement* node) { EASY_BLOCK("readItemFromNode"); ObjectLoadingStateIntf* lf = dynamic_cast(item); - if(lf) lf->objectLoadStarted(); - for (int i=0;ichildNodes().count();i++){ - QDomElement currentNode =node->childNodes().at(i).toElement(); - if (currentNode.attribute("Type")=="Object"){ - readQObject(item,¤tNode); - } else if (currentNode.attribute("Type")=="Collection") - { - readCollection(item,¤tNode); - } else if (currentNode.attribute("Type")=="Translation"){ - readTranslation(item,¤tNode); - } else readProperty(item,¤tNode); + if (lf) + lf->objectLoadStarted(); + for (int i = 0; i < node->childNodes().count(); i++) { + QDomElement currentNode = node->childNodes().at(i).toElement(); + if (currentNode.attribute("Type") == "Object") { + readQObject(item, ¤tNode); + } else if (currentNode.attribute("Type") == "Collection") { + readCollection(item, ¤tNode); + } else if (currentNode.attribute("Type") == "Translation") { + readTranslation(item, ¤tNode); + } else + readProperty(item, ¤tNode); } - if (lf) lf->objectLoadFinished(); + if (lf) + lf->objectLoadFinished(); BaseDesignIntf* baseObj = dynamic_cast(item); - if(baseObj) { - foreach(QGraphicsItem* childItem,baseObj->childItems()){ + if (baseObj) { + foreach (QGraphicsItem* childItem, baseObj->childItems()) { BaseDesignIntf* baseItem = dynamic_cast(childItem); - if (baseItem) baseItem->parentObjectLoadFinished(); + if (baseItem) + baseItem->parentObjectLoadFinished(); } } EASY_END_BLOCK; } -QString XMLReader::lastError() -{ - return m_error; -} +QString XMLReader::lastError() { return m_error; } -void XMLReader::setPassPhrase(const QString &passPhrase) -{ - m_passPhrase = passPhrase; -} +void XMLReader::setPassPhrase(const QString& passPhrase) { m_passPhrase = passPhrase; } bool XMLReader::extractFirstNode() { - if (m_firstNode.isNull()){ - if (m_doc->childNodes().count()==0){ - if (!prepareReader(m_doc.data())) return false; + if (m_firstNode.isNull()) { + if (m_doc->childNodes().count() == 0) { + if (!prepareReader(m_doc.data())) + return false; } m_firstNode = m_doc->documentElement(); if (!m_firstNode.hasAttributes()) - m_firstNode = m_firstNode.firstChildElement(); + m_firstNode = m_firstNode.firstChildElement(); } return !m_firstNode.isNull(); } -void XMLReader::readProperty(QObject *item, QDomElement *node) +void XMLReader::readProperty(QObject* item, QDomElement* node) { - item->setProperty(node->nodeName().toLatin1(),getValue(node)); + item->setProperty(node->nodeName().toLatin1(), getValue(node)); } -QVariant XMLReader::getValue(QDomElement *node) +QVariant XMLReader::getValue(QDomElement* node) { CreateSerializator creator = 0; try { - creator=XMLAbstractSerializatorFactory::instance().objectCreator( - node->attribute("Type") - ); - } catch(ReportError &e){ - qDebug()<attribute("Type")<attribute("Type")); + } catch (ReportError& e) { + qDebug() << node->attribute("Type") << e.what(); } if (creator) { - QScopedPointerserializator(creator(m_doc.data(),node)); + QScopedPointer serializator(creator(m_doc.data(), node)); CryptedSerializator* cs = dynamic_cast(serializator.data()); - if (cs){ + if (cs) { cs->setPassPhrase(m_passPhrase); } return serializator->loadValue(); @@ -195,21 +184,22 @@ void XMLReader::readQObject(QObject* item, QDomElement* node) EASY_BLOCK("readQObject"); QObject* childItem = qvariant_cast(item->property(node->nodeName().toLatin1())); if (childItem) - readItemFromNode(childItem,node); + readItemFromNode(childItem, node); EASY_END_BLOCK; } -void XMLReader::readCollection(QObject *item, QDomElement *node) +void XMLReader::readCollection(QObject* item, QDomElement* node) { EASY_BLOCK("readCollection") ICollectionContainer* collection = dynamic_cast(item); - if (collection){ + if (collection) { QString collectionName = node->nodeName(); - for(int i = 0; i < node->childNodes().count(); ++i){ - QDomElement currentNode =node->childNodes().at(i).toElement(); - QObject* obj = collection->createElement(collectionName,currentNode.attribute("ClassName")); + for (int i = 0; i < node->childNodes().count(); ++i) { + QDomElement currentNode = node->childNodes().at(i).toElement(); + QObject* obj + = collection->createElement(collectionName, currentNode.attribute("ClassName")); if (obj) - readItemFromNode(obj,¤tNode); + readItemFromNode(obj, ¤tNode); } collection->collectionLoadFinished(collectionName); } @@ -219,70 +209,81 @@ void XMLReader::readCollection(QObject *item, QDomElement *node) void XMLReader::readTranslation(QObject* item, QDomElement* node) { ITranslationContainer* tranclationContainer = dynamic_cast(item); - if (tranclationContainer){ + if (tranclationContainer) { Translations* translations = tranclationContainer->translations(); - for (int langIndex = 0; langIndexchildNodes().count(); ++langIndex){ + for (int langIndex = 0; langIndex < node->childNodes().count(); ++langIndex) { QDomElement languageNode = node->childNodes().at(langIndex).toElement(); - ReportTranslation* curTranslation = new ReportTranslation((QLocale::Language)(languageNode.attributeNode("Value").value().toInt())); - for (int pageIndex = 0; pageIndex < languageNode.childNodes().count(); ++pageIndex){ + ReportTranslation* curTranslation = new ReportTranslation( + (QLocale::Language)(languageNode.attributeNode("Value").value().toInt())); + for (int pageIndex = 0; pageIndex < languageNode.childNodes().count(); ++pageIndex) { QDomElement pageNode = languageNode.childNodes().at(pageIndex).toElement(); PageTranslation* pageTranslation = curTranslation->createEmptyPageTranslation(); pageTranslation->pageName = pageNode.nodeName(); - for (int itemIndex = 0; itemIndex < pageNode.childNodes().count(); ++itemIndex){ + for (int itemIndex = 0; itemIndex < pageNode.childNodes().count(); ++itemIndex) { QDomElement itemNode = pageNode.childNodes().at(itemIndex).toElement(); ItemTranslation* itemTranslation = new ItemTranslation(); itemTranslation->itemName = itemNode.nodeName(); - for (int propertyIndex = 0; propertyIndex < itemNode.childNodes().count(); ++propertyIndex){ - QDomElement propertyNode = itemNode.childNodes().at(propertyIndex).toElement(); + for (int propertyIndex = 0; propertyIndex < itemNode.childNodes().count(); + ++propertyIndex) { + QDomElement propertyNode + = itemNode.childNodes().at(propertyIndex).toElement(); PropertyTranslation* propertyTranslation = new PropertyTranslation; propertyTranslation->propertyName = propertyNode.nodeName(); propertyTranslation->value = propertyNode.attribute("Value"); propertyTranslation->sourceValue = propertyNode.attribute("SourceValue"); - propertyTranslation->checked = propertyNode.attribute("Checked").compare("Y") == 0; + propertyTranslation->checked + = propertyNode.attribute("Checked").compare("Y") == 0; itemTranslation->propertyesTranslation.append(propertyTranslation); } - pageTranslation->itemsTranslation.insert(itemTranslation->itemName, itemTranslation); + pageTranslation->itemsTranslation.insert(itemTranslation->itemName, + itemTranslation); } } - translations->insert(curTranslation->language(),curTranslation); + translations->insert(curTranslation->language(), curTranslation); } } } -FileXMLReader::FileXMLReader(QString fileName) - : m_fileName(fileName) -{ -} +FileXMLReader::FileXMLReader(QString fileName): m_fileName(fileName) { } -bool FileXMLReader::prepareReader(QDomDocument *doc) +bool FileXMLReader::prepareReader(QDomDocument* doc) { - if (!m_fileName.isEmpty()){ + if (!m_fileName.isEmpty()) { QFile source(m_fileName); if (source.open(QFile::ReadOnly)) { doc->setContent(&source); - if (doc->documentElement().nodeName()!="Report") { + if (doc->documentElement().nodeName() != "Report") { m_error = QString(QObject::tr("Wrong file format")); return false; } - } else {m_error=QString(QObject::tr("File %1 not opened")).arg(m_fileName); return false;} + } else { + m_error = QString(QObject::tr("File %1 not opened")).arg(m_fileName); + return false; + } } return true; } -bool StringXMLreader::prepareReader(QDomDocument *doc) +bool StringXMLreader::prepareReader(QDomDocument* doc) { - if (!m_content.isEmpty()){ + if (!m_content.isEmpty()) { doc->setContent(m_content); - }else {m_error = QString(QObject::tr("Content string is empty")); return false;} + } else { + m_error = QString(QObject::tr("Content string is empty")); + return false; + } return true; } -bool ByteArrayXMLReader::prepareReader(QDomDocument *doc) +bool ByteArrayXMLReader::prepareReader(QDomDocument* doc) { - if (m_content){ + if (m_content) { doc->setContent(*m_content); - } else {m_error = QString(QObject::tr("Content is empty")); return false;} + } else { + m_error = QString(QObject::tr("Content is empty")); + return false; + } return true; } -} +} // namespace LimeReport diff --git a/limereport/serializators/lrxmlreader.h b/limereport/serializators/lrxmlreader.h index dd92d7d..7ca4c42 100644 --- a/limereport/serializators/lrxmlreader.h +++ b/limereport/serializators/lrxmlreader.h @@ -30,43 +30,44 @@ #ifndef LRXMLREADER_H #define LRXMLREADER_H +#include "lrdesignelementsfactory.h" +#include "serializators/lrxmlwriter.h" + #include #include -#include "serializators/lrxmlwriter.h" -#include "lrdesignelementsfactory.h" +namespace LimeReport { -namespace LimeReport{ - -class XMLReader : public ItemsReaderIntf -{ +class XMLReader: public ItemsReaderIntf { public: XMLReader(); XMLReader(QSharedPointer doc); + protected: -//ItemsReaderIntf interface + // ItemsReaderIntf interface bool first(); bool next(); bool prior(); QString itemType(); QString itemClassName(); - bool readItem(QObject *item); + bool readItem(QObject* item); int firstLevelItemsCount(); QString lastError(); - void setPassPhrase(const QString &passPhrase); + void setPassPhrase(const QString& passPhrase); - virtual bool prepareReader(QDomDocument *doc); + virtual bool prepareReader(QDomDocument* doc); - void readItemFromNode(QObject *item, QDomElement *node); - void readProperty(QObject *item, QDomElement *node); - void readQObject(QObject *item, QDomElement *node); - void readCollection(QObject *item, QDomElement *node); - void readTranslation(QObject *item, QDomElement *node); - QVariant getValue(QDomElement *node); + void readItemFromNode(QObject* item, QDomElement* node); + void readProperty(QObject* item, QDomElement* node); + void readQObject(QObject* item, QDomElement* node); + void readCollection(QObject* item, QDomElement* node); + void readTranslation(QObject* item, QDomElement* node); + QVariant getValue(QDomElement* node); protected: bool extractFirstNode(); QString m_error; + private: QSharedPointer m_doc; QDomElement m_curNode; @@ -74,35 +75,50 @@ private: QString m_passPhrase; }; -class FileXMLReader : public XMLReader{ +class FileXMLReader: public XMLReader { public: - static ItemsReaderIntf::Ptr create(QString fileName){ return ItemsReaderIntf::Ptr(new FileXMLReader(fileName));} + static ItemsReaderIntf::Ptr create(QString fileName) + { + return ItemsReaderIntf::Ptr(new FileXMLReader(fileName)); + } + protected: - virtual bool prepareReader(QDomDocument *doc); + virtual bool prepareReader(QDomDocument* doc); + private: FileXMLReader(QString fileName); QString m_fileName; }; -class StringXMLreader : public XMLReader{ +class StringXMLreader: public XMLReader { public: - static ItemsReaderIntf::Ptr create(QString content){ return ItemsReaderIntf::Ptr(new StringXMLreader(content));} + static ItemsReaderIntf::Ptr create(QString content) + { + return ItemsReaderIntf::Ptr(new StringXMLreader(content)); + } + protected: - virtual bool prepareReader(QDomDocument *doc); + virtual bool prepareReader(QDomDocument* doc); + private: - StringXMLreader(QString content) : m_content(content){} + StringXMLreader(QString content): m_content(content) { } QString m_content; }; -class ByteArrayXMLReader : public XMLReader{ +class ByteArrayXMLReader: public XMLReader { public: - static ItemsReaderIntf::Ptr create(QByteArray* content){ return ItemsReaderIntf::Ptr(new ByteArrayXMLReader(content));} + static ItemsReaderIntf::Ptr create(QByteArray* content) + { + return ItemsReaderIntf::Ptr(new ByteArrayXMLReader(content)); + } + protected: - virtual bool prepareReader(QDomDocument *doc); + virtual bool prepareReader(QDomDocument* doc); + private: - ByteArrayXMLReader(QByteArray* content): m_content(content){} + ByteArrayXMLReader(QByteArray* content): m_content(content) { } QByteArray* m_content; }; -} +} // namespace LimeReport #endif // LRXMLREADER_H diff --git a/limereport/serializators/lrxmlserializatorsfactory.h b/limereport/serializators/lrxmlserializatorsfactory.h index 1f3d695..9eb3924 100644 --- a/limereport/serializators/lrxmlserializatorsfactory.h +++ b/limereport/serializators/lrxmlserializatorsfactory.h @@ -35,21 +35,25 @@ #include -namespace LimeReport{ +namespace LimeReport { -typedef SerializatorIntf* (*CreateSerializator)(QDomDocument *doc, QDomElement *parentNode); +typedef SerializatorIntf* (*CreateSerializator)(QDomDocument* doc, QDomElement* parentNode); -class XMLAbstractSerializatorFactory: public SimpleAbstractFactory -{ +class XMLAbstractSerializatorFactory: + public SimpleAbstractFactory { private: friend class Singleton; + public: - XMLAbstractSerializatorFactory(){} - ~XMLAbstractSerializatorFactory(){} - XMLAbstractSerializatorFactory(const XMLAbstractSerializatorFactory&){} - XMLAbstractSerializatorFactory& operator = (const XMLAbstractSerializatorFactory&){return *this;} + XMLAbstractSerializatorFactory() { } + ~XMLAbstractSerializatorFactory() { } + XMLAbstractSerializatorFactory(const XMLAbstractSerializatorFactory&) { } + XMLAbstractSerializatorFactory& operator=(const XMLAbstractSerializatorFactory&) + { + return *this; + } }; -} +} // namespace LimeReport #endif // LRXMLABSTRACTSERIALIZATORFABRIC_H diff --git a/limereport/serializators/lrxmlwriter.cpp b/limereport/serializators/lrxmlwriter.cpp index d07d8b8..1debc5b 100644 --- a/limereport/serializators/lrxmlwriter.cpp +++ b/limereport/serializators/lrxmlwriter.cpp @@ -28,58 +28,59 @@ * GNU General Public License for more details. * ****************************************************************************/ #include "lrxmlwriter.h" + #include "lrbasedesignintf.h" -#include "serializators/lrxmlserializatorsfactory.h" #include "lrcollection.h" #include "lrreporttranslation.h" +#include "serializators/lrxmlserializatorsfactory.h" + #include -namespace LimeReport{ +namespace LimeReport { -XMLWriter::XMLWriter() : m_doc(new QDomDocument) -{ - init(); -} +XMLWriter::XMLWriter(): m_doc(new QDomDocument) { init(); } -XMLWriter::XMLWriter(QSharedPointer doc) : m_doc(doc){ - init(); -} +XMLWriter::XMLWriter(QSharedPointer doc): m_doc(doc) { init(); } void XMLWriter::init() { - m_rootElement=m_doc->createElement("Report"); - QDomNode xmlNode = m_doc->createProcessingInstruction("xml", - "version=\"1.0\" encoding=\"UTF8\""); - m_doc->insertBefore(xmlNode,m_doc->firstChild()); + m_rootElement = m_doc->createElement("Report"); + QDomNode xmlNode + = m_doc->createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF8\""); + m_doc->insertBefore(xmlNode, m_doc->firstChild()); m_doc->appendChild(m_rootElement); } -void XMLWriter::putItem(QObject *item) +void XMLWriter::putItem(QObject* item) { - QDomElement node=putQObjectItem(item->metaObject()->className(),item); - if (!replaceNode(node,item)) m_rootElement.appendChild(node); + QDomElement node = putQObjectItem(item->metaObject()->className(), item); + if (!replaceNode(node, item)) + m_rootElement.appendChild(node); } -QString XMLWriter::extractClassName(QObject *item) +QString XMLWriter::extractClassName(QObject* item) { BaseDesignIntf* baseItem = dynamic_cast(item); - if(baseItem) return baseItem->storageTypeName(); - else return item->metaObject()->className(); + if (baseItem) + return baseItem->storageTypeName(); + else + return item->metaObject()->className(); } -void XMLWriter::putChildQObjectItem(QString name, QObject *item, QDomElement *parentNode) -{ +void XMLWriter::putChildQObjectItem(QString name, QObject* item, QDomElement* parentNode) +{ QDomElement itemNode = m_doc->createElement(name); - itemNode.setAttribute("ClassName",extractClassName(item)); - itemNode.setAttribute("Type","Object"); - if (parentNode) parentNode->appendChild(itemNode); - saveProperties(item,&itemNode); + itemNode.setAttribute("ClassName", extractClassName(item)); + itemNode.setAttribute("Type", "Object"); + if (parentNode) + parentNode->appendChild(itemNode); + saveProperties(item, &itemNode); } bool XMLWriter::setContent(QString fileName) { QFile xmlFile(fileName); - if (xmlFile.open(QFile::ReadOnly)){ + if (xmlFile.open(QFile::ReadOnly)) { m_doc->setContent(&xmlFile); return true; } @@ -88,11 +89,12 @@ bool XMLWriter::setContent(QString fileName) bool XMLWriter::saveToFile(QString fileName) { - if ((m_doc->childNodes().count()==0)||fileName.isEmpty()) return false; + if ((m_doc->childNodes().count() == 0) || fileName.isEmpty()) + return false; QFile xmlFile(fileName); if (xmlFile.open(QFile::WriteOnly)) { QTextStream buffer(&xmlFile); - m_doc->save(buffer,2); + m_doc->save(buffer, 2); xmlFile.close(); return true; } @@ -103,7 +105,7 @@ QString XMLWriter::saveToString() { QString res; QTextStream buffer(&res); - m_doc->save(buffer,2); + m_doc->save(buffer, 2); return res; } @@ -111,90 +113,95 @@ QByteArray XMLWriter::saveToByteArray() { QByteArray res; QTextStream buffer(&res); - m_doc->save(buffer,2); + m_doc->save(buffer, 2); return res; } -void XMLWriter::setPassPhrase(const QString &passPhrase) -{ - m_passPhrase = passPhrase; -} +void XMLWriter::setPassPhrase(const QString& passPhrase) { m_passPhrase = passPhrase; } -QDomElement XMLWriter::putQObjectItem(QString name, QObject *item) +QDomElement XMLWriter::putQObjectItem(QString name, QObject* item) { Q_UNUSED(name) QDomElement itemNode = m_doc->createElement("object"); - itemNode.setAttribute("ClassName",extractClassName(item)); - itemNode.setAttribute("Type","Object"); - saveProperties(item,&itemNode); + itemNode.setAttribute("ClassName", extractClassName(item)); + itemNode.setAttribute("Type", "Object"); + saveProperties(item, &itemNode); return itemNode; } -void XMLWriter::saveProperty(QString name, QObject* item, QDomElement *node) +void XMLWriter::saveProperty(QString name, QObject* item, QDomElement* node) { QString typeName; - if (name.compare("itemIndexMethod")==0) - typeName = item->metaObject()->property(item->metaObject()->indexOfProperty(name.toLatin1())).typeName(); + if (name.compare("itemIndexMethod") == 0) + typeName = item->metaObject() + ->property(item->metaObject()->indexOfProperty(name.toLatin1())) + .typeName(); else typeName = item->property(name.toLatin1()).typeName(); - CreateSerializator creator=0; - if (isCollection(name, item)) { saveCollection(name,item,node); return; } - if (isTranslation(name, item)) { saveTranslation(name, item, node); return; } + CreateSerializator creator = 0; + if (isCollection(name, item)) { + saveCollection(name, item, node); + return; + } + if (isTranslation(name, item)) { + saveTranslation(name, item, node); + return; + } - if (isQObject(name,item)) { - if (qvariant_cast(item->property(name.toLatin1()))) - putQObjectProperty(name,qvariant_cast(item->property(name.toLatin1())),node); + if (isQObject(name, item)) { + if (qvariant_cast(item->property(name.toLatin1()))) + putQObjectProperty(name, qvariant_cast(item->property(name.toLatin1())), + node); else { - qDebug()<<"Warnig property can`t be casted to QObject"<(item); + QDomElement collectionNode = m_doc->createElement(propertyName); + collectionNode.setAttribute("Type", "Collection"); - for(int i=0;ielementsCount(propertyName);i++){ - putCollectionItem(collection->elementAt(propertyName,i),&collectionNode); + for (int i = 0; i < collection->elementsCount(propertyName); i++) { + putCollectionItem(collection->elementAt(propertyName, i), &collectionNode); } node->appendChild(collectionNode); @@ -229,26 +237,27 @@ void XMLWriter::saveCollection(QString propertyName, QObject *item, QDomElement void XMLWriter::saveTranslation(QString propertyName, QObject* item, QDomElement* node) { ITranslationContainer* translationsContainer = dynamic_cast(item); - if (translationsContainer){ - QDomElement translationsNode=m_doc->createElement(propertyName); - translationsNode.setAttribute("Type","Translation"); + if (translationsContainer) { + QDomElement translationsNode = m_doc->createElement(propertyName); + translationsNode.setAttribute("Type", "Translation"); Translations* translations = translationsContainer->translations(); - foreach(QLocale::Language language, translations->keys()){ - QDomElement languageNode = m_doc->createElement(QLocale::languageToString(language).replace(' ', '_')); - languageNode.setAttribute("Value",QString::number(language)); + foreach (QLocale::Language language, translations->keys()) { + QDomElement languageNode + = m_doc->createElement(QLocale::languageToString(language).replace(' ', '_')); + languageNode.setAttribute("Value", QString::number(language)); translationsNode.appendChild(languageNode); ReportTranslation* curTranslation = translations->value(language); - foreach(PageTranslation* page, curTranslation->pagesTranslation()){ + foreach (PageTranslation* page, curTranslation->pagesTranslation()) { QDomElement pageNode = m_doc->createElement(page->pageName); languageNode.appendChild(pageNode); - foreach(ItemTranslation* item, page->itemsTranslation){ + foreach (ItemTranslation* item, page->itemsTranslation) { QDomElement itemNode = m_doc->createElement(item->itemName); - foreach(PropertyTranslation* property, item->propertyesTranslation){ - if (property->sourceValue.compare(property->value) != 0){ + foreach (PropertyTranslation* property, item->propertyesTranslation) { + if (property->sourceValue.compare(property->value) != 0) { QDomElement propertyNode = m_doc->createElement(property->propertyName); - propertyNode.setAttribute("Value",property->value); + propertyNode.setAttribute("Value", property->value); propertyNode.setAttribute("SourceValue", property->sourceValue); - propertyNode.setAttribute("Checked", property->checked ? "Y":"N"); + propertyNode.setAttribute("Checked", property->checked ? "Y" : "N"); itemNode.appendChild(propertyNode); } } @@ -259,53 +268,44 @@ void XMLWriter::saveTranslation(QString propertyName, QObject* item, QDomElement } node->appendChild(translationsNode); } - } -bool XMLWriter::isQObject(QString propertyName, QObject *item) +bool XMLWriter::isQObject(QString propertyName, QObject* item) { - QMetaProperty prop=item->metaObject()->property(item->metaObject()->indexOfProperty(propertyName.toLatin1())); - //TODO: Migrate to QMetaType + QMetaProperty prop = item->metaObject()->property( + item->metaObject()->indexOfProperty(propertyName.toLatin1())); + // TODO: Migrate to QMetaType #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QMetaType::fromName(prop.typeName()).id() == QMetaType::QObjectStar; #else return QMetaType::type(prop.typeName()) == QMetaType::QObjectStar; #endif - } bool XMLWriter::replaceNode(QDomElement node, QObject* item) { QDomElement element = m_rootElement.firstChildElement(item->metaObject()->className()); - while (!element.isNull()){ + while (!element.isNull()) { QDomElement objectName = element.firstChildElement(QLatin1String("objectName")); - if (!objectName.isNull()&&(objectName.text()==item->objectName())){ - QDomElement removeElement=element; - element=element.nextSiblingElement(item->metaObject()->className()); - m_rootElement.replaceChild(node,removeElement); + if (!objectName.isNull() && (objectName.text() == item->objectName())) { + QDomElement removeElement = element; + element = element.nextSiblingElement(item->metaObject()->className()); + m_rootElement.replaceChild(node, removeElement); return true; - } - else element=element.nextSiblingElement(item->metaObject()->className()); + } else + element = element.nextSiblingElement(item->metaObject()->className()); } return false; } -void XMLWriter::putCollectionItem(QObject *item, QDomElement *parentNode) +void XMLWriter::putCollectionItem(QObject* item, QDomElement* parentNode) { - putChildQObjectItem("item",item,parentNode); + putChildQObjectItem("item", item, parentNode); } void XMLWriter::putQObjectProperty(QString propertyName, QObject* item, QDomElement* parentNode) { - putChildQObjectItem(propertyName,item,parentNode); + putChildQObjectItem(propertyName, item, parentNode); } -} - - - - - - - - +} // namespace LimeReport diff --git a/limereport/serializators/lrxmlwriter.h b/limereport/serializators/lrxmlwriter.h index cbd4d4b..14da320 100644 --- a/limereport/serializators/lrxmlwriter.h +++ b/limereport/serializators/lrxmlwriter.h @@ -30,43 +30,45 @@ #ifndef LRXMLWRITER_H #define LRXMLWRITER_H -#include +#include "lrbasedesignintf.h" #include "serializators/lrstorageintf.h" #include "serializators/lrxmlserializatorsfactory.h" -#include "lrbasedesignintf.h" -namespace LimeReport{ +#include -class XMLWriter : public ItemsWriterIntf -{ +namespace LimeReport { + +class XMLWriter: public ItemsWriterIntf { public: XMLWriter(); XMLWriter(QSharedPointer doc); - ~XMLWriter() {} + ~XMLWriter() { } + private: // ItemsWriterIntf interface - void putItem(QObject* item); - bool saveToFile(QString fileName); + void putItem(QObject* item); + bool saveToFile(QString fileName); QString saveToString(); QByteArray saveToByteArray(); - void setPassPhrase(const QString &passPhrase); + void setPassPhrase(const QString& passPhrase); void init(); QDomElement putQObjectItem(QString name, QObject* item); void putChildQObjectItem(QString name, QObject* item, QDomElement* parentNode); - void putCollectionItem(QObject* item, QDomElement* parentNode=0); - void putQObjectProperty(QString propertyName, QObject *item, QDomElement* parentNode=0); + void putCollectionItem(QObject* item, QDomElement* parentNode = 0); + void putQObjectProperty(QString propertyName, QObject* item, QDomElement* parentNode = 0); void saveProperties(QObject* item, QDomElement* node); bool setContent(QString fileName); void saveProperty(QString name, QObject* item, QDomElement* node); bool enumOrFlag(QString name, QObject* item); QString extractClassName(QObject* item); - bool isCollection(QString propertyName, QObject *item); - bool isTranslation(QString propertyName, QObject *item); - void saveCollection(QString propertyName, QObject *item, QDomElement *node); - void saveTranslation(QString propertyName, QObject *item, QDomElement *node); - bool isQObject(QString propertyName, QObject *item); - bool replaceNode(QDomElement node, QObject *item); + bool isCollection(QString propertyName, QObject* item); + bool isTranslation(QString propertyName, QObject* item); + void saveCollection(QString propertyName, QObject* item, QDomElement* node); + void saveTranslation(QString propertyName, QObject* item, QDomElement* node); + bool isQObject(QString propertyName, QObject* item); + bool replaceNode(QDomElement node, QObject* item); + private: QSharedPointer m_doc; QString m_fileName; @@ -74,6 +76,6 @@ private: QString m_passPhrase; }; -} +} // namespace LimeReport #endif // LRXMLWRITER_H diff --git a/limereport/translationeditor/languageselectdialog.cpp b/limereport/translationeditor/languageselectdialog.cpp index 62aefb3..84e0e7d 100644 --- a/limereport/translationeditor/languageselectdialog.cpp +++ b/limereport/translationeditor/languageselectdialog.cpp @@ -1,16 +1,18 @@ #include "languageselectdialog.h" #include "ui_languageselectdialog.h" + +#include #include #include -#include -LanguageSelectDialog::LanguageSelectDialog(QWidget *parent) : +LanguageSelectDialog::LanguageSelectDialog(QWidget* parent): QDialog(parent), ui(new Ui::LanguageSelectDialog) { ui->setupUi(this); - for (int i = 2; icomboBox->addItem(QLocale::languageToString(static_cast(i)),static_cast(i)); + for (int i = 2; i < QLocale::LastLanguage; ++i) { + ui->comboBox->addItem(QLocale::languageToString(static_cast(i)), + static_cast(i)); } #if QT_VERSION < 0x050000 ui->comboBox->setEditText(""); @@ -19,10 +21,7 @@ LanguageSelectDialog::LanguageSelectDialog(QWidget *parent) : #endif } -LanguageSelectDialog::~LanguageSelectDialog() -{ - delete ui; -} +LanguageSelectDialog::~LanguageSelectDialog() { delete ui; } QLocale::Language LanguageSelectDialog::getSelectedLanguage() { diff --git a/limereport/translationeditor/languageselectdialog.h b/limereport/translationeditor/languageselectdialog.h index 48d53b4..a7e9263 100644 --- a/limereport/translationeditor/languageselectdialog.h +++ b/limereport/translationeditor/languageselectdialog.h @@ -8,16 +8,16 @@ namespace Ui { class LanguageSelectDialog; } -class LanguageSelectDialog : public QDialog { +class LanguageSelectDialog: public QDialog { Q_OBJECT - public: - explicit LanguageSelectDialog(QWidget *parent = 0); +public: + explicit LanguageSelectDialog(QWidget* parent = 0); ~LanguageSelectDialog(); QLocale::Language getSelectedLanguage(); - private: - Ui::LanguageSelectDialog *ui; +private: + Ui::LanguageSelectDialog* ui; }; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) diff --git a/limereport/translationeditor/translationeditor.cpp b/limereport/translationeditor/translationeditor.cpp index a2e693e..c31ee0d 100644 --- a/limereport/translationeditor/translationeditor.cpp +++ b/limereport/translationeditor/translationeditor.cpp @@ -1,41 +1,47 @@ #include "translationeditor.h" #include "ui_translationeditor.h" + +#include "languageselectdialog.h" #include "lrreportengine.h" #include "lrreportengine_p.h" #include "lrreporttranslation.h" -#include "languageselectdialog.h" + #include namespace LimeReport { -TranslationEditor::TranslationEditor(QWidget *parent) : +TranslationEditor::TranslationEditor(QWidget* parent): QWidget(parent), - ui(new Ui::TranslationEditor), m_translationContainer(0), - m_currentReportTranslation(0), m_currentPageTranslation(0), - m_currentPropertyTranslation(0), m_translationChanging(false) + ui(new Ui::TranslationEditor), + m_translationContainer(0), + m_currentReportTranslation(0), + m_currentPageTranslation(0), + m_currentPropertyTranslation(0), + m_translationChanging(false) { ui->setupUi(this); - ui->splitter_3->setStretchFactor(1,10); - ui->splitter_3->setStretchFactor(0,2); - ui->splitter_2->setStretchFactor(1,2); - ui->splitter->setStretchFactor(0,2); + ui->splitter_3->setStretchFactor(1, 10); + ui->splitter_3->setStretchFactor(0, 2); + ui->splitter_2->setStretchFactor(1, 2); + ui->splitter->setStretchFactor(0, 2); QTableWidgetItem* item = new QTableWidgetItem(); item->setIcon(QIcon(":/translationeditor/checked")); ui->tbStrings->setColumnCount(4); - ui->tbStrings->setColumnWidth(0,30); - ui->tbStrings->setColumnWidth(1,100); - ui->tbStrings->setColumnWidth(2,100); - ui->tbStrings->setHorizontalHeaderItem(0,item); - ui->tbStrings->setHorizontalHeaderItem(1,new QTableWidgetItem(tr("Report Item"))); - ui->tbStrings->setHorizontalHeaderItem(2,new QTableWidgetItem(tr("Property"))); - ui->tbStrings->setHorizontalHeaderItem(3,new QTableWidgetItem(tr("Source text"))); -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - m_clrReturn = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return), this, SLOT(slotItemChecked())); + ui->tbStrings->setColumnWidth(0, 30); + ui->tbStrings->setColumnWidth(1, 100); + ui->tbStrings->setColumnWidth(2, 100); + ui->tbStrings->setHorizontalHeaderItem(0, item); + ui->tbStrings->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Report Item"))); + ui->tbStrings->setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Property"))); + ui->tbStrings->setHorizontalHeaderItem(3, new QTableWidgetItem(tr("Source text"))); +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + m_clrReturn + = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return), this, SLOT(slotItemChecked())); #else - m_clrReturn = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(slotItemChecked())); + m_clrReturn + = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(slotItemChecked())); #endif - //ui->tbStrings->setSortingEnabled(true); - + // ui->tbStrings->setSortingEnabled(true); } void TranslationEditor::setReportEngine(ITranslationContainer* translationContainer) @@ -45,7 +51,7 @@ void TranslationEditor::setReportEngine(ITranslationContainer* translationContai m_currentPageTranslation = 0; m_currentPropertyTranslation = 0; - if (m_translationContainer){ + if (m_translationContainer) { m_translationContainer->updateTranslations(); updateUi(); } @@ -57,13 +63,14 @@ TranslationEditor::~TranslationEditor() delete m_clrReturn; } -QLocale::Language TranslationEditor::getLanguageByName(const QString& languageName){ - foreach(QLocale::Language language, m_translationContainer->translations()->keys()){ - if (QLocale::languageToString(language).compare(languageName) == 0){ - return language; - } - } - return QLocale::AnyLanguage; +QLocale::Language TranslationEditor::getLanguageByName(const QString& languageName) +{ + foreach (QLocale::Language language, m_translationContainer->translations()->keys()) { + if (QLocale::languageToString(language).compare(languageName) == 0) { + return language; + } + } + return QLocale::AnyLanguage; } void TranslationEditor::updateUi() @@ -75,16 +82,16 @@ void TranslationEditor::updateUi() ui->cbChecked->setEnabled(false); Q_ASSERT(m_translationContainer != 0); - if (m_translationContainer){ + if (m_translationContainer) { Translations* translations = m_translationContainer->translations(); Q_ASSERT(translations != 0); - if (translations){ - foreach(QLocale::Language language, translations->keys()){ + if (translations) { + foreach (QLocale::Language language, translations->keys()) { if (language != QLocale::AnyLanguage) ui->lvLanguages->addItem(QLocale::languageToString(language)); } - if (!translations->keys().isEmpty()){ - if (ui->lvLanguages->count() != 0){ + if (!translations->keys().isEmpty()) { + if (ui->lvLanguages->count() != 0) { ui->lvLanguages->item(0)->setSelected(true); activateLanguage(getLanguageByName(ui->lvLanguages->item(0)->text())); } else { @@ -105,19 +112,21 @@ void TranslationEditor::activateLanguage(QLocale::Language language) ui->twPages->clear(); Translations* translations = m_translationContainer->translations(); Q_ASSERT(translations != 0); - if (translations){ + if (translations) { m_currentReportTranslation = translations->value(language); Q_ASSERT(m_currentReportTranslation != 0); - if (m_currentReportTranslation){ - foreach(PageTranslation* pageTranslation, m_currentReportTranslation->pagesTranslation()){ - QTreeWidgetItem* pageItem = new QTreeWidgetItem(); - pageItem->setText(0,pageTranslation->pageName); - ui->twPages->addTopLevelItem(pageItem); - } + if (m_currentReportTranslation) { + foreach (PageTranslation* pageTranslation, + m_currentReportTranslation->pagesTranslation()) { + QTreeWidgetItem* pageItem = new QTreeWidgetItem(); + pageItem->setText(0, pageTranslation->pageName); + ui->twPages->addTopLevelItem(pageItem); + } } - if (ui->twPages->topLevelItem(0)){ + if (ui->twPages->topLevelItem(0)) { ui->twPages->topLevelItem(0)->setSelected(true); - activatePage(m_currentReportTranslation->findPageTranslation(ui->twPages->topLevelItem(0)->text(0))); + activatePage(m_currentReportTranslation->findPageTranslation( + ui->twPages->topLevelItem(0)->text(0))); } } m_translationChanging = false; @@ -128,46 +137,52 @@ void TranslationEditor::activatePage(PageTranslation* pageTranslation) ui->teTranslation->setEnabled(false); ui->cbChecked->setEnabled(false); Q_ASSERT(pageTranslation != 0); - if(pageTranslation){ + if (pageTranslation) { ui->tbStrings->clearContents(); ui->tbStrings->setRowCount(0); m_currentPageTranslation = pageTranslation; QStringList items = pageTranslation->itemsTranslation.keys(); items.sort(); - foreach(QString itemName, items){ + foreach (QString itemName, items) { ItemTranslation* itemTranslation = pageTranslation->itemsTranslation.value(itemName); int rowIndex = ui->tbStrings->rowCount(); - ui->tbStrings->setRowCount(rowIndex+1); - foreach(PropertyTranslation* propertyTranslation, itemTranslation->propertyesTranslation){ + ui->tbStrings->setRowCount(rowIndex + 1); + foreach (PropertyTranslation* propertyTranslation, + itemTranslation->propertyesTranslation) { QTableWidgetItem* checkItem = new QTableWidgetItem(); - if (propertyTranslation->sourceHasBeenChanged){ + if (propertyTranslation->sourceHasBeenChanged) { checkItem->setIcon(QIcon(":/translationeditor/question")); } - if (propertyTranslation->checked){ + if (propertyTranslation->checked) { checkItem->setIcon(QIcon(":/translationeditor/checked")); } - ui->tbStrings->setItem(rowIndex,0,checkItem); - ui->tbStrings->setItem(rowIndex,1,new QTableWidgetItem(itemTranslation->itemName)); - ui->tbStrings->setItem(rowIndex,2,new QTableWidgetItem(propertyTranslation->propertyName)); - ui->tbStrings->setItem(rowIndex,3,new QTableWidgetItem(propertyTranslation->sourceValue)); + ui->tbStrings->setItem(rowIndex, 0, checkItem); + ui->tbStrings->setItem(rowIndex, 1, + new QTableWidgetItem(itemTranslation->itemName)); + ui->tbStrings->setItem(rowIndex, 2, + new QTableWidgetItem(propertyTranslation->propertyName)); + ui->tbStrings->setItem(rowIndex, 3, + new QTableWidgetItem(propertyTranslation->sourceValue)); } } } - } void TranslationEditor::activateTranslation(const QString& itemName, const QString& propertyName) { Q_ASSERT(m_currentPageTranslation != 0); - if (m_currentPageTranslation){ - ItemTranslation* itemTranslation = m_currentPageTranslation->itemsTranslation.value(itemName); - Q_ASSERT(itemTranslation !=0 ); - if (itemTranslation){ - m_currentPropertyTranslation = m_currentPageTranslation->itemsTranslation.value(itemName)->findProperty(propertyName); + if (m_currentPageTranslation) { + ItemTranslation* itemTranslation + = m_currentPageTranslation->itemsTranslation.value(itemName); + Q_ASSERT(itemTranslation != 0); + if (itemTranslation) { + m_currentPropertyTranslation + = m_currentPageTranslation->itemsTranslation.value(itemName)->findProperty( + propertyName); Q_ASSERT(m_currentPropertyTranslation != 0); - if (m_currentPropertyTranslation){ + if (m_currentPropertyTranslation) { ui->teTranslation->setEnabled(true); ui->cbChecked->setEnabled(true); ui->teTranslation->setText(m_currentPropertyTranslation->value); @@ -180,7 +195,8 @@ void TranslationEditor::activateTranslation(const QString& itemName, const QStri void TranslationEditor::on_tbStrings_itemSelectionChanged() { if (m_currentPageTranslation && !m_translationChanging) - activateTranslation(ui->tbStrings->item(ui->tbStrings->currentRow(),1)->text(), ui->tbStrings->item(ui->tbStrings->currentRow(),2)->text()); + activateTranslation(ui->tbStrings->item(ui->tbStrings->currentRow(), 1)->text(), + ui->tbStrings->item(ui->tbStrings->currentRow(), 2)->text()); } void TranslationEditor::on_teTranslation_textChanged() @@ -191,28 +207,32 @@ void TranslationEditor::on_teTranslation_textChanged() void TranslationEditor::on_cbChecked_toggled(bool checked) { - if (m_currentPropertyTranslation){ + if (m_currentPropertyTranslation) { m_currentPropertyTranslation->checked = checked; - ui->tbStrings->item(ui->tbStrings->currentRow(),0)->setIcon(checked ? QIcon(":/translationeditor/checked"):QIcon()); + ui->tbStrings->item(ui->tbStrings->currentRow(), 0) + ->setIcon(checked ? QIcon(":/translationeditor/checked") : QIcon()); } } void TranslationEditor::on_twPages_itemSelectionChanged() { - if (!ui->twPages->selectedItems().isEmpty()){ - activatePage(m_currentReportTranslation->findPageTranslation(ui->twPages->selectedItems().at(0)->text(0))); + if (!ui->twPages->selectedItems().isEmpty()) { + activatePage(m_currentReportTranslation->findPageTranslation( + ui->twPages->selectedItems().at(0)->text(0))); } } void TranslationEditor::on_tbAddLanguage_clicked() { LanguageSelectDialog dialog; - if (dialog.exec()){ + if (dialog.exec()) { m_translationChanging = true; m_translationContainer->addTranslationLanguage(dialog.getSelectedLanguage()); updateUi(); activateLanguage(dialog.getSelectedLanguage()); - foreach (QListWidgetItem* item, ui->lvLanguages->findItems(QLocale::languageToString(dialog.getSelectedLanguage()), Qt::MatchExactly)){ + foreach (QListWidgetItem* item, + ui->lvLanguages->findItems(QLocale::languageToString(dialog.getSelectedLanguage()), + Qt::MatchExactly)) { item->setSelected(true); } m_translationChanging = false; @@ -221,7 +241,8 @@ void TranslationEditor::on_tbAddLanguage_clicked() void TranslationEditor::on_tbDeleteLanguage_clicked() { - if (!m_currentPageTranslation) return; + if (!m_currentPageTranslation) + return; m_translationChanging = true; m_translationContainer->removeTranslationLanguage(m_currentReportTranslation->language()); updateUi(); @@ -230,24 +251,18 @@ void TranslationEditor::on_tbDeleteLanguage_clicked() void TranslationEditor::slotItemChecked() { - if (ui->tbStrings->currentRow()tbStrings->rowCount()){ + if (ui->tbStrings->currentRow() < ui->tbStrings->rowCount()) { ui->cbChecked->setChecked(true); - ui->tbStrings->selectRow(ui->tbStrings->currentRow()+1); + ui->tbStrings->selectRow(ui->tbStrings->currentRow() + 1); ui->teTranslation->setFocus(); } } void TranslationEditor::on_lvLanguages_itemSelectionChanged() { - if (ui->lvLanguages->currentItem() && m_currentReportTranslation){ + if (ui->lvLanguages->currentItem() && m_currentReportTranslation) { activateLanguage(getLanguageByName(ui->lvLanguages->currentItem()->text())); } } -} //namespace LimeReport - - - - - - +} // namespace LimeReport diff --git a/limereport/translationeditor/translationeditor.h b/limereport/translationeditor/translationeditor.h index 2288b25..72d6676 100644 --- a/limereport/translationeditor/translationeditor.h +++ b/limereport/translationeditor/translationeditor.h @@ -1,25 +1,24 @@ #ifndef TRANSLATIONEDITOR_H #define TRANSLATIONEDITOR_H -#include -#include -#include -#include #include "lrreporttranslation.h" +#include +#include +#include +#include + namespace LimeReport { namespace Ui { -class TranslationEditor; + class TranslationEditor; } - -class TranslationEditor : public QWidget -{ +class TranslationEditor: public QWidget { Q_OBJECT public: - explicit TranslationEditor(QWidget *parent = 0); + explicit TranslationEditor(QWidget* parent = 0); void setReportEngine(ITranslationContainer* translationContainer); ~TranslationEditor(); void updateUi(); @@ -30,7 +29,7 @@ private slots: void on_tbStrings_itemSelectionChanged(); void on_teTranslation_textChanged(); void on_cbChecked_toggled(bool checked); - void on_twPages_itemSelectionChanged(); + void on_twPages_itemSelectionChanged(); void on_tbAddLanguage_clicked(); void on_tbDeleteLanguage_clicked(); void slotItemChecked(); @@ -38,8 +37,9 @@ private slots: private: QLocale::Language getLanguageByName(const QString& languageName); + private: - Ui::TranslationEditor *ui; + Ui::TranslationEditor* ui; ITranslationContainer* m_translationContainer; QMap m_reportTranslations; QMap m_pageTranslations; @@ -50,6 +50,6 @@ private: QShortcut* m_clrReturn; }; -} //namespace LimeReport +} // namespace LimeReport #endif // TRANSLATIONEDITOR_H diff --git a/lrdview/MainWindow.cpp b/lrdview/MainWindow.cpp index 1a26d00..a99e244 100644 --- a/lrdview/MainWindow.cpp +++ b/lrdview/MainWindow.cpp @@ -1,22 +1,25 @@ #include "MainWindow.h" #include "ui_MainWindow.h" + +#include + +#include #include #include -#include -#include #include #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) #include #endif -#include "XmlModel.h" #include "SettingDialog.h" +#include "XmlModel.h" #include "lrreportengine.h" //#ifndef QT_DEBUG -//Q_IMPORT_PLUGIN(adateeditorplugin) +// Q_IMPORT_PLUGIN(adateeditorplugin) //#endif -void centerWindow(QWidget* widget, double widthFactor, double heightFactor) { +void centerWindow(QWidget* widget, double widthFactor, double heightFactor) +{ #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 1)) QDesktopWidget desk; int ww = desk.width() * widthFactor; @@ -31,54 +34,59 @@ void centerWindow(QWidget* widget, double widthFactor, double heightFactor) { widget->resize(ww, wh); widget->move((desk->geometry().width() - ww) / 2, (desk->geometry().height() - wh) / 2); #endif - - } -MainWindow::MainWindow(QWidget *parent) : +MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow), - m_previewScene(0), m_isCert(false), m_deleteLastFile(false) + m_previewScene(0), + m_isCert(false), + m_deleteLastFile(false) { ui->setupUi(this); - m_report.dataManager()->addModel("reportData",&m_model,false); - ui->graphicsView->scale(0.5,0.5); + m_report.dataManager()->addModel("reportData", &m_model, false); + ui->graphicsView->scale(0.5, 0.5); centerWindow(this, 0.8, 0.8); - m_settings = new QSettings("OCKK Ltd","LRDView"); + m_settings = new QSettings("OCKK Ltd", "LRDView"); m_report.setSettings(m_settings); readSetting(); setWindowTitle("LRDView ver 1.30"); - if (QCoreApplication::arguments().count()>1){ + if (QCoreApplication::arguments().count() > 1) { loadReport(QCoreApplication::arguments().at(1)); } - //ui->statusBar->addWidget(new QLabel(" Designed by Arin Alexander (arin_a@bk.ru) ",this)); + // ui->statusBar->addWidget(new QLabel(" Designed by Arin Alexander (arin_a@bk.ru) ",this)); } -bool isFileExists(QZipReader& reader, QString fileName){ - foreach( QZipReader::FileInfo fi, reader.fileInfoList()){ - if (fi.filePath.compare(fileName)==0) return true; +bool isFileExists(QZipReader& reader, QString fileName) +{ + foreach (QZipReader::FileInfo fi, reader.fileInfoList()) { + if (fi.filePath.compare(fileName) == 0) + return true; } return false; } -void MainWindow::loadReport(QString fileName){ - if (!fileName.isEmpty()){ +void MainWindow::loadReport(QString fileName) +{ + if (!fileName.isEmpty()) { QZipReader reader(fileName); QByteArray fileData = reader.fileData("report.xml"); m_report.loadFromByteArray(&fileData); m_reportData = reader.fileData("data.xml"); m_model.setXMLData(&m_reportData); - if (m_previewScene) delete m_previewScene; - m_previewScene = dynamic_cast(m_report.createPreviewScene(ui->graphicsView)); + if (m_previewScene) + delete m_previewScene; + m_previewScene = dynamic_cast( + m_report.createPreviewScene(ui->graphicsView)); m_previewScene->setItemMode(LimeReport::PreviewMode); ui->graphicsView->setScene(m_previewScene); ui->graphicsView->centerOn(0, 0); ui->actionEdit->setChecked(false); - m_isCert = isFileExists(reader,"CertFlag.sgn"); - //m_lastReport = fileName; + m_isCert = isFileExists(reader, "CertFlag.sgn"); + // m_lastReport = fileName; ui->action_PDF->setEnabled(true); ui->actionPrint->setEnabled(true); reader.close(); - if (m_deleteLastFile){ + if (m_deleteLastFile) { QFile::remove(fileName); } } @@ -92,65 +100,53 @@ MainWindow::~MainWindow() void MainWindow::on_actionEdit_triggered() { - if (m_previewScene){ - if (m_previewScene->itemMode()==LimeReport::PreviewMode){ + if (m_previewScene) { + if (m_previewScene->itemMode() == LimeReport::PreviewMode) { m_previewScene->setItemMode(LimeReport::DesignMode); - } else m_previewScene->setItemMode(LimeReport::PreviewMode); + } else + m_previewScene->setItemMode(LimeReport::PreviewMode); } } void MainWindow::on_actionOpen_triggered() { - QString fileName = QFileDialog::getOpenFileName(0,tr("Открыть файл отчета"),QString(),"*.lrd"); - if (!fileName.isEmpty()){ + QString fileName + = QFileDialog::getOpenFileName(0, tr("Открыть файл отчета"), QString(), "*.lrd"); + if (!fileName.isEmpty()) { loadReport(fileName); } } -void MainWindow::on_actionDesign_triggered() -{ - m_report.designReport(); -} +void MainWindow::on_actionDesign_triggered() { m_report.designReport(); } -void MainWindow::closeEvent(QCloseEvent *event) -{ - writeSetting(); -} +void MainWindow::closeEvent(QCloseEvent* event) { writeSetting(); } -void MainWindow::writeSetting(){ - m_settings->setValue("geometry",saveGeometry()); -} +void MainWindow::writeSetting() { m_settings->setValue("geometry", saveGeometry()); } void MainWindow::readSetting() { QVariant v = m_settings->value("geometry"); - if (v.isValid()){ + if (v.isValid()) { restoreGeometry(v.toByteArray()); } - m_certPrinterName = m_settings->value("certPrinterName","").value(); - m_otherPrinterName = m_settings->value("otherPrinterName","").value(); - m_deleteLastFile = m_settings->value("deleteLastFile",false).value(); + m_certPrinterName = m_settings->value("certPrinterName", "").value(); + m_otherPrinterName = m_settings->value("otherPrinterName", "").value(); + m_deleteLastFile = m_settings->value("deleteLastFile", false).value(); } void MainWindow::settingAccepted() { - m_certPrinterName=((SettingDialog*)sender())->certPrinterName(); - m_otherPrinterName=((SettingDialog*)sender())->othenPrinterName(); + m_certPrinterName = ((SettingDialog*)sender())->certPrinterName(); + m_otherPrinterName = ((SettingDialog*)sender())->othenPrinterName(); m_deleteLastFile = ((SettingDialog*)sender())->deleteLastFile(); - m_settings->setValue("certPrinterName",m_certPrinterName); - m_settings->setValue("otherPrinterName",m_otherPrinterName); - m_settings->setValue("deleteLastFile",m_deleteLastFile); + m_settings->setValue("certPrinterName", m_certPrinterName); + m_settings->setValue("otherPrinterName", m_otherPrinterName); + m_settings->setValue("deleteLastFile", m_deleteLastFile); } -void MainWindow::on_actionZoomIn_triggered() -{ - ui->graphicsView->scale(1.2,1.2); -} +void MainWindow::on_actionZoomIn_triggered() { ui->graphicsView->scale(1.2, 1.2); } -void MainWindow::on_actionZoomOut_triggered() -{ - ui->graphicsView->scale(1/1.2,1/1.2); -} +void MainWindow::on_actionZoomOut_triggered() { ui->graphicsView->scale(1 / 1.2, 1 / 1.2); } void MainWindow::on_actionPrint_triggered() { @@ -161,29 +157,26 @@ void MainWindow::on_actionPrint_triggered() pi = getPrinterInfo(m_otherPrinterName); } QPrinter printer(pi); - QPrintDialog dialog(&printer,QApplication::activeWindow()); + QPrintDialog dialog(&printer, QApplication::activeWindow()); - - if (dialog.exec()){ + if (dialog.exec()) { if (m_previewScene->pageItems().isEmpty()) m_report.printReport(&printer); - else{ + else { printer.setPrintRange(QPrinter::PrintRange(dialog.printRange())); printer.setFromTo(dialog.fromPage(), dialog.toPage()); - m_report.printPages( - m_previewScene->pageItems(), &printer - ); - foreach(LimeReport::PageItemDesignIntf::Ptr pageItem, m_previewScene->pageItems()){ + m_report.printPages(m_previewScene->pageItems(), &printer); + foreach (LimeReport::PageItemDesignIntf::Ptr pageItem, m_previewScene->pageItems()) { m_previewScene->reactivatePageItem(pageItem); } } } - } -QPrinterInfo MainWindow::getPrinterInfo(QString printerName){ +QPrinterInfo MainWindow::getPrinterInfo(QString printerName) +{ foreach (QPrinterInfo pi, QPrinterInfo::availablePrinters()) { - if (pi.printerName().compare(printerName)==0) + if (pi.printerName().compare(printerName) == 0) return pi; } return QPrinterInfo::defaultPrinter(); @@ -199,30 +192,27 @@ void MainWindow::on_actionSetting_triggered() w.exec(); } - void MainWindow::on_actionDelete_triggered() { - if (m_previewScene){ + if (m_previewScene) { m_previewScene->deleteSelected(); } } void MainWindow::on_action_PDF_triggered() { - QString fileName = QFileDialog::getSaveFileName(this,tr("Имя файла для экспорта"),"","*.pdf" ); - if (!fileName.isEmpty()){ + QString fileName + = QFileDialog::getSaveFileName(this, tr("Имя файла для экспорта"), "", "*.pdf"); + if (!fileName.isEmpty()) { QPrinter printer; printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); - //m_report.printReport(&printer); + // m_report.printReport(&printer); if (m_previewScene->pageItems().isEmpty()) m_report.printReport(&printer); - else{ - m_report.printPages( - m_previewScene->pageItems(), - &printer - ); - foreach(LimeReport::PageItemDesignIntf::Ptr pageItem, m_previewScene->pageItems()){ + else { + m_report.printPages(m_previewScene->pageItems(), &printer); + foreach (LimeReport::PageItemDesignIntf::Ptr pageItem, m_previewScene->pageItems()) { m_previewScene->reactivatePageItem(pageItem); } } diff --git a/lrdview/MainWindow.h b/lrdview/MainWindow.h index 31c0e59..8f2f84e 100644 --- a/lrdview/MainWindow.h +++ b/lrdview/MainWindow.h @@ -1,22 +1,22 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H +#include "XmlModel.h" +#include "lrpagedesignintf.h" +#include "lrreportengine.h" + #include #include -#include "lrreportengine.h" -#include "lrpagedesignintf.h" -#include "XmlModel.h" namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ +class MainWindow: public QMainWindow { Q_OBJECT public: - explicit MainWindow(QWidget *parent = 0); + explicit MainWindow(QWidget* parent = 0); ~MainWindow(); private slots: @@ -29,7 +29,8 @@ private slots: void on_actionSetting_triggered(); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent* event); + private: void loadReport(QString fileName); void writeSetting(); @@ -42,8 +43,8 @@ private slots: void on_action_PDF_triggered(); private: - Ui::MainWindow *ui; - LimeReport::PageDesignIntf* m_previewScene; + Ui::MainWindow* ui; + LimeReport::PageDesignIntf* m_previewScene; LimeReport::ReportEngine m_report; XmlModel m_model; QByteArray m_reportData; diff --git a/lrdview/SettingDialog.cpp b/lrdview/SettingDialog.cpp index ee842c1..2b158a9 100644 --- a/lrdview/SettingDialog.cpp +++ b/lrdview/SettingDialog.cpp @@ -1,19 +1,15 @@ #include "SettingDialog.h" #include "ui_SettingDialog.h" + #include -SettingDialog::SettingDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::SettingDialog) +SettingDialog::SettingDialog(QWidget* parent): QDialog(parent), ui(new Ui::SettingDialog) { ui->setupUi(this); initPrinters(); } -SettingDialog::~SettingDialog() -{ - delete ui; -} +SettingDialog::~SettingDialog() { delete ui; } void SettingDialog::initPrinters() { @@ -23,7 +19,8 @@ void SettingDialog::initPrinters() } } -void SettingDialog::setCertPrinterName(QString printerName){ +void SettingDialog::setCertPrinterName(QString printerName) +{ ui->certPrinter->setCurrentIndex(ui->certPrinter->findText(printerName)); } @@ -33,21 +30,10 @@ void SettingDialog::setOtherPrinterName(QString printerName) ui->otherPrinter->setCurrentIndex(ui->otherPrinter->findText(printerName)); } -QString SettingDialog::certPrinterName(){ - return ui->certPrinter->currentText(); -} +QString SettingDialog::certPrinterName() { return ui->certPrinter->currentText(); } -QString SettingDialog::othenPrinterName() -{ - return ui->otherPrinter->currentText(); -} +QString SettingDialog::othenPrinterName() { return ui->otherPrinter->currentText(); } -bool SettingDialog::deleteLastFile(){ - return ui->checkBox->isChecked(); -} - -void SettingDialog::setDeleteLastFile(bool value) -{ - ui->checkBox->setChecked(value); -} +bool SettingDialog::deleteLastFile() { return ui->checkBox->isChecked(); } +void SettingDialog::setDeleteLastFile(bool value) { ui->checkBox->setChecked(value); } diff --git a/lrdview/SettingDialog.h b/lrdview/SettingDialog.h index b9eaa5b..4401620 100644 --- a/lrdview/SettingDialog.h +++ b/lrdview/SettingDialog.h @@ -7,12 +7,11 @@ namespace Ui { class SettingDialog; } -class SettingDialog : public QDialog -{ +class SettingDialog: public QDialog { Q_OBJECT public: - explicit SettingDialog(QWidget *parent = 0); + explicit SettingDialog(QWidget* parent = 0); ~SettingDialog(); void setCertPrinterName(QString printerName); void setOtherPrinterName(QString printerName); @@ -20,11 +19,12 @@ public: QString othenPrinterName(); bool deleteLastFile(); void setDeleteLastFile(bool value); + private: void initPrinters(); private: - Ui::SettingDialog *ui; + Ui::SettingDialog* ui; }; #endif // SETTINGDIALOG_H diff --git a/lrdview/XmlModel.cpp b/lrdview/XmlModel.cpp index 9942120..3307670 100644 --- a/lrdview/XmlModel.cpp +++ b/lrdview/XmlModel.cpp @@ -1,14 +1,17 @@ #include "XmlModel.h" + #include -XmlModel::XmlModel(QByteArray *data) { +XmlModel::XmlModel(QByteArray* data) +{ if (data) { m_doc.setContent(*data); initModel(); } } -void XmlModel::setXMLData(QByteArray *data) { +void XmlModel::setXMLData(QByteArray* data) +{ if (data) { beginResetModel(); m_doc.setContent(*data); @@ -17,7 +20,8 @@ void XmlModel::setXMLData(QByteArray *data) { } } -void XmlModel::initModel(){ +void XmlModel::initModel() +{ m_items = m_doc.firstChildElement("items"); parseHeaders(); } @@ -27,47 +31,41 @@ void XmlModel::parseHeaders() m_fields.clear(); QDomNode root = m_doc.firstChildElement("items"); QDomNode item = root.firstChild(); - for (int i=0; i #include -class XmlModel : public QAbstractItemModel -{ +class XmlModel: public QAbstractItemModel { public: XmlModel(QByteArray* data = 0); void setXMLData(QByteArray* data); void parseHeaders(); - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; + QModelIndex index(int row, int column, const QModelIndex& parent) const; + QModelIndex parent(const QModelIndex& child) const; + int rowCount(const QModelIndex& parent) const; + int columnCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; + private: void initModel(); + private: QDomDocument m_doc; QDomNode m_items; diff --git a/lrdview/main.cpp b/lrdview/main.cpp index da3fe56..7065de6 100644 --- a/lrdview/main.cpp +++ b/lrdview/main.cpp @@ -1,10 +1,11 @@ #include "MainWindow.h" + #include -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QApplication a(argc, argv); - //QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + // QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); MainWindow w; w.show(); diff --git a/tests/tst_callbackdstest.cpp b/tests/tst_callbackdstest.cpp index a7e0aa6..d27b132 100644 --- a/tests/tst_callbackdstest.cpp +++ b/tests/tst_callbackdstest.cpp @@ -1,13 +1,14 @@ -#include -#include #include "../limereport/lrdatadesignintf.h" -class CallbackDSTest : public QObject -{ +#include +#include + +class CallbackDSTest: public QObject { Q_OBJECT public: CallbackDSTest(); + private: LimeReport::CallbackDatasource* m_testDS; LimeReport::CallbackDatasource* m_test1DS; @@ -19,94 +20,104 @@ protected Q_SLOTS: private Q_SLOTS: void testOneSlotDS(); void testTwoSlotDS(); - }; CallbackDSTest::CallbackDSTest() { m_testDS = new LimeReport::CallbackDatasource(); - connect(m_testDS, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - this, SLOT(slotTestOneSlotDS(LimeReport::CallbackInfo,QVariant&))); + connect(m_testDS, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), this, + SLOT(slotTestOneSlotDS(LimeReport::CallbackInfo, QVariant&))); m_test1DS = new LimeReport::CallbackDatasource(); m_currentRow = -1; - connect(m_test1DS, SIGNAL(getCallbackData(LimeReport::CallbackInfo,QVariant&)), - this, SLOT(slotGetCallbackData(LimeReport::CallbackInfo,QVariant&))); - connect(m_test1DS, SIGNAL(changePos(LimeReport::CallbackInfo::ChangePosType,bool&)), - this, SLOT(slotChangePos(LimeReport::CallbackInfo::ChangePosType,bool&))); + connect(m_test1DS, SIGNAL(getCallbackData(LimeReport::CallbackInfo, QVariant&)), this, + SLOT(slotGetCallbackData(LimeReport::CallbackInfo, QVariant&))); + connect(m_test1DS, SIGNAL(changePos(LimeReport::CallbackInfo::ChangePosType, bool&)), this, + SLOT(slotChangePos(LimeReport::CallbackInfo::ChangePosType, bool&))); } - - void CallbackDSTest::slotTestOneSlotDS(LimeReport::CallbackInfo info, QVariant& data) { QStringList columns; - columns << "Name" << "Value"; + columns << "Name" + << "Value"; QVector values; - values<<"Mazda"<<"Nissan"; + values << "Mazda" + << "Nissan"; int dataIndex = 0; switch (info.dataType) { - case LimeReport::CallbackInfo::RowCount: - data = 10; - break; - case LimeReport::CallbackInfo::ColumnCount: - data = columns.size(); - break; - case LimeReport::CallbackInfo::ColumnHeaderData: { - data = columns.at(info.index); - break; + case LimeReport::CallbackInfo::RowCount: + data = 10; + break; + case LimeReport::CallbackInfo::ColumnCount: + data = columns.size(); + break; + case LimeReport::CallbackInfo::ColumnHeaderData: { + data = columns.at(info.index); + break; + } + case LimeReport::CallbackInfo::ColumnData: + if (info.index > 5) { + dataIndex = 1; } - case LimeReport::CallbackInfo::ColumnData: - if (info.index > 5){ - dataIndex = 1; - } - if (info.columnName == "Name") - data = values[dataIndex]; - else { - data = info.index; - } - break; - default: break; + if (info.columnName == "Name") + data = values[dataIndex]; + else { + data = info.index; + } + break; + default: + break; } } void CallbackDSTest::slotGetCallbackData(LimeReport::CallbackInfo info, QVariant& data) { QStringList columns; - columns << "Name" << "Value"; + columns << "Name" + << "Value"; QVector values; - values<<"Mazda"<<"Nissan"; + values << "Mazda" + << "Nissan"; int dataIndex = 0; switch (info.dataType) { - case LimeReport::CallbackInfo::ColumnCount: - data = columns.size(); - break; - case LimeReport::CallbackInfo::ColumnHeaderData: { - data = columns.at(info.index); - break; + case LimeReport::CallbackInfo::ColumnCount: + data = columns.size(); + break; + case LimeReport::CallbackInfo::ColumnHeaderData: { + data = columns.at(info.index); + break; + } + case LimeReport::CallbackInfo::HasNext: { + data = (info.index < 9); + break; + } + case LimeReport::CallbackInfo::ColumnData: + if (info.index > 5) { + dataIndex = 1; } - case LimeReport::CallbackInfo::HasNext:{ - data = (info.index < 9); - break; + if (info.columnName == "Name") + data = values[dataIndex]; + else { + data = m_currentRow; } - case LimeReport::CallbackInfo::ColumnData: - if (info.index > 5){ - dataIndex = 1; - } - if (info.columnName == "Name") - data = values[dataIndex]; - else { - data = m_currentRow; - } - break; - default: break; + break; + default: + break; } } -void CallbackDSTest::slotChangePos(const LimeReport::CallbackInfo::ChangePosType& type, bool& result) +void CallbackDSTest::slotChangePos(const LimeReport::CallbackInfo::ChangePosType& type, + bool& result) { - if (type == LimeReport::CallbackInfo::First) {m_currentRow = 0; result = true;} - else {if (m_currentRow<9) m_currentRow++; result = (m_currentRow <= 9);} + if (type == LimeReport::CallbackInfo::First) { + m_currentRow = 0; + result = true; + } else { + if (m_currentRow < 9) + m_currentRow++; + result = (m_currentRow <= 9); + } } void CallbackDSTest::testOneSlotDS() @@ -119,69 +130,70 @@ void CallbackDSTest::testOneSlotDS() QVERIFY2(m_testDS->columnNameByIndex(1).compare("Value") == 0, "Failure test column name"); QVERIFY2(m_testDS->columnIndexByName("Name") == 0, "Failure test column index"); QVERIFY2(m_testDS->columnIndexByName("Value") == 1, "Failure test column index"); - QVERIFY2(!m_testDS->data("Name").isValid(),"Failure test data on bof"); - QVERIFY2(!m_testDS->data("Value").isValid(),"Failure test data on bof"); + QVERIFY2(!m_testDS->data("Name").isValid(), "Failure test data on bof"); + QVERIFY2(!m_testDS->data("Value").isValid(), "Failure test data on bof"); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),0); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 0); QVERIFY2(!m_testDS->prior(), "Failure test prior"); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),1); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 1); QVERIFY2(m_testDS->prior(), "Failure test prior"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),0); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 0); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),1); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 1); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),2); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 2); QVERIFY2(m_testDS->prior(), "Failure test prior"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),1); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 1); QVERIFY2(!m_testDS->prior(), "Failure test prior"); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),2); - for(int i = 3; i < 6; ++i) m_testDS->next(); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),5); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 2); + for (int i = 3; i < 6; ++i) + m_testDS->next(); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 5); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),6); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 6); QVERIFY2(m_testDS->prior(), "Failure test prior"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_testDS->data("Value").toInt(),5); + QCOMPARE(m_testDS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_testDS->data("Value").toInt(), 5); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),6); - for(int i = 7; i < 9; ++i) m_testDS->next(); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),8); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 6); + for (int i = 7; i < 9; ++i) + m_testDS->next(); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 8); QVERIFY2(m_testDS->next(), "Failure next"); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),9); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 9); QCOMPARE(m_testDS->hasNext(), false); QCOMPARE(m_testDS->next(), false); QCOMPARE(m_testDS->bof(), false); QCOMPARE(m_testDS->eof(), true); QCOMPARE(m_testDS->prior(), true); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),8); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 8); QCOMPARE(m_testDS->hasNext(), true); QCOMPARE(m_testDS->next(), true); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),9); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 9); QCOMPARE(m_testDS->hasNext(), false); QCOMPARE(m_testDS->next(), false); QCOMPARE(m_testDS->bof(), false); QCOMPARE(m_testDS->eof(), true); - QCOMPARE(m_testDS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_testDS->data("Value").toInt(),9); + QCOMPARE(m_testDS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_testDS->data("Value").toInt(), 9); } - void CallbackDSTest::testTwoSlotDS() { @@ -193,66 +205,68 @@ void CallbackDSTest::testTwoSlotDS() QVERIFY2(m_test1DS->columnNameByIndex(1).compare("Value") == 0, "Failure test column name"); QVERIFY2(m_test1DS->columnIndexByName("Name") == 0, "Failure test column index"); QVERIFY2(m_test1DS->columnIndexByName("Value") == 1, "Failure test column index"); - QVERIFY2(!m_test1DS->data("Name").isValid(),"Failure test data on bof"); - QVERIFY2(!m_test1DS->data("Value").isValid(),"Failure test data on bof"); + QVERIFY2(!m_test1DS->data("Name").isValid(), "Failure test data on bof"); + QVERIFY2(!m_test1DS->data("Value").isValid(), "Failure test data on bof"); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),0); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 0); QVERIFY2(!m_test1DS->prior(), "Failure test prior"); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),1); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 1); QVERIFY2(m_test1DS->prior(), "Failure test prior"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),0); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 0); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),1); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 1); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),2); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 2); QVERIFY2(m_test1DS->prior(), "Failure test prior"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),1); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 1); QVERIFY2(!m_test1DS->prior(), "Failure test prior"); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),2); - for(int i = 3; i < 6; ++i) m_test1DS->next(); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),5); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 2); + for (int i = 3; i < 6; ++i) + m_test1DS->next(); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 5); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),6); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 6); QVERIFY2(m_test1DS->prior(), "Failure test prior"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Mazda")); - QCOMPARE(m_test1DS->data("Value").toInt(),5); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Mazda")); + QCOMPARE(m_test1DS->data("Value").toInt(), 5); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),6); - for(int i = 7; i < 9; ++i) m_test1DS->next(); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),8); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 6); + for (int i = 7; i < 9; ++i) + m_test1DS->next(); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 8); QVERIFY2(m_test1DS->next(), "Failure next"); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),9); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 9); QCOMPARE(m_test1DS->hasNext(), false); QCOMPARE(m_test1DS->next(), false); QCOMPARE(m_test1DS->bof(), false); QCOMPARE(m_test1DS->eof(), true); QCOMPARE(m_test1DS->prior(), true); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),8); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 8); QCOMPARE(m_test1DS->hasNext(), true); QCOMPARE(m_test1DS->next(), true); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),9); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 9); QCOMPARE(m_test1DS->hasNext(), false); QCOMPARE(m_test1DS->next(), false); QCOMPARE(m_test1DS->bof(), false); QCOMPARE(m_test1DS->eof(), true); - QCOMPARE(m_test1DS->data("Name").toString(),QString("Nissan")); - QCOMPARE(m_test1DS->data("Value").toInt(),9); + QCOMPARE(m_test1DS->data("Name").toString(), QString("Nissan")); + QCOMPARE(m_test1DS->data("Value").toInt(), 9); } QTEST_APPLESS_MAIN(CallbackDSTest) diff --git a/tools/check_code_style.sh b/tools/check_code_style.sh new file mode 100755 index 0000000..d3c68e1 --- /dev/null +++ b/tools/check_code_style.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +FORMATTER="clang-format-14" + +find . -type f \ + -regextype posix-extended -regex '^.*\.(cpp|c\+\+|cxx|cc|h|hh|hpp|h\+\+|hxx)$' \ + -not -path '*3rdparty*' \ + -exec ${FORMATTER} -i -style=file {} \; + +git status > /dev/null +git diff-index --exit-code --name-only HEAD