From cdb02fc9be18d341426d3b23cf92484ac12869b0 Mon Sep 17 00:00:00 2001 From: peri4 Date: Wed, 14 Dec 2022 14:14:33 +0300 Subject: [PATCH] code format --- libs/application/aboutwindow.cpp | 54 +- libs/application/aboutwindow.h | 61 +- libs/application/edockwidget.cpp | 33 +- libs/application/edockwidget.h | 73 +- libs/application/emainwindow.cpp | 144 +- libs/application/emainwindow.h | 110 +- libs/application/etabwidget.cpp | 46 +- libs/application/etabwidget.h | 78 +- libs/application/historyview.cpp | 28 +- libs/application/historyview.h | 64 +- libs/application/logview.cpp | 139 +- libs/application/logview.h | 71 +- libs/application/plugin/edockwidgetplugin.cpp | 8 +- libs/application/plugin/edockwidgetplugin.h | 6 +- libs/application/plugin/emainwindowplugin.cpp | 8 +- libs/application/plugin/emainwindowplugin.h | 6 +- libs/application/plugin/historyviewplugin.cpp | 8 +- libs/application/plugin/historyviewplugin.h | 6 +- libs/application/plugin/logviewplugin.cpp | 8 +- libs/application/plugin/logviewplugin.h | 6 +- libs/application/plugin/qad_application.cpp | 5 +- libs/application/plugin/qad_application.h | 13 +- libs/application/qsingleapplication.cpp | 25 +- libs/application/qsingleapplication.h | 46 +- libs/application/ribbon.cpp | 110 +- libs/application/ribbon.h | 89 +- libs/blockview/alignedtextitem.cpp | 6 +- libs/blockview/alignedtextitem.h | 88 +- libs/blockview/blockbase.cpp | 210 +- libs/blockview/blockbase.h | 67 +- libs/blockview/blockbusitem.cpp | 298 +- libs/blockview/blockbusitem.h | 125 +- libs/blockview/blockeditor.cpp | 100 +- libs/blockview/blockeditor.h | 57 +- libs/blockview/blockitem.cpp | 181 +- libs/blockview/blockitem.h | 119 +- libs/blockview/blockitempin.cpp | 74 +- libs/blockview/blockitempin.h | 108 +- libs/blockview/blockview.cpp | 959 ++++--- libs/blockview/blockview.h | 198 +- libs/blockview/blockviewwavetrace.cpp | 45 +- libs/blockview/blockviewwavetrace.h | 68 +- libs/blockview/drawtools.cpp | 329 ++- libs/blockview/drawtools.h | 122 +- libs/blockview/plugin/blockviewplugin.cpp | 8 +- libs/blockview/plugin/blockviewplugin.h | 6 +- libs/blockview/plugin/qad_blockview.cpp | 6 +- libs/blockview/plugin/qad_blockview.h | 13 +- libs/doc/markdown.cpp | 84 +- libs/doc/markdown.h | 27 +- libs/graphic/gif.h | 1165 ++++---- libs/graphic/graphic.cpp | 989 +++---- libs/graphic/graphic.h | 669 +++-- libs/graphic/graphic_conf.cpp | 12 +- libs/graphic/graphic_conf.h | 75 +- libs/graphic/plugin/graphicplugin.cpp | 13 +- libs/graphic/plugin/graphicplugin.h | 6 +- libs/graphic/plugin/qad_graphic.cpp | 6 +- libs/graphic/plugin/qad_graphic.h | 13 +- libs/graphic/uglwidget.h | 26 +- libs/graphic/uwidget.h | 16 +- libs/piqt/piqt.cpp | 18 +- libs/piqt/piqt.h | 722 +++-- libs/piqt/piqt_macros.h | 167 +- libs/piqt/qpiconnection.cpp | 16 +- libs/piqt/qpiconnection.h | 51 +- libs/piqt_widgets/piqt_connection_edit.cpp | 191 +- libs/piqt_widgets/piqt_connection_edit.h | 47 +- libs/piqt_widgets/piqt_connection_view.cpp | 72 +- libs/piqt_widgets/piqt_connection_view.h | 194 +- libs/piqt_widgets/piqt_highlighter.cpp | 24 +- libs/piqt_widgets/piqt_highlighter.h | 38 +- libs/piqt_widgets/piqt_iodevice_edit.cpp | 19 +- libs/piqt_widgets/piqt_iodevice_edit.h | 37 +- .../piqt_iodevice_edit_dialog.cpp | 40 +- libs/piqt_widgets/piqt_iodevice_edit_dialog.h | 37 +- libs/piqt_widgets/pivaluetree_edit.cpp | 2 +- libs/piqt_widgets/pivaluetree_edit.h | 24 +- libs/piqt_widgets/pivariant_edit.h | 24 +- libs/piqt_widgets/pivariant_edit_widgets.cpp | 4 +- libs/piqt_widgets/pivariant_edit_widgets.h | 24 +- libs/qglview/glcamera.cpp | 152 +- libs/qglview/glcamera.h | 116 +- libs/qglview/glframebuffer.cpp | 26 +- libs/qglview/glframebuffer.h | 42 +- libs/qglview/glmaterial.cpp | 158 +- libs/qglview/glmaterial.h | 220 +- libs/qglview/globject.cpp | 458 ++-- libs/qglview/globject.h | 353 ++- libs/qglview/globject_editor.cpp | 43 +- libs/qglview/globject_editor.h | 9 +- libs/qglview/glparticles_system.cpp | 127 +- libs/qglview/glparticles_system.h | 136 +- libs/qglview/glprimitives.cpp | 75 +- libs/qglview/glprimitives.h | 49 +- libs/qglview/glrendererbase.cpp | 178 +- libs/qglview/glrendererbase.h | 33 +- libs/qglview/glshaders.cpp | 183 +- libs/qglview/glshaders.h | 8 +- libs/qglview/gltexture_manager.cpp | 6 +- libs/qglview/gltexture_manager.h | 28 +- libs/qglview/gltypes.cpp | 167 +- libs/qglview/gltypes.h | 553 ++-- libs/qglview/glvbo.cpp | 87 +- libs/qglview/glvbo.h | 65 +- libs/qglview/glwidget.cpp | 25 +- libs/qglview/glwidget.h | 44 +- libs/qglview/loader_3ds.cpp | 511 ++-- libs/qglview/loader_3ds.h | 93 +- libs/qglview/loader_ase.cpp | 345 ++- libs/qglview/loader_ase.h | 5 +- libs/qglview/loader_dae.cpp | 194 +- libs/qglview/loader_dae.h | 11 +- libs/qglview/loader_obj.cpp | 141 +- libs/qglview/loader_obj.h | 26 +- libs/qglview/loader_qgl.cpp | 15 +- libs/qglview/loader_qgl.h | 4 +- libs/qglview/material_editor.cpp | 100 +- libs/qglview/material_editor.h | 14 +- libs/qglview/material_map_editor.cpp | 16 +- libs/qglview/material_map_editor.h | 14 +- libs/qglview/openglwindow.cpp | 42 +- libs/qglview/openglwindow.h | 23 +- .../qglview/plugin/qglview_designerplugin.cpp | 7 +- libs/qglview/plugin/qglview_designerplugin.h | 13 +- libs/qglview/plugin/qglviewplugin.cpp | 29 +- libs/qglview/plugin/qglviewplugin.h | 8 +- libs/qglview/propertyeditor.cpp | 429 ++- libs/qglview/propertyeditor.h | 68 +- libs/qglview/qglview.cpp | 312 +-- libs/qglview/qglview.h | 269 +- libs/qglview/qglview_test/main.cpp | 5 +- libs/qglview/qglview_test/qglview_window.cpp | 149 +- libs/qglview/qglview_test/qglview_window.h | 123 +- libs/qglview/renderer_deferred_shading.cpp | 229 +- libs/qglview/renderer_deferred_shading.h | 17 +- libs/qglview/renderer_simple.cpp | 26 +- libs/qglview/renderer_simple.h | 16 +- libs/qglview/shaders/fxaa_v3.h | 2396 +++++++++-------- libs/sql_table/plugin/qad_sql_table.cpp | 5 +- libs/sql_table/plugin/qad_sql_table.h | 13 +- libs/sql_table/plugin/sql_record_plugin.cpp | 8 +- libs/sql_table/plugin/sql_record_plugin.h | 6 +- libs/sql_table/plugin/sql_table_plugin.cpp | 8 +- libs/sql_table/plugin/sql_table_plugin.h | 6 +- libs/sql_table/sql_record_widget.cpp | 241 +- libs/sql_table/sql_record_widget.h | 111 +- libs/sql_table/sql_table_widget.cpp | 507 ++-- libs/sql_table/sql_table_widget.h | 399 ++- .../plugin/qad_touch_widgets.cpp | 5 +- libs/touch_widgets/plugin/qad_touch_widgets.h | 15 +- .../plugin/touchbuttframeplugin.cpp | 106 +- .../plugin/touchbuttframeplugin.h | 35 +- .../plugin/touchbuttonplugin.cpp | 72 +- libs/touch_widgets/plugin/touchbuttonplugin.h | 35 +- .../plugin/touchsliderplugin.cpp | 86 +- libs/touch_widgets/plugin/touchsliderplugin.h | 35 +- libs/touch_widgets/touch_bar.h | 30 +- libs/touch_widgets/touchbuttframe.cpp | 11 +- libs/touch_widgets/touchbuttframe.h | 252 +- libs/touch_widgets/touchbutton.cpp | 19 +- libs/touch_widgets/touchbutton.h | 290 +- libs/touch_widgets/touchslider.cpp | 56 +- libs/touch_widgets/touchslider.h | 126 +- libs/utils/chunkstream.cpp | 25 +- libs/utils/chunkstream.h | 140 +- libs/utils/plugin/qad_utils.cpp | 6 +- libs/utils/plugin/qad_utils.h | 15 +- libs/utils/propertystorage.cpp | 84 +- libs/utils/propertystorage.h | 167 +- libs/utils/qad_locations.cpp | 37 +- libs/utils/qad_locations.h | 71 +- libs/utils/qad_types.cpp | 69 +- libs/utils/qad_types.h | 309 ++- libs/utils/qpiconfig.cpp | 393 +-- libs/utils/qpiconfig.h | 26 +- libs/widgets/chardialog.cpp | 41 +- libs/widgets/chardialog.h | 45 +- libs/widgets/clineedit.cpp | 16 +- libs/widgets/clineedit.h | 42 +- libs/widgets/colorbutton.cpp | 46 +- libs/widgets/colorbutton.h | 35 +- libs/widgets/ecombobox.cpp | 46 +- libs/widgets/ecombobox.h | 33 +- libs/widgets/evalspinbox.cpp | 70 +- libs/widgets/evalspinbox.h | 48 +- libs/widgets/iconedlabel.cpp | 10 +- libs/widgets/iconedlabel.h | 44 +- libs/widgets/image_view.cpp | 23 +- libs/widgets/image_view.h | 33 +- libs/widgets/mathmatrixedit.cpp | 8 +- libs/widgets/mathmatrixedit.h | 30 +- libs/widgets/mathvectoredit.cpp | 10 +- libs/widgets/mathvectoredit.h | 32 +- libs/widgets/matrixedit.cpp | 18 +- libs/widgets/matrixedit.h | 32 +- libs/widgets/plugin/clineeditplugin.cpp | 8 +- libs/widgets/plugin/clineeditplugin.h | 6 +- libs/widgets/plugin/colorbuttonplugin.cpp | 8 +- libs/widgets/plugin/colorbuttonplugin.h | 6 +- libs/widgets/plugin/ecomboboxplugin.cpp | 8 +- libs/widgets/plugin/ecomboboxplugin.h | 6 +- libs/widgets/plugin/evalspinboxplugin.cpp | 8 +- libs/widgets/plugin/evalspinboxplugin.h | 6 +- libs/widgets/plugin/iconedlabelplugin.h | 6 +- libs/widgets/plugin/imageviewplugin.cpp | 8 +- libs/widgets/plugin/imageviewplugin.h | 6 +- libs/widgets/plugin/lconedlabelplugin.cpp | 5 +- libs/widgets/plugin/qad_widgets.cpp | 25 +- libs/widgets/plugin/qad_widgets.h | 13 +- libs/widgets/plugin/qcodeeditplugin.cpp | 8 +- libs/widgets/plugin/qcodeeditplugin.h | 6 +- libs/widgets/plugin/qipeditplugin.cpp | 8 +- libs/widgets/plugin/qipeditplugin.h | 6 +- libs/widgets/plugin/qpiconfigplugin.cpp | 8 +- libs/widgets/plugin/qpiconfigplugin.h | 6 +- libs/widgets/plugin/qpiconsoleplugin.cpp | 8 +- libs/widgets/plugin/qpiconsoleplugin.h | 6 +- libs/widgets/plugin/qpointeditplugin.cpp | 8 +- libs/widgets/plugin/qpointeditplugin.h | 6 +- libs/widgets/plugin/qrecteditplugin.cpp | 8 +- libs/widgets/plugin/qrecteditplugin.h | 6 +- libs/widgets/plugin/qvarianteditplugin.cpp | 8 +- libs/widgets/plugin/qvarianteditplugin.h | 6 +- libs/widgets/plugin/rangesliderplugin.cpp | 8 +- libs/widgets/plugin/rangesliderplugin.h | 6 +- libs/widgets/plugin/scroll_spin_boxplugin.cpp | 8 +- libs/widgets/plugin/scroll_spin_boxplugin.h | 6 +- libs/widgets/plugin/shortcutsplugin.cpp | 8 +- libs/widgets/plugin/shortcutsplugin.h | 6 +- libs/widgets/plugin/spinsliderplugin.cpp | 8 +- libs/widgets/plugin/spinsliderplugin.h | 6 +- libs/widgets/propertystorage_editor.cpp | 25 +- libs/widgets/propertystorage_editor.h | 36 +- libs/widgets/qcodeedit.cpp | 389 +-- libs/widgets/qcodeedit.h | 96 +- libs/widgets/qcodeedit_completer_p.cpp | 24 +- libs/widgets/qcodeedit_completer_p.h | 29 +- libs/widgets/qipedit.cpp | 36 +- libs/widgets/qipedit.h | 60 +- libs/widgets/qpiconfignewdialog.cpp | 14 +- libs/widgets/qpiconfignewdialog.h | 43 +- libs/widgets/qpiconfigvaluewidget.cpp | 274 +- libs/widgets/qpiconfigvaluewidget.h | 85 +- libs/widgets/qpiconfigwidget.cpp | 93 +- libs/widgets/qpiconfigwidget.h | 79 +- libs/widgets/qpiconsole.cpp | 206 +- libs/widgets/qpiconsole.h | 223 +- libs/widgets/qpievaluator_p.cpp | 574 ++-- libs/widgets/qpievaluator_p.h | 324 ++- libs/widgets/qpointedit.cpp | 1 + libs/widgets/qpointedit.h | 75 +- libs/widgets/qrectedit.cpp | 1 + libs/widgets/qrectedit.h | 106 +- libs/widgets/qvariantedit.cpp | 177 +- libs/widgets/qvariantedit.h | 116 +- libs/widgets/qvariantedit_custom.cpp | 7 +- libs/widgets/qvariantedit_custom.h | 36 +- libs/widgets/rangeslider.cpp | 160 +- libs/widgets/rangeslider.h | 34 +- libs/widgets/scroll_spin_box.cpp | 41 +- libs/widgets/scroll_spin_box.h | 38 +- libs/widgets/session_manager.cpp | 103 +- libs/widgets/session_manager.h | 174 +- libs/widgets/shortcuts.cpp | 80 +- libs/widgets/shortcuts.h | 49 +- libs/widgets/spinslider.cpp | 49 +- libs/widgets/spinslider.h | 138 +- utils/blockeditor/blockeditor_main.cpp | 6 +- utils/piintrospector/containers_view.cpp | 128 +- utils/piintrospector/containers_view.h | 35 +- utils/piintrospector/objects_view.cpp | 13 +- utils/piintrospector/objects_view.h | 17 +- utils/piintrospector/piintrospector.cpp | 107 +- utils/piintrospector/piintrospector.h | 21 +- utils/piintrospector/piintrospector_main.cpp | 43 +- utils/piintrospector/threads_view.cpp | 112 +- utils/piintrospector/threads_view.h | 41 +- 278 files changed, 15371 insertions(+), 12176 deletions(-) diff --git a/libs/application/aboutwindow.cpp b/libs/application/aboutwindow.cpp index 28f2dfc..aec573d 100644 --- a/libs/application/aboutwindow.cpp +++ b/libs/application/aboutwindow.cpp @@ -1,7 +1,9 @@ #include "aboutwindow.h" -#include "ui_aboutwindow.h" + #include "qad_types.h" #include "qpiconfig.h" +#include "ui_aboutwindow.h" + #include #include #if QT_VERSION < 0x050000 @@ -23,44 +25,41 @@ AboutWindow::AboutWindow(QWidget * parent): QDialog(parent), ui(new Ui::AboutWin #ifdef ANDROID QDialog::setStyleSheet("font: 12pt \"DejaVu Sans\";"); #endif - if (!stylesheet.isEmpty()) - QDialog::setStyleSheet(stylesheet); + if (!stylesheet.isEmpty()) QDialog::setStyleSheet(stylesheet); ui->setupUi(this); ui->labelAuthors->setOpenExternalLinks(true); QImage logo_im = logo; - if (logo_im.isNull()) - logo_im.load(":/icons/splash.png"); + if (logo_im.isNull()) logo_im.load(":/icons/splash.png"); setWindowTitle(QApplication::applicationName() + " - " + tr("About")); QIcon ic = QApplication::windowIcon(); if (ic.isNull()) { QWidgetList tlw = QApplication::topLevelWidgets(); - foreach (QWidget * w, tlw) + foreach(QWidget * w, tlw) if (!w->windowIcon().isNull()) { ic = w->windowIcon(); break; } } - if (ic.isNull()) - ic = QIcon(QPixmap::fromImage(logo_im)); + if (ic.isNull()) ic = QIcon(QPixmap::fromImage(logo_im)); setWindowIcon(ic); - QFormLayout * lay = (QFormLayout*)(ui->groupVersions->layout()); - foreach (SSPair p, versions) { + QFormLayout * lay = (QFormLayout *)(ui->groupVersions->layout()); + foreach(SSPair p, versions) { lay->addRow(p.first, new QLabel(p.second)); } - lay = (QFormLayout*)(ui->groupBuild->layout()); - foreach (SSPair p, builds) { + lay = (QFormLayout *)(ui->groupBuild->layout()); + foreach(SSPair p, builds) { lay->addRow(p.first, new QLabel(p.second)); } ui->imageView->setPixmap(QPixmap::fromImage(logo_im)); ui->labelComment->setText(comment); ui->labelComment->setOpenExternalLinks(true); ui->labelComment->setHidden(comment.isEmpty()); - //ui->labelArch->setText(QSysInfo::currentCpuArchitecture()); + // ui->labelArch->setText(QSysInfo::currentCpuArchitecture()); ui->labelAuthors->setText(authors()); connect(ui->buttonQt, SIGNAL(clicked()), qApp, SLOT(aboutQt())); #ifdef MOBILE_VIEW ui->layoutMain->insertWidget(0, ui->imageView); - //ui->verticalSpacer->changeSize(1, 1, QSizePolicy::Preferred, QSizePolicy::Preferred); + // ui->verticalSpacer->changeSize(1, 1, QSizePolicy::Preferred, QSizePolicy::Preferred); #endif #ifdef MOBILE_VIEW ui->layoutMain->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Preferred, QSizePolicy::Expanding)); @@ -70,18 +69,17 @@ AboutWindow::AboutWindow(QWidget * parent): QDialog(parent), ui(new Ui::AboutWin r = QApplication::desktop()->geometry(); # else QScreen * scr = -# if QT_VERSION >= 0x050A00 - QApplication::screenAt(QCursor::pos()); -# else - QApplication::screens()[0]; -# endif +# if QT_VERSION >= 0x050A00 + QApplication::screenAt(QCursor::pos()); +# else + QApplication::screens()[0]; +# endif if (scr) { r.setSize(scr->availableSize() / 2); r.moveCenter(scr->availableGeometry().center()); } # endif - if (r.isValid()) - setGeometry(r); + if (r.isValid()) setGeometry(r); #endif } @@ -103,7 +101,7 @@ void AboutWindow::setLogo(QString path) { void AboutWindow::addVersion(QString name, QString version) { if (!name.endsWith(":")) name.append(":"); - foreach (const SSPair & p, versions) { + foreach(const SSPair & p, versions) { if (p.first == name) return; } version.prepend(""); @@ -117,7 +115,7 @@ void AboutWindow::addVersion(QString name, QString version) { void AboutWindow::addBuildInfo(QString name, QString value) { if (!name.endsWith(":")) name.append(":"); - foreach (const SSPair & p, builds) { + foreach(const SSPair & p, builds) { if (p.first == name) return; } builds << SSPair(name, value); @@ -143,13 +141,13 @@ void AboutWindow::show() { int AboutWindow::exec() { #ifdef MOBILE_VIEW showFullScreen(); - //setWindowState(Qt::WindowFullScreen); + // setWindowState(Qt::WindowFullScreen); #endif return QDialog::exec(); } -void AboutWindow::changeEvent(QEvent *e) { +void AboutWindow::changeEvent(QEvent * e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: @@ -202,14 +200,13 @@ QString AboutWindow::authors() { } else { QPIConfig conf(&fc); QPIConfig::Branch br = conf.allLeaves(); - foreach (QPIConfig::Entry * e, br) { + foreach(QPIConfig::Entry * e, br) { l = e->toString().trimmed(); if (!l.contains("<")) continue; QString name, mail; name = l.left(l.indexOf("<")); mail = l.mid(name.size() + 1); - if (mail.endsWith(">")) - mail.chop(1); + if (mail.endsWith(">")) mail.chop(1); name = name.trimmed(); mail = mail.trimmed(); addAuthor(ret, name, mail); @@ -217,4 +214,3 @@ QString AboutWindow::authors() { } return ret; } - diff --git a/libs/application/aboutwindow.h b/libs/application/aboutwindow.h index 7837cf7..85e1522 100644 --- a/libs/application/aboutwindow.h +++ b/libs/application/aboutwindow.h @@ -1,61 +1,61 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef ABOUTWINDOW_H #define ABOUTWINDOW_H -#include #include "qad_application_export.h" +#include -#define ADD_ABOUT_VERSION(lib) \ - { \ - if (lib##_VERSION_BUILD > 0) \ + +#define ADD_ABOUT_VERSION(lib) \ + { \ + if (lib##_VERSION_BUILD > 0) \ AboutWindow::addVersion(#lib, lib##_VERSION_NAME " (build " + QString::number(lib##_VERSION_BUILD) + ")"); \ - else \ - AboutWindow::addVersion(#lib, lib##_VERSION_NAME); \ + else \ + AboutWindow::addVersion(#lib, lib##_VERSION_NAME); \ } -#define ADD_ABOUT_VERSION_NAMED(lib, label) \ - { \ - if (lib##_VERSION_BUILD > 0) \ +#define ADD_ABOUT_VERSION_NAMED(lib, label) \ + { \ + if (lib##_VERSION_BUILD > 0) \ AboutWindow::addVersion(label, lib##_VERSION_NAME " (build " + QString::number(lib##_VERSION_BUILD) + ")"); \ - else \ - AboutWindow::addVersion(label, lib##_VERSION_NAME); \ + else \ + AboutWindow::addVersion(label, lib##_VERSION_NAME); \ } -#define ADD_ABOUT_BUILD_INFO(lib) \ - AboutWindow::addBuildInfo("Arch", lib##_ARCH); \ +#define ADD_ABOUT_BUILD_INFO(lib) \ + AboutWindow::addBuildInfo("Arch", lib##_ARCH); \ AboutWindow::addBuildInfo("Compiler", lib##_CXX_COMPILER); \ - AboutWindow::addBuildInfo("CMake", lib##_CMAKE_VERSION); \ + AboutWindow::addBuildInfo("CMake", lib##_CMAKE_VERSION); \ AboutWindow::addBuildInfo("Date", lib##_BUILD_DATE); namespace Ui { - class AboutWindow; +class AboutWindow; } -class QAD_APPLICATION_EXPORT AboutWindow: public QDialog -{ +class QAD_APPLICATION_EXPORT AboutWindow: public QDialog { Q_OBJECT typedef QPair SSPair; explicit AboutWindow(QWidget * parent = 0); ~AboutWindow(); -public: +public: static void setLogo(QImage im); static void setLogo(QString path); static void addVersion(QString name, QString version); @@ -77,7 +77,6 @@ private: static QImage logo; static QVector versions, builds; static QString stylesheet, comment; - }; #endif // ABOUTWINDOW_H diff --git a/libs/application/edockwidget.cpp b/libs/application/edockwidget.cpp index cd99ee2..9fe05da 100644 --- a/libs/application/edockwidget.cpp +++ b/libs/application/edockwidget.cpp @@ -1,5 +1,7 @@ #include "edockwidget.h" + #include "qad_types.h" + #include #include @@ -18,14 +20,14 @@ void EDockWidget::setWindowTitle(const QString & title) { void EDockWidget::setWindowIcon(const QIcon & icon) { -//#ifndef Q_OS_MACOS + // #ifndef Q_OS_MACOS lbl_icon->setPixmap(icon.pixmap(QSize(256, 256))); QDockWidget::setWindowIcon(icon); if (!icon.isNull()) { lbl_icon->setScaledContents(true); lbl_icon->setFixedSize(preferredIconSize(1.5, this)); } - //#endif + // #endif } @@ -40,32 +42,33 @@ bool EDockWidget::event(QEvent * e) { void EDockWidget::init() { header = new QFrame(); header->setFrameShape(QFrame::StyledPanel); - QBoxLayout * lay = new QBoxLayout(features().testFlag(QDockWidget::DockWidgetVerticalTitleBar) ? QBoxLayout::TopToBottom : QBoxLayout::LeftToRight); + QBoxLayout * lay = + new QBoxLayout(features().testFlag(QDockWidget::DockWidgetVerticalTitleBar) ? QBoxLayout::TopToBottom : QBoxLayout::LeftToRight); lay->setContentsMargins(2, 2, 2, 2); lay->setSpacing(2); lbl_icon = new QLabel(); -//#ifndef Q_OS_MACOS + // #ifndef Q_OS_MACOS QIcon wi = windowIcon(); if (!wi.isNull()) { - lbl_icon->setPixmap(wi.pixmap(QSize(256,256))); -/*#if QT_VERSION >= 0x500000 - if (lbl_icon->pixmap()) - const_cast(lbl_icon->pixmap())->setDevicePixelRatio(1.); -#endif*/ - //qDebug() << windowTitle() << wi.pixmap(QSize(256,256)).size(); + lbl_icon->setPixmap(wi.pixmap(QSize(256, 256))); + /*#if QT_VERSION >= 0x500000 + if (lbl_icon->pixmap()) + const_cast(lbl_icon->pixmap())->setDevicePixelRatio(1.); + #endif*/ + // qDebug() << windowTitle() << wi.pixmap(QSize(256,256)).size(); lbl_icon->setScaledContents(true); } lbl_icon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); -//#endif + // #endif lbl_title = new QLabel(windowTitle()); lbl_title->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); btn_dock = new QToolButton(); - //btn_dock->setIconSize(QSize(16, 16)); + // btn_dock->setIconSize(QSize(16, 16)); btn_dock->setAutoRaise(true); btn_dock->setFocusPolicy(Qt::NoFocus); btn_dock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); btn_hide = new QToolButton(); - //btn_hide->setIconSize(QSize(16, 16)); + // btn_hide->setIconSize(QSize(16, 16)); btn_hide->setAutoRaise(true); btn_hide->setFocusPolicy(Qt::NoFocus); btn_hide->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -83,8 +86,8 @@ void EDockWidget::init() { void EDockWidget::updateStyle() { QSize icon_size = preferredIconSize(0.75, this); - int bm = 2 * style()->pixelMetric(QStyle::PM_DockWidgetTitleBarButtonMargin, 0, this); - QSize btn_size = icon_size; + int bm = 2 * style()->pixelMetric(QStyle::PM_DockWidgetTitleBarButtonMargin, 0, this); + QSize btn_size = icon_size; btn_size += QSize(bm, bm); btn_dock->setIcon(style()->standardIcon(QStyle::SP_TitleBarNormalButton)); btn_dock->setIconSize(icon_size); diff --git a/libs/application/edockwidget.h b/libs/application/edockwidget.h index 5c5807c..b0645eb 100644 --- a/libs/application/edockwidget.h +++ b/libs/application/edockwidget.h @@ -1,59 +1,68 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef EDOCKWIDGET_H #define EDOCKWIDGET_H -#include -#include -#include -#include -#include -#include -#include #include "qad_application_export.h" +#include +#include +#include +#include +#include +#include +#include -class QAD_APPLICATION_EXPORT EDockWidget: public QDockWidget -{ + +class QAD_APPLICATION_EXPORT EDockWidget: public QDockWidget { Q_OBJECT + public: - explicit EDockWidget(const QString & title, QWidget * parent = 0, Qt::WindowFlags flags = Qt::WindowFlags()): QDockWidget(title, parent, flags) {init();} - explicit EDockWidget(QWidget * parent = 0, Qt::WindowFlags flags = Qt::WindowFlags()): QDockWidget(parent, flags) {init();} - ~EDockWidget() {delete btn_hide; delete btn_dock; delete lbl_title; delete lbl_icon; delete header;} - + explicit EDockWidget(const QString & title, QWidget * parent = 0, Qt::WindowFlags flags = Qt::WindowFlags()) + : QDockWidget(title, parent, flags) { + init(); + } + explicit EDockWidget(QWidget * parent = 0, Qt::WindowFlags flags = Qt::WindowFlags()): QDockWidget(parent, flags) { init(); } + ~EDockWidget() { + delete btn_hide; + delete btn_dock; + delete lbl_title; + delete lbl_icon; + delete header; + } + void setFeatures(QDockWidget::DockWidgetFeatures features); void setWindowTitle(const QString & title); void setWindowIcon(const QIcon & icon); - + private: bool event(QEvent * e); void init(); void updateStyle(); - + QFrame * header; - QLabel * lbl_title, * lbl_icon; - QToolButton * btn_hide, * btn_dock; - + QLabel *lbl_title, *lbl_icon; + QToolButton *btn_hide, *btn_dock; + private slots: - void dockClicked() {setFloating(!isFloating());} - + void dockClicked() { setFloating(!isFloating()); } }; #endif // EDOCKWIDGET_H diff --git a/libs/application/emainwindow.cpp b/libs/application/emainwindow.cpp index a540b00..7203708 100644 --- a/libs/application/emainwindow.cpp +++ b/libs/application/emainwindow.cpp @@ -1,13 +1,19 @@ #include "emainwindow.h" + #include -#include -#include #include +#include +#include -EMainWindow::EMainWindow(QWidget * parent): QMainWindow(parent), action_show_all_tools(this), action_hide_all_tools(this), -action_show_all_docks(this), action_hide_all_docks(this), first_show(true) { - menu_recent = 0; +EMainWindow::EMainWindow(QWidget * parent) + : QMainWindow(parent) + , action_show_all_tools(this) + , action_hide_all_tools(this) + , action_show_all_docks(this) + , action_hide_all_docks(this) + , first_show(true) { + menu_recent = 0; action_clear_recent = new QAction(QIcon(":/icons/edit-clear.png"), tr("Clear recent list"), this); connect(action_clear_recent, SIGNAL(triggered()), this, SLOT(clearRecent())); qRegisterMetaType("Qt::DockWidgetArea"); @@ -26,8 +32,7 @@ action_show_all_docks(this), action_hide_all_docks(this), first_show(true) { } -EMainWindow::~EMainWindow() { -} +EMainWindow::~EMainWindow() {} void EMainWindow::setRecentFiles(const QStringList & rl) { @@ -39,7 +44,7 @@ void EMainWindow::setRecentFiles(const QStringList & rl) { QStringList EMainWindow::recentFiles() const { QStringList ret; - foreach (QAction * a, actions_recent) + foreach(QAction * a, actions_recent) ret << a->data().toString(); return ret; } @@ -56,7 +61,7 @@ void EMainWindow::showEvent(QShowEvent * e) { initMenus(); if (!first_show) return; first_show = false; - QList docks(findChildren()); + QList docks(findChildren()); for (QDockWidget * d: docks) { connect(d, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)), this, SLOT(changedDock())); connect(d, SIGNAL(topLevelChanged(bool)), this, SLOT(changedDock())); @@ -67,16 +72,18 @@ void EMainWindow::showEvent(QShowEvent * e) { void EMainWindow::closeEvent(QCloseEvent * e) { - if (!checkSave()) e->ignore(); - else saveSession(); + if (!checkSave()) + e->ignore(); + else + saveSession(); } bool EMainWindow::eventFilter(QObject * o, QEvent * e) { - if (tbars.contains((QTabBar*)o) && e->type() == QEvent::MouseButtonDblClick) { - int tab = ((QTabBar*)o)->tabAt(((QMouseEvent * )e)->pos()); + if (tbars.contains((QTabBar *)o) && e->type() == QEvent::MouseButtonDblClick) { + int tab = ((QTabBar *)o)->tabAt(((QMouseEvent *)e)->pos()); if (tab >= 0) { - QDockWidget * dock = (QDockWidget * )(((QTabBar*)o)->tabData(tab).toULongLong()); + QDockWidget * dock = (QDockWidget *)(((QTabBar *)o)->tabData(tab).toULongLong()); if (dock) { dock->setFloating(true); return true; @@ -84,25 +91,25 @@ bool EMainWindow::eventFilter(QObject * o, QEvent * e) { } } /*if (e->type() == QEvent::Show || e->type() == QEvent::Hide) { - if (tdocks.contains((QDockWidget*)o)) { - changedDock(); - } + if (tdocks.contains((QDockWidget*)o)) { + changedDock(); + } }*/ if (e->type() == QEvent::MouseButtonPress) { - if (tbars.contains((QTabBar*)o) || tdocks.contains((QDockWidget*)o)) { + if (tbars.contains((QTabBar *)o) || tdocks.contains((QDockWidget *)o)) { if (e->type() == QEvent::MouseButtonPress) { - if (((QMouseEvent*)e)->button() == Qt::RightButton) { - bool popup = tbars.contains((QTabBar*)o); - if (tdocks.contains((QDockWidget*)o)) - popup = popup || ((QDockWidget*)o)->titleBarWidget()->geometry().contains(((QMouseEvent*)e)->pos()); + if (((QMouseEvent *)e)->button() == Qt::RightButton) { + bool popup = tbars.contains((QTabBar *)o); + if (tdocks.contains((QDockWidget *)o)) + popup = popup || ((QDockWidget *)o)->titleBarWidget()->geometry().contains(((QMouseEvent *)e)->pos()); if (popup) { createPopupMenu()->popup( #if QT_VERSION_MAJOR <= 5 - ((QMouseEvent*)e)->globalPos() + ((QMouseEvent *)e)->globalPos() #else - ((QMouseEvent*)e)->globalPosition().toPoint() + ((QMouseEvent *)e)->globalPosition().toPoint() #endif - ); + ); return true; } } @@ -123,8 +130,7 @@ void EMainWindow::changeEvent(QEvent * e) { action_hide_all_docks.setText(tr("Hide all")); action_clear_recent->setText(tr("Clear recent list")); break; - default: - break; + default: break; } } @@ -137,9 +143,9 @@ QMenu * EMainWindow::createPopupMenu() { QFont f; f.setBold(true); // Toolbars - QList tools = findChildren(); + QList tools = findChildren(); if (!tools.isEmpty()) { - wa = new QWidgetAction(menuPopup); + wa = new QWidgetAction(menuPopup); lbl = new QLabel(); lbl->setFrameShape(QFrame::StyledPanel); lbl->setFrameShadow(QFrame::Sunken); @@ -162,9 +168,9 @@ QMenu * EMainWindow::createPopupMenu() { menuPopup->addAction(&action_hide_all_tools); } // Docks - QList docks = findChildren(); + QList docks = findChildren(); if (!docks.isEmpty()) { - wa = new QWidgetAction(menuPopup); + wa = new QWidgetAction(menuPopup); lbl = new QLabel(); lbl->setFrameShape(QFrame::StyledPanel); lbl->setFrameShadow(QFrame::Sunken); @@ -193,7 +199,7 @@ QMenu * EMainWindow::createPopupMenu() { void EMainWindow::addToRecent(const QString & path) { if (path.isEmpty()) return; QFileInfo fi(path); - QString fp = fi.absoluteFilePath(); + QString fp = fi.absoluteFilePath(); bool insert = true; for (int i = 0; i < actions_recent.size(); ++i) if (actions_recent[i]->data().toString() == fp) { @@ -232,7 +238,7 @@ void EMainWindow::initMenus() { action_show_all_docks.disconnect(); action_hide_all_docks.disconnect(); - QList tools = findChildren(); + QList tools = findChildren(); for (QToolBar * i: tools) { if (i->property("ribbon").toBool()) continue; i->toggleViewAction()->setIcon(i->windowIcon()); @@ -240,7 +246,7 @@ void EMainWindow::initMenus() { connect(&action_hide_all_tools, SIGNAL(triggered(bool)), i, SLOT(hide())); } - QList docks = findChildren(); + QList docks = findChildren(); for (QDockWidget * i: docks) { if (i->property("ribbon").toBool()) continue; i->toggleViewAction()->setIcon(i->windowIcon()); @@ -248,7 +254,7 @@ void EMainWindow::initMenus() { connect(&action_hide_all_docks, SIGNAL(triggered(bool)), i, SLOT(hide())); } - QList actions = findChildren(); + QList actions = findChildren(); for (QAction * i: actions) i->setIconVisibleInMenu(true); addActions(actions); @@ -256,8 +262,8 @@ void EMainWindow::initMenus() { void EMainWindow::initSession() { - connect(&session, SIGNAL(loading(QPIConfig & )), this, SLOT(sessionLoading(QPIConfig & ))); - connect(&session, SIGNAL(saving(QPIConfig & )), this, SLOT(sessionSaving(QPIConfig & ))); + connect(&session, SIGNAL(loading(QPIConfig &)), this, SLOT(sessionLoading(QPIConfig &))); + connect(&session, SIGNAL(saving(QPIConfig &)), this, SLOT(sessionSaving(QPIConfig &))); } @@ -279,18 +285,18 @@ bool EMainWindow::checkSave() { void EMainWindow::changedDock() { if (isHidden()) return; - QSet invalid_tab_docks; - QList tabs(findChildren()); - QList docks = findChildren(); - QRect geom = geometry(); - //qDebug() << "### change" << docks.size() << tabs.size(); + QSet invalid_tab_docks; + QList tabs(findChildren()); + QList docks = findChildren(); + QRect geom = geometry(); + // qDebug() << "### change" << docks.size() << tabs.size(); for (QTabBar * t: tabs) { if (!t->objectName().isEmpty() || t->isHidden()) continue; if (!tbars.contains(t)) { - //qDebug() << "add tab" << t; + // qDebug() << "add tab" << t; tbars << t; connect(t, SIGNAL(tabCloseRequested(int)), this, SLOT(closeDock(int))); - connect(t, &QObject::destroyed, this, [this,t](){tbars.removeOne(t);}); + connect(t, &QObject::destroyed, this, [this, t]() { tbars.removeOne(t); }); t->installEventFilter(this); #ifndef Q_OS_MACOS t->setIconSize(dockTabsIconSize()); @@ -298,12 +304,11 @@ void EMainWindow::changedDock() { t->setTabsClosable(true); } for (int i = 0; i < t->count(); ++i) { - QDockWidget * dock = (QDockWidget * )t->tabData(i).toULongLong(); - //qDebug() << i << t->tabText(i) << t->isTabVisible(i) << dock; + QDockWidget * dock = (QDockWidget *)t->tabData(i).toULongLong(); + // qDebug() << i << t->tabText(i) << t->isTabVisible(i) << dock; if (!dock) continue; if (!docks.contains(dock)) continue; - if (!geom.intersects(t->geometry())) - invalid_tab_docks << dock; + if (!geom.intersects(t->geometry())) invalid_tab_docks << dock; #ifndef Q_OS_MACOS QSize is = dockTabsIconSize(); if (t->iconSize() != is) t->setIconSize(is); @@ -318,24 +323,24 @@ void EMainWindow::changedDock() { if (!d->property("__titleWidget").isValid()) { d->setProperty("__titleWidget", qulonglong(ctb)); QWidget * ntb = new QWidget(); - int m = style()->pixelMetric(QStyle::PM_DockWidgetTitleMargin); + int m = style()->pixelMetric(QStyle::PM_DockWidgetTitleMargin); ntb->setLayout(new QBoxLayout(QBoxLayout::BottomToTop)); ntb->layout()->setContentsMargins(m, m, 0, 0); d->setProperty("__titleEmptyWidget", qulonglong(ntb)); } if (!tdocks.contains(d)) { - //qDebug() << "add dock" << d; + // qDebug() << "add dock" << d; tdocks << d; - connect(d, &QObject::destroyed, this, [this,d](){tdocks.removeOne(d);}); + connect(d, &QObject::destroyed, this, [this, d]() { tdocks.removeOne(d); }); d->installEventFilter(this); } - //qDebug() << d->windowTitle() << tabifiedDockWidgets(d); + // qDebug() << d->windowTitle() << tabifiedDockWidgets(d); if (tabifiedDockWidgets(d).isEmpty() || invalid_tab_docks.contains(d)) { - if (d->titleBarWidget() != (QWidget * )(d->property("__titleWidget").toULongLong())) - d->setTitleBarWidget((QWidget * )(d->property("__titleWidget").toULongLong())); + if (d->titleBarWidget() != (QWidget *)(d->property("__titleWidget").toULongLong())) + d->setTitleBarWidget((QWidget *)(d->property("__titleWidget").toULongLong())); } else { - if (d->titleBarWidget() != (QWidget * )(d->property("__titleEmptyWidget").toULongLong())) { - d->setTitleBarWidget((QWidget * )(d->property("__titleEmptyWidget").toULongLong())); + if (d->titleBarWidget() != (QWidget *)(d->property("__titleEmptyWidget").toULongLong())) { + d->setTitleBarWidget((QWidget *)(d->property("__titleEmptyWidget").toULongLong())); d->layout()->setContentsMargins(0, 20, 0, 0); } } @@ -344,20 +349,19 @@ void EMainWindow::changedDock() { void EMainWindow::closeDock(int index) { - QDockWidget * dock = (QDockWidget * )((QTabBar*)sender())->tabData(index).toULongLong(); + QDockWidget * dock = (QDockWidget *)((QTabBar *)sender())->tabData(index).toULongLong(); if (dock == 0) return; dock->close(); } void EMainWindow::recentTriggered() { - QAction * a = qobject_cast(sender()); + QAction * a = qobject_cast(sender()); if (!a) return; QString path = a->data().toString(); if (path.isEmpty()) return; if (!checkSave()) return; - if (load(path)) - addToRecent(path); + if (load(path)) addToRecent(path); } @@ -379,31 +383,32 @@ void EMainWindow::openFile() { if (!checkSave()) return; QString ret = QFileDialog::getOpenFileName(this, tr("Select file to open"), file_name, loadFilter()); if (ret.isEmpty()) return; - if (load(ret)) - addToRecent(ret); + if (load(ret)) addToRecent(ret); } void EMainWindow::openFiles() { if (!checkSave()) return; QStringList ret = QFileDialog::getOpenFileNames(this, tr("Select files to open"), file_name, loadFilter()); - foreach (QString s, ret) { - if (load(s)) - addToRecent(s); + foreach(QString s, ret) { + if (load(s)) addToRecent(s); } } bool EMainWindow::saveFile(bool ask) { if (ask) { - int ret = QMessageBox::question(this, windowTitle(), tr("Save changes%1?").arg(!file_name.isEmpty() ? (tr(" in") + " \"" + file_name + "\"") : ""), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); + int ret = QMessageBox::question(this, + windowTitle(), + tr("Save changes%1?").arg(!file_name.isEmpty() ? (tr(" in") + " \"" + file_name + "\"") : ""), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Save); if (ret == QMessageBox::Cancel) return false; if (ret == QMessageBox::Save) return saveFile(); return true; } if (file_name.isEmpty()) return saveAsFile(); - if (save(file_name)) - addToRecent(file_name); + if (save(file_name)) addToRecent(file_name); return true; } @@ -411,8 +416,7 @@ bool EMainWindow::saveFile(bool ask) { bool EMainWindow::saveAsFile() { QString ret = QFileDialog::getSaveFileName(this, tr("Select file to save"), file_name, saveFilter()); if (ret.isEmpty()) return false; - if (save(ret)) - addToRecent(ret); + if (save(ret)) addToRecent(ret); return true; } diff --git a/libs/application/emainwindow.h b/libs/application/emainwindow.h index 8a0cdd4..d0d0b5d 100644 --- a/libs/application/emainwindow.h +++ b/libs/application/emainwindow.h @@ -1,43 +1,45 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef EMAINWINDOW_H #define EMAINWINDOW_H +#include "qad_application_export.h" +#include "ribbon.h" +#include "session_manager.h" + +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include "session_manager.h" -#include "ribbon.h" -#include "qad_application_export.h" class QAD_APPLICATION_EXPORT UAction: public QAction { Q_OBJECT + public: - UAction(int ind,const QString & text, QObject * parent): QAction(text, parent) { + UAction(int ind, const QString & text, QObject * parent): QAction(text, parent) { index = ind; connect(this, SIGNAL(triggered()), this, SLOT(triggered())); connect(this, SIGNAL(toggled(bool)), this, SLOT(toggled(bool))); @@ -50,16 +52,17 @@ public: connect(this, SIGNAL(hovered()), this, SLOT(hovered())); } public slots: - void show() {setVisible(true);} - void hide() {setVisible(false);} - void setCheckedTrue() {setChecked(true);} - void setCheckedFalse() {setChecked(false);} + void show() { setVisible(true); } + void hide() { setVisible(false); } + void setCheckedTrue() { setChecked(true); } + void setCheckedFalse() { setChecked(false); } + private: int index; private slots: - void triggered() {emit itriggered(this, index);} - void toggled(bool t) {emit itoggled(t, this, index);} - void hovered() {emit ihovered(this);} + void triggered() { emit itriggered(this, index); } + void toggled(bool t) { emit itoggled(t, this, index); } + void hovered() { emit ihovered(this); } signals: void itriggered(QAction *, int); void itoggled(bool, QAction *, int); @@ -67,55 +70,63 @@ signals: }; -class QAD_APPLICATION_EXPORT EMainWindow: public QMainWindow -{ +class QAD_APPLICATION_EXPORT EMainWindow: public QMainWindow { Q_OBJECT Q_PROPERTY(int maxRecentItems READ maxRecentItems WRITE setMaxRecentItems) + public: EMainWindow(QWidget * parent = 0); ~EMainWindow(); virtual void reset(bool full = false) {} - virtual bool load(const QString & path) {return true;} - virtual bool save(const QString & path) {return true;} + virtual bool load(const QString & path) { return true; } + virtual bool save(const QString & path) { return true; } void addSeparator() {} void setRecentFiles(const QStringList & rl); QStringList recentFiles() const; void setRecentMenu(QMenu * m); - int maxRecentItems() const {return max_recent;} + int maxRecentItems() const { return max_recent; } protected: // Qt`s overloaded - void showEvent(QShowEvent * ); - void closeEvent(QCloseEvent * ); + void showEvent(QShowEvent *); + void closeEvent(QCloseEvent *); bool eventFilter(QObject * o, QEvent * e); void changeEvent(QEvent * e); QMenu * createPopupMenu(); void addToRecent(const QString & path); void prepareRecent(); - void init(const QString & config) {session.setFile(config); initMenus(); initSession(); loadSession();} // unusable + void init(const QString & config) { + session.setFile(config); + initMenus(); + initSession(); + loadSession(); + } // unusable void saveSession(); void loadSession(); virtual void savingSession(QPIConfig & conf) {} virtual void loadingSession(QPIConfig & conf) {} - virtual QSize dockTabsIconSize() const {return iconSize();} - virtual QString loadFilter() {return "All files(*)";} - virtual QString saveFilter() {return "All files(*)";} + virtual QSize dockTabsIconSize() const { return iconSize(); } + virtual QString loadFilter() { return "All files(*)"; } + virtual QString saveFilter() { return "All files(*)"; } bool checkSave(); - void setChanged(bool yes = true) {isChanged = yes; setWindowModified(yes);} + void setChanged(bool yes = true) { + isChanged = yes; + setWindowModified(yes); + } void initMenus(); void initSession(); QAction action_show_all_tools, action_hide_all_tools, action_show_all_docks, action_hide_all_docks; QString file_name; - QList tbars; - QList tdocks; - QList actions_recent; + QList tbars; + QList tdocks; + QList actions_recent; QAction * action_clear_recent; QMenu * menu_recent; SessionManager session; @@ -124,24 +135,23 @@ protected: private slots: void changedDock(); - void sessionLoading(QPIConfig & conf) {loadingSession(conf);} - void sessionSaving(QPIConfig & conf) {savingSession(conf);} + void sessionLoading(QPIConfig & conf) { loadingSession(conf); } + void sessionSaving(QPIConfig & conf) { savingSession(conf); } void closeDock(int index); void recentTriggered(); public slots: void setMaxRecentItems(int mr); - void changed() {setChanged(true);} + void changed() { setChanged(true); } void newFile(); void openFile(); void openFiles(); bool saveFile(bool ask); - bool saveFile() {return saveFile(false);} + bool saveFile() { return saveFile(false); } bool saveAsFile(); void clearRecent(); signals: - }; #endif // MAINWINDOW_H diff --git a/libs/application/etabwidget.cpp b/libs/application/etabwidget.cpp index 437409f..f5412d7 100644 --- a/libs/application/etabwidget.cpp +++ b/libs/application/etabwidget.cpp @@ -1,7 +1,7 @@ #include "etabwidget.h" -ETabWidget::ETabWidget(QWidget* parent): QTabWidget(parent) { +ETabWidget::ETabWidget(QWidget * parent): QTabWidget(parent) { tabBar()->setMouseTracking(true); tabBar()->installEventFilter(this); } @@ -9,26 +9,27 @@ ETabWidget::ETabWidget(QWidget* parent): QTabWidget(parent) { void ETabWidget::retranslate() { for (int i = 0; i < buttons.size(); ++i) - buttons[i].toolTip = QApplication::translate("MainWindow", buttons[i].srcToolTip.toUtf8(), 0/*, QCoreApplication::UnicodeUTF8*/); - QList bl = findChildren(); - foreach (QToolButton * i, bl) - i->setToolTip(QApplication::translate("MainWindow", i->property("sourceToolTip").toString().toUtf8(), 0/*, QCoreApplication::UnicodeUTF8*/)); + buttons[i].toolTip = QApplication::translate("MainWindow", buttons[i].srcToolTip.toUtf8(), 0 /*, QCoreApplication::UnicodeUTF8*/); + QList bl = findChildren(); + foreach(QToolButton * i, bl) + i->setToolTip( + QApplication::translate("MainWindow", i->property("sourceToolTip").toString().toUtf8(), 0 /*, QCoreApplication::UnicodeUTF8*/)); } int ETabWidget::addTab(QWidget * page, const QIcon & icon, const QString & label) { - int ret = QTabWidget::addTab(page, icon, label); + int ret = QTabWidget::addTab(page, icon, label); QWidget * w = new QWidget(); w->setLayout(new QBoxLayout(QBoxLayout::RightToLeft)); w->layout()->setContentsMargins(0, 0, 0, 0); w->layout()->setSpacing(2); QToolButton * b; - foreach (const TabButton & i, buttons) { + foreach(const TabButton & i, buttons) { b = new QToolButton(); b->setToolTip(i.toolTip); b->setIconSize(QSize(16, 16)); b->setIcon(i.icon); - //b->setFlat(true); + // b->setFlat(true); b->setProperty("sourceToolTip", i.toolTip); b->setProperty("buttonRole", i.role); connect(b, SIGNAL(clicked(bool)), this, SLOT(buttonClicked())); @@ -41,14 +42,12 @@ int ETabWidget::addTab(QWidget * page, const QIcon & icon, const QString & label void ETabWidget::setButtonVisible(int role, bool yes) { - QList bl = findChildren(); - foreach (QToolButton * i, bl) - if (i->property("buttonRole").toInt() == role) - i->setVisible(yes); + QList bl = findChildren(); + foreach(QToolButton * i, bl) + if (i->property("buttonRole").toInt() == role) i->setVisible(yes); QWidget * w; for (int i = 0; i < buttons.size(); ++i) { - if (buttons[i].role == role) - buttons[i].visible = yes; + if (buttons[i].role == role) buttons[i].visible = yes; w = tabBar()->tabButton(i, QTabBar::RightSide); if (w != 0) w->adjustSize(); } @@ -57,19 +56,19 @@ void ETabWidget::setButtonVisible(int role, bool yes) { /* void ETabWidget::removeTab(int index) { - tbs.removeAll(qobject_cast(tabBar()->tabButton(index, QTabBar::RightSide)->layout()->itemAt(1)->widget())); - tbs.removeAll(qobject_cast(tabBar()->tabButton(index, QTabBar::RightSide)->layout()->itemAt(0)->widget())); - QTabWidget::removeTab(index); + tbs.removeAll(qobject_cast(tabBar()->tabButton(index, QTabBar::RightSide)->layout()->itemAt(1)->widget())); + tbs.removeAll(qobject_cast(tabBar()->tabButton(index, QTabBar::RightSide)->layout()->itemAt(0)->widget())); + QTabWidget::removeTab(index); } */ bool ETabWidget::eventFilter(QObject * o, QEvent * e) { static int prev = -1; if (e->type() == QEvent::MouseMove) { - QTabBar * t = qobject_cast(o); + QTabBar * t = qobject_cast(o); if (t == 0) return QTabWidget::eventFilter(o, e); for (int i = 0; i < count(); ++i) - if (t->tabRect(i).contains(((QMouseEvent * )e)->pos())) { + if (t->tabRect(i).contains(((QMouseEvent *)e)->pos())) { if (i != prev) { prev = i; emit tabHovered(i); @@ -94,17 +93,14 @@ bool ETabWidget::eventFilter(QObject * o, QEvent * e) { void ETabWidget::changeEvent(QEvent * e) { QTabWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslate(); - break; - default: - break; + case QEvent::LanguageChange: retranslate(); break; + default: break; } } void ETabWidget::buttonClicked() { - QToolButton * s = qobject_cast(sender()); + QToolButton * s = qobject_cast(sender()); if (s == 0) return; QWidget * pw = s->parentWidget(); if (pw == 0) return; diff --git a/libs/application/etabwidget.h b/libs/application/etabwidget.h index f1d8aeb..5780f8c 100644 --- a/libs/application/etabwidget.h +++ b/libs/application/etabwidget.h @@ -1,75 +1,81 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef ETABWIDGET_H #define ETABWIDGET_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "qad_application_export.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -class QAD_APPLICATION_EXPORT ETabWidget: public QTabWidget -{ + +class QAD_APPLICATION_EXPORT ETabWidget: public QTabWidget { Q_OBJECT + public: explicit ETabWidget(QWidget * parent = 0); - + void retranslate(); - void addTabButton(int role, const QIcon & icon, const QString & toolTip = QString()) {buttons << TabButton(role, icon, toolTip);} + void addTabButton(int role, const QIcon & icon, const QString & toolTip = QString()) { buttons << TabButton(role, icon, toolTip); } int addTab(QWidget * page, const QIcon & icon, const QString & label); - int addTab(QWidget * page, const QString & label) {return addTab(page, QIcon(), label);} + int addTab(QWidget * page, const QString & label) { return addTab(page, QIcon(), label); } void setButtonVisible(int role, bool yes); - + private: bool eventFilter(QObject * o, QEvent * e); - void tabInserted(int) {emit countChanged();} - void tabRemoved(int) {emit countChanged();} + void tabInserted(int) { emit countChanged(); } + void tabRemoved(int) { emit countChanged(); } void changeEvent(QEvent * e); - + struct QAD_APPLICATION_EXPORT TabButton { - TabButton(int r, const QIcon & i, const QString & t) {role = r; icon = i; visible = true; srcToolTip = t; toolTip = QApplication::translate("MainWindow", t.toUtf8(), 0/*, QCoreApplication::UnicodeUTF8*/);} + TabButton(int r, const QIcon & i, const QString & t) { + role = r; + icon = i; + visible = true; + srcToolTip = t; + toolTip = QApplication::translate("MainWindow", t.toUtf8(), 0 /*, QCoreApplication::UnicodeUTF8*/); + } int role; bool visible; QIcon icon; QString srcToolTip; QString toolTip; }; - + QList buttons; - + private slots: void buttonClicked(); - + signals: void countChanged(); void tabHovered(int tab); void tabButtonClicked(int tab, int role); - }; #endif // ETABWIDGET_H diff --git a/libs/application/historyview.cpp b/libs/application/historyview.cpp index 11375d0..99aa189 100644 --- a/libs/application/historyview.cpp +++ b/libs/application/historyview.cpp @@ -1,26 +1,26 @@ #include "historyview.h" -#include + #include +#include -HistoryView::HistoryView(QWidget* parent): QListWidget(parent) { +HistoryView::HistoryView(QWidget * parent): QListWidget(parent) { setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); setSelectionMode(QAbstractItemView::MultiSelection); setEditTriggers(NoEditTriggers); - active_ = true; + active_ = true; duplicates_ = false; - index = 0; + index = 0; setLimit(32); setHistoryColor(palette().color(QPalette::Highlight)); - connect(this, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(itemClicked(QListWidgetItem*))); + connect(this, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(itemClicked(QListWidgetItem *))); connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(itemSelectionChanged())); registerAction(-1, tr("History cleared"), QImage(":/icons/clear-history.png")); } -HistoryView::~HistoryView() { -} +HistoryView::~HistoryView() {} QByteArray HistoryView::current() const { @@ -37,8 +37,7 @@ void HistoryView::addEntry(int action, int count_, const QString & suffix) { QByteArray ba; emit commandRequest(ba); if (!duplicates_) - if (current() == ba) - return; + if (current() == ba) return; int cnt = count(); for (int i = index; i < cnt; ++i) if (i >= 0) delete takeItem(index); @@ -94,11 +93,8 @@ void HistoryView::checkLimit() { void HistoryView::changeEvent(QEvent * e) { QListWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - actions_[-1].text = tr("History cleared"); - break; - default: - break; + case QEvent::LanguageChange: actions_[-1].text = tr("History cleared"); break; + default: break; } } @@ -107,7 +103,7 @@ void HistoryView::itemClicked(QListWidgetItem * item) { if (!active_) return; if (index == row(item) + 1) return; index = row(item) + 1; - //qDebug() << actions[index - 1].command; + // qDebug() << actions[index - 1].command; emit commandExecute(history_[index - 1].command); emit changed(); itemSelectionChanged(); @@ -117,7 +113,7 @@ void HistoryView::itemClicked(QListWidgetItem * item) { void HistoryView::itemSelectionChanged() { if (!active_) return; if (index < 1) index = 1; - //qDebug() << "changed" << count(); + // qDebug() << "changed" << count(); int vpos = verticalScrollBar()->value(); blockSignals(true); setCurrentItem(item(index - 1)); diff --git a/libs/application/historyview.h b/libs/application/historyview.h index e57bef7..6f8bf1b 100644 --- a/libs/application/historyview.h +++ b/libs/application/historyview.h @@ -1,50 +1,51 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef HISTORYVIEW_H #define HISTORYVIEW_H -#include -#include #include "qad_application_export.h" +#include +#include -class QAD_APPLICATION_EXPORT HistoryView: public QListWidget -{ + +class QAD_APPLICATION_EXPORT HistoryView: public QListWidget { Q_OBJECT Q_PROPERTY(bool active READ isActive WRITE setActive) Q_PROPERTY(bool duplicatesEnabled READ isDuplicatesEnabled WRITE setDuplicatesEnabled) Q_PROPERTY(int limit READ limit WRITE setLimit) Q_PROPERTY(QColor historyColor READ historyColor WRITE setHistoryColor) + public: explicit HistoryView(QWidget * parent = 0); ~HistoryView(); - - bool isActive() const {return active_;} - bool isDuplicatesEnabled() const {return duplicates_;} - int limit() const {return limit_;} - QColor historyColor() const {return color_;} + + bool isActive() const { return active_; } + bool isDuplicatesEnabled() const { return duplicates_; } + int limit() const { return limit_; } + QColor historyColor() const { return color_; } QByteArray current() const; - + void addEntry(int action, int count = 0, const QString & suffix = QString()); void registerAction(int action, const QString & text, const QImage & icon = QImage()); - + private: struct QAD_APPLICATION_EXPORT Action { Action(int i = -1, const QString & t = QString(), const QImage & c = QImage()): id(i), text(t) { @@ -63,31 +64,31 @@ private: int action; QByteArray command; }; - + void checkLimit(); void changeEvent(QEvent * e); QString actionText(int action, int count_); - + QMap actions_; QVector history_; QColor color_; bool active_, duplicates_; int index, limit_; - + public slots: - void setActive(bool yes) {active_ = yes;} - void setDuplicatesEnabled(bool yes) {duplicates_ = yes;} + void setActive(bool yes) { active_ = yes; } + void setDuplicatesEnabled(bool yes) { duplicates_ = yes; } void setLimit(int l); void setHistoryColor(const QColor & c); void clear(bool silent); - void clear() {clear(false);} + void clear() { clear(false); } void undo(); void redo(); - + private slots: void itemClicked(QListWidgetItem * item); void itemSelectionChanged(); - + signals: void undoAvailable(bool); void redoAvailable(bool); @@ -95,7 +96,6 @@ signals: void commandRequest(QByteArray & s); void commandExecute(const QByteArray & s); void changed(); - }; #endif // HISTORYVIEW_H diff --git a/libs/application/logview.cpp b/libs/application/logview.cpp index 1864996..4cf9e19 100644 --- a/libs/application/logview.cpp +++ b/libs/application/logview.cpp @@ -1,15 +1,17 @@ #include "logview.h" -#include "ui_logview.h" -#include "qad_types.h" + #include "ecombobox.h" -#include +#include "qad_types.h" +#include "ui_logview.h" + #include -#include -#include -#include -#include #include +#include +#include +#include #include +#include +#include class TextBlockData: public QTextBlockUserData { @@ -19,8 +21,6 @@ public: }; - - LogView::Category::Category() { bold = false; } @@ -104,33 +104,45 @@ int LogView::linesLimit() const { } -void LogView::registerCategory(const QString & label, QString keyword, const QImage & icon, QBrush text_brush, QBrush background, bool bold) { +void LogView::registerCategory(const QString & label, + QString keyword, + const QImage & icon, + QBrush text_brush, + QBrush background, + bool bold) { QRegularExpression regexp(keyword, #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - QRegularExpression::PatternOptions(QRegularExpression::CaseInsensitiveOption) + QRegularExpression::PatternOptions(QRegularExpression::CaseInsensitiveOption) #else - Qt::CaseInsensitive + Qt::CaseInsensitive #endif - ); + ); registerCategory(label, regexp, icon, text_brush, background, bold); } -void LogView::registerCategory(const QString & label, QRegularExpression regexp, const QImage & icon, QBrush text_brush, QBrush background, bool bold) { +void LogView::registerCategory(const QString & label, + QRegularExpression regexp, + const QImage & icon, + QBrush text_brush, + QBrush background, + bool bold) { if (!regexp.isValid() || regexp.pattern().isEmpty()) return; removeCategory(regexp); Category c; - c.regexp = regexp; - c.label = label; - c.image = icon; + c.regexp = regexp; + c.label = label; + c.image = icon; c.text_brush = text_brush; c.background = background; - c.bold = bold; - c.makeIcon(iconImageSize(), preferredIconSize(1., this) + c.bold = bold; + c.makeIcon(iconImageSize(), + preferredIconSize(1., this) #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) - , devicePixelRatioF() + , + devicePixelRatioF() #endif - ); + ); categories.append(c); ui->comboCategory->addItem(c.icon, label, QVariant(regexp)); } @@ -139,11 +151,11 @@ void LogView::registerCategory(const QString & label, QRegularExpression regexp, void LogView::removeCategory(QString keyword) { QRegularExpression regexp(keyword, #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - QRegularExpression::PatternOptions(QRegularExpression::CaseInsensitiveOption) + QRegularExpression::PatternOptions(QRegularExpression::CaseInsensitiveOption) #else - Qt::CaseInsensitive + Qt::CaseInsensitive #endif - ); + ); removeCategory(regexp); } @@ -153,13 +165,14 @@ void LogView::removeCategory(QRegularExpression regexp) { c.regexp = regexp; categories.removeAll(c); for (int i = 1; i < ui->comboCategory->count(); ++i) { - if (ui->comboCategory->itemData(i). + if (ui->comboCategory->itemData(i) + . #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - toRegularExpression() + toRegularExpression() #else - toRegExp() + toRegExp() #endif - .pattern() == regexp.pattern()) { + .pattern() == regexp.pattern()) { ui->comboCategory->removeItem(i); --i; } @@ -188,16 +201,13 @@ void LogView::addText(const QString & text, const QString & keyword, bool insert QStringList sl = text.split("\n"); tc.movePosition(QTextCursor::End); QScrollBar * bar = ui->textEdit->verticalScrollBar(); - bool at_end = (bar->value() == bar->maximum()) || bar->isHidden(); + bool at_end = (bar->value() == bar->maximum()) || bar->isHidden(); for (int i = 0; i < sl.size(); ++i) { tc.insertText(sl[i]); - if (!keyword.isEmpty()) - tc.block().setUserData(new TextBlockData(keyword)); - if ((i < sl.size() - 1) || insert_newline) - newLine(keyword); + if (!keyword.isEmpty()) tc.block().setUserData(new TextBlockData(keyword)); + if ((i < sl.size() - 1) || insert_newline) newLine(keyword); } - if (at_end) - scrollToBottom(); + if (at_end) scrollToBottom(); } @@ -215,12 +225,14 @@ void LogView::changeEvent(QEvent * e) { ui->labelIconSearch->setFixedSize(preferredIconSize(1.2, this)); QSize is = iconImageSize(), is_i = preferredIconSize(1., this); for (int i = 0; i < categories.size(); ++i) - categories[i].makeIcon(is, is_i + categories[i].makeIcon(is, + is_i #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) - , devicePixelRatioF() + , + devicePixelRatioF() #endif - ); - } break; + ); + } break; default: break; } } @@ -232,19 +244,18 @@ void LogView::newLine(const QString & keyword) { tc.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); QString line = tc.selectedText(); QImage icon; - foreach (const Category & c, categories) { + foreach(const Category & c, categories) { bool matched = false; - if (keyword.isEmpty()) matched = line.contains(c.regexp); - else matched = (keyword == c.regexp.pattern()); + if (keyword.isEmpty()) + matched = line.contains(c.regexp); + else + matched = (keyword == c.regexp.pattern()); if (matched) { - QTextCharFormat cf = def_cf; + QTextCharFormat cf = def_cf; QTextBlockFormat bf = def_bf; - if (c.text_brush != Qt::NoBrush) - cf.setForeground(c.text_brush); - if (c.background != Qt::NoBrush) - bf.setBackground(c.background); - if (c.bold) - cf.setFontWeight(QFont::Bold); + if (c.text_brush != Qt::NoBrush) cf.setForeground(c.text_brush); + if (c.background != Qt::NoBrush) bf.setBackground(c.background); + if (c.bold) cf.setFontWeight(QFont::Bold); tc.setCharFormat(cf); tc.setBlockFormat(bf); icon = c.icon_image; @@ -257,13 +268,12 @@ void LogView::newLine(const QString & keyword) { } QRegularExpression regexp = #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - ui->comboCategory->currentData().toRegularExpression(); + ui->comboCategory->currentData().toRegularExpression(); #else - ui->comboCategory->itemData(ui->comboCategory->currentIndex()).toRegExp(); + ui->comboCategory->itemData(ui->comboCategory->currentIndex()).toRegExp(); #endif QString fs = ui->lineEdit->text(); - if (isFilterVisible()) - filterBlock(tc.block(), fs, regexp); + if (isFilterVisible()) filterBlock(tc.block(), fs, regexp); tc.movePosition(QTextCursor::End); tc.setCharFormat(def_cf); tc.insertBlock(); @@ -278,15 +288,14 @@ QSize LogView::iconImageSize() { void LogView::filterBlock(QTextBlock block, const QString & fs, const QRegularExpression & regexp) { - bool vis = true;//, pvis = block.isVisible(); + bool vis = true; //, pvis = block.isVisible(); QString line = block.text(); if (!line.isEmpty()) { - if (line[0] == QChar::ObjectReplacementCharacter) - line.remove(0, 1); + if (line[0] == QChar::ObjectReplacementCharacter) line.remove(0, 1); } if (regexp.isValid() && !regexp.pattern().isEmpty()) { QString kw; - TextBlockData * bd = (TextBlockData*)block.userData(); + TextBlockData * bd = (TextBlockData *)block.userData(); if (bd) kw = bd->keyword; if (!kw.isEmpty()) vis = vis && (bd->keyword == regexp.pattern()); @@ -295,8 +304,8 @@ void LogView::filterBlock(QTextBlock block, const QString & fs, const QRegularEx } if (!fs.isEmpty()) vis = vis && line.contains(fs, Qt::CaseInsensitive); block.setVisible(vis); - //qDebug() << "filterBlock" << line << vis; - //if (vis != pvis) + // qDebug() << "filterBlock" << line << vis; + // if (vis != pvis) // ;//ui->textEdit->document()->mar } @@ -325,16 +334,16 @@ void LogView::scrollToBottom() { void LogView::filter() { QTextDocument * doc = ui->textEdit->document(); - int bc = doc->blockCount(); + int bc = doc->blockCount(); QRegularExpression regexp; QString fs; if (isFilterVisible()) { regexp = - #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - ui->comboCategory->currentData().toRegularExpression(); - #else - ui->comboCategory->itemData(ui->comboCategory->currentIndex()).toRegExp(); - #endif +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + ui->comboCategory->currentData().toRegularExpression(); +#else + ui->comboCategory->itemData(ui->comboCategory->currentIndex()).toRegExp(); +#endif fs = ui->lineEdit->text(); } QTextBlock bl; diff --git a/libs/application/logview.h b/libs/application/logview.h index 1c1d53b..7c61ae4 100644 --- a/libs/application/logview.h +++ b/libs/application/logview.h @@ -1,34 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef LOGVIEW_H #define LOGVIEW_H -#include #include #include #include +#include #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) # include #else # include - typedef QRegExp QRegularExpression; +typedef QRegExp QRegularExpression; #endif #include "qad_application_export.h" @@ -37,19 +37,19 @@ class QTextBlock; class QAction; namespace Ui { - class LogView; +class LogView; } -class QAD_APPLICATION_EXPORT LogView: public QWidget -{ +class QAD_APPLICATION_EXPORT LogView: public QWidget { Q_OBJECT Q_PROPERTY(bool filterVisible READ isFilterVisible WRITE setFilterVisible) Q_PROPERTY(int linesLimit READ linesLimit WRITE setLinesLimit) Q_PROPERTY(QFont logFont READ logFont WRITE setLogFont) + public: explicit LogView(QWidget * parent = 0); ~LogView(); - + const QTextEdit * textEdit() const; void setLogFont(QFont f); QFont logFont() const; @@ -58,25 +58,25 @@ public: int linesLimit() const; void registerCategory(const QString & label, - QString keyword = QString(), - const QImage & icon = QImage(), - QBrush text_brush = Qt::NoBrush, - QBrush background = Qt::NoBrush, - bool bold = false); + QString keyword = QString(), + const QImage & icon = QImage(), + QBrush text_brush = Qt::NoBrush, + QBrush background = Qt::NoBrush, + bool bold = false); void registerCategory(const QString & label, - QRegularExpression regexp, - const QImage & icon = QImage(), - QBrush text_brush = Qt::NoBrush, - QBrush background = Qt::NoBrush, - bool bold = false); + QRegularExpression regexp, + const QImage & icon = QImage(), + QBrush text_brush = Qt::NoBrush, + QBrush background = Qt::NoBrush, + bool bold = false); void removeCategory(QString keyword); void removeCategory(QRegularExpression regexp); void clearCategories(); void addText(const QString & text, bool insert_newline = true); void addText(const QString & text, const QString & keyword, bool insert_newline = true); - + private: struct QAD_APPLICATION_EXPORT Category { Category(); @@ -88,31 +88,30 @@ private: QBrush text_brush; QBrush background; bool bold; - inline bool operator ==(const Category & it) const {return (regexp.pattern() == it.regexp.pattern());} + inline bool operator==(const Category & it) const { return (regexp.pattern() == it.regexp.pattern()); } }; - + void changeEvent(QEvent * e); void newLine(const QString & keyword); QSize iconImageSize(); void filterBlock(QTextBlock block, const QString & fs, const QRegularExpression & regexp); - + Ui::LogView * ui; QList categories; QTextCharFormat def_cf; QTextBlockFormat def_bf; - QAction * actionLogSelectAll, * actionLogCopy, * actionLogClear; + QAction *actionLogSelectAll, *actionLogCopy, *actionLogClear; public slots: void setFilterVisible(bool yes); void setLinesLimit(int l); void clear(); - + private slots: void scrollToBottom(); void filter(); - + signals: - }; diff --git a/libs/application/plugin/edockwidgetplugin.cpp b/libs/application/plugin/edockwidgetplugin.cpp index 61a5d87..522d230 100644 --- a/libs/application/plugin/edockwidgetplugin.cpp +++ b/libs/application/plugin/edockwidgetplugin.cpp @@ -1,5 +1,7 @@ -#include "edockwidget.h" #include "edockwidgetplugin.h" + +#include "edockwidget.h" + #include @@ -9,8 +11,7 @@ EDockWidgetPlugin::EDockWidgetPlugin(QObject * parent): QObject(parent) { void EDockWidgetPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString EDockWidgetPlugin::domXml() const { QString EDockWidgetPlugin::includeFile() const { return QLatin1String("edockwidget.h"); } - diff --git a/libs/application/plugin/edockwidgetplugin.h b/libs/application/plugin/edockwidgetplugin.h index 0edc9bd..66ff8fa 100644 --- a/libs/application/plugin/edockwidgetplugin.h +++ b/libs/application/plugin/edockwidgetplugin.h @@ -8,8 +8,9 @@ # include #endif -class EDockWidgetPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class EDockWidgetPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif diff --git a/libs/application/plugin/emainwindowplugin.cpp b/libs/application/plugin/emainwindowplugin.cpp index 630d637..22daad0 100644 --- a/libs/application/plugin/emainwindowplugin.cpp +++ b/libs/application/plugin/emainwindowplugin.cpp @@ -1,5 +1,7 @@ -#include "emainwindow.h" #include "emainwindowplugin.h" + +#include "emainwindow.h" + #include @@ -9,8 +11,7 @@ EMainWindowPlugin::EMainWindowPlugin(QObject * parent): QObject(parent) { void EMainWindowPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString EMainWindowPlugin::domXml() const { QString EMainWindowPlugin::includeFile() const { return QLatin1String("emainwindow.h"); } - diff --git a/libs/application/plugin/emainwindowplugin.h b/libs/application/plugin/emainwindowplugin.h index 51c420c..31dce40 100644 --- a/libs/application/plugin/emainwindowplugin.h +++ b/libs/application/plugin/emainwindowplugin.h @@ -8,8 +8,9 @@ # include #endif -class EMainWindowPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class EMainWindowPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif diff --git a/libs/application/plugin/historyviewplugin.cpp b/libs/application/plugin/historyviewplugin.cpp index 7113e6e..b95dd9f 100644 --- a/libs/application/plugin/historyviewplugin.cpp +++ b/libs/application/plugin/historyviewplugin.cpp @@ -1,5 +1,7 @@ -#include "historyview.h" #include "historyviewplugin.h" + +#include "historyview.h" + #include @@ -9,8 +11,7 @@ HistoryViewPlugin::HistoryViewPlugin(QObject * parent): QObject(parent) { void HistoryViewPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString HistoryViewPlugin::domXml() const { QString HistoryViewPlugin::includeFile() const { return QLatin1String("historyview.h"); } - diff --git a/libs/application/plugin/historyviewplugin.h b/libs/application/plugin/historyviewplugin.h index 16bf1c4..308f106 100644 --- a/libs/application/plugin/historyviewplugin.h +++ b/libs/application/plugin/historyviewplugin.h @@ -8,8 +8,9 @@ # include #endif -class HistoryViewPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class HistoryViewPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // HISTORYVIEWPLUGIN_H diff --git a/libs/application/plugin/logviewplugin.cpp b/libs/application/plugin/logviewplugin.cpp index add48ea..7d503f4 100644 --- a/libs/application/plugin/logviewplugin.cpp +++ b/libs/application/plugin/logviewplugin.cpp @@ -1,5 +1,7 @@ -#include "logview.h" #include "logviewplugin.h" + +#include "logview.h" + #include @@ -9,8 +11,7 @@ LogViewPlugin::LogViewPlugin(QObject * parent): QObject(parent) { void LogViewPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString LogViewPlugin::domXml() const { QString LogViewPlugin::includeFile() const { return QLatin1String("logview.h"); } - diff --git a/libs/application/plugin/logviewplugin.h b/libs/application/plugin/logviewplugin.h index fc680bc..e5fd0dd 100644 --- a/libs/application/plugin/logviewplugin.h +++ b/libs/application/plugin/logviewplugin.h @@ -8,8 +8,9 @@ # include #endif -class LogViewPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class LogViewPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // LOGVIEWPLUGIN_H diff --git a/libs/application/plugin/qad_application.cpp b/libs/application/plugin/qad_application.cpp index 18b0093..a6abe10 100644 --- a/libs/application/plugin/qad_application.cpp +++ b/libs/application/plugin/qad_application.cpp @@ -1,4 +1,5 @@ #include "qad_application.h" + #include "edockwidgetplugin.h" #include "emainwindowplugin.h" #include "historyviewplugin.h" @@ -6,14 +7,14 @@ QADApplication::QADApplication(QObject * parent): QObject(parent) { - //m_widgets.append(new EDockWidgetPlugin(this)); + // m_widgets.append(new EDockWidgetPlugin(this)); m_widgets.append(new EMainWindowPlugin(this)); m_widgets.append(new HistoryViewPlugin(this)); m_widgets.append(new LogViewPlugin(this)); } -QList QADApplication::customWidgets() const { +QList QADApplication::customWidgets() const { return m_widgets; } diff --git a/libs/application/plugin/qad_application.h b/libs/application/plugin/qad_application.h index 5ccdcbd..b9761f3 100644 --- a/libs/application/plugin/qad_application.h +++ b/libs/application/plugin/qad_application.h @@ -1,23 +1,24 @@ #ifndef QAD_APPLICATION_H #define QAD_APPLICATION_H -#include #include +#include -class QADApplication: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADApplication + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.application") #endif + public: explicit QADApplication(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_APPLICATION_H diff --git a/libs/application/qsingleapplication.cpp b/libs/application/qsingleapplication.cpp index 428c4bb..d6f8992 100644 --- a/libs/application/qsingleapplication.cpp +++ b/libs/application/qsingleapplication.cpp @@ -1,6 +1,7 @@ -#include #include "qsingleapplication.h" +#include + #define QSA_SHMSIZE 4096 #define QSA_MSGSIZE (QSA_SHMSIZE - sizeof(quint32) - sizeof(quint32)) @@ -9,12 +10,11 @@ QSingleApplication::QSingleApplication(const QString & app_name): QThread() { shm.setKey(app_name); exiting = false; - first = !shm.attach(); + first = !shm.attach(); if (!first) { shm.detach(); first = !shm.attach(); - if (!first) - return; + if (!first) return; } shm.create(QSA_SHMSIZE); shm.attach(); @@ -23,7 +23,7 @@ QSingleApplication::QSingleApplication(const QString & app_name): QThread() { if (d) memset(d, 0, sizeof(quint32)); shm.unlock(); start(); - //qDebug() << "start listen"; + // qDebug() << "start listen"; } @@ -31,15 +31,14 @@ QSingleApplication::~QSingleApplication() { if (first) { exiting = true; quit(); - if (!wait(100)) - terminate(); + if (!wait(100)) terminate(); } if (shm.isAttached()) shm.detach(); } void QSingleApplication::sendMessage(const QByteArray & m) { - //qDebug() << "send message" << first << shm.isAttached(); + // qDebug() << "send message" << first << shm.isAttached(); if (first || !shm.isAttached()) return; if (m.size() > int(QSA_MSGSIZE)) { qDebug() << "[QSingleApplication] Too large message:" << m.size() << ">" << QSA_MSGSIZE; @@ -52,8 +51,8 @@ void QSingleApplication::sendMessage(const QByteArray & m) { memcpy(&num, d, sizeof(quint32)); num++; memcpy(d, &num, sizeof(quint32)); - memcpy((((char*)d) + sizeof(quint32)), &size, sizeof(quint32)); - memcpy((((char*)d) + sizeof(quint32) + sizeof(quint32)), m.constData(), size); + memcpy((((char *)d) + sizeof(quint32)), &size, sizeof(quint32)); + memcpy((((char *)d) + sizeof(quint32) + sizeof(quint32)), m.constData(), size); } shm.unlock(); } @@ -68,12 +67,12 @@ void QSingleApplication::run() { memcpy(&num, d, sizeof(quint32)); if (pnum != num) { pnum = num; - //qDebug() << "new message" << num; - memcpy(&size, (((const char*)d) + sizeof(quint32)), sizeof(quint32)); + // qDebug() << "new message" << num; + memcpy(&size, (((const char *)d) + sizeof(quint32)), sizeof(quint32)); if (size <= int(QSA_MSGSIZE)) { QByteArray msg; msg.resize(size); - memcpy(msg.data(), (((const char*)d) + sizeof(quint32) + sizeof(quint32)), size); + memcpy(msg.data(), (((const char *)d) + sizeof(quint32) + sizeof(quint32)), size); emit messageReceived(msg); } else { qDebug() << "[QSingleApplication] Invalid message size:" << size; diff --git a/libs/application/qsingleapplication.h b/libs/application/qsingleapplication.h index 3c6163b..26d0ceb 100644 --- a/libs/application/qsingleapplication.h +++ b/libs/application/qsingleapplication.h @@ -1,51 +1,51 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QSINGLEAPPLICATION_H #define QSINGLEAPPLICATION_H -#include -#include #include "qad_application_export.h" +#include +#include -class QAD_APPLICATION_EXPORT QSingleApplication: public QThread -{ + +class QAD_APPLICATION_EXPORT QSingleApplication: public QThread { Q_OBJECT + public: QSingleApplication(const QString & app_name = QString("qapp")); ~QSingleApplication(); - - bool isFirst() const {return first;} - + + bool isFirst() const { return first; } + private: void run(); - + QSharedMemory shm; bool first, exiting; - + public slots: void sendMessage(const QByteArray & m); - + signals: void messageReceived(QByteArray); - }; #endif // QSINGLEAPPLICATION_H diff --git a/libs/application/ribbon.cpp b/libs/application/ribbon.cpp index f87f999..54ebf3f 100644 --- a/libs/application/ribbon.cpp +++ b/libs/application/ribbon.cpp @@ -1,49 +1,45 @@ #include "ribbon.h" + #include "qad_types.h" + #include Ribbon::Ribbon(QMainWindow * parent_): QToolBar() { - tab = 0; + tab = 0; scroll_area = 0; - delay_e = true; - delay = 1000; - hovered = -1; + delay_e = true; + delay = 1000; + hovered = -1; setObjectName("ribbon"); setProperty("ribbon", true); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); parent = parent_; - if (parent_) - parent_->installEventFilter(this); + if (parent_) parent_->installEventFilter(this); init(); } -Ribbon::~Ribbon() { -} +Ribbon::~Ribbon() {} bool Ribbon::eventFilter(QObject * o, QEvent * e) { - //qDebug() << e; + // qDebug() << e; if (o == parent) { - if (e->type() == QEvent::Resize || e->type() == QEvent::WindowActivate) - _resize(); - if (e->type() == QEvent::FontChange || e->type() == QEvent::Polish) - _setIconsSize(); + if (e->type() == QEvent::Resize || e->type() == QEvent::WindowActivate) _resize(); + if (e->type() == QEvent::FontChange || e->type() == QEvent::Polish) _setIconsSize(); return QToolBar::eventFilter(o, e); } if (e->type() == QEvent::ActionChanged) { - QToolButton * b = qobject_cast((QObject * )o->property("ribbonButton").toLongLong()); - if (b != 0) - b->setEnabled(qobject_cast(o)->isEnabled()); + QToolButton * b = qobject_cast((QObject *)o->property("ribbonButton").toLongLong()); + if (b != 0) b->setEnabled(qobject_cast(o)->isEnabled()); } return QToolBar::eventFilter(o, e); } void Ribbon::timerEvent(QTimerEvent * e) { - if (hovers.value(e->timerId(), -1) == hovered) - tab->setCurrentIndex(hovered); + if (hovers.value(e->timerId(), -1) == hovered) tab->setCurrentIndex(hovered); hovers.remove(e->timerId()); killTimer(e->timerId()); } @@ -52,11 +48,8 @@ void Ribbon::timerEvent(QTimerEvent * e) { void Ribbon::changeEvent(QEvent * e) { QToolBar::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslate(); - break; - default: - break; + case QEvent::LanguageChange: retranslate(); break; + default: break; } } @@ -64,16 +57,16 @@ void Ribbon::changeEvent(QEvent * e) { void Ribbon::_resize() { return; // WARNING for (int i = 0; i < tab->count(); ++i) { - int h = ((QScrollArea*)(tab->widget(i)))->sizeHint().height(); - if (((QScrollArea*)(tab->widget(i)))->horizontalScrollBar()->isVisible()) - h += ((QScrollArea*)(tab->widget(i)))->horizontalScrollBar()->height(); - ((QScrollArea*)(tab->widget(i)))->setMinimumHeight(h); + int h = ((QScrollArea *)(tab->widget(i)))->sizeHint().height(); + if (((QScrollArea *)(tab->widget(i)))->horizontalScrollBar()->isVisible()) + h += ((QScrollArea *)(tab->widget(i)))->horizontalScrollBar()->height(); + ((QScrollArea *)(tab->widget(i)))->setMinimumHeight(h); } } void Ribbon::_setIconsSize() { - //qDebug() << "resize" << preferredIconSize() << QApplication::font(); + // qDebug() << "resize" << preferredIconSize() << QApplication::font(); setTabIconSize(preferredIconSize(2, this)); setIconSize(preferredIconSize(3, this)); } @@ -86,7 +79,6 @@ void Ribbon::_setButtonText(QToolButton * b, QAction * a) { sc += "\n" + s.toString(QKeySequence::NativeText); } b->setToolTip(a->text() + sc); - } @@ -101,11 +93,10 @@ void Ribbon::setVisible(bool yes) { void Ribbon::init() { if (parent == 0) return; if (parent->menuBar() == 0) return; - QList lm = parent->menuBar()->actions(), la; + QList lm = parent->menuBar()->actions(), la; QString prev_tab; if (tab) { - if (tab->currentIndex() >= 0) - prev_tab = tab->tabText(tab->currentIndex()); + if (tab->currentIndex() >= 0) prev_tab = tab->tabText(tab->currentIndex()); tab->deleteLater(); } clear(); @@ -117,24 +108,24 @@ void Ribbon::init() { connect(tab, SIGNAL(currentChanged(int)), this, SIGNAL(currentTabChanged(int))); tab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QFrame * g; - QBoxLayout * l, * tl; + QBoxLayout *l, *tl; QToolButton * b; - //tab->setIconSize(QSize(32, 32)); + // tab->setIconSize(QSize(32, 32)); for (QAction * i: lm) { if (!i->menu()) continue; - //if (!i->menu()->isVisible()) continue; - la = i->menu()->actions(); + // if (!i->menu()->isVisible()) continue; + la = i->menu()->actions(); QIcon tic = i->icon(); if (!tic.isNull()) i->setProperty("__icon", QVariant::fromValue(tic)); else tic = i->property("__icon").value(); -//#ifdef Q_OS_MACOS -// tic = QIcon(); -//#endif + // #ifdef Q_OS_MACOS + // tic = QIcon(); + // #endif tab->addTab(new QWidget(), tic, i->text()); - //qDebug() << this << i->icon() << i->text(); - //continue; + // qDebug() << this << i->icon() << i->text(); + // continue; /*QScrollArea * sa = new QScrollArea(); sa->setWidget(new QWidget()); sa->setWidgetResizable(true); @@ -143,7 +134,7 @@ void Ribbon::init() { sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); sa->setFrameShape(QFrame::NoFrame); tab->addTab(sa, i->icon(), i->text());*/ - tab->widget(tab->count() - 1)->setProperty("ribbonAction", qlonglong((void * )i)); + tab->widget(tab->count() - 1)->setProperty("ribbonAction", qlonglong((void *)i)); i->setIcon(QIcon()); tl = new QBoxLayout(QBoxLayout::LeftToRight); tl->setSpacing(2); @@ -152,7 +143,8 @@ void Ribbon::init() { #else tl->setContentsMargins(2, 0, 2, 2); #endif - g = new QFrame(); g->setFrameShape(QFrame::StyledPanel); + g = new QFrame(); + g->setFrameShape(QFrame::StyledPanel); l = new QBoxLayout(QBoxLayout::LeftToRight); g->setLayout(l); l->setSpacing(2); @@ -161,24 +153,25 @@ void Ribbon::init() { if (j->isSeparator()) { if (l->isEmpty()) continue; tl->addWidget(g); - g = new QFrame(); g->setFrameShape(QFrame::StyledPanel); + g = new QFrame(); + g->setFrameShape(QFrame::StyledPanel); l = new QBoxLayout(QBoxLayout::LeftToRight); l->setSpacing(2); l->setContentsMargins(2, 2, 2, 2); g->setLayout(l); continue; } - if (qobject_cast(j)) { - QWidget * _w = qobject_cast(j)->defaultWidget(); + if (qobject_cast(j)) { + QWidget * _w = qobject_cast(j)->defaultWidget(); l->addWidget(_w); _w->show(); continue; } b = new QToolButton(); - //b->setVisible(j->isVisible()); + // b->setVisible(j->isVisible()); b->setEnabled(j->isEnabled()); - b->setProperty("ribbonAction", qlonglong((void * )j)); - j->setProperty("ribbonButton", qlonglong((void * )b)); + b->setProperty("ribbonAction", qlonglong((void *)j)); + j->setProperty("ribbonButton", qlonglong((void *)b)); j->installEventFilter(this); if (j->menu() != 0) { b->setPopupMode(QToolButton::InstantPopup); @@ -193,11 +186,11 @@ void Ribbon::init() { } else connect(b, SIGNAL(clicked()), j, SLOT(trigger())); } - //b->setIconSize(QSize(16, 16)); + // b->setIconSize(QSize(16, 16)); b->setIcon(j->icon()); _setButtonText(b, j); - //b->addAction(j); - //b->setShortcut(j->shortcut()); + // b->addAction(j); + // b->setShortcut(j->shortcut()); b->setAutoRaise(true); b->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); b->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); @@ -206,10 +199,9 @@ void Ribbon::init() { } tl->addWidget(g); tl->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed)); - //sa->widget()->setLayout(tl); + // sa->widget()->setLayout(tl); tab->widget(tab->count() - 1)->setLayout(tl); - if (i->text() == prev_tab) - tab->setCurrentIndex(tab->count() - 1); + if (i->text() == prev_tab) tab->setCurrentIndex(tab->count() - 1); } setFloatable(false); setMovable(false); @@ -219,7 +211,7 @@ void Ribbon::init() { scroll_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scroll_area->setWidget(tab);*/ _resize(); - //addWidget(scroll_area); + // addWidget(scroll_area); addWidget(tab); parent->addToolBar(Qt::TopToolBarArea, this); parent->menuBar()->hide(); @@ -231,13 +223,13 @@ void Ribbon::init() { void Ribbon::retranslate() { QAction * a; for (QToolButton * i: buttons) { - a = (QAction * )(i->property("ribbonAction").toLongLong()); + a = (QAction *)(i->property("ribbonAction").toLongLong()); if (a == 0) continue; _setButtonText(i, a); - //i->setShortcut(a->shortcut()); + // i->setShortcut(a->shortcut()); } for (int i = 0; i < tab->count(); ++i) { - a = (QAction * )(tab->widget(i)->property("ribbonAction").toLongLong()); + a = (QAction *)(tab->widget(i)->property("ribbonAction").toLongLong()); if (a == 0) continue; tab->setTabText(i, a->text()); } diff --git a/libs/application/ribbon.h b/libs/application/ribbon.h index 916650f..8e5a51a 100644 --- a/libs/application/ribbon.h +++ b/libs/application/ribbon.h @@ -1,42 +1,43 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef RIBBON_H #define RIBBON_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "etabwidget.h" #include "qad_application_export.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -class QAD_APPLICATION_EXPORT Ribbon: public QToolBar -{ + +class QAD_APPLICATION_EXPORT Ribbon: public QToolBar { Q_OBJECT + public: explicit Ribbon(QMainWindow * parent = 0); ~Ribbon(); @@ -45,41 +46,51 @@ public: void retranslate(); void setIconSize(const QSize & size); void setTabIconSize(const QSize & size); - void setButtonStyle(const Qt::ToolButtonStyle & style) {foreach (QToolButton * i, buttons) i->setToolButtonStyle(style);} - void setAutoSwitchEnabled(bool yes) {delay_e = yes;} - void setAutoSwitchDelay(float delay_s) {delay = delay_s * 1000;} - void setCurrentTab(int tab_) {if (tab_ < 0 || tab_ >= tab->count()) return; tab->setCurrentIndex(tab_);} - int currentTab() const {return tab->currentIndex();} - QTabWidget * tabWidget() const {return tab;} + void setButtonStyle(const Qt::ToolButtonStyle & style) { + foreach(QToolButton * i, buttons) + i->setToolButtonStyle(style); + } + void setAutoSwitchEnabled(bool yes) { delay_e = yes; } + void setAutoSwitchDelay(float delay_s) { delay = delay_s * 1000; } + void setCurrentTab(int tab_) { + if (tab_ < 0 || tab_ >= tab->count()) return; + tab->setCurrentIndex(tab_); + } + int currentTab() const { return tab->currentIndex(); } + QTabWidget * tabWidget() const { return tab; } private: bool eventFilter(QObject * o, QEvent * e); void timerEvent(QTimerEvent * e); - void changeEvent(QEvent *e); + void changeEvent(QEvent * e); void _resize(); void _setIconsSize(); void _setButtonText(QToolButton * b, QAction * a); int hovered, delay; bool delay_e; - QList buttons; + QList buttons; QMap hovers; ETabWidget * tab; QScrollArea * scroll_area; QMainWindow * parent; private slots: - void tabHovered(int tab) {if (!delay_e) return; hovers.clear(); hovered = tab; hovers.insert(startTimer(delay), tab);} - + void tabHovered(int tab) { + if (!delay_e) return; + hovers.clear(); + hovered = tab; + hovers.insert(startTimer(delay), tab); + } + public slots: void setVisible(bool yes); - void setHidden(bool yes) {setVisible(!yes);} - void show() {setVisible(true);} - void hide() {setVisible(false);} - + void setHidden(bool yes) { setVisible(!yes); } + void show() { setVisible(true); } + void hide() { setVisible(false); } + signals: void currentTabChanged(int); - }; #endif // RIBBON_H diff --git a/libs/blockview/alignedtextitem.cpp b/libs/blockview/alignedtextitem.cpp index 805bf09..6bab9df 100644 --- a/libs/blockview/alignedtextitem.cpp +++ b/libs/blockview/alignedtextitem.cpp @@ -1,8 +1,10 @@ #include "alignedtextitem.h" + #include "blockbase.h" + #include -#include #include +#include AlignedTextItem::AlignedTextItem(QGraphicsItem * parent): QGraphicsItem(parent), text_(this) { @@ -28,7 +30,7 @@ void AlignedTextItem::setFont(const QFont & f) { QFont AlignedTextItem::sceneFont(const QFont & f) { - QFont ret = f; + QFont ret = f; double scl = 16. / fontHeight(); ret.setPointSizeF(ret.pointSizeF() * scl); return ret; diff --git a/libs/blockview/alignedtextitem.h b/libs/blockview/alignedtextitem.h index 81bf9a6..f70241a 100644 --- a/libs/blockview/alignedtextitem.h +++ b/libs/blockview/alignedtextitem.h @@ -1,67 +1,81 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef ALIGNEDTEXTITEM_H #define ALIGNEDTEXTITEM_H -#include -#include +#include "qad_blockview_export.h" + #include #include -#include "qad_blockview_export.h" +#include +#include class QAD_BLOCKVIEW_EXPORT AlignedTextItem: public QGraphicsItem { public: AlignedTextItem(QGraphicsItem * parent = 0); AlignedTextItem(const QString & text, QGraphicsItem * parent = 0); - - void setText(const QString & t) {text_.setText(t); _move();} + + void setText(const QString & t) { + text_.setText(t); + _move(); + } void setFont(const QFont & f); - void setPen(const QPen & p) {text_.setPen(p); _move();} - void setBrush(const QBrush & b) {text_.setBrush(b); _move();} - void setAlignment(Qt::Alignment align) {align_ = align; _move();} - - QString text() const {return text_.text();} - QFont font() const {return font_;} - QPen pen() const {return text_.pen();} - QBrush brush() const {return text_.brush();} - Qt::Alignment alignment() const {return align_;} - - void clear() {setText(QString());} - - enum {Type = UserType + 0x100}; + void setPen(const QPen & p) { + text_.setPen(p); + _move(); + } + void setBrush(const QBrush & b) { + text_.setBrush(b); + _move(); + } + void setAlignment(Qt::Alignment align) { + align_ = align; + _move(); + } + + QString text() const { return text_.text(); } + QFont font() const { return font_; } + QPen pen() const { return text_.pen(); } + QBrush brush() const { return text_.brush(); } + Qt::Alignment alignment() const { return align_; } + + void clear() { setText(QString()); } + + enum { + Type = UserType + 0x100 + }; static QFont sceneFont(const QFont & f); - + protected: - virtual QRectF boundingRect() const {return text_.boundingRect().translated(text_.pos());} + virtual QRectF boundingRect() const { return text_.boundingRect().translated(text_.pos()); } virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0); - virtual int type() const {return Type;} - - void _move() {text_.setPos(-_point(align_));} + virtual int type() const { return Type; } + + void _move() { text_.setPos(-_point(align_)); } QPointF _point(Qt::Alignment a) const; - + QGraphicsSimpleTextItem text_; Qt::Alignment align_; QFont font_; - }; diff --git a/libs/blockview/blockbase.cpp b/libs/blockview/blockbase.cpp index d93d87c..2fc65f8 100644 --- a/libs/blockview/blockbase.cpp +++ b/libs/blockview/blockbase.cpp @@ -1,20 +1,21 @@ #include "blockbase.h" + #include "alignedtextitem.h" #include "qvariantedit.h" -QDataStream & operator <<(QDataStream & s, const QGraphicsItem * item) { +QDataStream & operator<<(QDataStream & s, const QGraphicsItem * item) { if (!item) { s << int(-1); return s; } - const QGraphicsRectItem * irect = qgraphicsitem_cast(item); - const QGraphicsEllipseItem * iell = qgraphicsitem_cast(item); - const QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(item); - const AlignedTextItem * iatext = qgraphicsitem_cast(item); - const QGraphicsLineItem * iline = qgraphicsitem_cast(item); - const QGraphicsPathItem * ipath = qgraphicsitem_cast(item); - const QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(item); + const QGraphicsRectItem * irect = qgraphicsitem_cast(item); + const QGraphicsEllipseItem * iell = qgraphicsitem_cast(item); + const QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(item); + const AlignedTextItem * iatext = qgraphicsitem_cast(item); + const QGraphicsLineItem * iline = qgraphicsitem_cast(item); + const QGraphicsPathItem * ipath = qgraphicsitem_cast(item); + const QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(item); if (irect) { s << int(0) << (irect->pen()) << (irect->brush()) << (irect->rect()); } else if (iell) { @@ -38,72 +39,181 @@ QDataStream & operator <<(QDataStream & s, const QGraphicsItem * item) { } -QDataStream & operator >>(QDataStream & s, QGraphicsItem *& item) { - int type_; s >> type_; +QDataStream & operator>>(QDataStream & s, QGraphicsItem *& item) { + int type_; + s >> type_; if (type_ < 0) { item = 0; return s; } - QGraphicsRectItem * nrect = 0; - QGraphicsEllipseItem * nell = 0; + QGraphicsRectItem * nrect = 0; + QGraphicsEllipseItem * nell = 0; QGraphicsSimpleTextItem * ntext = 0; - AlignedTextItem * natext = 0; - QGraphicsLineItem * nline = 0; - QGraphicsPathItem * npath = 0; - QGraphicsPixmapItem * npixmap = 0; - item = 0; + AlignedTextItem * natext = 0; + QGraphicsLineItem * nline = 0; + QGraphicsPathItem * npath = 0; + QGraphicsPixmapItem * npixmap = 0; + item = 0; switch (type_) { case 0: - nrect = new QGraphicsRectItem(); item = nrect; - {QPen _v; s >> _v; nrect->setPen(_v);} - {QBrush _v; s >> _v; nrect->setBrush(_v);} - {QRectF _v; s >> _v; nrect->setRect(_v);} + nrect = new QGraphicsRectItem(); + item = nrect; + { + QPen _v; + s >> _v; + nrect->setPen(_v); + } + { + QBrush _v; + s >> _v; + nrect->setBrush(_v); + } + { + QRectF _v; + s >> _v; + nrect->setRect(_v); + } break; case 1: - nell = new QGraphicsEllipseItem(); item = nell; - {QPen _v; s >> _v; nell->setPen(_v);} - {QBrush _v; s >> _v; nell->setBrush(_v);} - {QRectF _v; s >> _v; nell->setRect(_v);} + nell = new QGraphicsEllipseItem(); + item = nell; + { + QPen _v; + s >> _v; + nell->setPen(_v); + } + { + QBrush _v; + s >> _v; + nell->setBrush(_v); + } + { + QRectF _v; + s >> _v; + nell->setRect(_v); + } break; case 2: - ntext = new QGraphicsSimpleTextItem(); item = ntext; - {QPen _v; s >> _v; ntext->setPen(_v);} - {QBrush _v; s >> _v; ntext->setBrush(_v);} - {QFont _v; s >> _v; ntext->setFont(_v);} - {QString _v; s >> _v; ntext->setText(_v);} + ntext = new QGraphicsSimpleTextItem(); + item = ntext; + { + QPen _v; + s >> _v; + ntext->setPen(_v); + } + { + QBrush _v; + s >> _v; + ntext->setBrush(_v); + } + { + QFont _v; + s >> _v; + ntext->setFont(_v); + } + { + QString _v; + s >> _v; + ntext->setText(_v); + } break; case 6: - natext = new AlignedTextItem(); item = natext; - {QPen _v; s >> _v; natext->setPen(_v);} - {QBrush _v; s >> _v; natext->setBrush(_v);} - {QFont _v; s >> _v; natext->setFont(_v);} - {QString _v; s >> _v; natext->setText(_v);} - {int _v; s >> _v; natext->setAlignment((Qt::AlignmentFlag)_v);} + natext = new AlignedTextItem(); + item = natext; + { + QPen _v; + s >> _v; + natext->setPen(_v); + } + { + QBrush _v; + s >> _v; + natext->setBrush(_v); + } + { + QFont _v; + s >> _v; + natext->setFont(_v); + } + { + QString _v; + s >> _v; + natext->setText(_v); + } + { + int _v; + s >> _v; + natext->setAlignment((Qt::AlignmentFlag)_v); + } break; case 3: - nline = new QGraphicsLineItem(); item = nline; - {QPen _v; s >> _v; nline->setPen(_v);} - {QLineF _v; s >> _v; nline->setLine(_v);} + nline = new QGraphicsLineItem(); + item = nline; + { + QPen _v; + s >> _v; + nline->setPen(_v); + } + { + QLineF _v; + s >> _v; + nline->setLine(_v); + } break; case 4: - npath = new QGraphicsPathItem(); item = npath; - {QPen _v; s >> _v; npath->setPen(_v);} - {QPainterPath _v; s >> _v; npath->setPath(_v);} + npath = new QGraphicsPathItem(); + item = npath; + { + QPen _v; + s >> _v; + npath->setPen(_v); + } + { + QPainterPath _v; + s >> _v; + npath->setPath(_v); + } break; case 5: - npixmap = new QGraphicsPixmapItem(); item = npixmap; - {QPixmap _v; s >> _v; npixmap->setPixmap(_v);} + npixmap = new QGraphicsPixmapItem(); + item = npixmap; + { + QPixmap _v; + s >> _v; + npixmap->setPixmap(_v); + } break; case 7: - npixmap = new QGraphicsPixmapItem(); item = npixmap; - {QPixmap _v; s >> _v; npixmap->setPixmap(_v);} - {QTransform _t; s >> _t; npixmap->setTransform(_t);} + npixmap = new QGraphicsPixmapItem(); + item = npixmap; + { + QPixmap _v; + s >> _v; + npixmap->setPixmap(_v); + } + { + QTransform _t; + s >> _t; + npixmap->setTransform(_t); + } break; } if (item) { - {QPointF _v; s >> _v; item->setPos(_v);} - {qreal _v; s >> _v; item->setRotation(_v);} - {int _v; s >> _v; item->setFlags((QGraphicsItem::GraphicsItemFlags)_v);} + { + QPointF _v; + s >> _v; + item->setPos(_v); + } + { + qreal _v; + s >> _v; + item->setRotation(_v); + } + { + int _v; + s >> _v; + item->setFlags((QGraphicsItem::GraphicsItemFlags)_v); + } } return s; } diff --git a/libs/blockview/blockbase.h b/libs/blockview/blockbase.h index fe62f19..cfa9bc1 100644 --- a/libs/blockview/blockbase.h +++ b/libs/blockview/blockbase.h @@ -1,52 +1,53 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKBASE_H #define BLOCKBASE_H -#include -#include +#include "qad_blockview_export.h" +#include "qad_types.h" + +#include #include #include -#include +#include #include #include +#include #include -#include "qad_types.h" -#include "qad_blockview_export.h" static const int _blockitem_current_version_ = 1; enum BlockviewItemData { - bvidSelected = 1000, // bool - bvidType , // BlockviewItemType - bvidItemPos , // QPointF - bvidDecorText , // QString src text for QGraphicsSimpleTextItem - bvidMoveParent , // bool flag for move parent - bvidVisualizeSelection , // bool flag for visualize selection - bvidItemSelection , // bool BlockItem selection - bvidTmpItem , // bool item is temporary, ignore - bvidBlockDecor , // bool item is BlockItem decor - bvidDTHandle , // bool - bvidCorrectMove , // bool + bvidSelected = 1000, // bool + bvidType, // BlockviewItemType + bvidItemPos, // QPointF + bvidDecorText, // QString src text for QGraphicsSimpleTextItem + bvidMoveParent, // bool flag for move parent + bvidVisualizeSelection, // bool flag for visualize selection + bvidItemSelection, // bool BlockItem selection + bvidTmpItem, // bool item is temporary, ignore + bvidBlockDecor, // bool item is BlockItem decor + bvidDTHandle, // bool + bvidCorrectMove, // bool }; enum BlockviewItemType { @@ -57,16 +58,15 @@ enum BlockviewItemType { bvitDecor, }; -QAD_BLOCKVIEW_EXPORT QDataStream & operator <<(QDataStream & s, const QGraphicsItem * item); -QAD_BLOCKVIEW_EXPORT QDataStream & operator >>(QDataStream & s, QGraphicsItem *& item); +QAD_BLOCKVIEW_EXPORT QDataStream & operator<<(QDataStream & s, const QGraphicsItem * item); +QAD_BLOCKVIEW_EXPORT QDataStream & operator>>(QDataStream & s, QGraphicsItem *& item); -class QAD_BLOCKVIEW_EXPORT BlockItemBase: public QObject -{ +class QAD_BLOCKVIEW_EXPORT BlockItemBase: public QObject { Q_OBJECT Q_ENUMS(Action) + public: - enum Action { BlockAdd = 1, BlockMove, @@ -82,7 +82,6 @@ public: BusSegmentRemove, Paste }; - }; #endif // BLOCKBASE_H diff --git a/libs/blockview/blockbusitem.cpp b/libs/blockview/blockbusitem.cpp index 14be82f..6b8bcf5 100644 --- a/libs/blockview/blockbusitem.cpp +++ b/libs/blockview/blockbusitem.cpp @@ -1,12 +1,15 @@ #include "blockview.h" + #include BlockBusItem::BlockBusItem(bool temp): QGraphicsObject(), PropertyStorage() { temp_ = temp; _init(); - if (!temp) setData(bvidType, bvitBus); - else hide(); + if (!temp) + setData(bvidType, bvitBus); + else + hide(); } @@ -17,12 +20,12 @@ BlockBusItem::BlockBusItem(const BlockBusItem & other): QGraphicsObject(), Prope setPen(other.pen()); setBrush(other.brush()); setBusType(other.busType()); - square_node = other.square_node; - max_ep = other.max_ep; - pol = other.pol; - segments = other.segments; - im_bus = other.im_bus; - im_end = other.im_end; + square_node = other.square_node; + max_ep = other.max_ep; + pol = other.pol; + segments = other.segments; + im_bus = other.im_bus; + im_end = other.im_end; im_bus_scale = other.im_bus_scale; im_end_scale = other.im_end_scale; updateGeometry(); @@ -33,26 +36,34 @@ void BlockBusItem::_init() { setZValue(1.); setBusType(-1); setAcceptHoverEvents(true); - ph.setColor(Qt::blue); ph.setJoinStyle(Qt::MiterJoin); - bh.setColor(Qt::blue); bh.setStyle(Qt::SolidPattern); - pu = pa = pr = ph; bu = ba = br = bh; - grid_step = 10.; + ph.setColor(Qt::blue); + ph.setJoinStyle(Qt::MiterJoin); + bh.setColor(Qt::blue); + bh.setStyle(Qt::SolidPattern); + pu = pa = pr = ph; + bu = ba = br = bh; + grid_step = 10.; pu.setWidth(1); - pu.setColor(Qt::black); bu.setColor(Qt::black); - pa.setColor(Qt::darkGreen); ba.setColor(Qt::darkGreen); - pr.setColor(Qt::darkRed); br.setColor(Qt::darkRed); - pn.setColor(Qt::gray); pn.setStyle(Qt::DashLine); + pu.setColor(Qt::black); + bu.setColor(Qt::black); + pa.setColor(Qt::darkGreen); + ba.setColor(Qt::darkGreen); + pr.setColor(Qt::darkRed); + br.setColor(Qt::darkRed); + pn.setColor(Qt::gray); + pn.setStyle(Qt::DashLine); if (temp_) { pu.setStyle(Qt::DashLine); pu.setColor(Qt::darkGray); bu.setColor(Qt::darkGray); } - setPen(pu); setBrush(bu); + setPen(pu); + setBrush(bu); square_node = false; - max_ep = 0; + max_ep = 0; selPoint = selSegment = state_ = -1; - pen_width = 2.; - point_size = 3.; + pen_width = 2.; + point_size = 3.; im_bus_scale = im_end_scale = 1.; moved = deleted = mark_in = mark_out = new_segment = mm_cancel = lm_point = false; anim_point_size.setTargetObject(this); @@ -68,19 +79,19 @@ void BlockBusItem::reconnect() { if (temp_) return; if (!scene()) return; if (scene()->views().isEmpty()) return; - qobject_cast(scene()->views().back())->reconnectAll(); + qobject_cast(scene()->views().back())->reconnectAll(); } bool BlockBusItem::sceneEvent(QEvent * e) { if (temp_) return QGraphicsObject::sceneEvent(e); switch (e->type()) { - case QEvent::GraphicsSceneHoverEnter: hoverEnterEvent((QGraphicsSceneHoverEvent * )e); break; - case QEvent::GraphicsSceneHoverMove: hoverMoveEvent((QGraphicsSceneHoverEvent * )e); break; - case QEvent::GraphicsSceneHoverLeave: hoverLeaveEvent((QGraphicsSceneHoverEvent * )e); break; - case QEvent::GraphicsSceneMousePress: mousePressEvent((QGraphicsSceneMouseEvent * )e); break; - case QEvent::GraphicsSceneMouseMove: mouseMoveEvent((QGraphicsSceneMouseEvent * )e); break; - case QEvent::GraphicsSceneMouseRelease: mouseReleaseEvent((QGraphicsSceneMouseEvent * )e); break; + case QEvent::GraphicsSceneHoverEnter: hoverEnterEvent((QGraphicsSceneHoverEvent *)e); break; + case QEvent::GraphicsSceneHoverMove: hoverMoveEvent((QGraphicsSceneHoverEvent *)e); break; + case QEvent::GraphicsSceneHoverLeave: hoverLeaveEvent((QGraphicsSceneHoverEvent *)e); break; + case QEvent::GraphicsSceneMousePress: mousePressEvent((QGraphicsSceneMouseEvent *)e); break; + case QEvent::GraphicsSceneMouseMove: mouseMoveEvent((QGraphicsSceneMouseEvent *)e); break; + case QEvent::GraphicsSceneMouseRelease: mouseReleaseEvent((QGraphicsSceneMouseEvent *)e); break; default: break; } return QGraphicsObject::sceneEvent(e); @@ -95,7 +106,7 @@ int BlockBusItem::addPoint(const QPointF & point, bool update) { selPoint = pol.size() - 1; segments << QPair(selPoint, segments[selSegment].second); segments[selSegment].second = selPoint; - selSegment = -1; + selSegment = -1; updateGeometry(); if (scene() != 0 && update) scene()->update(); return pol.size() - 1; @@ -122,32 +133,33 @@ void BlockBusItem::removePoint(int index) { if (index < 0 || index > pol.size() - 1) return; int sc = 0, fs = -1, ss = -1; for (int i = 0; i < segments.size(); ++i) - if (segments[i].first == index || - segments[i].second == index) { - sc++; - if (fs < 0) fs = i; - else ss = i; + if (segments[i].first == index || segments[i].second == index) { + sc++; + if (fs < 0) + fs = i; + else + ss = i; } int ei(0); switch (sc) { - case 1: - segments.removeAt(fs); - break; + case 1: segments.removeAt(fs); break; case 2: - if (segments[ss].first == index) ei = segments[ss].second; - else ei = segments[ss].first; - if (segments[fs].first == index) segments[fs].first = ei; - else segments[fs].second = ei; + if (segments[ss].first == index) + ei = segments[ss].second; + else + ei = segments[ss].first; + if (segments[fs].first == index) + segments[fs].first = ei; + else + segments[fs].second = ei; segments.removeAt(ss); break; default: return; } pol.remove(index); for (int i = 0; i < segments.size(); ++i) { - if (segments[i].first >= index) - segments[i].first--; - if (segments[i].second >= index) - segments[i].second--; + if (segments[i].first >= index) segments[i].first--; + if (segments[i].second >= index) segments[i].second--; } selPoint = -1; checkDelete(); @@ -162,25 +174,19 @@ void BlockBusItem::removeSegment(int index) { if (pif > pis) qSwap(pif, pis); int scf = 0, scs = 0; for (int i = 0; i < segments.size(); ++i) { - if (segments[i].first == pif || - segments[i].second == pif) - scf++; - if (segments[i].first == pis || - segments[i].second == pis) - scs++; + if (segments[i].first == pif || segments[i].second == pif) scf++; + if (segments[i].first == pis || segments[i].second == pis) scs++; } if (scs <= 2) removePoint(pis); if (scf <= 2) removePoint(pif); if (scs <= 2 || scf <= 2) selSegment = -1; if (scene() != 0) scene()->update(); - } void BlockBusItem::appendPoint(const QPointF & p) { pol << p; - if (pol.size() > 1) - segments << QPair(pol.size() - 2, pol.size() - 1); + if (pol.size() > 1) segments << QPair(pol.size() - 2, pol.size() - 1); updateGeometry(); } @@ -229,13 +235,13 @@ void BlockBusItem::setSquareNodes(bool yes) { void BlockBusItem::markAsInput() { - mark_in = true; + mark_in = true; mark_out = false; } void BlockBusItem::markAsOutput() { - mark_in = false; + mark_in = false; mark_out = true; } @@ -266,17 +272,23 @@ void BlockBusItem::simplify(bool full) { int s0 = segs[0], s1 = segs[1]; QPointF cp = pol[p], sp[2]; for (int i = 0; i < 2; ++i) { - if (segments[segs[i]].first == p) sp[i] = pol[segments[segs[i]].second]; - else sp[i] = pol[segments[segs[i]].first]; + if (segments[segs[i]].first == p) + sp[i] = pol[segments[segs[i]].second]; + else + sp[i] = pol[segments[segs[i]].first]; } QLineF l0(sp[0], cp), l1(cp, sp[1]); if (qAbs(l0.angle() - l1.angle()) > 0.1) continue; if (segments[s0].first == p) { - if (segments[s1].first == p) segments[s0].first = segments[s1].second; - else segments[s0].first = segments[s1].first; + if (segments[s1].first == p) + segments[s0].first = segments[s1].second; + else + segments[s0].first = segments[s1].first; } else { - if (segments[s1].first == p) segments[s0].second = segments[s1].second; - else segments[s0].second = segments[s1].first; + if (segments[s1].first == p) + segments[s0].second = segments[s1].second; + else + segments[s0].second = segments[s1].first; } segments.removeAt(s1); pol.remove(p); @@ -292,8 +304,7 @@ void BlockBusItem::simplify(bool full) { } -void BlockBusItem::adjustLine() { -} +void BlockBusItem::adjustLine() {} int BlockBusItem::endpointCount() const { @@ -301,16 +312,16 @@ int BlockBusItem::endpointCount() const { } -QList BlockBusItem::connectedBlocks() const { - QList pins = connections_.values(); - QSet ret; - foreach (BlockItemPin * p, pins) +QList BlockBusItem::connectedBlocks() const { + QList pins = connections_.values(); + QSet ret; + foreach(BlockItemPin * p, pins) ret << p->parent(); return ret.values(); } -QList BlockBusItem::connectedPins() const { +QList BlockBusItem::connectedPins() const { return connections_.values(); } @@ -318,14 +329,14 @@ QList BlockBusItem::connectedPins() const { BlockBusItem::PointInfo BlockBusItem::pointInfo(QPointF pos) const { PointInfo ret; int pi = -1, si = -1; - testPoint(pos, &pi, & si); + testPoint(pos, &pi, &si); if (pi < 0 && si < 0) return ret; if (si >= 0) { ret.type = PointInfo::Type::Segment; } else { if (endpoints().contains(pi)) { ret.type = PointInfo::Type::Endpoint; - ret.pin = connections_.value(pi, nullptr); + ret.pin = connections_.value(pi, nullptr); } else ret.type = PointInfo::Type::Node; } @@ -350,9 +361,8 @@ void BlockBusItem::clearBusState() { QByteArray BlockBusItem::save() const { ChunkStream cs; - cs << cs.chunk(1, busType()) << cs.chunk(2, busName()) << cs.chunk(3, width()) << cs.chunk(4, pen()) - << cs.chunk(5, brush()) << cs.chunk(6, pol) << cs.chunk(7, segments) << cs.chunk(8, props) - << cs.chunk(9, im_bus_scale) << cs.chunk(10, im_end_scale); + cs << cs.chunk(1, busType()) << cs.chunk(2, busName()) << cs.chunk(3, width()) << cs.chunk(4, pen()) << cs.chunk(5, brush()) + << cs.chunk(6, pol) << cs.chunk(7, segments) << cs.chunk(8, props) << cs.chunk(9, im_bus_scale) << cs.chunk(10, im_end_scale); return cs.data(); } @@ -369,9 +379,9 @@ void BlockBusItem::load(const QByteArray & data) { case 4: setPen(cs.getData()); break; case 5: setBrush(cs.getData()); break; case 6: pol = cs.getData(); break; - case 7: segments = cs.getData > >(); break; - case 8: props = cs.getData >(); break; - case 9: im_bus_scale = cs.getData(); break; + case 7: segments = cs.getData>>(); break; + case 8: props = cs.getData>(); break; + case 9: im_bus_scale = cs.getData(); break; case 10: im_end_scale = cs.getData(); break; } } @@ -387,16 +397,16 @@ BlockBusItem * BlockBusItem::copy() const { void BlockBusItem::saveState() { segments_s = segments; ends_ind_s = ends_ind; - ends_s = ends; - pol_s = pol; + ends_s = ends; + pol_s = pol; } void BlockBusItem::restoreState() { segments = segments_s; ends_ind = ends_ind_s; - ends = ends_s; - pol = pol_s; + ends = ends_s; + pol = pol_s; } @@ -429,8 +439,8 @@ bool BlockBusItem::checkDelete() { void BlockBusItem::emitAction(BlockItemBase::Action a) { - qobject_cast(scene()->views().back())->schemeAction(a, QList() << this); - qobject_cast(scene()->views().back())->connectionsChanged(); + qobject_cast(scene()->views().back())->schemeAction(a, QList() << this); + qobject_cast(scene()->views().back())->connectionsChanged(); } @@ -441,8 +451,7 @@ QVector BlockBusItem::endpoints() const { counts[segments[i].second]++; } for (int i = 0; i < counts.size(); ++i) { - if (counts[i] == 1) - ret << i; + if (counts[i] == 1) ret << i; } return ret; } @@ -455,16 +464,16 @@ QVector BlockBusItem::endpointLine(int ep, double angle) const { if (ep < 0 || np < 0) return ret; if (pol[np] == pol[ep]) return ret; QLineF l(pol[ep], pol[np]); - //qDebug() << "first" << l.angle() << angle << (l.angle() != angle); + // qDebug() << "first" << l.angle() << angle << (l.angle() != angle); if (qAbs(l.angle() - angle) > 0.1) return ret; - //qDebug() << "check next" << segments.size(); + // qDebug() << "check next" << segments.size(); for (int i = 0; i < segments.size(); ++i) { - //qDebug() << i << np << pointSegmentsCount(np); + // qDebug() << i << np << pointSegmentsCount(np); if (np < 0) break; if (pointSegmentsCount(np) != 2) break; if (i > 0) { QLineF l(pol[pp], pol[np]); - //qDebug() << i << l.angle() << angle; + // qDebug() << i << l.angle() << angle; if (qAbs(l.angle() - angle) > 0.1) break; } ret << np; @@ -472,7 +481,6 @@ QVector BlockBusItem::endpointLine(int ep, double angle) const { np = neighborSegmentPoint(np, &seg); } return ret; - } @@ -492,8 +500,14 @@ int BlockBusItem::neighborSegmentPoint(int point, int * seg) const { if (point < 0 || !seg) return -1; for (int i = 0; i < segments.size(); ++i) { if (i == *seg) continue; - if (segments[i].first == point) {*seg = i; return segments[i].second;} - if (segments[i].second == point) {*seg = i; return segments[i].first ;} + if (segments[i].first == point) { + *seg = i; + return segments[i].second; + } + if (segments[i].second == point) { + *seg = i; + return segments[i].first; + } } return -1; } @@ -502,57 +516,58 @@ int BlockBusItem::neighborSegmentPoint(int point, int * seg) const { void BlockBusItem::testPoint(QPointF pos, int * sel_point, int * sel_segment, bool for_trace) const { for (int i = 0; i < pol.size(); ++i) { if ((pol[i] - pos).manhattanLength() <= (for_trace ? 5. : 10.)) { // Point - *sel_point = i; + *sel_point = i; *sel_segment = -1; return; } } for (int i = 0; i < segments.size(); ++i) { if (distPointToLine(pol[segments[i].first], pol[segments[i].second], pos) <= (for_trace ? 5. : 7.)) { // Segment - *sel_point = -1; + *sel_point = -1; *sel_segment = i; return; } } - *sel_point = -1; + *sel_point = -1; *sel_segment = -1; } void BlockBusItem::hoverEnterEvent(QGraphicsSceneHoverEvent * e) { - tt = bus_name + (bus_name.isEmpty() ? "" : "\n\n") - + tr("Add point: Ctrl + LeftClick\n" - "Remove point\\segment: Ctrl + RightClick\n" - "Remove connection: Shift + RightClick\n" - "Move point\\segment: Shift + LeftPress\n" - "Change trace mode: press Shift, when mouse move"); + tt = bus_name + (bus_name.isEmpty() ? "" : "\n\n") + + tr("Add point: Ctrl + LeftClick\n" + "Remove point\\segment: Ctrl + RightClick\n" + "Remove connection: Shift + RightClick\n" + "Move point\\segment: Shift + LeftPress\n" + "Change trace mode: press Shift, when mouse move"); } void BlockBusItem::hoverMoveEvent(QGraphicsSceneHoverEvent * e) { if (temp_) return; QPointF sp = e->scenePos(); - int pp = selPoint; - int ps = selSegment; - bool empt = !(selPoint >= 0 || selSegment >= 0); + int pp = selPoint; + int ps = selSegment; + bool empt = !(selPoint >= 0 || selSegment >= 0); testPoint(sp, &selPoint, &selSegment); BlockView * bv = 0; if (!scene()->views().isEmpty()) { - bv = qobject_cast(scene()->views().back()); + bv = qobject_cast(scene()->views().back()); } - if ((selPoint >= 0 && pp != selPoint) || (selSegment >= 0 && ps != selSegment)) { + if ((selPoint >= 0 && pp != selPoint) || (selSegment >= 0 && ps != selSegment)) { if (bv) { if (bv->isBlockAnimationEnabled()) { setPointSize(0); anim_point_size.start(); } - } else setPointSize(anim_point_size.endValue().toDouble()); + } else + setPointSize(anim_point_size.endValue().toDouble()); } if (selPoint >= 0 || selSegment >= 0) { if (empt) { - QList pins = connectedPins(); - foreach (BlockItemPin * p, pins) { + QList pins = connectedPins(); + foreach(BlockItemPin * p, pins) { p->animAccept(); } } @@ -563,15 +578,15 @@ void BlockBusItem::hoverMoveEvent(QGraphicsSceneHoverEvent * e) { } if (bv) bv->cur_bus = 0; setToolTip(QString()); - QList il = scene()->items(sp, Qt::ContainsItemBoundingRect, Qt::DescendingOrder), bil; + QList il = scene()->items(sp, Qt::ContainsItemBoundingRect, Qt::DescendingOrder), bil; bil << this; for (int i = 0; i < il.size(); ++i) { QGraphicsItem * b = il[i]; if ((b->data(bvidType).toInt() == bvitBus) && b != this) { int tp = -1, ts = -1; - ((BlockBusItem*)b)->testPoint(sp, &tp, &ts); + ((BlockBusItem *)b)->testPoint(sp, &tp, &ts); if (tp >= 0 || ts >= 0) { - foreach (QGraphicsItem * b2, bil) + foreach(QGraphicsItem * b2, bil) b2->stackBefore(b); break; } @@ -585,14 +600,13 @@ void BlockBusItem::hoverMoveEvent(QGraphicsSceneHoverEvent * e) { void BlockBusItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { if (temp_) return; selPoint = selSegment = -1; - setPen(pu); setBrush(bu); + setPen(pu); + setBrush(bu); setToolTip(QString()); anim_point_size.stop(); BlockView * bv = 0; - if (!scene()->views().isEmpty()) - bv = qobject_cast(scene()->views().back()); - if (bv && (QApplication::mouseButtons() == 0)) - bv->cur_bus = 0; + if (!scene()->views().isEmpty()) bv = qobject_cast(scene()->views().back()); + if (bv && (QApplication::mouseButtons() == 0)) bv->cur_bus = 0; update(); QGraphicsObject::hoverLeaveEvent(e); } @@ -601,18 +615,16 @@ void BlockBusItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { void BlockBusItem::mousePressEvent(QGraphicsSceneMouseEvent * e) { if (temp_) return; lp = quantize(e->scenePos(), grid_step); - if (e->button() != Qt::RightButton) - bpol = pol; + if (e->button() != Qt::RightButton) bpol = pol; BlockView * bv = 0; if (!scene()->views().isEmpty()) { - bv = qobject_cast(scene()->views().back()); + bv = qobject_cast(scene()->views().back()); } if (bv) { - if (selPoint >= 0 || selSegment >= 0) - bv->cur_bus = this; + if (selPoint >= 0 || selSegment >= 0) bv->cur_bus = this; } if (new_segment) { - qobject_cast(scene()->views().back())->newBranchCancel(); + qobject_cast(scene()->views().back())->newBranchCancel(); } new_segment = false; if ((selPoint < 0 || selPoint > pol.size() - 1) && (selSegment < 0) && e->modifiers().testFlag(Qt::ShiftModifier)) { @@ -621,23 +633,24 @@ void BlockBusItem::mousePressEvent(QGraphicsSceneMouseEvent * e) { } int btncnt = 0; if ((e->button() == Qt::LeftButton) && e->modifiers().testFlag(Qt::ShiftModifier)) { - if (endpoints().contains(selPoint)) qobject_cast(scene()->views().back())->startBusPointMove(bus_type); + if (endpoints().contains(selPoint)) qobject_cast(scene()->views().back())->startBusPointMove(bus_type); } - if (e->buttons().testFlag(Qt::LeftButton )) btncnt++; + if (e->buttons().testFlag(Qt::LeftButton)) btncnt++; if (e->buttons().testFlag(Qt::RightButton)) btncnt++; - if (e->buttons().testFlag(QT_MID_BUTTON )) btncnt++; + if (e->buttons().testFlag(QT_MID_BUTTON)) btncnt++; if (btncnt > 0) mm_mods = e->modifiers(); if (btncnt >= 2 && e->button() == Qt::RightButton) { - //qDebug() << "bus revert"; + // qDebug() << "bus revert"; mm_cancel = true; - moved = false; - pol = bpol; + moved = false; + pol = bpol; prepareGeometryChange(); return; } if (e->buttons().testFlag(Qt::LeftButton) && e->modifiers().testFlag(Qt::NoModifier)) { if (selSegment >= 0) - press_pos = quantize(nearestPointOnLine(pol[segments[selSegment].first], pol[segments[selSegment].second], e->scenePos()), grid_step); + press_pos = + quantize(nearestPointOnLine(pol[segments[selSegment].first], pol[segments[selSegment].second], e->scenePos()), grid_step); else { if (selPoint >= 0) press_pos = pol[selPoint]; @@ -646,10 +659,9 @@ void BlockBusItem::mousePressEvent(QGraphicsSceneMouseEvent * e) { } if (max_ep >= 2) { if (endpointCount() >= max_ep) - if (pointSegmentsCount(selPoint) >= 2 || selSegment >= 0) - return; + if (pointSegmentsCount(selPoint) >= 2 || selSegment >= 0) return; } - qobject_cast(scene()->views().back())->newBranch(this); + qobject_cast(scene()->views().back())->newBranch(this); new_segment = true; return; } @@ -657,7 +669,7 @@ void BlockBusItem::mousePressEvent(QGraphicsSceneMouseEvent * e) { deleteLater(); } if (e->modifiers().testFlag(Qt::ControlModifier)) { - //qDebug() << "remove" << selPoint << selSegment; + // qDebug() << "remove" << selPoint << selSegment; if (e->buttons().testFlag(Qt::RightButton)) { if (selPoint >= 0 && selPoint <= pol.size() - 1) { removePoint(selPoint); @@ -673,8 +685,7 @@ void BlockBusItem::mousePressEvent(QGraphicsSceneMouseEvent * e) { } } if (e->buttons().testFlag(Qt::LeftButton) && selSegment >= 0) { - if (addPoint(e->scenePos()) >= 0) - emitAction(BlockItemBase::BusPointAdd); + if (addPoint(e->scenePos()) >= 0) emitAction(BlockItemBase::BusPointAdd); return; } } @@ -693,12 +704,12 @@ void BlockBusItem::mouseMoveEvent(QGraphicsSceneMouseEvent * e) { } BlockView * bv = 0; if (!scene()->views().isEmpty()) { - bv = qobject_cast(scene()->views().back()); + bv = qobject_cast(scene()->views().back()); } qp = quantize(e->scenePos(), grid_step); lp = qp - lp; if (e->buttons().testFlag(Qt::LeftButton) && mm_mods.testFlag(Qt::NoModifier) && new_segment) { - if (bv) qobject_cast(scene()->views().back())->newBranchTrace(this, e->scenePos()); + if (bv) qobject_cast(scene()->views().back())->newBranchTrace(this, e->scenePos()); return; } if (new_segment) { @@ -707,8 +718,7 @@ void BlockBusItem::mouseMoveEvent(QGraphicsSceneMouseEvent * e) { } else { if (e->buttons().testFlag(Qt::LeftButton)) { lm_point = selPoint >= 0; - if (selPoint >= 0 && selPoint <= pol.size() - 1) - pol[selPoint] += lp; + if (selPoint >= 0 && selPoint <= pol.size() - 1) pol[selPoint] += lp; if (selSegment >= 0 && selSegment <= segments.size() - 1) { pol[segments[selSegment].first] += lp; pol[segments[selSegment].second] += lp; @@ -722,14 +732,14 @@ void BlockBusItem::mouseMoveEvent(QGraphicsSceneMouseEvent * e) { void BlockBusItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * e) { - mm_mods = Qt::KeyboardModifiers(); + mm_mods = Qt::KeyboardModifiers(); int btncnt = 0; - if (e->buttons().testFlag(Qt::LeftButton )) btncnt++; + if (e->buttons().testFlag(Qt::LeftButton)) btncnt++; if (e->buttons().testFlag(Qt::RightButton)) btncnt++; - if (e->buttons().testFlag(QT_MID_BUTTON )) btncnt++; + if (e->buttons().testFlag(QT_MID_BUTTON)) btncnt++; if (btncnt == 0) mm_cancel = false; if (new_segment) { - qobject_cast(scene()->views().back())->newBranchAccept(this); + qobject_cast(scene()->views().back())->newBranchAccept(this); updateGeometry(); selPoint = selSegment = -1; } @@ -739,7 +749,7 @@ void BlockBusItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * e) { emitAction(BlockItemBase::BusPointMove); } else { reconnect(); - emitAction( BlockItemBase::BusSegmentMove); + emitAction(BlockItemBase::BusSegmentMove); } } moved = new_segment = false; diff --git a/libs/blockview/blockbusitem.h b/libs/blockview/blockbusitem.h index 9bef578..7a5d409 100644 --- a/libs/blockview/blockbusitem.h +++ b/libs/blockview/blockbusitem.h @@ -1,20 +1,20 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKBUSITEM_H @@ -24,15 +24,18 @@ #include "qad_blockview_export.h" -class QAD_BLOCKVIEW_EXPORT BlockBusItem: public QGraphicsObject, public PropertyStorage { +class QAD_BLOCKVIEW_EXPORT BlockBusItem + : public QGraphicsObject + , public PropertyStorage { Q_OBJECT Q_INTERFACES(QGraphicsItem) Q_PROPERTY(double pointSize READ pointSize WRITE setPointSize DESIGNABLE false SCRIPTABLE false) friend class BlockView; + public: BlockBusItem(bool temp = false); BlockBusItem(const BlockBusItem & other); - ~BlockBusItem() {;} + ~BlockBusItem() { ; } struct QAD_BLOCKVIEW_EXPORT PointInfo { enum class Type { @@ -41,30 +44,46 @@ public: Endpoint, Segment }; - Type type = Type::None; + Type type = Type::None; BlockItemPin * pin = nullptr; // if tEndpoint and pin connected }; - - void setGridStep(double gs) {grid_step = gs;} - void setEndpointsNumber(int num) {max_ep = num;} - void setImages(const QImage & bus, const QImage & end = QImage()) {im_bus = bus; im_end = end; update();} - void setBusImageScale(double s) {im_bus_scale = s; update();} - void setEndpointImageScale(double s) {im_end_scale = s; update();} - void setBusType(int type_) {bus_type = type_;} - void setBusName(const QString & name) {bus_name = name;} - int busType() const {return bus_type;} - QString busName() const {return bus_name;} - double busImageScale() const {return im_bus_scale;} - double endpointImageScale() const {return im_end_scale;} + + void setGridStep(double gs) { grid_step = gs; } + void setEndpointsNumber(int num) { max_ep = num; } + void setImages(const QImage & bus, const QImage & end = QImage()) { + im_bus = bus; + im_end = end; + update(); + } + void setBusImageScale(double s) { + im_bus_scale = s; + update(); + } + void setEndpointImageScale(double s) { + im_end_scale = s; + update(); + } + void setBusType(int type_) { bus_type = type_; } + void setBusName(const QString & name) { bus_name = name; } + int busType() const { return bus_type; } + QString busName() const { return bus_name; } + double busImageScale() const { return im_bus_scale; } + double endpointImageScale() const { return im_end_scale; } void appendPoint(const QPointF & p); void appendPoint(qreal x, qreal y); void movePolyline(const QPointF & dp); void clear(); - void setPen(const QPen & p) {p_ = p; update();} - QPen pen() const {return p_;} - void setBrush(const QBrush & b) {b_ = b; update();} - QBrush brush() const {return b_;} - double width() const {return pen_width;} + void setPen(const QPen & p) { + p_ = p; + update(); + } + QPen pen() const { return p_; } + void setBrush(const QBrush & b) { + b_ = b; + update(); + } + QBrush brush() const { return b_; } + double width() const { return pen_width; } void setWidth(const double & w); void setColor(const QColor & c); void setSquareNodes(bool yes); @@ -74,24 +93,26 @@ public: void simplify(bool full = true); void adjustLine(); int endpointCount() const; - bool isBusSelected() const {return selSegment >= 0 || selPoint >= 0;} - QList connectedBlocks() const; - QList connectedPins() const; + bool isBusSelected() const { return selSegment >= 0 || selPoint >= 0; } + QList connectedBlocks() const; + QList connectedPins() const; PointInfo pointInfo(QPointF pos) const; - + void setBusState(bool state); - bool busState() const {return state_ > 0;} + bool busState() const { return state_ > 0; } void clearBusState(); - + QByteArray save() const; void load(const QByteArray & data); BlockBusItem * copy() const; void saveState(); void restoreState(); - - enum {Type = UserType + 2}; - + + enum { + Type = UserType + 2 + }; + protected: void _init(); void reconnect(); @@ -108,7 +129,7 @@ protected: QVector endpoints() const; QVector endpointLine(int ep, double angle) const; int neighborSegmentPoint(int point, int * seg) const; - int type() const {return Type;} + int type() const { return Type; } QRectF boundingRect() const; bool sceneEvent(QEvent * e); void hoverEnterEvent(QGraphicsSceneHoverEvent * e); @@ -118,13 +139,13 @@ protected: void mouseMoveEvent(QGraphicsSceneMouseEvent * e); void mouseReleaseEvent(QGraphicsSceneMouseEvent * e); void paint(QPainter * p, const QStyleOptionGraphicsItem * o, QWidget * w = 0); - + QPointF lp, new_start, new_end, press_pos, qp; QPen p_, ph, pu, pa, pr, pn; QBrush b_, bh, bu, ba, br; QString tt, bus_name; - QList > segments, ends_ind, segments_s, ends_ind_s; - QMap connections_; + QList> segments, ends_ind, segments_s, ends_ind_s; + QMap connections_; QVector ends, ends_s; QImage im_bus, im_end; QPolygonF pol, bpol, pol_s; @@ -133,9 +154,9 @@ protected: double pen_width, grid_step, im_bus_scale, im_end_scale; int selPoint, selSegment, max_ep, bus_type, state_; bool moved, deleted, mark_in, mark_out, new_segment, mm_cancel, lm_point; - + private: - double pointSize() const {return point_size;} + double pointSize() const { return point_size; } void setPointSize(double s); double point_size; @@ -143,9 +164,13 @@ private: }; -inline QDataStream & operator <<(QDataStream & s, const BlockBusItem * b) {s << b->save(); return s;} -inline QDataStream & operator >>(QDataStream & s, BlockBusItem *& b) { - QByteArray ba; s >> ba; +inline QDataStream & operator<<(QDataStream & s, const BlockBusItem * b) { + s << b->save(); + return s; +} +inline QDataStream & operator>>(QDataStream & s, BlockBusItem *& b) { + QByteArray ba; + s >> ba; b = new BlockBusItem(); b->load(ba); return s; diff --git a/libs/blockview/blockeditor.cpp b/libs/blockview/blockeditor.cpp index dcf8e09..defd9e1 100644 --- a/libs/blockview/blockeditor.cpp +++ b/libs/blockview/blockeditor.cpp @@ -1,17 +1,19 @@ #include "blockeditor.h" -#include "ui_blockeditor.h" -#include "drawtools.h" + #include "blockview.h" -#include +#include "drawtools.h" +#include "ui_blockeditor.h" + #include -#include #include +#include #include +#include -BlockEditor::BlockEditor(QWidget *parent) : QWidget(parent), ui(new Ui::BlockEditor) { - init = false; - m_editorMode = false; +BlockEditor::BlockEditor(QWidget * parent): QWidget(parent), ui(new Ui::BlockEditor) { + init = false; + m_editorMode = false; m_pinsEditable = true; ui->setupUi(this); src_title = windowTitle(); @@ -20,13 +22,15 @@ BlockEditor::BlockEditor(QWidget *parent) : QWidget(parent), ui(new Ui::BlockEdi ui->blockView->addItem(&block); ui->blockView->viewport()->installEventFilter(this); DrawTools * drawtools = new DrawTools(ui->blockView); - connect(drawtools, SIGNAL(itemCreated(QGraphicsItem*)), this, SLOT(addItem(QGraphicsItem*))); - drawtools->textEditCombo()->addItems(QStringList() << "%name" << "%value" << "%id"); + connect(drawtools, SIGNAL(itemCreated(QGraphicsItem *)), this, SLOT(addItem(QGraphicsItem *))); + drawtools->textEditCombo()->addItems(QStringList() << "%name" + << "%value" + << "%id"); ui->layoutProperties->addWidget(drawtools->propertyWidget()); ui->actionRemove_items->setEnabled(false); ui->button_color->setColor(Qt::lightGray); ui->treePins->setItemDelegateForColumn(1, new PinBusDelegate()); - connect(ui->treePins, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(updateBlock())); + connect(ui->treePins, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(updateBlock())); ui->treePins->viewport()->installEventFilter(this); QToolBar * bar; @@ -39,7 +43,7 @@ BlockEditor::BlockEditor(QWidget *parent) : QWidget(parent), ui(new Ui::BlockEdi bar->setOrientation(Qt::Vertical); bar->addActions(drawtools->actionsForZ()); bar->addSeparator(); - bar->addActions(QList() << ui->actionRemove_items); + bar->addActions(QList() << ui->actionRemove_items); ui->widgetBarZ->setMinimumSize(bar->sizeHint()); init = true; on_buttonClear_clicked(); @@ -64,7 +68,7 @@ void BlockEditor::loadFile(QString path) { } -void BlockEditor::loadModel(const QByteArray &model) { +void BlockEditor::loadModel(const QByteArray & model) { BlockItem b; b.loadModel(model); ui->spin_w->setValue(b.width()); @@ -74,15 +78,15 @@ void BlockEditor::loadModel(const QByteArray &model) { block.loadModel(model); treePinsClear(); ui->treePins->blockSignals(true); - QVector pins = block.pins(); - foreach (BlockItemPin * p, pins) { + QVector pins = block.pins(); + foreach(BlockItemPin * p, pins) { QTreeWidgetItem * ti = new QTreeWidgetItem(QStringList() << p->text() << QString::number(p->busType())); ti->setData(0, Qt::UserRole, qulonglong(p)); ti->setData(0, Qt::UserRole + 1, (int)p->alignment()); ti->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled); pin_tli[p->alignment()]->addChild(ti); } - foreach (QGraphicsItem * i, block.decors()) { + foreach(QGraphicsItem * i, block.decors()) { i->setData(bvidMoveParent, false); i->setData(bvidCorrectMove, true); } @@ -121,7 +125,7 @@ void BlockEditor::selectionChanged() { } -void BlockEditor::addItem(QGraphicsItem *item) { +void BlockEditor::addItem(QGraphicsItem * item) { block.addDecor(item); item->setData(bvidMoveParent, false); item->setData(bvidCorrectMove, true); @@ -138,9 +142,13 @@ void BlockEditor::updateBlock() { void BlockEditor::treePinsClear() { ui->treePins->blockSignals(true); ui->treePins->clear(); - QFont bf(font()); bf.setBold(true); - QList al = QList() << Qt::AlignLeft << Qt::AlignRight << Qt::AlignTop << Qt::AlignBottom; - QStringList an = QStringList() << "Left" << "Right" << "Top" << "Bottom"; + QFont bf(font()); + bf.setBold(true); + QList al = QList() << Qt::AlignLeft << Qt::AlignRight << Qt::AlignTop << Qt::AlignBottom; + QStringList an = QStringList() << "Left" + << "Right" + << "Top" + << "Bottom"; pin_tli.clear(); for (int i = 0; i < al.size(); ++i) { QTreeWidgetItem * ti = new QTreeWidgetItem(); @@ -157,7 +165,7 @@ void BlockEditor::treePinsClear() { } -bool BlockEditor::eventFilter(QObject *o, QEvent *e) { +bool BlockEditor::eventFilter(QObject * o, QEvent * e) { if (!init) QWidget::eventFilter(o, e); if (o == ui->treePins->viewport()) { if (e->type() == QEvent::Drop) { @@ -176,17 +184,15 @@ bool BlockEditor::eventFilter(QObject *o, QEvent *e) { void BlockEditor::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void BlockEditor::on_actionRemove_items_triggered() { - QList si = ui->blockView->scene()->selectedItems(); - foreach (QGraphicsItem * i, si) + QList si = ui->blockView->scene()->selectedItems(); + foreach(QGraphicsItem * i, si) block.removeDecor(i); } @@ -233,10 +239,10 @@ void BlockEditor::on_buttonClear_clicked() { } - void BlockEditor::on_buttonPinAdd_clicked() { ui->treePins->blockSignals(true); - QTreeWidgetItem * ti = new QTreeWidgetItem(QStringList() << "" << "0"); + QTreeWidgetItem * ti = new QTreeWidgetItem(QStringList() << "" + << "0"); ti->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled); ti->setData(0, Qt::UserRole, qulonglong(block.addPin(Qt::AlignLeft, ti->text(1).toInt(), ti->text(0)))); ti->setData(0, Qt::UserRole + 1, (int)Qt::AlignLeft); @@ -265,10 +271,10 @@ void BlockEditor::on_buttonPinDup_clicked() { void BlockEditor::on_buttonPinDelete_clicked() { ui->treePins->blockSignals(true); - QList si = ui->treePins->selectedItems(); - foreach (QTreeWidgetItem * i, si) { + QList si = ui->treePins->selectedItems(); + foreach(QTreeWidgetItem * i, si) { if (!i->parent()) continue; - block.removePin((BlockItemPin*)(i->data(0, Qt::UserRole).toLongLong())); + block.removePin((BlockItemPin *)(i->data(0, Qt::UserRole).toLongLong())); delete i; } ui->treePins->blockSignals(false); @@ -283,7 +289,7 @@ void BlockEditor::on_buttonPinClear_clicked() { void BlockEditor::on_treePins_itemChanged(QTreeWidgetItem * item, int column) { if (!item) return; - BlockItemPin * pin = (BlockItemPin*)item->data(0, Qt::UserRole).toULongLong(); + BlockItemPin * pin = (BlockItemPin *)item->data(0, Qt::UserRole).toULongLong(); if (!pin) return; switch (column) { case 0: @@ -297,16 +303,15 @@ void BlockEditor::on_treePins_itemChanged(QTreeWidgetItem * item, int column) { } - void BlockEditor::arrangePins() { - QVector pins = block.pins(); - QList tli = pin_tli.values(); - foreach (QTreeWidgetItem * ti, tli) { + QVector pins = block.pins(); + QList tli = pin_tli.values(); + foreach(QTreeWidgetItem * ti, tli) { for (int i = 0; i < ti->childCount(); ++i) { - foreach (BlockItemPin * p, pins) - if (p == (BlockItemPin*)(ti->child(i)->data(0, Qt::UserRole).toULongLong())) { + foreach(BlockItemPin * p, pins) + if (p == (BlockItemPin *)(ti->child(i)->data(0, Qt::UserRole).toULongLong())) { p->setAlignment((Qt::Alignment)ti->data(0, Qt::UserRole).toInt()); - BlockItemPin * np = block.addPin(p, false); + BlockItemPin * np = block.addPin(p, false); ti->child(i)->setData(0, Qt::UserRole, qulonglong(np)); ti->child(i)->setData(0, Qt::UserRole + 1, ti->data(0, Qt::UserRole).toInt()); break; @@ -325,11 +330,15 @@ void BlockEditor::arrangePins() { QWidget * PinAlignDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const { QComboBox * combo = new QComboBox(parent); - int cv = index.data().toInt(); - combo->addItem("Left", int(Qt::AlignLeft)); if (cv == Qt::AlignLeft) combo->setCurrentIndex(0); - combo->addItem("Right", int(Qt::AlignRight)); if (cv == Qt::AlignRight) combo->setCurrentIndex(1); - combo->addItem("Top", int(Qt::AlignTop)); if (cv == Qt::AlignTop) combo->setCurrentIndex(2); - combo->addItem("Bottom", int(Qt::AlignBottom)); if (cv == Qt::AlignBottom) combo->setCurrentIndex(3); + int cv = index.data().toInt(); + combo->addItem("Left", int(Qt::AlignLeft)); + if (cv == Qt::AlignLeft) combo->setCurrentIndex(0); + combo->addItem("Right", int(Qt::AlignRight)); + if (cv == Qt::AlignRight) combo->setCurrentIndex(1); + combo->addItem("Top", int(Qt::AlignTop)); + if (cv == Qt::AlignTop) combo->setCurrentIndex(2); + combo->addItem("Bottom", int(Qt::AlignBottom)); + if (cv == Qt::AlignBottom) combo->setCurrentIndex(3); combo->setGeometry(option.rect); return combo; } @@ -348,7 +357,7 @@ QString PinAlignDelegate::displayText(const QVariant & value, const QLocale & lo void PinAlignDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const { - model->setData(index, ((QComboBox*)editor)->itemData(((QComboBox*)editor)->currentIndex()).toInt()); + model->setData(index, ((QComboBox *)editor)->itemData(((QComboBox *)editor)->currentIndex()).toInt()); } @@ -374,6 +383,5 @@ QString PinBusDelegate::displayText(const QVariant & value, const QLocale & loca void PinBusDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const { - model->setData(index, ((QSpinBox*)editor)->value()); + model->setData(index, ((QSpinBox *)editor)->value()); } - diff --git a/libs/blockview/blockeditor.h b/libs/blockview/blockeditor.h index 9d45cb7..b6841b6 100644 --- a/libs/blockview/blockeditor.h +++ b/libs/blockview/blockeditor.h @@ -1,49 +1,50 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKEDITOR_H #define BLOCKEDITOR_H -#include -#include -#include #include "blockitem.h" #include "qad_blockview_export.h" +#include +#include +#include + namespace Ui { - class BlockEditor; +class BlockEditor; } -class QAD_BLOCKVIEW_EXPORT BlockEditor : public QWidget -{ +class QAD_BLOCKVIEW_EXPORT BlockEditor: public QWidget { Q_OBJECT Q_PROPERTY(bool editorMode READ editorMode WRITE setEditorMode) Q_PROPERTY(bool pinsEditable READ pinsEditable WRITE setPinsEditable) + public: - explicit BlockEditor(QWidget *parent = 0); + explicit BlockEditor(QWidget * parent = 0); ~BlockEditor(); - bool editorMode() const {return m_editorMode;} - bool pinsEditable() const {return m_pinsEditable;} + bool editorMode() const { return m_editorMode; } + bool pinsEditable() const { return m_pinsEditable; } public slots: void loadFile(QString path); @@ -67,14 +68,14 @@ private slots: void on_buttonPinDup_clicked(); void on_buttonPinDelete_clicked(); void on_buttonPinClear_clicked(); - void on_treePins_itemChanged(QTreeWidgetItem *item, int column); + void on_treePins_itemChanged(QTreeWidgetItem * item, int column); private: bool eventFilter(QObject * o, QEvent * e); void changeEvent(QEvent * e); - Ui::BlockEditor *ui; - QMap pin_tli; + Ui::BlockEditor * ui; + QMap pin_tli; BlockItem block; QString src_title, cur_file; bool init; @@ -83,26 +84,28 @@ private: }; - class QAD_BLOCKVIEW_EXPORT PinAlignDelegate: public QStyledItemDelegate { Q_OBJECT + public: PinAlignDelegate(QObject * parent = 0): QStyledItemDelegate(parent) {} QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const; QString displayText(const QVariant & value, const QLocale & locale) const; void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; - QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const {return QSize(60, 26);} + QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const { return QSize(60, 26); } }; class QAD_BLOCKVIEW_EXPORT PinBusDelegate: public QStyledItemDelegate { Q_OBJECT + public: PinBusDelegate(QObject * parent = 0): QStyledItemDelegate(parent) {} QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const; QString displayText(const QVariant & value, const QLocale & locale) const; void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; - QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const {return QSize(60, 26);} + QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const { return QSize(60, 26); } + private: typedef QPair ISPair; QVector buses; diff --git a/libs/blockview/blockitem.cpp b/libs/blockview/blockitem.cpp index c447185..949437f 100644 --- a/libs/blockview/blockitem.cpp +++ b/libs/blockview/blockitem.cpp @@ -1,11 +1,11 @@ #include "blockview.h" + #include #define BLOCKITEM_DEFAULT_PIN_MARGIN 20 -BlockItem::BlockItem(QGraphicsItem * parent): QGraphicsObject(parent), PropertyStorage(), -g_main(this), g_selection(this) { +BlockItem::BlockItem(QGraphicsItem * parent): QGraphicsObject(parent), PropertyStorage(), g_main(this), g_selection(this) { setData(bvidType, bvitBlock); setZValue(2.); setAcceptHoverEvents(true); @@ -58,11 +58,9 @@ void BlockItem::_resize(QSizeF s) { void BlockItem::_moveToTop(bool only_decors) { qreal dy = -g_main.rect().center().y() + 10; - if (!only_decors) - moveBy(0., dy); - foreach (QGraphicsItem * d, decors_) + if (!only_decors) moveBy(0., dy); + foreach(QGraphicsItem * d, decors_) d->moveBy(0., -dy); - } @@ -70,30 +68,27 @@ BlockItemPin * BlockItem::addPin(BlockItemPin * pin, bool update_) { pin->setParentItem(this); if (!pins_[pin->alignment()].contains(pin)) pins_[pin->alignment()] << pin; pin->parent_ = this; - if (update_) - arrangePins(); + if (update_) arrangePins(); return pin; } BlockItemPin * BlockItem::addPin(Qt::Alignment align, int bus_type, const QString & text, bool update_) { BlockItemPin * pin = new BlockItemPin(align, bus_type, text, this); - pin->parent_ = this; + pin->parent_ = this; pins_[pin->alignment()] << pin; - if (update_) - arrangePins(); + if (update_) arrangePins(); return pin; } void BlockItem::removePin(BlockItemPin * pin) { if (!pin) return; - QMutableMapIterator > it(pins_); + QMutableMapIterator> it(pins_); while (it.hasNext()) { it.next(); - QVector & pv(it.value()); - if (pv.contains(pin)) - pv.remove(it.value().indexOf(pin)); + QVector & pv(it.value()); + if (pv.contains(pin)) pv.remove(it.value().indexOf(pin)); } delete pin; arrangePins(); @@ -102,12 +97,13 @@ void BlockItem::removePin(BlockItemPin * pin) { void BlockItem::addDecor(QGraphicsItem * item) { if (decors_.contains(item)) return; - if (qgraphicsitem_cast(item)) - qgraphicsitem_cast(item)->setTransformationMode(Qt::SmoothTransformation); - if (qgraphicsitem_cast(item)) - qgraphicsitem_cast(item)->setData(bvidDecorText, qgraphicsitem_cast(item)->text()); - if (qgraphicsitem_cast(item)) - qgraphicsitem_cast(item)->setData(bvidDecorText, qgraphicsitem_cast(item)->text()); + if (qgraphicsitem_cast(item)) + qgraphicsitem_cast(item)->setTransformationMode(Qt::SmoothTransformation); + if (qgraphicsitem_cast(item)) + qgraphicsitem_cast(item)->setData(bvidDecorText, + qgraphicsitem_cast(item)->text()); + if (qgraphicsitem_cast(item)) + qgraphicsitem_cast(item)->setData(bvidDecorText, qgraphicsitem_cast(item)->text()); item->setData(bvidMoveParent, true); item->setData(bvidBlockDecor, true); decors_ << item; @@ -117,12 +113,13 @@ void BlockItem::addDecor(QGraphicsItem * item) { void BlockItem::addDecor(QGraphicsItem & item) { if (decors_.contains(&item)) return; - if (qgraphicsitem_cast(&item)) - qgraphicsitem_cast(&item)->setTransformationMode(Qt::SmoothTransformation); - if (qgraphicsitem_cast(&item)) - qgraphicsitem_cast(&item)->setData(bvidDecorText, qgraphicsitem_cast(&item)->text()); - if (qgraphicsitem_cast(&item)) - qgraphicsitem_cast(&item)->setData(bvidDecorText, qgraphicsitem_cast(&item)->text()); + if (qgraphicsitem_cast(&item)) + qgraphicsitem_cast(&item)->setTransformationMode(Qt::SmoothTransformation); + if (qgraphicsitem_cast(&item)) + qgraphicsitem_cast(&item)->setData(bvidDecorText, + qgraphicsitem_cast(&item)->text()); + if (qgraphicsitem_cast(&item)) + qgraphicsitem_cast(&item)->setData(bvidDecorText, qgraphicsitem_cast(&item)->text()); item.setData(bvidMoveParent, true); item.setData(bvidBlockDecor, true); item.setParentItem(this); @@ -130,22 +127,21 @@ void BlockItem::addDecor(QGraphicsItem & item) { void BlockItem::removeDecor(QGraphicsItem * item) { - if (scene() && item) - scene()->sendEvent(item, new QGraphicsSceneEvent(QEvent::Close)); + if (scene() && item) scene()->sendEvent(item, new QGraphicsSceneEvent(QEvent::Close)); decors_.removeAll(item); delete item; } -QVector BlockItem::takePins() { - QVector ret = pins(); +QVector BlockItem::takePins() { + QVector ret = pins(); pins_.clear(); return ret; } void BlockItem::clearPins() { - QList > mp = pins_.values(); + QList> mp = pins_.values(); for (int i = 0; i < mp.size(); ++i) qDeleteAll(mp[i]); pins_.clear(); @@ -156,7 +152,7 @@ void BlockItem::clearDecors() { bool pbs = false; if (scene()) pbs = scene()->blockSignals(true); if (scene()) { - foreach (QGraphicsItem * i, decors_) + foreach(QGraphicsItem * i, decors_) scene()->sendEvent(i, new QGraphicsSceneEvent(QEvent::Close)); } qDeleteAll(decors_); @@ -168,9 +164,9 @@ void BlockItem::clearDecors() { } -QVector BlockItem::pins() const { - QList > mp = pins_.values(); - QVector ret; +QVector BlockItem::pins() const { + QList> mp = pins_.values(); + QVector ret; for (int i = 0; i < mp.size(); ++i) ret << mp[i]; return ret; @@ -186,15 +182,15 @@ QByteArray BlockItem::saveModel() { void BlockItem::loadModel(const QByteArray & data) { - //qDebug() << "load from" << data.size() << "bytes"; + // qDebug() << "load from" << data.size() << "bytes"; clearPins(); clearDecors(); col = Qt::lightGray; _resize(QSizeF(100., 60.)); if (data.isEmpty()) return; ChunkStream cs(data); - QVector tp; - QList dl; + QVector tp; + QList dl; int version = -1; while (!cs.atEnd()) { switch (cs.read()) { @@ -204,30 +200,32 @@ void BlockItem::loadModel(const QByteArray & data) { case 4: setColor(cs.getData()); break; case 5: cs.get(tp); - foreach (BlockItemPin * p, tp) addPin(p); + foreach(BlockItemPin * p, tp) + addPin(p); break; case 6: cs.get(dl); - foreach (QGraphicsItem * d, dl) addDecor(d); + foreach(QGraphicsItem * d, dl) + addDecor(d); break; case 7: setPinsMargin(cs.getData()); break; case 0xFF: cs.get(version); break; } } - if (version <= 0) - _moveToTop(true); + if (version <= 0) _moveToTop(true); } QByteArray BlockItem::save() const { ChunkStream cs; - QMap > pp; - foreach (BlockItemPin * p, pins()) { - //qDebug() << "save pin" << p->text() << "->" << p->properties().size(); + QMap> pp; + foreach(BlockItemPin * p, pins()) { + // qDebug() << "save pin" << p->text() << "->" << p->properties().size(); pp[p->text()] = p->properties(); } cs << cs.chunk(1, pos()) << cs.chunk(2, rotation()) << cs.chunk(3, props) << cs.chunk(5, pp) << cs.chunk(6, size()); - cs << cs.chunk(10, data(2000)) << cs.chunk(11, data(2001)) << cs.chunk(12, prop_bindings) << cs.chunk(0xFF, _blockitem_current_version_); + cs << cs.chunk(10, data(2000)) << cs.chunk(11, data(2001)) << cs.chunk(12, prop_bindings) + << cs.chunk(0xFF, _blockitem_current_version_); return cs.data(); } @@ -235,7 +233,7 @@ QByteArray BlockItem::save() const { void BlockItem::load(const QByteArray & data) { if (data.isEmpty()) return; ChunkStream cs(data); - QMap > _p; + QMap> _p; int version = -1; while (!cs.atEnd()) { switch (cs.read()) { @@ -244,17 +242,16 @@ void BlockItem::load(const QByteArray & data) { case 3: cs.get(props); break; case 5: cs.get(_p); - //qDebug() << "load pins" << _p.size(); - foreach (BlockItemPin * p, pins()) { - //qDebug() << "load pin" << p->text() << "->" << _p.contains(p->text()); - if (_p.contains(p->text())) - p->properties() = _p[p->text()]; + // qDebug() << "load pins" << _p.size(); + foreach(BlockItemPin * p, pins()) { + // qDebug() << "load pin" << p->text() << "->" << _p.contains(p->text()); + if (_p.contains(p->text())) p->properties() = _p[p->text()]; } break; case 6: setSize(cs.getData()); break; case 10: setData(2000, cs.getData()); break; case 11: setData(2001, cs.getData()); break; - case 12: prop_bindings = cs.getData > >(); break; + case 12: prop_bindings = cs.getData>>(); break; case 0xFF: cs.get(version); break; } } @@ -272,8 +269,8 @@ BlockItem * BlockItem::copy() const { ret->setSelected(false); ret->props = props; ret->setPinsMargin(pinsMargin()); - QVector mp = pins(); - foreach (BlockItemPin * p, mp) { + QVector mp = pins(); + foreach(BlockItemPin * p, mp) { BlockItemPin * np = new BlockItemPin(); np->setBusType(p->busType()); np->setAlignment(p->alignment()); @@ -283,39 +280,38 @@ BlockItem * BlockItem::copy() const { ret->addPin(np); } QByteArray ba; - foreach (QGraphicsItem * i, decors_) { + foreach(QGraphicsItem * i, decors_) { ba.clear(); QGraphicsItem * ni = 0; - QDataStream s(&ba, QIODevice::ReadWrite); s << i; - QDataStream s2(ba); s2 >> ni; - if (ni) - ret->addDecor(ni); + QDataStream s(&ba, QIODevice::ReadWrite); + s << i; + QDataStream s2(ba); + s2 >> ni; + if (ni) ret->addDecor(ni); } return ret; } -QList BlockItem::connectedBuses() const { - QList ret; - foreach (BlockItemPin * p, pins()) +QList BlockItem::connectedBuses() const { + QList ret; + foreach(BlockItemPin * p, pins()) ret << p->connectedBuses(); return ret; } BlockItemPin * BlockItem::pinByText(const QString & t) const { - foreach (BlockItemPin * p, pins()) - if (p->text() == t) - return p; + foreach(BlockItemPin * p, pins()) + if (p->text() == t) return p; return 0; } BlockItemPin * BlockItem::pinAtBus(BlockBusItem * bus) const { if (bus == 0) return 0; - foreach (BlockItemPin * p, pins()) - if (p->connectedBuses().contains(bus)) - return p; + foreach(BlockItemPin * p, pins()) + if (p->connectedBuses().contains(bus)) return p; return 0; } @@ -337,7 +333,8 @@ void BlockItem::hoverEnterEvent(QGraphicsSceneHoverEvent * e) { anim_thick.setStartValue(thickness()); anim_thick.setEndValue(2.5); anim_thick.start(); - } else setThickness(2.5); + } else + setThickness(2.5); emit blockHoverEnter(this); } @@ -349,7 +346,8 @@ void BlockItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { anim_thick.setStartValue(thickness()); anim_thick.setEndValue(1); anim_thick.start(); - } else setThickness(1); + } else + setThickness(1); emit blockHoverLeave(this); } @@ -357,25 +355,29 @@ void BlockItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { #define _POS(m) (i - ((cp.size() - 1) / 2)) * m void BlockItem::arrangePins() { - QVector pl = pins(); + QVector pl = pins(); pins_.clear(); - foreach (BlockItemPin * p, pl) + foreach(BlockItemPin * p, pl) pins_[p->alignment()] << p; - QVector cp = pins_.value(Qt::AlignBottom); - for (int i = 0; i < cp.size(); ++i) cp[i]->setPos(_POS(pins_margin), bottom()); + QVector cp = pins_.value(Qt::AlignBottom); + for (int i = 0; i < cp.size(); ++i) + cp[i]->setPos(_POS(pins_margin), bottom()); cp = pins_.value(Qt::AlignTop); - for (int i = 0; i < cp.size(); ++i) cp[i]->setPos(_POS(pins_margin), top()); + for (int i = 0; i < cp.size(); ++i) + cp[i]->setPos(_POS(pins_margin), top()); cp = pins_.value(Qt::AlignLeft); - for (int i = 0; i < cp.size(); ++i) cp[i]->setPos(left(), i * pins_margin); + for (int i = 0; i < cp.size(); ++i) + cp[i]->setPos(left(), i * pins_margin); cp = pins_.value(Qt::AlignRight); - for (int i = 0; i < cp.size(); ++i) cp[i]->setPos(right(), i * pins_margin); + for (int i = 0; i < cp.size(); ++i) + cp[i]->setPos(right(), i * pins_margin); } #undef _POS void BlockItem::removeBindings(const QString & bind_name) { - for(int i=0; i > & bindings) { +void BlockItem::setBindings(const QList> & bindings) { prop_bindings = bindings; } -QList > BlockItem::getBindings() { +QList> BlockItem::getBindings() { return prop_bindings; } QString BlockItem::getBindName(const QString & prop_name) const { - for(int i=0; iviews().back())->isBlockAnimationEnabled() && t_sel.elapsed() > 50) { g_selection.setRect(enlargedRect(g_main.rect(), 0, 0, 16)); anim_sel.setStartValue(selectionRect()); @@ -490,4 +492,3 @@ QRectF BlockItem::selectionRect() const { void BlockItem::setSelectionRect(const QRectF & r) { g_selection.setRect(r); } - diff --git a/libs/blockview/blockitem.h b/libs/blockview/blockitem.h index 49a0ff1..9e3b693 100644 --- a/libs/blockview/blockitem.h +++ b/libs/blockview/blockitem.h @@ -1,38 +1,41 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKITEM_H #define BLOCKITEM_H -#include #include "blockitempin.h" #include "qad_blockview_export.h" +#include -class QAD_BLOCKVIEW_EXPORT BlockItem: public QGraphicsObject, public PropertyStorage -{ + +class QAD_BLOCKVIEW_EXPORT BlockItem + : public QGraphicsObject + , public PropertyStorage { friend class BlockView; friend class BlockItemPin; friend class DrawTools; Q_OBJECT Q_PROPERTY(double _thickness READ thickness WRITE setThickness DESIGNABLE false SCRIPTABLE false) Q_PROPERTY(QRectF _selRect READ selectionRect WRITE setSelectionRect DESIGNABLE false SCRIPTABLE false) + public: BlockItem(QGraphicsItem * parent = 0); ~BlockItem(); @@ -44,26 +47,32 @@ public: void addDecor(QGraphicsItem * item); void addDecor(QGraphicsItem & item); void removeDecor(QGraphicsItem * item); - QVector takePins(); + QVector takePins(); void clearPins(); void clearDecors(); - QVector pins() const; - QList decors() const {return decors_;} - QList connectedBuses() const; + QVector pins() const; + QList decors() const { return decors_; } + QList connectedBuses() const; BlockItemPin * pinByText(const QString & t) const; BlockItemPin * pinAtBus(BlockBusItem * bus) const; - QColor color() const {return col;} - void setColor(QColor c) {col = c; _resize(size());} - QSizeF size() const {return g_main.rect().size();} + QColor color() const { return col; } + void setColor(QColor c) { + col = c; + _resize(size()); + } + QSizeF size() const { return g_main.rect().size(); } QRectF sceneRect() const; - qreal width() const {return size().width();} - qreal height() const {return size().height();} - int pinsMargin() const {return pins_margin;} - void setSize(QSizeF s) {_resize(s);} - void setSize(qreal w, qreal h) {setSize(QSizeF(w, h));} - void setWidth(qreal w) {setSize(QSizeF(w, size().height()));} - void setHeight(qreal h) {setSize(QSizeF(size().width(), h));} - void setPinsMargin(int marg) {if (marg > 1 && marg < 256) pins_margin = marg; arrangePins();} + qreal width() const { return size().width(); } + qreal height() const { return size().height(); } + int pinsMargin() const { return pins_margin; } + void setSize(QSizeF s) { _resize(s); } + void setSize(qreal w, qreal h) { setSize(QSizeF(w, h)); } + void setWidth(qreal w) { setSize(QSizeF(w, size().height())); } + void setHeight(qreal h) { setSize(QSizeF(size().width(), h)); } + void setPinsMargin(int marg) { + if (marg > 1 && marg < 256) pins_margin = marg; + arrangePins(); + } QByteArray saveModel(); void loadModel(const QByteArray & data); @@ -76,34 +85,36 @@ public: void addBinding(const QString & prop_name, const QString & bind_name); void applyBinding(const QString & bind_name, const QVariant & bind_value); void applyBindings(const PropertyStorage & bindings); - void setBindings(const QList > & bindings); - QList > getBindings(); + void setBindings(const QList> & bindings); + QList> getBindings(); QString getBindName(const QString & prop_name) const; QStringList getBindNames() const; QStringList getBindProps() const; - enum {Type = UserType + 1}; + enum { + Type = UserType + 1 + }; protected: void _resize(QSizeF s); void _moveToTop(bool only_decors = false); - int type() const {return Type;} + int type() const { return Type; } QRectF boundingRect() const; void hoverEnterEvent(QGraphicsSceneHoverEvent * event); void hoverLeaveEvent(QGraphicsSceneHoverEvent * event); - double left() const {return boundingRect().left();} - double right() const {return boundingRect().right();} - double top() const {return boundingRect().top();} - double bottom() const {return boundingRect().bottom();} + double left() const { return boundingRect().left(); } + double right() const { return boundingRect().right(); } + double top() const { return boundingRect().top(); } + double bottom() const { return boundingRect().bottom(); } void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr) {} QVariant itemChange(GraphicsItemChange change, const QVariant & value); QGraphicsRectItem g_main, g_selection; int pins_margin; QColor col; - QMap > pins_; - QList decors_; - QList > prop_bindings; // + QMap> pins_; + QList decors_; + QList> prop_bindings; // private: double thickness() const; @@ -120,28 +131,34 @@ signals: }; -inline QDataStream & operator <<(QDataStream & s, const BlockItemPin * p) { +inline QDataStream & operator<<(QDataStream & s, const BlockItemPin * p) { ChunkStream cs; cs << cs.chunk(1, int(p->alignment())) << cs.chunk(2, p->busType()) << cs.chunk(3, p->text()) << cs.chunk(4, p->toolTip()); - s << cs.data(); return s;} -inline QDataStream & operator >>(QDataStream & s, BlockItemPin *& p) { + s << cs.data(); + return s; +} +inline QDataStream & operator>>(QDataStream & s, BlockItemPin *& p) { ChunkStream cs(s); p = new BlockItemPin(); while (!cs.atEnd()) { switch (cs.read()) { - case 1: p->setAlignment((Qt::Alignment)cs.getData()); break; - case 2: p->setBusType(cs.getData()); break; - case 3: p->setText(cs.getData()); break; - case 4: p->setToolTip(cs.getData()); break; + case 1: p->setAlignment((Qt::Alignment)cs.getData()); break; + case 2: p->setBusType(cs.getData()); break; + case 3: p->setText(cs.getData()); break; + case 4: p->setToolTip(cs.getData()); break; } } return s; } -inline QDataStream & operator <<(QDataStream & s, const BlockItem * b) {s << b->save(); return s;} -inline QDataStream & operator >>(QDataStream & s, BlockItem *& b) { - QByteArray ba; s >> ba; +inline QDataStream & operator<<(QDataStream & s, const BlockItem * b) { + s << b->save(); + return s; +} +inline QDataStream & operator>>(QDataStream & s, BlockItem *& b) { + QByteArray ba; + s >> ba; b = new BlockItem(); b->load(ba); return s; diff --git a/libs/blockview/blockitempin.cpp b/libs/blockview/blockitempin.cpp index 7e058d7..7a70031 100644 --- a/libs/blockview/blockitempin.cpp +++ b/libs/blockview/blockitempin.cpp @@ -1,19 +1,23 @@ #include "blockview.h" + #include -BlockItemPin::BlockItemPin(Qt::Alignment a, int bus_type_, const QString & text_, QGraphicsObject * _parent): QGraphicsObject(_parent), ell_item(this), text_item(this) { +BlockItemPin::BlockItemPin(Qt::Alignment a, int bus_type_, const QString & text_, QGraphicsObject * _parent) + : QGraphicsObject(_parent) + , ell_item(this) + , text_item(this) { parent_ = 0; setData(bvidType, bvitPin); setAcceptHoverEvents(true); text_item.setData(bvidMoveParent, true); ell_item.setData(bvidVisualizeSelection, true); br[Disconnected] = QBrush(Qt::lightGray); - br[Connected] = QBrush(Qt::darkGreen); - br[Hover] = QBrush(Qt::blue); - br[Drop] = QBrush(Qt::green); - br[Accept] = QBrush(Qt::green); - br[Reject] = QBrush(Qt::red); + br[Connected] = QBrush(Qt::darkGreen); + br[Hover] = QBrush(Qt::blue); + br[Drop] = QBrush(Qt::green); + br[Accept] = QBrush(Qt::green); + br[Reject] = QBrush(Qt::red); anim_pin_size.setTargetObject(this); anim_pin_size.setPropertyName("pinSize"); anim_pin_size.setEasingCurve(QEasingCurve::OutElastic); @@ -42,7 +46,7 @@ void BlockItemPin::animAccept() { void BlockItemPin::setState(State s) { State os = state_; - state_ = s; + state_ = s; setBrush(br[int(state_)]); if (s == Accept && os != Accept) { animAccept(); @@ -61,8 +65,7 @@ void BlockItemPin::enlargePin(bool enlarge) { resizePin(sz); return; } - if (sz == anim_pin_size.endValue()) - return; + if (sz == anim_pin_size.endValue()) return; anim_pin_size.stop(); anim_pin_size.setStartValue(pinSize()); anim_pin_size.setEndValue(sz); @@ -71,7 +74,7 @@ void BlockItemPin::enlargePin(bool enlarge) { void BlockItemPin::resizePin(double r) { - ell_item.setRect(-r, -r, r+r, r+r); + ell_item.setRect(-r, -r, r + r, r + r); } @@ -90,29 +93,44 @@ void BlockItemPin::animationAccept() { void BlockItemPin::_init(bool affect_parent) { text_item.setFont(AlignedTextItem::sceneFont(QApplication::font())); - QRectF tbr = text_item.boundingRect(); + QRectF tbr = text_item.boundingRect(); const double r = 7.; - ell_item.setRect(-r, -r, r+r, r+r); - ell_item.setSpanAngle(16*180); + ell_item.setRect(-r, -r, r + r, r + r); + ell_item.setSpanAngle(16 * 180); text_item.resetTransform(); text_item.setPos(0, -tbr.height() / 2.); text_item.setTransformOriginPoint(0, tbr.height() / 2.); switch (align) { - case Qt::AlignBottom: ell_item.setStartAngle(16*0); text_item.setRotation(-90.); text_item.moveBy(0, -r * 1.5); break; - case Qt::AlignRight: ell_item.setStartAngle(16*90); text_item.setRotation(0.); text_item.moveBy(-tbr.width() - r * 1.5, 0); break; - case Qt::AlignTop: ell_item.setStartAngle(16*180); text_item.setRotation(-90.); text_item.moveBy(0, tbr.width() + r * 1.5); break; - case Qt::AlignLeft: ell_item.setStartAngle(16*270); text_item.setRotation(0.); text_item.moveBy(r * 1.5, 0); break; + case Qt::AlignBottom: + ell_item.setStartAngle(16 * 0); + text_item.setRotation(-90.); + text_item.moveBy(0, -r * 1.5); + break; + case Qt::AlignRight: + ell_item.setStartAngle(16 * 90); + text_item.setRotation(0.); + text_item.moveBy(-tbr.width() - r * 1.5, 0); + break; + case Qt::AlignTop: + ell_item.setStartAngle(16 * 180); + text_item.setRotation(-90.); + text_item.moveBy(0, tbr.width() + r * 1.5); + break; + case Qt::AlignLeft: + ell_item.setStartAngle(16 * 270); + text_item.setRotation(0.); + text_item.moveBy(r * 1.5, 0); + break; default: break; } - if (affect_parent && parent_) - parent_->arrangePins(); + if (affect_parent && parent_) parent_->arrangePins(); } void BlockItemPin::_reparent() { if (parentItem() == 0) return; - if (qgraphicsitem_cast(parentItem()) == 0) return; - QPen p = qgraphicsitem_cast(parentItem())->g_main.pen(); + if (qgraphicsitem_cast(parentItem()) == 0) return; + QPen p = qgraphicsitem_cast(parentItem())->g_main.pen(); ell_item.setPen(p); if (scene()) { text_item.setFont(AlignedTextItem::sceneFont(scene()->font())); @@ -132,18 +150,20 @@ QGraphicsView * BlockItemPin::_view() const { QVariant BlockItemPin::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant & value) { - if (change == QGraphicsItem::ItemParentChange) - _reparent(); + if (change == QGraphicsItem::ItemParentChange) _reparent(); return QGraphicsItem::itemChange(change, value); } void BlockItemPin::hoverEnterEvent(QGraphicsSceneHoverEvent * e) { QGraphicsView * v = _view(); - bool m_pin_mc = false; + bool m_pin_mc = false; if (v) { - qobject_cast(v)->getPinMC(&m_pin_mc); - QMetaObject::invokeMethod(v, [this, v](){qobject_cast(v)->pinHoverInOut(this);}, Qt::QueuedConnection); + qobject_cast(v)->getPinMC(&m_pin_mc); + QMetaObject::invokeMethod( + v, + [this, v]() { qobject_cast(v)->pinHoverInOut(this); }, + Qt::QueuedConnection); } if ((state() != Disconnected) && !m_pin_mc) return; saveState(); @@ -159,6 +179,6 @@ void BlockItemPin::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { enlargePin(false); update(); if (v) { - qobject_cast(v)->pinHoverInOut(nullptr); + qobject_cast(v)->pinHoverInOut(nullptr); } } diff --git a/libs/blockview/blockitempin.h b/libs/blockview/blockitempin.h index 56239b6..2d86aca 100644 --- a/libs/blockview/blockitempin.h +++ b/libs/blockview/blockitempin.h @@ -1,50 +1,53 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKITEMPIN_H #define BLOCKITEMPIN_H -#include -#include -#include +#include "alignedtextitem.h" +#include "blockbase.h" +#include "qad_blockview_export.h" + +#include #include +#include +#include #include #include -#include -#include +#include #include +#include #include -#include "blockbase.h" -#include "alignedtextitem.h" -#include "qad_blockview_export.h" class BlockItem; class BlockBusItem; -class QAD_BLOCKVIEW_EXPORT BlockItemPin: public QGraphicsObject, public PropertyStorage -{ +class QAD_BLOCKVIEW_EXPORT BlockItemPin + : public QGraphicsObject + , public PropertyStorage { friend class BlockView; friend class BlockItem; Q_OBJECT Q_PROPERTY(double pinSize READ pinSize WRITE resizePin DESIGNABLE false SCRIPTABLE false) + public: BlockItemPin(Qt::Alignment a = Qt::AlignLeft, int bus_type = 0, const QString & text_ = QString(), QGraphicsObject * parent_ = 0); @@ -58,45 +61,59 @@ public: }; enum Direction { - None = 0x0, - Input = 0x1, - Output = 0x2, + None = 0x0, + Input = 0x1, + Output = 0x2, InputOutput = 0x3 }; - void setPen(const QPen & p) {ell_item.setPen(p);} - QPen pen() const {return ell_item.pen();} - void setBrush(const QBrush & b) {ell_item.setBrush(b);} - QBrush brush() const {return ell_item.brush();} + void setPen(const QPen & p) { ell_item.setPen(p); } + QPen pen() const { return ell_item.pen(); } + void setBrush(const QBrush & b) { ell_item.setBrush(b); } + QBrush brush() const { return ell_item.brush(); } - int busType() const {return bus_type;} - Qt::Alignment alignment() const {return align;} - QString text() const {return text_item.text();} - State state() const {return state_;} + int busType() const { return bus_type; } + Qt::Alignment alignment() const { return align; } + QString text() const { return text_item.text(); } + State state() const { return state_; } - void setBusType(int type_) {bus_type = type_;} - void setAlignment(Qt::Alignment a) {align = a; _init(true);} - void setText(const QString & t) {text_item.setText(t); _init(true);} + void setBusType(int type_) { bus_type = type_; } + void setAlignment(Qt::Alignment a) { + align = a; + _init(true); + } + void setText(const QString & t) { + text_item.setText(t); + _init(true); + } void setState(State s); - void saveState() {sstate_.push(state_);} - bool restoreState() {if (sstate_.isEmpty()) return false; setState(sstate_.pop()); return true;} - void clearStateStack() {sstate_.clear();} + void saveState() { sstate_.push(state_); } + bool restoreState() { + if (sstate_.isEmpty()) return false; + setState(sstate_.pop()); + return true; + } + void clearStateStack() { sstate_.clear(); } void enlargePin(bool enlarge); - BlockItem * parent() const {return parent_;} - QList connectedBuses() const {return buses_;} + BlockItem * parent() const { return parent_; } + QList connectedBuses() const { return buses_; } - enum {Type = UserType + 3}; + enum { + Type = UserType + 3 + }; public slots: void animAccept(); protected: void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {} - QRectF boundingRect() const {return ell_item.boundingRect().translated(ell_item.pos()) | text_item.boundingRect().translated(text_item.pos());} - int type() const {return Type;} + QRectF boundingRect() const { + return ell_item.boundingRect().translated(ell_item.pos()) | text_item.boundingRect().translated(text_item.pos()); + } + int type() const { return Type; } QVariant itemChange(GraphicsItemChange change, const QVariant & value); void hoverEnterEvent(QGraphicsSceneHoverEvent * e); void hoverLeaveEvent(QGraphicsSceneHoverEvent * e); @@ -108,7 +125,7 @@ protected: QGraphicsEllipseItem ell_item; QGraphicsSimpleTextItem text_item; QStack sstate_; - QList buses_; + QList buses_; BlockItem * parent_; Qt::Alignment align; QBrush br[6]; @@ -122,7 +139,6 @@ private: QPropertyAnimation anim_pin_size; QPropertyAnimation anim_accept; - }; diff --git a/libs/blockview/blockview.cpp b/libs/blockview/blockview.cpp index d333b02..27dcf00 100644 --- a/libs/blockview/blockview.cpp +++ b/libs/blockview/blockview.cpp @@ -1,15 +1,17 @@ #include "blockview.h" + #include "qad_types.h" -#include -#include -#include -#include + #include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include const QString _BlockView_Mime_ = "_BlockView_copypaste_"; @@ -24,33 +26,32 @@ BlockView::BlockView(QGraphicsScene * scene, QWidget * parent): QGraphicsView(sc } -BlockView::~BlockView() { -} +BlockView::~BlockView() {} void BlockView::_init() { - qRegisterMetaType(); - qRegisterMetaType(); - qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); grid_visible = grid_snap = pm_connect = navigation = m_connect = m_trace_with_buses = prev_tcb = minimap = true; mm_drag = moved = new_branch = new_bus = mm_cancel = iconnect = mm_copy = m_pin_mc = mm_thumb = move_bus_point = wheel_zoom = false; match_bus = bus_from = cur_bus = 0; - mm_ci = 0; - hpin = 0; - ghost_ = 0; - grid_step = 10.; - grid_points = 1; - grid_pen = QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 1, Qt::NoPen); - thick = 1; - thumb_hide_delay = 500; - timer_thumb = 0; - smode = BlockView::MultiSelection; + mm_ci = 0; + hpin = 0; + ghost_ = 0; + grid_step = 10.; + grid_points = 1; + grid_pen = QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 1, Qt::NoPen); + thick = 1; + thumb_hide_delay = 500; + timer_thumb = 0; + smode = BlockView::MultiSelection; cur_scl = thumb_scl = prev_app_scale = 1.; - _talpha = 0.; + _talpha = 0.; ae_enabled = is_block_anim = is_nav_anim = true; nav_prev_aa = nav_prev_imaa = nav_prev_grid = true; square_node = block_emit_selection = false; - thumb_size = QSizeF(200, 200); + thumb_size = QSizeF(200, 200); if (scene() == 0) { scene_ = new QGraphicsScene; setScene(scene_); @@ -120,18 +121,12 @@ bool BlockView::event(QEvent * e) { bool BlockView::eventFilter(QObject * o, QEvent * e) { if (o == &widget_thumb) { - QMouseEvent * me = (QMouseEvent*)e; - if(!me) return true; + QMouseEvent * me = (QMouseEvent *)e; + if (!me) return true; switch (e->type()) { - case QEvent::Paint: - drawThumb(); - return true; - case QEvent::Enter: - thumbShow(); - break; - case QEvent::Leave: - restartTimer(timer_thumb, thumb_hide_delay); - break; + case QEvent::Paint: drawThumb(); return true; + case QEvent::Enter: thumbShow(); break; + case QEvent::Leave: restartTimer(timer_thumb, thumb_hide_delay); break; case QEvent::MouseButtonPress: thumb_press = me->pos(); widget_thumb.setCursor(Qt::ClosedHandCursor); @@ -140,12 +135,9 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { scrollFromThumb(); } break; - case QEvent::MouseButtonRelease: - widget_thumb.setCursor(Qt::OpenHandCursor); - break; + case QEvent::MouseButtonRelease: widget_thumb.setCursor(Qt::OpenHandCursor); break; case QEvent::MouseMove: - if (me->buttons() == 0) - widget_thumb.setCursor(thumb_vr.contains(me->pos()) ? Qt::OpenHandCursor : Qt::CrossCursor); + if (me->buttons() == 0) widget_thumb.setCursor(thumb_vr.contains(me->pos()) ? Qt::OpenHandCursor : Qt::CrossCursor); if (me->buttons().testFlag(Qt::LeftButton)) { thumb_vr.translate(me->pos() - thumb_press); scrollFromThumb(); @@ -157,24 +149,30 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { return QGraphicsView::eventFilter(o, e); } if (o == scene_) { - QGraphicsSceneMouseEvent * me = (QGraphicsSceneMouseEvent*)e; - QList mil; + QGraphicsSceneMouseEvent * me = (QGraphicsSceneMouseEvent *)e; + QList mil; QPointF mdp; bool fmm_drag = false; - int btncnt = 0; + int btncnt = 0; switch (e->type()) { case QEvent::GraphicsSceneMouseDoubleClick: scene_point = me->scenePos(); - mil = scene_->items(scene_point); - foreach (QGraphicsItem * i, mil) { + mil = scene_->items(scene_point); + foreach(QGraphicsItem * i, mil) { if (i->data(bvidTmpItem).toBool()) continue; if (i->data(bvidType).toInt() == bvitBlock) { - QMetaObject::invokeMethod(this, [this, i](){blockDoubleClicked(qgraphicsitem_cast(i));}, Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, + [this, i]() { blockDoubleClicked(qgraphicsitem_cast(i)); }, + Qt::QueuedConnection); return true; } if (i->data(bvidType).toInt() == bvitBus) { - if (qgraphicsitem_cast(i)->isBusSelected()) { - QMetaObject::invokeMethod(this, [this, i](){busDoubleClicked(qgraphicsitem_cast(i));}, Qt::QueuedConnection); + if (qgraphicsitem_cast(i)->isBusSelected()) { + QMetaObject::invokeMethod( + this, + [this, i]() { busDoubleClicked(qgraphicsitem_cast(i)); }, + Qt::QueuedConnection); return true; } } @@ -187,23 +185,23 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { break; } } - if (me->buttons().testFlag(Qt::LeftButton )) btncnt++; + if (me->buttons().testFlag(Qt::LeftButton)) btncnt++; if (me->buttons().testFlag(Qt::RightButton)) btncnt++; - if (me->buttons().testFlag(QT_MID_BUTTON )) btncnt++; + if (me->buttons().testFlag(QT_MID_BUTTON)) btncnt++; mm_cancel = btncnt >= 2; match_bus = bus_from = 0; - hpin = 0; - copy_dp = QPointF(); - //qDebug() << mm_cancel << moved << sel_rect.isVisible(); + hpin = 0; + copy_dp = QPointF(); + // qDebug() << mm_cancel << moved << sel_rect.isVisible(); if (sel_rect.isVisible()) { - QList gi = scene_->items(); - block_emit_selection = true; - foreach (QGraphicsItem * i, gi) + QList gi = scene_->items(); + block_emit_selection = true; + foreach(QGraphicsItem * i, gi) i->setSelected(i->data(bvidSelected).toBool()); block_emit_selection = false; emit selectionChanged(); } - //qDebug() << "cur_bus" << cur_bus; + // qDebug() << "cur_bus" << cur_bus; if (cur_bus) { return false; } @@ -235,30 +233,30 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } mm_mods = me->modifiers(); mm_drag = moved = false; - screen_point = me->screenPos(); - scene_point = me->scenePos(); + screen_point = me->screenPos(); + scene_point = me->scenePos(); if ((me->button() == QT_MID_BUTTON) || (me->button() == Qt::RightButton)) { thumbShow(); restartTimer(timer_thumb, thumb_hide_delay); return true; } mil = scene_->items(scene_point); - //qDebug() << "mil" << mil; + // qDebug() << "mil" << mil; while (!mil.isEmpty()) { mm_ci = mil.front(); if (mm_ci->data(bvidDTHandle).toBool()) return QGraphicsView::eventFilter(o, e); if (mm_ci->data(bvidTmpItem).toBool() || mm_ci->data(bvidItemSelection).toBool()) { mil.pop_front(); - } else break; + } else + break; } if (mil.isEmpty()) { mm_ci = 0; return true; } while (mm_ci->data(bvidType).toInt() == bvitBus) { - if (qgraphicsitem_cast(mm_ci)) - if (qgraphicsitem_cast(mm_ci)->isBusSelected()) - break; + if (qgraphicsitem_cast(mm_ci)) + if (qgraphicsitem_cast(mm_ci)->isBusSelected()) break; if (mil.size() > 1) { mm_ci = mil[1]; mil.pop_front(); @@ -272,8 +270,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { mm_ci = mil[1]; mil.pop_front(); if (mm_ci->data(bvidVisualizeSelection).toBool()) - if (mil.size() > 1) - mm_ci = mil[1]; + if (mil.size() > 1) mm_ci = mil[1]; } else mm_ci = 0; } @@ -282,10 +279,10 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { while (mm_ci->parentItem() != 0) mm_ci = mm_ci->parentItem(); if (!ti->data(bvidDecorText).toString().isEmpty()) { // text item, check for rect - BlockItem * bi = qgraphicsitem_cast(mm_ci); + BlockItem * bi = qgraphicsitem_cast(mm_ci); if (bi) { if (!bi->sceneRect().contains(scene_point)) { - //qDebug() << "return"; + // qDebug() << "return"; mm_ci = 0; } } @@ -294,27 +291,27 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } if (mm_ci) { if ((mm_ci->data(bvidType).toInt() == bvitPin) && m_connect) { - if (qgraphicsitem_cast(mm_ci)->state() == BlockItemPin::Hover) { + if (qgraphicsitem_cast(mm_ci)->state() == BlockItemPin::Hover) { trace_from = mm_ci->scenePos(); - qgraphicsitem_cast(mm_ci)->clearStateStack(); + qgraphicsitem_cast(mm_ci)->clearStateStack(); hideTmpBuses(); - tmp_bus.setBusType(qgraphicsitem_cast(mm_ci)->busType()); + tmp_bus.setBusType(qgraphicsitem_cast(mm_ci)->busType()); tmp_bus.setEndpointsNumber(3); tmp_bus.show(); new_bus = true; qDeleteAll(tmp_buses); tmp_buses.clear(); - foreach (BlockItemPin * p, last_multiconnect_pl) { + foreach(BlockItemPin * p, last_multiconnect_pl) { tmp_buses << new BlockBusItem(true); tmp_buses.back()->setBusType(p->busType()); addItem(tmp_buses.back()); } - //qDebug() << "new" << ; + // qDebug() << "new" << ; prev_tcb = m_trace_with_buses; newBusStarted(tmp_bus.busType()); markPins(tmp_bus.busType()); - if (qgraphicsitem_cast(mm_ci)->alignment() == Qt::AlignLeft || - qgraphicsitem_cast(mm_ci)->alignment() == Qt::AlignRight) + if (qgraphicsitem_cast(mm_ci)->alignment() == Qt::AlignLeft || + qgraphicsitem_cast(mm_ci)->alignment() == Qt::AlignRight) wavetrace.setPreferredDirection(BlockViewWavetrace::Horizontal); else wavetrace.setPreferredDirection(BlockViewWavetrace::Vertical); @@ -325,11 +322,11 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { cur_scl = qSqrt(transform().determinant()); break; case QEvent::GraphicsSceneMouseMove: - //qDebug() << "move" << (mm_ci != 0 ? mm_ci : 0) << mm_mods << mm_cancel << mm_drag; + // qDebug() << "move" << (mm_ci != 0 ? mm_ci : 0) << mm_mods << mm_cancel << mm_drag; if (cur_bus) { return false; } - //qDebug() << "move mm_ci" << mm_ci << mm_cancel; + // qDebug() << "move mm_ci" << mm_ci << mm_cancel; if (mm_ci) if (mm_ci->data(bvidTmpItem).toBool()) { mm_ci = 0; @@ -346,19 +343,21 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } } else { if (tmp_bus.isVisible()) { - mil = scene_->items(me->scenePos()); + mil = scene_->items(me->scenePos()); hpin = 0; - foreach (QGraphicsItem * i, mil) + foreach(QGraphicsItem * i, mil) if (i->data(bvidType).toInt() == bvitPin) { - hpin = qgraphicsitem_cast(i); + hpin = qgraphicsitem_cast(i); break; } if (hpin) { if (hpin->state() == BlockItemPin::Accept) { unhoverPins(hpin); hoverAcceptedPin(hpin, true); - } else hpin = 0; - } else unhoverPins(); + } else + hpin = 0; + } else + unhoverPins(); if (new_branch) { matchBus(); break; @@ -366,7 +365,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { trace(trace_from, me->scenePos(), &tmp_bus); for (int i = 0; i < qMin(tmp_buses.size(), last_multiconnect_pl.size()); ++i) { QPointF dp = last_multiconnect_pl[i]->scenePos() - trace_from; - //qDebug() << "trace" << i << dp; + // qDebug() << "trace" << i << dp; trace(trace_from + dp, me->scenePos() + dp, tmp_buses[i], false); tmp_buses[i]->show(); } @@ -378,7 +377,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { if (fmm_drag) { fmm_drag = false; if (mm_ci) { - if ((mm_ci->data(bvidType).toInt() == bvitBlock) && !mm_ci->data(bvidTmpItem).toBool()) { + if ((mm_ci->data(bvidType).toInt() == bvitBlock) && !mm_ci->data(bvidTmpItem).toBool()) { if (!mm_ci->isSelected() && sel_items.isEmpty()) { clearSelection(); mm_ci->setSelected(true); @@ -392,21 +391,22 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } sel_items = scene_->selectedItems(); deleteCopyTemp(); - QList bi; - foreach (QGraphicsItem * i, sel_items) { + QList bi; + foreach(QGraphicsItem * i, sel_items) { if ((i->data(bvidType).toInt() == bvitBlock) && !i->data(bvidTmpItem).toBool()) { - //qDebug() << "copy"; - bi << qgraphicsitem_cast(i); + // qDebug() << "copy"; + bi << qgraphicsitem_cast(i); BlockItem * ti = bi.back()->copy(); ti->g_main.setPen(QPen(ti->g_main.pen().color(), ti->g_main.pen().widthF(), Qt::DashLine)); - QColor bc = ti->g_main.brush().color(); bc.setAlphaF(bc.alphaF() * 0.5); + QColor bc = ti->g_main.brush().color(); + bc.setAlphaF(bc.alphaF() * 0.5); ti->g_main.setBrush(bc); copy_items << ti; scene_->addItem(ti); } } - QList ibi = internalBuses(bi); - foreach (BlockBusItem * i, ibi) { + QList ibi = internalBuses(bi); + foreach(BlockBusItem * i, ibi) { i = i->copy(); i->setOpacity(i->opacity() * 0.5); copy_buses << i; @@ -416,7 +416,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { setCursor(Qt::DragCopyCursor); } } else { - //qDebug() << "move smode" << smode; + // qDebug() << "move smode" << smode; if (smode == BlockView::SingleSelection) { if (fmm_drag) { clearSelection(); @@ -432,8 +432,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { if (mm_ci == 0) { scene_->addItem(&sel_rect); sel_rect.show(); - if (!mm_mods.testFlag(Qt::ControlModifier)) - clearSelection(); + if (!mm_mods.testFlag(Qt::ControlModifier)) clearSelection(); } else { if (!mm_mods.testFlag(Qt::ControlModifier) && !mm_ci->isSelected()) { clearSelection(); @@ -442,8 +441,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } saveSelState(); if (mm_ci != 0) - if (!sel_items.contains(mm_ci)) - mm_ci = 0; + if (!sel_items.contains(mm_ci)) mm_ci = 0; } } } @@ -452,46 +450,39 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { else { if (mm_drag && mm_ci != 0) { mdp = (me->scenePos() - scene_point); - if (grid_snap) - mdp = quantize(mdp, grid_step); + if (grid_snap) mdp = quantize(mdp, grid_step); if (!mdp.isNull()) { scene_point += mdp; copy_dp += mdp; } if (mm_copy) { - if (!mdp.isNull()) - moved = true; - foreach (QGraphicsItem * i, copy_items) + if (!mdp.isNull()) moved = true; + foreach(QGraphicsItem * i, copy_items) i->setPos(i->pos() + mdp); - foreach (BlockBusItem * i, copy_buses) + foreach(BlockBusItem * i, copy_buses) i->movePolyline(mdp); } if (!mm_mods.testFlag(Qt::ControlModifier) && !mm_mods.testFlag(Qt::ShiftModifier)) { - if (!mdp.isNull()) - moved = true; - foreach (QGraphicsItem * i, sel_items) - if (i->flags().testFlag(QGraphicsItem::ItemIsMovable)) - i->setPos(i->pos() + mdp); - if (!me->modifiers().testFlag(Qt::AltModifier)) - moveBuses(sel_items, mdp); + if (!mdp.isNull()) moved = true; + foreach(QGraphicsItem * i, sel_items) + if (i->flags().testFlag(QGraphicsItem::ItemIsMovable)) i->setPos(i->pos() + mdp); + if (!me->modifiers().testFlag(Qt::AltModifier)) moveBuses(sel_items, mdp); setCursor(Qt::ClosedHandCursor); } return true; } } if (mm_ci) - if (mm_ci->data(bvidBlockDecor).toBool()) - return true; + if (mm_ci->data(bvidBlockDecor).toBool()) return true; } - if (me->modifiers().testFlag(Qt::ControlModifier) && me->buttons() != 0 && mm_ci == 0) - return true; - //qDebug() << "scene mouse"; + if (me->modifiers().testFlag(Qt::ControlModifier) && me->buttons() != 0 && mm_ci == 0) return true; + // qDebug() << "scene mouse"; break; case QEvent::GraphicsSceneMouseRelease: if (me->buttons().testFlag(Qt::LeftButton)) btncnt++; if (me->buttons().testFlag(Qt::RightButton)) btncnt++; if (me->buttons().testFlag(QT_MID_BUTTON)) btncnt++; - cur_bus = 0; + cur_bus = 0; mm_cancel = btncnt > 0; if (mm_cancel || (me->button() == QT_MID_BUTTON) || (me->button() == Qt::RightButton)) { mm_ci = 0; @@ -504,15 +495,15 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } if (mm_ci->data(bvidItemSelection).toBool()) break; if (mm_copy) { - QList ai; + QList ai; blockSignals(true); if (moved) { - QList ci; - QList bi; - foreach (QGraphicsItem * b, sel_items) + QList ci; + QList bi; + foreach(QGraphicsItem * b, sel_items) if ((b->data(bvidType).toInt() == bvitBlock) && !b->data(bvidTmpItem).toBool()) { - ci << qgraphicsitem_cast(b); - ai << qgraphicsitem_cast(b); + ci << qgraphicsitem_cast(b); + ai << qgraphicsitem_cast(b); } bi = internalBuses(ci); if (!ci.isEmpty()) copyBlocks(ci, copy_dp); @@ -530,10 +521,9 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { hideTmpBuses(false); } if (moved && pm_connect) { - QList ci; - foreach (QGraphicsItem * b, sel_items) - if (b->data(bvidType).toInt() == bvitBlock) - ci << b; + QList ci; + foreach(QGraphicsItem * b, sel_items) + if (b->data(bvidType).toInt() == bvitBlock) ci << b; simplifyBuses(); emitActionEvent(BlockItemBase::BlockMove, ci); reconnectAll(); @@ -545,7 +535,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { BlockBusItem * nb = new BlockBusItem(tmp_bus); addItem(nb, tmp_buses.isEmpty()); newBusCreated(nb); - foreach (BlockBusItem * b, tmp_buses) { + foreach(BlockBusItem * b, tmp_buses) { nb = new BlockBusItem(*b); addItem(nb, b == tmp_buses.back()); newBusCreated(nb); @@ -553,7 +543,7 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { } else { if (connectTmpToBus(match_bus)) { newBusCreated(match_bus); - emitActionEvent(BlockItemBase::BusAdd, QList() << match_bus); + emitActionEvent(BlockItemBase::BusAdd, QList() << match_bus); emit connectionsChanged(); } } @@ -570,34 +560,28 @@ bool BlockView::eventFilter(QObject * o, QEvent * e) { switch (smode) { case SingleSelection: clearSelection(); - if (mm_ci) - mm_ci->setSelected(true); + if (mm_ci) mm_ci->setSelected(true); break; case MultiSelection: if (mm_ci == 0 || !me->modifiers().testFlag(Qt::ControlModifier)) { clearSelection(); - if (mm_ci) - mm_ci->setSelected(true); + if (mm_ci) mm_ci->setSelected(true); } else { if (mm_ci != 0) { if (me->modifiers().testFlag(Qt::ControlModifier)) { - if (mm_ci->data(bvidType).toInt() == bvitBlock) - mm_ci->setSelected(!mm_ci->isSelected()); + if (mm_ci->data(bvidType).toInt() == bvitBlock) mm_ci->setSelected(!mm_ci->isSelected()); } else mm_ci->setSelected(true); } } break; - default: - clearSelection(); - break; + default: clearSelection(); break; } } sel_rect.hide(); - if (sel_rect.scene()) - scene_->removeItem(&sel_rect); + if (sel_rect.scene()) scene_->removeItem(&sel_rect); mm_drag = false; - mm_ci = 0; + mm_ci = 0; unsetCursor(); break; default: break; @@ -637,9 +621,8 @@ void BlockView::wheelEvent(QWheelEvent * e) { #else double scl = 1. - e->angleDelta().y() / 500.; #endif - if (!is_nav_anim || (nav_anim.state() != QPropertyAnimation::Running)) - nav_target = _nav(); - QRectF r = nav_target; + if (!is_nav_anim || (nav_anim.state() != QPropertyAnimation::Running)) nav_target = _nav(); + QRectF r = nav_target; double vw = viewport()->width(), vh = viewport()->height(); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) double cx = double(e->pos().x()) / vw, cy = double(e->pos().y()) / vh; @@ -661,8 +644,7 @@ void BlockView::mousePressEvent(QMouseEvent * event) { press_point = event->pos(); if (event->buttons().testFlag(QT_MID_BUTTON) || event->buttons().testFlag(Qt::RightButton)) { setCursor(Qt::ClosedHandCursor); - if (sel_rect.scene()) - scene_->removeItem(&sel_rect); + if (sel_rect.scene()) scene_->removeItem(&sel_rect); } QGraphicsView::mousePressEvent(event); } @@ -677,7 +659,7 @@ void BlockView::mouseReleaseEvent(QMouseEvent * event) { void BlockView::updateNavRect() { QPointF t = mapToScene(viewport()->rect().topLeft()); QPointF b = mapToScene(viewport()->rect().bottomRight()); - nav_rect = QRectF(t, b); + nav_rect = QRectF(t, b); } @@ -717,7 +699,7 @@ void BlockView::mouseDoubleClickEvent(QMouseEvent * event) { void BlockView::keyPressEvent(QKeyEvent * e) { BlockItemPin * pin = getPin(items(mapFromGlobal(QCursor::pos()))); if (pin) { - //qDebug() << "pin" << pin->state(); + // qDebug() << "pin" << pin->state(); if (pin->state() == BlockItemPin::Hover) { highlightNearPins(pin, e->modifiers()); } @@ -727,20 +709,20 @@ void BlockView::keyPressEvent(QKeyEvent * e) { if (e->key() == Qt::Key_Shift) { retrace = true; switch (wavetrace.preferredDirection()) { - case BlockViewWavetrace::NoTrace: wavetrace.setPreferredDirection(BlockViewWavetrace::Horizontal); break; - case BlockViewWavetrace::Horizontal: wavetrace.setPreferredDirection(BlockViewWavetrace::Vertical); break; - case BlockViewWavetrace::Vertical: wavetrace.setPreferredDirection(BlockViewWavetrace::NoTrace); break; + case BlockViewWavetrace::NoTrace: wavetrace.setPreferredDirection(BlockViewWavetrace::Horizontal); break; + case BlockViewWavetrace::Horizontal: wavetrace.setPreferredDirection(BlockViewWavetrace::Vertical); break; + case BlockViewWavetrace::Vertical: wavetrace.setPreferredDirection(BlockViewWavetrace::NoTrace); break; } } if (e->key() == Qt::Key_Alt) { - retrace = true; + retrace = true; m_trace_with_buses = !m_trace_with_buses; } if (retrace) { trace(last_trace_from, trace_to, &tmp_bus); for (int i = 0; i < qMin(tmp_buses.size(), last_multiconnect_pl.size()); ++i) { QPointF dp = last_multiconnect_pl[i]->scenePos() - last_trace_from; - //qDebug() << "trace" << i << dp; + // qDebug() << "trace" << i << dp; trace(last_trace_from + dp, trace_to + dp, tmp_buses[i], false); tmp_buses[i]->show(); } @@ -754,7 +736,7 @@ void BlockView::keyPressEvent(QKeyEvent * e) { void BlockView::keyReleaseEvent(QKeyEvent * e) { BlockItemPin * pin = getPin(items(mapFromGlobal(QCursor::pos()))); if (pin) { - //qDebug() << "pin" << pin->state(); + // qDebug() << "pin" << pin->state(); if (pin->state() == BlockItemPin::Hover) { highlightNearPins(pin, e->modifiers()); } @@ -781,7 +763,10 @@ void BlockView::scrollContentsBy(int dx, int dy) { thumbShow(); restartTimer(timer_thumb, thumb_hide_delay); QWidget * w = &widget_thumb; - QMetaObject::invokeMethod(this, [w](){w->update();}, Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, + [w]() { w->update(); }, + Qt::QueuedConnection); } @@ -796,26 +781,26 @@ void BlockView::drawBackground(QPainter * painter, const QRectF & rect) { sy *= scl; } if (!grid_visible) return; - rx = quantize(rect.left(), sx); - ry = quantize(rect.top(), sy); + rx = quantize(rect.left(), sx); + ry = quantize(rect.top(), sy); bool gp = grid_points > 0.5; if (gp) { QPen pp(grid_pen.color(), qMax(grid_points, thick), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); pp.setCosmetic(true); painter->setPen(pp); - for(int i = 0; i < qCeil(rect.width() / sx) + 1; ++i) - for(int j = 0; j < qCeil(rect.height() / sy) + 1; ++j) + for (int i = 0; i < qCeil(rect.width() / sx) + 1; ++i) + for (int j = 0; j < qCeil(rect.height() / sy) + 1; ++j) painter->drawPoint(rx + i * sx, ry + j * sy); } if (grid_pen.style() == Qt::NoPen) return; QPen pen = grid_pen; pen.setWidth(qMax(pen.width(), thick)); painter->setPen(grid_pen); - for(int i = 0; i < qCeil(rect.width() / sx) + 1; ++i) { + for (int i = 0; i < qCeil(rect.width() / sx) + 1; ++i) { double cx = rx + i * sx; painter->drawLine(cx, ry, cx, ry + rect.height()); } - for(int j = 0; j < qCeil(rect.height() / sy) + 1; ++j) { + for (int j = 0; j < qCeil(rect.height() / sy) + 1; ++j) { double cy = ry + j * sy; painter->drawLine(rx, cy, rx + rect.width(), cy); } @@ -838,7 +823,7 @@ void BlockView::deleteCopyTemp() { } -void BlockView::emitActionEvent(BlockItemBase::Action action, QList items) { +void BlockView::emitActionEvent(BlockItemBase::Action action, QList items) { if (!ae_enabled) return; emit schemeAction(action, items); } @@ -868,18 +853,20 @@ void BlockView::getPinMC(bool * v) { void BlockView::drawThumb() { if (!minimap) return; QPainter p(&widget_thumb); - QRect wr = widget_thumb.rect().adjusted(0, 0, -1, -1); + QRect wr = widget_thumb.rect().adjusted(0, 0, -1, -1); QSizeF sr = sceneRect().size(), tr; if (sr.width() >= sr.height()) thumb_scl = thumb_size.width() / sr.width(); else thumb_scl = thumb_size.height() / sr.height(); - tr = sr * thumb_scl; + tr = sr * thumb_scl; cur_scl = qSqrt(transform().determinant()); thumb_scl /= cur_scl; QSizeF vs(size().width() - verticalScrollBar()->width(), size().height() - horizontalScrollBar()->height()); QRectF vr(QPointF(horizontalScrollBar()->value() - horizontalScrollBar()->minimum(), - verticalScrollBar()->value() - verticalScrollBar()->minimum()) * thumb_scl, vs * thumb_scl); + verticalScrollBar()->value() - verticalScrollBar()->minimum()) * + thumb_scl, + vs * thumb_scl); vr.adjust(0, 0, -1, -1); p.setBrush(Qt::lightGray); @@ -920,7 +907,7 @@ void BlockView::thumbHide() { thumb_anim.setStartValue(_thumb()); thumb_anim.setEndValue(0.); thumb_anim.start(); - //qDebug() << "hide" << thumb_anim.startValue() << thumb_anim.endValue(); + // qDebug() << "hide" << thumb_anim.startValue() << thumb_anim.endValue(); } @@ -929,20 +916,19 @@ void BlockView::thumbShow() { if (widget_thumb.isHidden() || (_talpha < 0.1)) drawSceneThumb(); thumb_anim.stop(); _setThumb(1.); - //qDebug() << "show" << thumb_anim.startValue() << thumb_anim.endValue(); + // qDebug() << "show" << thumb_anim.startValue() << thumb_anim.endValue(); } void BlockView::clearSelection() { - bool pb = block_emit_selection; + bool pb = block_emit_selection; block_emit_selection = true; sel_items.clear(); - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) if (i->flags().testFlag(QGraphicsItem::ItemIsSelectable)) i->setSelected(false); block_emit_selection = pb; - if (!block_emit_selection) - emit selectionChanged(); + if (!block_emit_selection) emit selectionChanged(); } @@ -950,84 +936,80 @@ void BlockView::addItem(QGraphicsItem * item, bool emit_action) { scene_->addItem(item); applyGridStep(); if (item->data(bvidType).toInt() == bvitBus) { - loadBus(qgraphicsitem_cast(item)); - ((BlockBusItem*)item)->setSquareNodes(square_node); - connect((BlockBusItem*)item, SIGNAL(destroyed(QObject*)), this, SLOT(removedBus(QObject*)), Qt::UniqueConnection); - if (emit_action) emitActionEvent(BlockItemBase::BusAdd, QList() << item); + loadBus(qgraphicsitem_cast(item)); + ((BlockBusItem *)item)->setSquareNodes(square_node); + connect((BlockBusItem *)item, SIGNAL(destroyed(QObject *)), this, SLOT(removedBus(QObject *)), Qt::UniqueConnection); + if (emit_action) emitActionEvent(BlockItemBase::BusAdd, QList() << item); emit connectionsChanged(); return; } if (item->data(bvidType).toInt() == bvitBlock) { - connect((BlockItem*)item, SIGNAL(destroyed(QObject*)), this, SLOT(removedBlock(QObject*)), Qt::UniqueConnection); - connect((BlockItem*)item, SIGNAL(blockHoverEnter(BlockItem*)), this, SIGNAL(blockHoverEnter(BlockItem*)), Qt::UniqueConnection); - connect((BlockItem*)item, SIGNAL(blockHoverLeave(BlockItem*)), this, SIGNAL(blockHoverLeave(BlockItem*)), Qt::UniqueConnection); - if (emit_action) emitActionEvent(BlockItemBase::BlockAdd, QList() << item); + connect((BlockItem *)item, SIGNAL(destroyed(QObject *)), this, SLOT(removedBlock(QObject *)), Qt::UniqueConnection); + connect((BlockItem *)item, SIGNAL(blockHoverEnter(BlockItem *)), this, SIGNAL(blockHoverEnter(BlockItem *)), Qt::UniqueConnection); + connect((BlockItem *)item, SIGNAL(blockHoverLeave(BlockItem *)), this, SIGNAL(blockHoverLeave(BlockItem *)), Qt::UniqueConnection); + if (emit_action) emitActionEvent(BlockItemBase::BlockAdd, QList() << item); return; } item->setData(bvidType, bvitDecor); } -QList BlockView::buses() const { - QList ret; - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) +QList BlockView::buses() const { + QList ret; + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) if ((i->data(bvidType).toInt() == bvitBus) && !i->data(bvidTmpItem).toBool()) - if (!copy_buses.contains((BlockBusItem*)i)) - ret << qgraphicsitem_cast(i); + if (!copy_buses.contains((BlockBusItem *)i)) ret << qgraphicsitem_cast(i); return ret; } -QList BlockView::wrongConnectedBuses() const { - QList sl = buses(), ret; - QList bl = blocks(); - foreach (BlockItem * b, bl) { - QVector pins = b->pins(); - foreach (BlockItemPin * p, pins) +QList BlockView::wrongConnectedBuses() const { + QList sl = buses(), ret; + QList bl = blocks(); + foreach(BlockItem * b, bl) { + QVector pins = b->pins(); + foreach(BlockItemPin * p, pins) if (p->state() == BlockItemPin::Reject) { QPointF pp = p->scenePos(); - foreach (BlockBusItem * s, sl) + foreach(BlockBusItem * s, sl) if (s->pol.contains(pp)) - if (!ret.contains(s)) - ret << s; + if (!ret.contains(s)) ret << s; } } return ret; } -QList BlockView::blocks() const { - QList ret; - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) - if ((i->data(bvidType).toInt() == bvitBlock) && !i->data(bvidTmpItem).toBool()) - ret << qgraphicsitem_cast(i); +QList BlockView::blocks() const { + QList ret; + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) + if ((i->data(bvidType).toInt() == bvitBlock) && !i->data(bvidTmpItem).toBool()) ret << qgraphicsitem_cast(i); return ret; } -QList BlockView::decors() const { - QList ret, gi = scene_->items(); - foreach (QGraphicsItem * i, gi) - if ((i->data(bvidType).toInt() == bvitDecor) && !i->data(bvidTmpItem).toBool() && !i->data(bvidItemSelection).toBool() && (i->parentItem() == 0) - && (i != &sel_rect) && (i != &tmp_bus) && !tmp_buses.contains((BlockBusItem*)i)) +QList BlockView::decors() const { + QList ret, gi = scene_->items(); + foreach(QGraphicsItem * i, gi) + if ((i->data(bvidType).toInt() == bvitDecor) && !i->data(bvidTmpItem).toBool() && !i->data(bvidItemSelection).toBool() && + (i->parentItem() == 0) && (i != &sel_rect) && (i != &tmp_bus) && !tmp_buses.contains((BlockBusItem *)i)) ret << i; return ret; } BlockBusItem * BlockView::connectionBus(BlockItem * b0, BlockItem * b1) const { - QList cbl = connectionBuses(b0, b1); + QList cbl = connectionBuses(b0, b1); if (cbl.isEmpty()) return 0; return cbl.front(); } -QList BlockView::connectionBuses(BlockItem * b0, BlockItem * b1) const { - if (!b0 || !b1) return QList(); - QSet bs0 = QList2QSet(b0->connectedBuses()), - bs1 = QList2QSet(b1->connectedBuses()); +QList BlockView::connectionBuses(BlockItem * b0, BlockItem * b1) const { + if (!b0 || !b1) return QList(); + QSet bs0 = QList2QSet(b0->connectedBuses()), bs1 = QList2QSet(b1->connectedBuses()); return (bs0 & bs1).values(); } @@ -1036,25 +1018,31 @@ bool BlockView::connectPins(BlockItemPin * p0, BlockItemPin * p1) { if (!p0 || !p1) return false; if (p0 == p1) return false; if (p0->busType() != p1->busType()) return false; - QList bl0 = p0->connectedBuses(), bl1 = p1->connectedBuses(); + QList bl0 = p0->connectedBuses(), bl1 = p1->connectedBuses(); if (!(QList2QSet(bl0) & QList2QSet(bl1)).isEmpty()) return true; BlockBusItem * nb = new BlockBusItem(); nb->setBusType(p0->busType()); loadBus(nb); - if (!bl0.isEmpty() && !bl1.isEmpty()) { // connect two existing buses + if (!bl0.isEmpty() && !bl1.isEmpty()) { // connect two existing buses } else { if ((bl0.isEmpty() && !bl1.isEmpty()) || (bl1.isEmpty() && !bl0.isEmpty())) { // connect empty pin to existing bus BlockItemPin * ep = 0; BlockBusItem * eb = 0; - if (bl0.isEmpty()) {ep = p0; eb = bl1[0];} - else {ep = p1; eb = bl0[0];} - double md = -1; int mi = -1; + if (bl0.isEmpty()) { + ep = p0; + eb = bl1[0]; + } else { + ep = p1; + eb = bl0[0]; + } + double md = -1; + int mi = -1; QPointF sp = ep->scenePos(); if (eb->pol.size() == 2) { eb->selSegment = 0; eb->addPoint((eb->pol[0] + eb->pol[1]) / 2.); eb->selPoint = -1; - mi = 2; + mi = 2; } else { for (int i = 0; i < eb->pol.size(); ++i) { if (eb->ends.contains(i)) continue; @@ -1092,7 +1080,7 @@ bool BlockView::connectPins(BlockItemPin * p0, BlockItemPin * p1) { } reconnectAll(); newBusCreated(nb); - emitActionEvent(BlockItemBase::BusAdd, QList() << nb); + emitActionEvent(BlockItemBase::BusAdd, QList() << nb); emit connectionsChanged(); return true; } @@ -1159,17 +1147,19 @@ void BlockView::fitInView() { QRectF BlockView::itemsBoundingRect() const { - QList gi = scene_->items(); + QList gi = scene_->items(); if (gi.isEmpty()) return QRectF(); bool f = true; QRectF ret; - foreach (QGraphicsItem * i, gi) - if (i->isVisible() && (i != &tmp_bus) && !tmp_buses.contains((BlockBusItem*)i)) { + foreach(QGraphicsItem * i, gi) + if (i->isVisible() && (i != &tmp_bus) && !tmp_buses.contains((BlockBusItem *)i)) { if (!(i->data(bvidItemSelection).toBool()) && !i->data(bvidTmpItem).toBool()) { QRectF br = i->mapRectToScene(i->boundingRect()); if (br.width() <= 1 || br.height() <= 1) continue; - if (f) ret = br; - else ret |= br; + if (f) + ret = br; + else + ret |= br; f = false; } } @@ -1178,96 +1168,93 @@ QRectF BlockView::itemsBoundingRect() const { void BlockView::restoreSelState() { - //qDebug() << "restoreSelState"; - foreach (QGraphicsItem * i, sel_items) { + // qDebug() << "restoreSelState"; + foreach(QGraphicsItem * i, sel_items) { i->setPos(i->data(bvidItemPos).toPointF()); } - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) if (i->data(bvidType).toInt() == bvitBus) { - BlockBusItem * bi = qgraphicsitem_cast(i); - bi->pol = bi->bpol; + BlockBusItem * bi = qgraphicsitem_cast(i); + bi->pol = bi->bpol; bi->prepareGeometryChange(); } } void BlockView::saveSelState() { - //qDebug() << "saveSelState"; - QList gi = scene_->items(); - sel_items = scene_->selectedItems(); - foreach (QGraphicsItem * i, gi) { + // qDebug() << "saveSelState"; + QList gi = scene_->items(); + sel_items = scene_->selectedItems(); + foreach(QGraphicsItem * i, gi) { i->setData(bvidSelected, i->isSelected()); i->setData(bvidItemPos, i->pos()); - if (i->data(bvidType).toInt() == bvitBus) - qgraphicsitem_cast(i)->bpol = qgraphicsitem_cast(i)->pol; + if (i->data(bvidType).toInt() == bvitBus) qgraphicsitem_cast(i)->bpol = qgraphicsitem_cast(i)->pol; } } void BlockView::saveBusesState() { - QList bl = buses(); - foreach (BlockBusItem * b, bl) + QList bl = buses(); + foreach(BlockBusItem * b, bl) b->saveState(); } void BlockView::restoreBusesState() { - QList bl = buses(); - foreach (BlockBusItem * b, bl) + QList bl = buses(); + foreach(BlockBusItem * b, bl) b->restoreState(); } void BlockView::applySelRect(QGraphicsSceneMouseEvent * me) { - QList ci = sel_rect.collidingItems(Qt::IntersectsItemBoundingRect); - QList gi = scene_->items(); - bool add = me->modifiers().testFlag(Qt::ControlModifier); - QList sil = scene_->selectedItems(); - block_emit_selection = true; - if (!add) clearSelection(); + QList ci = sel_rect.collidingItems(Qt::IntersectsItemBoundingRect); + QList gi = scene_->items(); + bool add = me->modifiers().testFlag(Qt::ControlModifier); + QList sil = scene_->selectedItems(); + block_emit_selection = true; + if (!add) + clearSelection(); else { - foreach (QGraphicsItem * i, gi) + foreach(QGraphicsItem * i, gi) i->setSelected(i->data(bvidSelected).toBool()); } - foreach (QGraphicsItem * i, ci) { + foreach(QGraphicsItem * i, ci) { i->setSelected(!i->isSelected()); } block_emit_selection = false; - if (sil != scene_->selectedItems()) - emit selectionChanged(); + if (sil != scene_->selectedItems()) emit selectionChanged(); } void BlockView::applyGridStep() { - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) - if (i->type() == QGraphicsItem::UserType + 2) - qgraphicsitem_cast(i)->setGridStep(grid_step); + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) + if (i->type() == QGraphicsItem::UserType + 2) qgraphicsitem_cast(i)->setGridStep(grid_step); } void BlockView::trace(QPointF scene_pos_from, QPointF scene_pos_to, BlockBusItem * bus, bool primary) { if (primary) { - if (hpin) - scene_pos_to = hpin->scenePos(); + if (hpin) scene_pos_to = hpin->scenePos(); last_trace_from = scene_pos_from; - trace_to = scene_pos_to; + trace_to = scene_pos_to; } QRect sr = scene_->sceneRect().toRect(); int dx = sr.left() / grid_step, dy = sr.top() / grid_step; - QPoint dp(-dx, -dy), qpt = quantize(scene_pos_to, grid_step).toPoint() / grid_step + dp; + QPoint dp(-dx, -dy), qpt = quantize(scene_pos_to, grid_step).toPoint() / grid_step + dp; QElapsedTimer tm; tm.restart(); wavetrace.resize(sr.size() / grid_step); wavetrace.fill(BlockViewWavetrace::Empty); - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) if (i->data(bvidType).toInt() == bvitBlock) { QRect ir = i->mapRectToScene(i->boundingRect()).toRect().normalized(); wavetrace.fill(QRect(ir.topLeft() / grid_step + dp, ir.bottomRight() / grid_step + dp), BlockViewWavetrace::Blocked); - QVector pins = qgraphicsitem_cast(i)->pins(); - foreach (BlockItemPin * p, pins) { + QVector pins = qgraphicsitem_cast(i)->pins(); + foreach(BlockItemPin * p, pins) { if (p->busType() == bus->busType()) wavetrace.fill(quantize(p->scenePos(), grid_step).toPoint() / grid_step + dp, BlockViewWavetrace::Empty); if (!m_pin_mc && !p->connectedBuses().isEmpty()) @@ -1275,9 +1262,9 @@ void BlockView::trace(QPointF scene_pos_from, QPointF scene_pos_to, BlockBusItem } } if (m_trace_with_buses) { - foreach (QGraphicsItem * i, gi) + foreach(QGraphicsItem * i, gi) if (i->data(bvidType).toInt() == bvitBus) { - BlockBusItem * b = qgraphicsitem_cast(i); + BlockBusItem * b = qgraphicsitem_cast(i); if (!b) continue; for (int s = 0; s < b->segments.size(); ++s) { QPointF p0 = b->pol[b->segments[s].first], p1 = b->pol[b->segments[s].second], cp = p0; @@ -1287,24 +1274,23 @@ void BlockView::trace(QPointF scene_pos_from, QPointF scene_pos_to, BlockBusItem if ((dx + dy) < grid_step) continue; BlockViewWavetrace::CellState cs = BlockViewWavetrace::Blocked; if (dx >= dy) { // by x - sx = grid_step; - sy = sx * dy / dx; + sx = grid_step; + sy = sx * dy / dx; steps = qRound(dx / grid_step); - cs = BlockViewWavetrace::HorizontalBus; + cs = BlockViewWavetrace::HorizontalBus; } else { - sy = grid_step; - sx = sy * dx / dy; + sy = grid_step; + sx = sy * dx / dy; steps = qRound(dy / grid_step); - cs = BlockViewWavetrace::VerticalBus; + cs = BlockViewWavetrace::VerticalBus; } sx *= signx; sy *= signy; - //qDebug() << "fill" << p0 << "->" << p1 << "in" << steps << sx << sy; + // qDebug() << "fill" << p0 << "->" << p1 << "in" << steps << sx << sy; for (int j = 0; j <= steps; ++j) { QPoint tp = quantize(cp, grid_step).toPoint() / grid_step + dp; - if (tp != qpt) - wavetrace.fill(tp, (j > 0 && j < steps) ? cs : BlockViewWavetrace::Blocked); - //qDebug() << " set" << cp << ((j > 0 && j < steps) ? cs : BlockViewWavetrace::Blocked); + if (tp != qpt) wavetrace.fill(tp, (j > 0 && j < steps) ? cs : BlockViewWavetrace::Blocked); + // qDebug() << " set" << cp << ((j > 0 && j < steps) ? cs : BlockViewWavetrace::Blocked); cp += QPointF(sx, sy); } } @@ -1313,67 +1299,63 @@ void BlockView::trace(QPointF scene_pos_from, QPointF scene_pos_to, BlockBusItem bus->clear(); if (wavetrace.trace(quantize(scene_pos_from, grid_step).toPoint() / grid_step + dp, qpt)) { wavetrace.gatherPath(); - foreach (const QPoint & p, wavetrace.path()) { + foreach(const QPoint & p, wavetrace.path()) { bus->appendPoint((p - dp) * grid_step); } } - //qDebug() << quantize(scene_pos_from, grid_step).toPoint() / grid_step + dp << qpt; + // qDebug() << quantize(scene_pos_from, grid_step).toPoint() / grid_step + dp << qpt; scene_->update(); } void BlockView::clearBusStates() { - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) if (i->data(bvidType).toInt() == bvitBus) { - BlockBusItem * b = qgraphicsitem_cast(i); + BlockBusItem * b = qgraphicsitem_cast(i); b->clearBusState(); } } void BlockView::matchBus() { - match_bus = 0; - bool bv = tmp_bus.isVisible(); - QList gi = scene_->items(); - QList buses; - QList blockl; + match_bus = 0; + bool bv = tmp_bus.isVisible(); + QList gi = scene_->items(); + QList buses; + QList blockl; int sp = -1, ss = -1; QPointF point; iconnect = false; - if (!tmp_bus.pol.isEmpty()) - point = tmp_bus.pol.back(); - foreach (QGraphicsItem * i, gi) { + if (!tmp_bus.pol.isEmpty()) point = tmp_bus.pol.back(); + foreach(QGraphicsItem * i, gi) { if (i != bus_from) { - if (i->data(bvidType).toInt() == bvitBus) - buses << qgraphicsitem_cast(i); - if (i->data(bvidType).toInt() == bvitBlock) - blockl << qgraphicsitem_cast(i); + if (i->data(bvidType).toInt() == bvitBus) buses << qgraphicsitem_cast(i); + if (i->data(bvidType).toInt() == bvitBlock) blockl << qgraphicsitem_cast(i); } } - foreach (BlockBusItem * b, buses) { + foreach(BlockBusItem * b, buses) { b->clearBusState(); b->selPoint = b->selSegment = -1; } if (!bv) return; BlockBusItem * b(0); if (m_pin_mc) { - foreach (BlockItem * b_, blockl) - foreach (BlockItemPin * p_, b_->pins()) + foreach(BlockItem * b_, blockl) + foreach(BlockItemPin * p_, b_->pins()) if (p_->scenePos() == point) { - return; } } - //qDebug() << "1" << buses.size() << tmp_bus.pol; + // qDebug() << "1" << buses.size() << tmp_bus.pol; for (int i = 0; i < buses.size(); ++i) { b = buses[i]; b->testPoint(point, &sp, &ss, true); - //qDebug() << i << sp << ss; + // qDebug() << i << sp << ss; if (sp >= 0 || ss >= 0) break; } if ((sp < 0 && ss < 0) || b == 0) return; - //qDebug("2"); + // qDebug("2"); match_bus = b; if ((b->busType() != tmp_bus.busType()) || b->connections_.value(sp, 0) != 0) { b->setBusState(false); @@ -1405,7 +1387,7 @@ void BlockView::matchBus() { } iconnect = true; b->setBusState(true); - b->selPoint = sp; + b->selPoint = sp; b->selSegment = ss; } } @@ -1416,8 +1398,7 @@ bool BlockView::connectTmpToBus(BlockBusItem * bus) { if (!bus->busState()) return false; if (tmp_bus.pol.size() < 2) return false; int np = bus->selPoint; - if (np < 0) - np = bus->addPoint(tmp_bus.pol.back()); + if (np < 0) np = bus->addPoint(tmp_bus.pol.back()); if (np < 0) return false; tmp_bus.pol.pop_back(); int lp = bus->pol.size(); @@ -1433,18 +1414,16 @@ bool BlockView::connectTmpToBus(BlockBusItem * bus) { void BlockView::markPins(int bus_type) { unhoverPins(); - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) { + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) { if (i->data(bvidType).toInt() == bvitPin) { - BlockItemPin * p = qgraphicsitem_cast(i); + BlockItemPin * p = qgraphicsitem_cast(i); p->saveState(); if (m_pin_mc) { - if (p->busType() == bus_type) - p->setState(BlockItemPin::Accept); + if (p->busType() == bus_type) p->setState(BlockItemPin::Accept); } else { if (p->busType() == bus_type) { - if (p->state() == BlockItemPin::Disconnected) - p->setState(BlockItemPin::Accept); + if (p->state() == BlockItemPin::Disconnected) p->setState(BlockItemPin::Accept); } } } @@ -1454,12 +1433,13 @@ void BlockView::markPins(int bus_type) { void BlockView::unmarkPins(bool to_normal) { unhoverPins(); - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) { + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) { if (i->data(bvidType).toInt() == bvitPin) { - qgraphicsitem_cast(i)->restoreState(); + qgraphicsitem_cast(i)->restoreState(); if (to_normal) - while (qgraphicsitem_cast(i)->restoreState()); + while (qgraphicsitem_cast(i)->restoreState()) + ; } } } @@ -1471,60 +1451,71 @@ void BlockView::hoverAcceptedPin(BlockItemPin * pin, bool hover) { } -void BlockView::unhoverPins(BlockItemPin* excl_pin) { - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) { - if (excl_pin == ((BlockItemPin*)i)) continue; +void BlockView::unhoverPins(BlockItemPin * excl_pin) { + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) { + if (excl_pin == ((BlockItemPin *)i)) continue; if (i->data(bvidType).toInt() == bvitPin) { - ((BlockItemPin*)i)->enlargePin(false); + ((BlockItemPin *)i)->enlargePin(false); } } } void BlockView::simplifyBuses() { - QList bl = buses(); - foreach (BlockBusItem * b, bl) + QList bl = buses(); + foreach(BlockBusItem * b, bl) b->simplify(); } -void BlockView::moveBuses(const QList & items, QPointF dp) { +void BlockView::moveBuses(const QList & items, QPointF dp) { if (dp.isNull()) return; - QList gi = scene_->items(); - QVector pins; - QList buses; - //qDebug() << "move" << dp; - foreach (QGraphicsItem * i, items) + QList gi = scene_->items(); + QVector pins; + QList buses; + // qDebug() << "move" << dp; + foreach(QGraphicsItem * i, items) if ((i->data(bvidType).toInt() == bvitBlock) && i->flags().testFlag(QGraphicsItem::ItemIsMovable)) - pins << qgraphicsitem_cast(i)->pins(); - foreach (QGraphicsItem * i, gi) - if (i->data(bvidType).toInt() == bvitBus) - buses << qgraphicsitem_cast(i); - foreach (BlockBusItem * b, buses) { - QList bpins = b->connections_.values(); + pins << qgraphicsitem_cast(i)->pins(); + foreach(QGraphicsItem * i, gi) + if (i->data(bvidType).toInt() == bvitBus) buses << qgraphicsitem_cast(i); + foreach(BlockBusItem * b, buses) { + QList bpins = b->connections_.values(); if (!bpins.isEmpty()) { - foreach (BlockItemPin * p, pins) + foreach(BlockItemPin * p, pins) bpins.removeAll(p); if (bpins.isEmpty()) { b->movePolyline(dp); continue; } } - foreach (BlockItemPin * p, pins) { + foreach(BlockItemPin * p, pins) { QList ends = b->connections_.keys(p); for (int i = 0; i < ends.size(); ++i) { QPointF pdp = dp; - double ang = 0.; + double ang = 0.; switch (p->alignment()) { - case Qt::AlignRight : pdp.setX(0.); ang = 0.; break; - case Qt::AlignTop : pdp.setY(0.); ang = 90.; break; - case Qt::AlignLeft : pdp.setX(0.); ang = 180.; break; - case Qt::AlignBottom: pdp.setY(0.); ang = 270.; break; + case Qt::AlignRight: + pdp.setX(0.); + ang = 0.; + break; + case Qt::AlignTop: + pdp.setY(0.); + ang = 90.; + break; + case Qt::AlignLeft: + pdp.setX(0.); + ang = 180.; + break; + case Qt::AlignBottom: + pdp.setY(0.); + ang = 270.; + break; default: break; } QVector epl = b->endpointLine(ends[i], ang); - foreach (int e, epl) + foreach(int e, epl) b->movePoint(e, pdp); b->movePoint(ends[i], dp); } @@ -1533,27 +1524,26 @@ void BlockView::moveBuses(const QList & items, QPointF dp) { } -QList BlockView::internalBuses(const QList & items) { - QList ret; +QList BlockView::internalBuses(const QList & items) { + QList ret; if (items.isEmpty()) return ret; - QList sbl = buses(); - QSet sis = QList2QSet(items); - foreach (BlockBusItem * bi, sbl) { + QList sbl = buses(); + QSet sis = QList2QSet(items); + foreach(BlockBusItem * bi, sbl) { if (bi->connectedBlocks().isEmpty()) continue; - QSet bis = QList2QSet(bi->connectedBlocks()); - if ((bis - sis).isEmpty()) - ret << bi; + QSet bis = QList2QSet(bi->connectedBlocks()); + if ((bis - sis).isEmpty()) ret << bi; } return ret; } -QList BlockView::nearPins(BlockItemPin * pin, Qt::KeyboardModifiers km) { - QList ret; +QList BlockView::nearPins(BlockItemPin * pin, Qt::KeyboardModifiers km) { + QList ret; bool up = km.testFlag(Qt::ShiftModifier); bool down = km.testFlag(Qt::ControlModifier); bool ab = km.testFlag(Qt::AltModifier); - //qDebug() << "nearPins" << km; + // qDebug() << "nearPins" << km; if (!pin || (!up && !down)) return ret; const BlockItem * src = pin->parent(); if (!src) return ret; @@ -1562,17 +1552,16 @@ QList BlockView::nearPins(BlockItemPin * pin, Qt::KeyboardModif for (int i = 0; i < 2; ++i) { if (!dirs[i]) continue; const BlockItem * cb = src; - BlockItemPin * cpin = pin; - //qDebug() << "dir" << dirs[i]; + BlockItemPin * cpin = pin; + // qDebug() << "dir" << dirs[i]; while (cpin) { - //qDebug() << "cur" << cpin; - QList il = scene_->items(cpin->scenePos() + QPointF(0., dy[i] * cb->pinsMargin())); - BlockItemPin * np = getPin(il); + // qDebug() << "cur" << cpin; + QList il = scene_->items(cpin->scenePos() + QPointF(0., dy[i] * cb->pinsMargin())); + BlockItemPin * np = getPin(il); if (np == cpin) break; cpin = np; if (cpin) { - if (((cb != cpin->parent()) && !ab) || - (cpin->state() != BlockItemPin::Disconnected)) { + if (((cb != cpin->parent()) && !ab) || (cpin->state() != BlockItemPin::Disconnected)) { break; } cb = cpin->parent(); @@ -1585,20 +1574,19 @@ QList BlockView::nearPins(BlockItemPin * pin, Qt::KeyboardModif BlockItemPin * BlockView::getPin(const QList & list) const { - foreach (QGraphicsItem * i, list) { - if (i->data(bvidType).toInt() == bvitPin) - return qgraphicsitem_cast(i); + foreach(QGraphicsItem * i, list) { + if (i->data(bvidType).toInt() == bvitPin) return qgraphicsitem_cast(i); } return 0; } void BlockView::highlightNearPins(BlockItemPin * pin, Qt::KeyboardModifiers km) { - //qDebug() << "restore for" << last_multiconnect_pl.size(); - foreach (BlockItemPin * p, last_multiconnect_pl) + // qDebug() << "restore for" << last_multiconnect_pl.size(); + foreach(BlockItemPin * p, last_multiconnect_pl) p->restoreState(); - QList pl = nearPins(pin, km); - foreach (BlockItemPin * p, pl) { + QList pl = nearPins(pin, km); + foreach(BlockItemPin * p, pl) { p->saveState(); p->setState(BlockItemPin::Hover); } @@ -1616,21 +1604,19 @@ void BlockView::hideTmpBuses(bool clear) { } -QList BlockView::selectedBlocks() const { - QList ret; - QList sil = scene()->selectedItems(); - foreach (QGraphicsItem * b, sil) - if ((b->data(bvidType).toInt() == bvitBlock) && !b->data(bvidTmpItem).toBool()) - ret << qgraphicsitem_cast(b); +QList BlockView::selectedBlocks() const { + QList ret; + QList sil = scene()->selectedItems(); + foreach(QGraphicsItem * b, sil) + if ((b->data(bvidType).toInt() == bvitBlock) && !b->data(bvidTmpItem).toBool()) ret << qgraphicsitem_cast(b); return ret; } -QList BlockView::selectedDecors() const { - QList ret, sil = decors(); - foreach (QGraphicsItem * b, sil) - if (b->isSelected()) - ret << b; +QList BlockView::selectedDecors() const { + QList ret, sil = decors(); + foreach(QGraphicsItem * b, sil) + if (b->isSelected()) ret << b; return ret; } @@ -1643,7 +1629,7 @@ void BlockView::animateNav(QRectF d, double scl) { return; } if (nav_anim.state() != QAbstractAnimation::Running) { - nav_prev_aa = renderHints().testFlag(QPainter::Antialiasing); + nav_prev_aa = renderHints().testFlag(QPainter::Antialiasing); nav_prev_imaa = renderHints().testFlag(QPainter::SmoothPixmapTransform); nav_prev_grid = isGridVisible(); setRenderHint(QPainter::Antialiasing, false); @@ -1667,14 +1653,11 @@ void BlockView::adjustThumb() { scl = thumb_size.width() / sr.width(); else scl = thumb_size.height() / sr.height(); - tr = sr * scl; + tr = sr * scl; int sx = 0, sy = 0; - if (verticalScrollBar()->isVisible() && (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff)) - sx = verticalScrollBar()->width(); - if (horizontalScrollBar()->isVisible() && (horizontalScrollBarPolicy() != Qt::ScrollBarAlwaysOff)) - sy = horizontalScrollBar()->height(); - widget_thumb.setGeometry(QRect(QPoint(width() - tr.width() - 10 - sx, - height() - tr.height() - 10 - sy), tr.toSize())); + if (verticalScrollBar()->isVisible() && (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff)) sx = verticalScrollBar()->width(); + if (horizontalScrollBar()->isVisible() && (horizontalScrollBarPolicy() != Qt::ScrollBarAlwaysOff)) sy = horizontalScrollBar()->height(); + widget_thumb.setGeometry(QRect(QPoint(width() - tr.width() - 10 - sx, height() - tr.height() - 10 - sy), tr.toSize())); } @@ -1695,38 +1678,41 @@ void BlockView::newBranch(BlockBusItem * item) { void BlockView::startBusPointMove(int bus_type) { move_bus_point = true; - prev_tcb = m_trace_with_buses; + prev_tcb = m_trace_with_buses; newBusStarted(bus_type); markPins(bus_type); } void BlockView::pinHoverInOut(BlockItemPin * pin) { - //qDebug() << "pinHoverInOut" << pin << pin->state(); + // qDebug() << "pinHoverInOut" << pin << pin->state(); highlightNearPins(pin, QApplication::keyboardModifiers()); } void BlockView::checkPaste(bool queued) { const QMimeData * mime = QApplication::clipboard()->mimeData(); - bool ret = false; - if (mime) - ret = mime->hasFormat(_BlockView_Mime_); - if (queued) QMetaObject::invokeMethod(this, [this, ret](){pasteEnabledChanged(ret);}, Qt::QueuedConnection); - else emit pasteEnabledChanged(ret); + bool ret = false; + if (mime) ret = mime->hasFormat(_BlockView_Mime_); + if (queued) + QMetaObject::invokeMethod( + this, + [this, ret]() { pasteEnabledChanged(ret); }, + Qt::QueuedConnection); + else + emit pasteEnabledChanged(ret); } void BlockView::setBusSquareNodes(bool yes) { - square_node = yes; - QList sbl = buses(); - foreach (BlockBusItem * b, sbl) { + square_node = yes; + QList sbl = buses(); + foreach(BlockBusItem * b, sbl) { b->setSquareNodes(square_node); } } - void BlockView::newBranchTrace(BlockBusItem * item, QPointF to) { trace(item->press_pos, to, &tmp_bus); tmp_bus.show(); @@ -1740,17 +1726,18 @@ void BlockView::newBranchAccept(BlockBusItem * item) { tmp_bus.hide(); if (tmp_bus.pol.size() < 2) return; tmp_bus.pol.pop_front(); - if ((tmp_bus.pol.size() == 1) && (tmp_bus.pol[0] == item->press_pos)) - return; + if ((tmp_bus.pol.size() == 1) && (tmp_bus.pol[0] == item->press_pos)) return; int np = item->addPoint(item->press_pos); if (np < 0) return; if (match_bus) { - if (iconnect) tmp_bus.pol.pop_back(); - else return; + if (iconnect) + tmp_bus.pol.pop_back(); + else + return; } if (item == match_bus) return; int snp = np; - int lp = item->pol.size(); + int lp = item->pol.size(); if (!tmp_bus.pol.isEmpty()) { item->pol << tmp_bus.pol; item->segments << QPair(np, lp); @@ -1760,8 +1747,7 @@ void BlockView::newBranchAccept(BlockBusItem * item) { if (match_bus != 0) { if (!iconnect) return; np = match_bus->selPoint; - if (np < 0) - np = match_bus->addPoint(trace_to); + if (np < 0) np = match_bus->addPoint(trace_to); if (np < 0) return; lp = item->pol.size(); item->pol << match_bus->pol; @@ -1777,7 +1763,7 @@ void BlockView::newBranchAccept(BlockBusItem * item) { } item->updateGeometry(); newBusCreated(item); - emitActionEvent(BlockItemBase::BusAdd, QList() << item); + emitActionEvent(BlockItemBase::BusAdd, QList() << item); emit connectionsChanged(); tmp_bus.clear(); } @@ -1785,7 +1771,7 @@ void BlockView::newBranchAccept(BlockBusItem * item) { void BlockView::newBranchCancel() { unmarkPins(); - //qDebug() << "cancel"; + // qDebug() << "cancel"; new_branch = false; hideTmpBuses(); } @@ -1794,25 +1780,25 @@ void BlockView::newBranchCancel() { void BlockView::removedBus(QObject * o) { mm_ci = 0; reconnectAll(); - BlockBusItem * bus = (BlockBusItem*)o; + BlockBusItem * bus = (BlockBusItem *)o; if (bus->property("_nodelete_").toBool()) return; - emitActionEvent(BlockItemBase::BusRemove, QList() << bus); + emitActionEvent(BlockItemBase::BusRemove, QList() << bus); emit connectionsChanged(); } void BlockView::removedBlock(QObject * o) { if (o == ghost_) return; - emit blockRemoved((BlockItem*)o); - emitActionEvent(BlockItemBase::BlockRemove, QList() << qgraphicsitem_cast((BlockItem*)o)); + emit blockRemoved((BlockItem *)o); + emitActionEvent(BlockItemBase::BlockRemove, QList() << qgraphicsitem_cast((BlockItem *)o)); } void BlockView::removeJunk() { - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) { + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) { if (i->data(bvidType).toInt() != bvitBus) continue; - BlockBusItem * b = qgraphicsitem_cast(i); + BlockBusItem * b = qgraphicsitem_cast(i); if (b->pol.size() <= 1) { b->deleteLater(); } @@ -1823,17 +1809,21 @@ void BlockView::removeJunk() { void BlockView::sceneSelectionChanged() { bool ie = scene()->selectedItems().isEmpty(); emit copyEnabledChanged(!ie); - if (!block_emit_selection) - emit selectionChanged(); + if (!block_emit_selection) emit selectionChanged(); } void BlockView::_setThumb(double v) { - _talpha = v; + _talpha = v; QWidget * w = &widget_thumb; - QMetaObject::invokeMethod(this, [w](){w->update();}, Qt::QueuedConnection); - if (_talpha <= 0.01) widget_thumb.hide(); - else widget_thumb.show(); + QMetaObject::invokeMethod( + this, + [w]() { w->update(); }, + Qt::QueuedConnection); + if (_talpha <= 0.01) + widget_thumb.hide(); + else + widget_thumb.show(); } @@ -1841,7 +1831,7 @@ void BlockView::_setNav(QRectF v) { double vw = viewport()->width(), vh = viewport()->height(); if (vw < 1. || vh < 1. || v.isEmpty()) return; QTransform matrix; - double scl = qMin(vw / v.width(), vh / v.height()); + double scl = qMin(vw / v.width(), vh / v.height()); double ascl = appScale(this); if (scl > 0.02 * ascl && scl < 50.0 * ascl) { matrix.scale(scl, scl); @@ -1865,23 +1855,21 @@ void BlockView::_navFinished() { void BlockView::reconnectAll() { - //qDebug() << "reconnect"; + // qDebug() << "reconnect"; removeJunk(); - QList gi = scene_->items(); - QList pins; - QList buses; - foreach (QGraphicsItem * i, gi) { - if (i->data(bvidType).toInt() == bvitPin) - pins << qgraphicsitem_cast(i); - if (i->data(bvidType).toInt() == bvitBus) - buses << qgraphicsitem_cast(i); + QList gi = scene_->items(); + QList pins; + QList buses; + foreach(QGraphicsItem * i, gi) { + if (i->data(bvidType).toInt() == bvitPin) pins << qgraphicsitem_cast(i); + if (i->data(bvidType).toInt() == bvitBus) buses << qgraphicsitem_cast(i); } - foreach (BlockItemPin * p, pins) { + foreach(BlockItemPin * p, pins) { p->clearStateStack(); p->setState(BlockItemPin::Disconnected); p->buses_.clear(); } - foreach (BlockBusItem * b, buses) { + foreach(BlockBusItem * b, buses) { b->connections_.clear(); QVector conns(b->endpoints()); for (int c = 0; c < conns.size(); ++c) { @@ -1890,11 +1878,10 @@ void BlockView::reconnectAll() { if (!pins[j]->isVisible()) continue; QPointF pp = pins[j]->scenePos(); if ((cp - pp).manhattanLength() <= (grid_step / 2.)) { - //qDebug() << "found"; + // qDebug() << "found"; if (b->busType() == pins[j]->busType()) { b->connections_[conns[c]] = pins[j]; - if (!pins[j]->buses_.contains(b)) - pins[j]->buses_ << b; + if (!pins[j]->buses_.contains(b)) pins[j]->buses_ << b; pins[j]->setState(BlockItemPin::Connected); } else pins[j]->setState(BlockItemPin::Reject); @@ -1903,17 +1890,18 @@ void BlockView::reconnectAll() { } } } - //qDebug() << pins.size() << buses.size(); + // qDebug() << pins.size() << buses.size(); } void BlockView::zoom(double factor) { - if (!is_nav_anim || (nav_anim.state() != QPropertyAnimation::Running)) - nav_target = _nav(); + if (!is_nav_anim || (nav_anim.state() != QPropertyAnimation::Running)) nav_target = _nav(); QRectF r = nav_target; QPoint mp; - if (underMouse()) mp = mapFromGlobal(QCursor::pos()); - else mp = QPoint(viewport()->width() / 2, viewport()->height() / 2); + if (underMouse()) + mp = mapFromGlobal(QCursor::pos()); + else + mp = QPoint(viewport()->width() / 2, viewport()->height() / 2); double cx = double(mp.x()) / viewport()->width(), cy = double(mp.y()) / viewport()->height(); double pw = r.width(), ph = r.height(); r.setWidth(r.width() / factor); @@ -1930,11 +1918,11 @@ void BlockView::zoomReset() { void BlockView::copyToClipboard() { - QList bll = selectedBlocks(); - QList del = selectedDecors(); - //qDebug() << "copy" << bll.size() << del.size(); + QList bll = selectedBlocks(); + QList del = selectedDecors(); + // qDebug() << "copy" << bll.size() << del.size(); if (bll.isEmpty() && del.isEmpty()) return; - QList bul = internalBuses(bll); + QList bul = internalBuses(bll); QByteArray ba; QDataStream s(&ba, QIODevice::ReadWrite); s << uint(0x89abcdef) << bll << bul << del; @@ -1949,11 +1937,11 @@ void BlockView::pasteFromClipboard() { if (!mime) return; if (!mime->hasFormat(_BlockView_Mime_)) return; QByteArray ba = mime->data(_BlockView_Mime_); - //qDebug() << "paste" << ba.size(); + // qDebug() << "paste" << ba.size(); if (ba.size() < 4) return; - QList bll; - QList bul; - QList del, gl; + QList bll; + QList bul; + QList del, gl; uint hdr = 0; QDataStream s(ba); s >> hdr; @@ -1962,24 +1950,26 @@ void BlockView::pasteFromClipboard() { int all = bll.size() + bul.size() + del.size(); if (all == 0) return; QRectF br; - foreach (BlockItem * b, bll) { + foreach(BlockItem * b, bll) { br |= b->boundingRect().translated(b->pos()); gl << b; } - foreach (BlockBusItem * b, bul) + foreach(BlockBusItem * b, bul) gl << b; - foreach (QGraphicsItem * b, del) + foreach(QGraphicsItem * b, del) br |= b->boundingRect().translated(b->pos()); gl << del; QPointF copy_dp; - if (underMouse()) copy_dp = mapToScene(mapFromGlobal(QCursor::pos())); - else copy_dp = mapToScene(rect().center()); + if (underMouse()) + copy_dp = mapToScene(mapFromGlobal(QCursor::pos())); + else + copy_dp = mapToScene(rect().center()); copy_dp -= br.center(); - copy_dp = quantize(copy_dp, grid_step); + copy_dp = quantize(copy_dp, grid_step); ae_enabled = false; if (!bll.isEmpty()) copyBlocks(bll, copy_dp); if (!bul.isEmpty()) copyBuses(bul, copy_dp); - foreach (QGraphicsItem * i, del) + foreach(QGraphicsItem * i, del) i->setPos(i->pos() + copy_dp); addItems(del); ae_enabled = true; @@ -1988,80 +1978,75 @@ void BlockView::pasteFromClipboard() { void BlockView::selectNone() { - bool pb = block_emit_selection; - block_emit_selection = true; - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) + bool pb = block_emit_selection; + block_emit_selection = true; + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) i->setSelected(false); block_emit_selection = pb; - if (!block_emit_selection) - emit selectionChanged(); + if (!block_emit_selection) emit selectionChanged(); } void BlockView::selectAll() { - bool pb = block_emit_selection; - block_emit_selection = true; - QList gi = scene_->items(); - foreach (QGraphicsItem * i, gi) - if (i->flags().testFlag(QGraphicsItem::ItemIsSelectable)) - i->setSelected(true); + bool pb = block_emit_selection; + block_emit_selection = true; + QList gi = scene_->items(); + foreach(QGraphicsItem * i, gi) + if (i->flags().testFlag(QGraphicsItem::ItemIsSelectable)) i->setSelected(true); block_emit_selection = pb; - if (!block_emit_selection) - emit selectionChanged(); + if (!block_emit_selection) emit selectionChanged(); } void BlockView::removeSelected() { - QList gi = scene_->selectedItems(), ai; + QList gi = scene_->selectedItems(), ai; blockSignals(true); - QList sbuses = buses(), dbuses, wbuses = wrongConnectedBuses(); - foreach (BlockBusItem * i, sbuses) - if (i->connectedBlocks().isEmpty()) - dbuses << i; - foreach (QGraphicsItem * i, gi) { + QList sbuses = buses(), dbuses, wbuses = wrongConnectedBuses(); + foreach(BlockBusItem * i, sbuses) + if (i->connectedBlocks().isEmpty()) dbuses << i; + foreach(QGraphicsItem * i, gi) { if (i->data(bvidTmpItem).toBool()) continue; - if (i->data(bvidType).toInt() == bvitBlock) - ai << qgraphicsitem_cast(i); - if ((i->data(bvidType).toInt() == bvitBlock) || (i->data(bvidType).toInt() == bvitBus) || (i->data(bvidType).toInt() == bvitDecor)) { + if (i->data(bvidType).toInt() == bvitBlock) ai << qgraphicsitem_cast(i); + if ((i->data(bvidType).toInt() == bvitBlock) || (i->data(bvidType).toInt() == bvitBus) || + (i->data(bvidType).toInt() == bvitDecor)) { scene_->sendEvent(i, new QGraphicsSceneEvent(QEvent::Close)); delete i; } } reconnectAll(); - foreach (BlockBusItem * i, sbuses) + foreach(BlockBusItem * i, sbuses) if (i->connectedBlocks().isEmpty()) - if (!dbuses.contains(i)) - delete i; + if (!dbuses.contains(i)) delete i; blockSignals(false); - foreach (QGraphicsItem * i, ai) - emit blockRemoved((BlockItem*)i); + foreach(QGraphicsItem * i, ai) + emit blockRemoved((BlockItem *)i); emitActionEvent(BlockItemBase::BlockRemove, ai); } void BlockView::removeAll() { last_multiconnect_pl.clear(); - QList gi = scene_->items(), ai; + QList gi = scene_->items(), ai; blockSignals(true); match_bus = bus_from = cur_bus = nullptr; - mm_ci = nullptr; - hpin = nullptr; - ghost_ = nullptr; - foreach (QGraphicsItem * i, gi) { + mm_ci = nullptr; + hpin = nullptr; + ghost_ = nullptr; + foreach(QGraphicsItem * i, gi) { if (i->data(bvidTmpItem).toBool()) continue; - if (i->data(bvidType).toInt() == bvitBlock) - ai << qgraphicsitem_cast(i); - if ((i->data(bvidType).toInt() == bvitBlock) || (i->data(bvidType).toInt() == bvitBus) || (i->data(bvidType).toInt() == bvitDecor)) { + if (i->data(bvidType).toInt() == bvitBlock) ai << qgraphicsitem_cast(i); + if ((i->data(bvidType).toInt() == bvitBlock) || (i->data(bvidType).toInt() == bvitBus) || + (i->data(bvidType).toInt() == bvitDecor)) { if ((i != &sel_rect) && (i != &tmp_bus) && (i->parentItem() == 0) && !(i->data(bvidItemSelection).toBool())) { - //qDebug() << "delete" << i->data(1005).toInt(); + // qDebug() << "delete" << i->data(1005).toInt(); scene_->sendEvent(i, new QGraphicsSceneEvent(QEvent::Close)); delete i; } } } blockSignals(false); - foreach (QGraphicsItem * i, ai) - emit blockRemoved((BlockItem*)i); + foreach(QGraphicsItem * i, ai) + emit blockRemoved((BlockItem *)i); } diff --git a/libs/blockview/blockview.h b/libs/blockview/blockview.h index 7eb1dc4..7704eeb 100644 --- a/libs/blockview/blockview.h +++ b/libs/blockview/blockview.h @@ -1,45 +1,45 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKVIEW_H #define BLOCKVIEW_H -#include -#include -#include -#include -#include -#include -#include -#include -#include "blockviewwavetrace.h" #include "blockbusitem.h" +#include "blockviewwavetrace.h" #include "qad_blockview_export.h" - -Q_DECLARE_METATYPE(BlockItem*) -Q_DECLARE_METATYPE(BlockItemPin*) -Q_DECLARE_METATYPE(BlockBusItem*) +#include +#include +#include +#include +#include +#include +#include +#include -class QAD_BLOCKVIEW_EXPORT BlockView: public QGraphicsView -{ +Q_DECLARE_METATYPE(BlockItem *) +Q_DECLARE_METATYPE(BlockItemPin *) +Q_DECLARE_METATYPE(BlockBusItem *) + + +class QAD_BLOCKVIEW_EXPORT BlockView: public QGraphicsView { Q_OBJECT Q_ENUMS(SelectionMode) @@ -77,34 +77,37 @@ public: MultiSelection }; - QPen gridPen() const {return grid_pen;} - bool isGridVisible() const {return grid_visible;} - bool isSnapToGrid() const {return grid_snap;} - bool isPostMoveConnectEnabled() const {return pm_connect;} - bool isNavigationEnabled() const {return navigation;} - bool isNavigateAnimationEnabled() const {return is_nav_anim;} - bool isBlockAnimationEnabled() const {return is_block_anim;} - bool isConnectByMouseEnabled() const {return m_connect;} - bool isTraceConsiderBuses() const {return m_trace_with_buses;} - bool isPinMulticonnectEnabled() const {return m_pin_mc;} - bool isMiniMapEnabled() const {return minimap;} - bool isZoomWheelOnly() const {return wheel_zoom;} - bool isBusSquareNodes() const {return square_node;} - double gridStep() const {return grid_step;} - double gridPointsWidth() const {return grid_points;} - SelectionMode selectionMode() const {return smode;} - void setSelectionMode(SelectionMode mode) {smode = mode;} + QPen gridPen() const { return grid_pen; } + bool isGridVisible() const { return grid_visible; } + bool isSnapToGrid() const { return grid_snap; } + bool isPostMoveConnectEnabled() const { return pm_connect; } + bool isNavigationEnabled() const { return navigation; } + bool isNavigateAnimationEnabled() const { return is_nav_anim; } + bool isBlockAnimationEnabled() const { return is_block_anim; } + bool isConnectByMouseEnabled() const { return m_connect; } + bool isTraceConsiderBuses() const { return m_trace_with_buses; } + bool isPinMulticonnectEnabled() const { return m_pin_mc; } + bool isMiniMapEnabled() const { return minimap; } + bool isZoomWheelOnly() const { return wheel_zoom; } + bool isBusSquareNodes() const { return square_node; } + double gridStep() const { return grid_step; } + double gridPointsWidth() const { return grid_points; } + SelectionMode selectionMode() const { return smode; } + void setSelectionMode(SelectionMode mode) { smode = mode; } - void addItems(QList items) {foreach (QGraphicsItem * i, items) addItem(i);} - QList buses() const; - QList wrongConnectedBuses() const; - QList blocks() const; - QList decors() const; + void addItems(QList items) { + foreach(QGraphicsItem * i, items) + addItem(i); + } + QList buses() const; + QList wrongConnectedBuses() const; + QList blocks() const; + QList decors() const; BlockBusItem * connectionBus(BlockItem * b0, BlockItem * b1) const; - QList connectionBuses(BlockItem * b0, BlockItem * b1) const; + QList connectionBuses(BlockItem * b0, BlockItem * b1) const; bool connectPins(BlockItemPin * p0, BlockItemPin * p1); - QList selectedBlocks() const; - QList selectedDecors() const; + QList selectedBlocks() const; + QList selectedDecors() const; void setTransform(const QTransform & matrix, bool combine = false); void centerOn(const QPointF & pos); @@ -149,42 +152,42 @@ protected: void trace(QPointF scene_pos_from, QPointF scene_pos_to, BlockBusItem * bus, bool primary = true); void clearBusStates(); void matchBus(); - bool connectTmpToBus(BlockBusItem* bus); + bool connectTmpToBus(BlockBusItem * bus); void markPins(int bus_type); void unmarkPins(bool to_normal = false); void hoverAcceptedPin(BlockItemPin * pin, bool hover); void unhoverPins(BlockItemPin * excl_pin = 0); void simplifyBuses(); - void moveBuses(const QList & items, QPointF dp); - QList internalBuses(const QList & items); - QList nearPins(BlockItemPin * pin, Qt::KeyboardModifiers km); - BlockItemPin * getPin(const QList & list) const; + void moveBuses(const QList & items, QPointF dp); + QList internalBuses(const QList & items); + QList nearPins(BlockItemPin * pin, Qt::KeyboardModifiers km); + BlockItemPin * getPin(const QList & list) const; void highlightNearPins(BlockItemPin * pin, Qt::KeyboardModifiers km); void hideTmpBuses(bool clear = true); - double _thumb() const {return _talpha;} + double _thumb() const { return _talpha; } QRectF _nav() const; void animateNav(QRectF d, double scl = 0.); void scrollFromThumb(); void deleteCopyTemp(); - void emitActionEvent(BlockItemBase::Action action, QList items); + void emitActionEvent(BlockItemBase::Action action, QList items); void setGhost(BlockItem * item); void clearGhost(); - BlockItem * ghost() const {return ghost_;} + BlockItem * ghost() const { return ghost_; } virtual void loadBus(BlockBusItem * bus) {} - virtual void copyBlocks(QList items, QPointF offset) {} - virtual void copyBuses(QList items, QPointF offset) {} + virtual void copyBlocks(QList items, QPointF offset) {} + virtual void copyBuses(QList items, QPointF offset) {} virtual void newBusStarted(int bus_type) {} virtual void newBusCreated(BlockBusItem * bus) {} QGraphicsScene * scene_; QGraphicsRectItem sel_rect; QGraphicsItem * mm_ci; - QList sel_items; - QList copy_items; - QList last_multiconnect_pl; - QList copy_buses, tmp_buses; - BlockBusItem tmp_bus, * match_bus, * bus_from, * cur_bus; + QList sel_items; + QList copy_items; + QList last_multiconnect_pl; + QList copy_buses, tmp_buses; + BlockBusItem tmp_bus, *match_bus, *bus_from, *cur_bus; BlockItemPin * hpin; BlockItem * ghost_; BlockViewWavetrace wavetrace; @@ -200,7 +203,8 @@ protected: Qt::KeyboardModifiers mm_mods; QPropertyAnimation thumb_anim, nav_anim; int timer_thumb, thumb_hide_delay, thick; - bool mm_drag, new_bus, new_branch, moved, mm_cancel, iconnect, mm_copy, mm_thumb, ae_enabled, is_nav_anim, is_block_anim, move_bus_point; + bool mm_drag, new_bus, new_branch, moved, mm_cancel, iconnect, mm_copy, mm_thumb, ae_enabled, is_nav_anim, is_block_anim, + move_bus_point; bool grid_visible, grid_snap, pm_connect, navigation, m_connect, m_trace_with_buses, m_pin_mc, minimap, prev_tcb, wheel_zoom; bool nav_prev_aa, nav_prev_imaa, nav_prev_grid, square_node, block_emit_selection; double grid_step, grid_points, cur_scl, _talpha, thumb_scl; @@ -225,28 +229,41 @@ protected slots: void startBusPointMove(int bus_type); void pinHoverInOut(BlockItemPin * pin); void checkPaste(bool queued); - void checkPaste() {checkPaste(false);} + void checkPaste() { checkPaste(false); } public slots: - void setGridPen(const QPen & pen) {grid_pen = pen; _updateBack();} - void setGridVisible(bool yes) {grid_visible = yes; _updateBack();} - void setSnapToGrid(bool yes) {grid_snap = yes;} - void setGridStep(double step) {grid_step = step; applyGridStep(); _updateBack();} - void setGridPointsWidth(double width_) {grid_points = width_; _updateBack();} - void setPostMoveConnectEnabled(bool on) {pm_connect = on;} - void setNavigationEnabled(bool on) {navigation = on;} - void setNavigateAnimationEnabled(bool on) {is_nav_anim = on;} - void setBlockAnimationEnabled(bool on) {is_block_anim = on;} - void setConnectByMouseEnabled(bool on) {m_connect = on;} - void setTraceConsiderBuses(bool on) {m_trace_with_buses = on;} - void setPinMulticonnectEnabled(bool on) {m_pin_mc = on;} - void setMiniMapEnabled(bool on) {minimap = on;} - void setZoomWheelOnly(bool on) {wheel_zoom = on;} + void setGridPen(const QPen & pen) { + grid_pen = pen; + _updateBack(); + } + void setGridVisible(bool yes) { + grid_visible = yes; + _updateBack(); + } + void setSnapToGrid(bool yes) { grid_snap = yes; } + void setGridStep(double step) { + grid_step = step; + applyGridStep(); + _updateBack(); + } + void setGridPointsWidth(double width_) { + grid_points = width_; + _updateBack(); + } + void setPostMoveConnectEnabled(bool on) { pm_connect = on; } + void setNavigationEnabled(bool on) { navigation = on; } + void setNavigateAnimationEnabled(bool on) { is_nav_anim = on; } + void setBlockAnimationEnabled(bool on) { is_block_anim = on; } + void setConnectByMouseEnabled(bool on) { m_connect = on; } + void setTraceConsiderBuses(bool on) { m_trace_with_buses = on; } + void setPinMulticonnectEnabled(bool on) { m_pin_mc = on; } + void setMiniMapEnabled(bool on) { minimap = on; } + void setZoomWheelOnly(bool on) { wheel_zoom = on; } void setBusSquareNodes(bool yes); void zoom(double factor); - void zoomIn() {zoom(1.2);} - void zoomOut() {zoom(1. / 1.2);} + void zoomIn() { zoom(1.2); } + void zoomOut() { zoom(1. / 1.2); } void zoomReset(); void copyToClipboard(); @@ -261,17 +278,16 @@ public slots: void addItem(QGraphicsItem * item, bool emit_action = true); signals: - void blockDoubleClicked(BlockItem * ); - void blockHoverEnter(BlockItem * ); - void blockHoverLeave(BlockItem * ); - void busDoubleClicked(BlockBusItem * ); - void schemeAction(BlockItemBase::Action action, QList items); + void blockDoubleClicked(BlockItem *); + void blockHoverEnter(BlockItem *); + void blockHoverLeave(BlockItem *); + void busDoubleClicked(BlockBusItem *); + void schemeAction(BlockItemBase::Action action, QList items); void blockRemoved(BlockItem * item); void connectionsChanged(); void copyEnabledChanged(bool); void pasteEnabledChanged(bool); void selectionChanged(); - }; #endif // BLOCKVIEW_H diff --git a/libs/blockview/blockviewwavetrace.cpp b/libs/blockview/blockviewwavetrace.cpp index 6c2ba90..f714528 100644 --- a/libs/blockview/blockviewwavetrace.cpp +++ b/libs/blockview/blockviewwavetrace.cpp @@ -11,8 +11,7 @@ BlockViewWavetrace::BlockViewWavetrace(int width, int height) { void BlockViewWavetrace::resize(int width, int height) { wid = width; hei = height; - if (field.size() != wid) - field.resize(wid); + if (field.size() != wid) field.resize(wid); for (int i = 0; i < wid; ++i) { if (field[i].size() != hei) { field[i].resize(hei); @@ -41,8 +40,7 @@ void BlockViewWavetrace::fill(const QRect & rect, short val) { void BlockViewWavetrace::fill(int px, int py, short val) { short p = field[px][py].value; - if ((val == HorizontalBus && p == VerticalBus ) || - (val == VerticalBus && p == HorizontalBus)) + if ((val == HorizontalBus && p == VerticalBus) || (val == VerticalBus && p == HorizontalBus)) field[px][py].value = Blocked; else field[px][py].value = val; @@ -54,14 +52,13 @@ bool BlockViewWavetrace::trace(const QPoint & start, const QPoint & finish) { st = start; fn = finish; if (dir_ == NoTrace) return true; - //qDebug() << "trace" << start << finish; + // qDebug() << "trace" << start << finish; short cl = 0; QRect frect(0, 0, wid - 1, hei - 1); QVector cpnts, npnts; fill(st, cl); cpnts.push_back(st); - if (field[fn.x()][fn.y()].value == (short)Blocked) - return false; + if (field[fn.x()][fn.y()].value == (short)Blocked) return false; auto checkAndFill = [this, &npnts, &frect](int x, int y, short acc_dir, short c) { if (!frect.contains(x, y)) return; short p = field[x][y].value; @@ -73,18 +70,16 @@ bool BlockViewWavetrace::trace(const QPoint & start, const QPoint & finish) { while (cpnts.size() > 0) { npnts.clear(); cl++; - if (cl >= max_steps) - return false; + if (cl >= max_steps) return false; for (int i = 0; i < cpnts.size(); ++i) { - if (cpnts[i] == fn) - return true; - checkAndFill(cpnts[i].x() - 1, cpnts[i].y() , (short)VerticalBus , cl); - checkAndFill(cpnts[i].x() + 1, cpnts[i].y() , (short)VerticalBus , cl); - checkAndFill(cpnts[i].x() , cpnts[i].y() - 1, (short)HorizontalBus, cl); - checkAndFill(cpnts[i].x() , cpnts[i].y() + 1, (short)HorizontalBus, cl); + if (cpnts[i] == fn) return true; + checkAndFill(cpnts[i].x() - 1, cpnts[i].y(), (short)VerticalBus, cl); + checkAndFill(cpnts[i].x() + 1, cpnts[i].y(), (short)VerticalBus, cl); + checkAndFill(cpnts[i].x(), cpnts[i].y() - 1, (short)HorizontalBus, cl); + checkAndFill(cpnts[i].x(), cpnts[i].y() + 1, (short)HorizontalBus, cl); } cpnts = npnts; - //qDebug() << cl << ": " << cpnts.size(); + // qDebug() << cl << ": " << cpnts.size(); } return false; } @@ -99,25 +94,22 @@ void BlockViewWavetrace::gatherPath() { } int pa = -1, ca = -1; bool first = true; - short cl = field[fn.x()][fn.y()].value; + short cl = field[fn.x()][fn.y()].value; QRect frect(0, 0, wid, hei); - QPoint cpnt = fn; - auto checkAndStep = [this, &cpnt, &first, &frect] (int dir, short c, int & ca_, int pa_)->bool { + QPoint cpnt = fn; + auto checkAndStep = [this, &cpnt, &first, &frect](int dir, short c, int & ca_, int pa_) -> bool { int cx = cpnt.x() + dps[dir].x(); int cy = cpnt.y() + dps[dir].y(); if (frect.contains(cx, cy)) { const Cell & cell(field[cx][cy]); if (cell.value == c) { if (cell.direction == HorizontalBus || cell.direction == VerticalBus) { - if (dps[dir].x() == 0 && cell.direction == VerticalBus) - return false; - if (dps[dir].y() == 0 && cell.direction == HorizontalBus) - return false; + if (dps[dir].x() == 0 && cell.direction == VerticalBus) return false; + if (dps[dir].y() == 0 && cell.direction == HorizontalBus) return false; } ca_ = QLineF(QPointF(cx, cy), cpnt).angle(); - if (ca_ != pa_ && !first) - path_.push_front(cpnt); - cpnt = QPoint(cx, cy); + if (ca_ != pa_ && !first) path_.push_front(cpnt); + cpnt = QPoint(cx, cy); first = false; return true; } @@ -132,7 +124,6 @@ void BlockViewWavetrace::gatherPath() { if (checkAndStep(1, cl, ca, pa)) continue; if (checkAndStep(2, cl, ca, pa)) continue; if (checkAndStep(3, cl, ca, pa)) continue; - } path_.push_front(st); } diff --git a/libs/blockview/blockviewwavetrace.h b/libs/blockview/blockviewwavetrace.h index c7c48cb..1d93be4 100644 --- a/libs/blockview/blockviewwavetrace.h +++ b/libs/blockview/blockviewwavetrace.h @@ -1,20 +1,20 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef BLOCKVIEWWAVETRACE_H @@ -27,28 +27,37 @@ class QAD_BLOCKVIEW_EXPORT BlockViewWavetrace { public: BlockViewWavetrace(int width = 1, int height = 1); - - enum CellState {Empty = -1, Blocked = -2, HorizontalBus = -3, VerticalBus = -4}; - enum Direction {NoTrace, Horizontal, Vertical}; - - int width() const {return wid;} - int height() const {return hei;} + + enum CellState { + Empty = -1, + Blocked = -2, + HorizontalBus = -3, + VerticalBus = -4 + }; + enum Direction { + NoTrace, + Horizontal, + Vertical + }; + + int width() const { return wid; } + int height() const { return hei; } void resize(int width, int height); - void resize(const QSize & sz) {resize(sz.width(), sz.height());} + void resize(const QSize & sz) { resize(sz.width(), sz.height()); } void fill(short val = -1); void fill(const QRect & rect, short val = -1); - void fill(const QPoint & point, short val = -1) {fill(point.x(), point.y(), val);} + void fill(const QPoint & point, short val = -1) { fill(point.x(), point.y(), val); } void fill(int px, int py, short val); - void fill(BlockViewWavetrace::CellState val = Empty) {fill((short)val);} - void fill(const QRect & rect, BlockViewWavetrace::CellState val = Empty) {fill(rect, (short)val);} - void fill(const QPoint & point, BlockViewWavetrace::CellState val = Empty) {fill(point, (short)val);} - void fill(int px, int py, BlockViewWavetrace::CellState val = Empty) {fill(px, py, (short)val);} - void clear() {fill(-1);} + void fill(BlockViewWavetrace::CellState val = Empty) { fill((short)val); } + void fill(const QRect & rect, BlockViewWavetrace::CellState val = Empty) { fill(rect, (short)val); } + void fill(const QPoint & point, BlockViewWavetrace::CellState val = Empty) { fill(point, (short)val); } + void fill(int px, int py, BlockViewWavetrace::CellState val = Empty) { fill(px, py, (short)val); } + void clear() { fill(-1); } bool trace(const QPoint & start, const QPoint & finish); - Direction preferredDirection() const {return dir_;} + Direction preferredDirection() const { return dir_; } void setPreferredDirection(Direction dir); - void setMaximumSteps(int steps) {max_steps = steps;} - int maximumSteps() const {return max_steps;} + void setMaximumSteps(int steps) { max_steps = steps; } + int maximumSteps() const { return max_steps; } void gatherPath(); const QVector & path() const; @@ -61,11 +70,10 @@ private: int wid, hei, max_steps; Direction dir_; - QVector > field; + QVector> field; QVector path_; QVector jumps; QPoint dps[4], st, fn; - }; #endif // BLOCKVIEWWAVETRACE_H diff --git a/libs/blockview/drawtools.cpp b/libs/blockview/drawtools.cpp index 5b9e344..45ef5b8 100644 --- a/libs/blockview/drawtools.cpp +++ b/libs/blockview/drawtools.cpp @@ -1,23 +1,25 @@ #include "drawtools.h" -#include "ui_drawtools.h" + #include "alignedtextitem.h" -#include -#include -#include -#include -#include -#include -#include +#include "ui_drawtools.h" + #include +#include +#include +#include +#include +#include +#include +#include _DTSizeItem::_DTSizeItem(): QGraphicsObject() { - cur_item = nullptr; - grid = 10.; + cur_item = nullptr; + grid = 10.; in_process = can_drag = false; setData(bvidItemSelection, true); for (int i = 0; i < 8; ++i) { - //qDebug() << &(rects[i]); + // qDebug() << &(rects[i]); rects[i].setData(bvidItemSelection, true); rects[i].setData(bvidDTHandle, true); rects[i].setFlag(QGraphicsItem::ItemIgnoresTransformations); @@ -32,7 +34,7 @@ _DTSizeItem::_DTSizeItem(): QGraphicsObject() { _DTSizeItem::~_DTSizeItem() { assignObject(nullptr); - //qDebug() << "!!!"; + // qDebug() << "!!!"; } @@ -52,15 +54,15 @@ void _DTSizeItem::assignObject(QGraphicsItem * item) { } if (cur_item->scene()) { if (!cur_item->scene()->views().isEmpty()) { - grid = qobject_cast(cur_item->scene()->views()[0])->gridStep(); + grid = qobject_cast(cur_item->scene()->views()[0])->gridStep(); } } - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); - QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); if (irect || iell || iline) { resizeHandles(); - is_line = qgraphicsitem_cast(cur_item); + is_line = qgraphicsitem_cast(cur_item); for (int i = 0; i < (is_line ? 2 : 8); ++i) { rects[i].setParentItem(cur_item); rects[i].installSceneEventFilter(this); @@ -78,26 +80,36 @@ void _DTSizeItem::moveRects() { QRectF rect = itemRect(cur_item); QPointF tl = rect.topLeft(), tr = rect.topRight(), bl = rect.bottomLeft(), br = rect.bottomRight(); if (is_line) { - rects[0].setPos(tl); rects[0].setData(2001, int(Qt::SizeAllCursor)); - rects[1].setPos(br); rects[1].setData(2001, int(Qt::SizeAllCursor)); + rects[0].setPos(tl); + rects[0].setData(2001, int(Qt::SizeAllCursor)); + rects[1].setPos(br); + rects[1].setData(2001, int(Qt::SizeAllCursor)); } else { - rects[0].setPos(tl); rects[0].setData(2001, int(Qt::SizeFDiagCursor)); - rects[1].setPos((tl + tr) / 2.); rects[1].setData(2001, int(Qt::SizeVerCursor)); - rects[2].setPos(tr); rects[2].setData(2001, int(Qt::SizeBDiagCursor)); - rects[3].setPos((tr + br) / 2.); rects[3].setData(2001, int(Qt::SizeHorCursor)); - rects[4].setPos(br); rects[4].setData(2001, int(Qt::SizeFDiagCursor)); - rects[5].setPos((br + bl) / 2.); rects[5].setData(2001, int(Qt::SizeVerCursor)); - rects[6].setPos(bl); rects[6].setData(2001, int(Qt::SizeBDiagCursor)); - rects[7].setPos((bl + tl) / 2.); rects[7].setData(2001, int(Qt::SizeHorCursor)); + rects[0].setPos(tl); + rects[0].setData(2001, int(Qt::SizeFDiagCursor)); + rects[1].setPos((tl + tr) / 2.); + rects[1].setData(2001, int(Qt::SizeVerCursor)); + rects[2].setPos(tr); + rects[2].setData(2001, int(Qt::SizeBDiagCursor)); + rects[3].setPos((tr + br) / 2.); + rects[3].setData(2001, int(Qt::SizeHorCursor)); + rects[4].setPos(br); + rects[4].setData(2001, int(Qt::SizeFDiagCursor)); + rects[5].setPos((br + bl) / 2.); + rects[5].setData(2001, int(Qt::SizeVerCursor)); + rects[6].setPos(bl); + rects[6].setData(2001, int(Qt::SizeBDiagCursor)); + rects[7].setPos((bl + tl) / 2.); + rects[7].setData(2001, int(Qt::SizeHorCursor)); } } void _DTSizeItem::applyRect() { if (!cur_item) return; - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); - QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); if (irect) irect->setRect(nrect); if (iell) iell->setRect(nrect); if (iline) iline->setLine(QLineF(nrect.topLeft(), nrect.bottomRight())); @@ -105,21 +117,27 @@ void _DTSizeItem::applyRect() { void _DTSizeItem::doubleClick() { - QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(cur_item); - AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); - QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); + QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(cur_item); + AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); + QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); if (itext || iatext) { - QMetaObject::invokeMethod(this, [this](){textEditRequest();}, Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, + [this]() { textEditRequest(); }, + Qt::QueuedConnection); } if (ipixmap) { - QMetaObject::invokeMethod(this, [this](){pixmapEditRequest();}, Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, + [this]() { pixmapEditRequest(); }, + Qt::QueuedConnection); } } void _DTSizeItem::resizeHandles() { double sz = fontHeight() / 3.; - QRectF r(-sz, -sz, sz*2, sz*2); + QRectF r(-sz, -sz, sz * 2, sz * 2); for (int i = 0; i < 8; ++i) { rects[i].setRect(r); } @@ -128,9 +146,9 @@ void _DTSizeItem::resizeHandles() { QRectF _DTSizeItem::itemRect(const QGraphicsItem *) const { if (!cur_item) return QRectF(); - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); - QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); if (irect) return irect->rect(); if (iell) return iell->rect(); if (iline) return QRectF(iline->line().p1(), iline->line().p2()); @@ -148,7 +166,7 @@ QRectF _DTSizeItem::boundingRect() const { bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { - QGraphicsSceneMouseEvent * me = (QGraphicsSceneMouseEvent * )event; + QGraphicsSceneMouseEvent * me = (QGraphicsSceneMouseEvent *)event; if (watched == cur_item) { if (event->type() == QEvent::Close) { assignObject(nullptr); @@ -166,11 +184,13 @@ bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { view_ = nullptr; switch (event->type()) { case QEvent::GraphicsSceneHoverEnter: - if (watched->scene()) if (!watched->scene()->views().isEmpty()) view_ = watched->scene()->views()[0]; + if (watched->scene()) + if (!watched->scene()->views().isEmpty()) view_ = watched->scene()->views()[0]; if (view_) view_->setCursor(Qt::CursorShape(watched->data(2001).toInt())); break; case QEvent::GraphicsSceneHoverLeave: - if (watched->scene()) if (!watched->scene()->views().isEmpty()) view_ = watched->scene()->views()[0]; + if (watched->scene()) + if (!watched->scene()->views().isEmpty()) view_ = watched->scene()->views()[0]; if (view_) view_->unsetCursor(); break; case QEvent::GraphicsSceneMousePress: @@ -181,7 +201,7 @@ bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { moveRects(); } in_process = false; - pp = quantize(me->scenePos(), grid); + pp = quantize(me->scenePos(), grid); cur_item->setData(2000, itemRect(cur_item)); return true; case QEvent::GraphicsSceneMouseMove: @@ -189,7 +209,7 @@ bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { sp = quantize(me->scenePos(), grid); if (pp != sp && can_drag) { in_process = true; - nrect = itemRect(cur_item); + nrect = itemRect(cur_item); if (is_line) { if (watched == &(rects[0])) nrect.setTopLeft(rects[0].pos() + (sp - pp)); if (watched == &(rects[1])) nrect.setBottomRight(rects[1].pos() + (sp - pp)); @@ -213,7 +233,7 @@ bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { case QEvent::GraphicsSceneMouseRelease: if (in_process) emit sizeChanged(); in_process = false; - can_drag = false; + can_drag = false; return true; default: break; } @@ -221,19 +241,21 @@ bool _DTSizeItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event) { } - - -DrawTools::DrawTools(BlockView * parent): QWidget(parent), -actions_Z_up(this), actions_Z_top(this), actions_Z_down(this), actions_Z_bottom(this) { +DrawTools::DrawTools(BlockView * parent) + : QWidget(parent) + , actions_Z_up(this) + , actions_Z_top(this) + , actions_Z_down(this) + , actions_Z_bottom(this) { widget_props = new QWidget(); - ui = new Ui::DrawTools(); + ui = new Ui::DrawTools(); ui->setupUi(widget_props); ui->labelPen->setMinimumSize(preferredIconSize(1.5, widget_props)); ui->labelPen->setMaximumSize(ui->labelPen->minimumSize()); ui->labelBrush->setMinimumSize(ui->labelPen->minimumSize()); ui->labelBrush->setMaximumSize(ui->labelBrush->minimumSize()); widget_props->setEnabled(false); - int fh = qMax(fontHeight(this), 22); + int fh = qMax(fontHeight(this), 22); int thick = lineThickness(this); QSize sz(fh * 2.5, fh); ui->comboLineStyle->setIconSize(sz); @@ -251,36 +273,37 @@ actions_Z_up(this), actions_Z_top(this), actions_Z_down(this), actions_Z_bottom( #else setAlignCompact(false); #endif - menu_hor.addActions(QList() << ui->actionLeft << ui->actionHCenter << ui->actionRight); - menu_ver.addActions(QList() << ui->actionTop << ui->actionVCenter << ui->actionBottom); + menu_hor.addActions(QList() << ui->actionLeft << ui->actionHCenter << ui->actionRight); + menu_ver.addActions(QList() << ui->actionTop << ui->actionVCenter << ui->actionBottom); ui->buttonAlignHor->setMenu(&menu_hor); ui->buttonAlignVer->setMenu(&menu_ver); new_type = -1; new_item = cur_item = nullptr; - view_ = nullptr; - resize_enabled = true; + view_ = nullptr; + resize_enabled = true; text_dlg.setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); QDialogButtonBox * bbox = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel); connect(bbox, SIGNAL(accepted()), &text_dlg, SLOT(accept())); connect(bbox, SIGNAL(rejected()), &text_dlg, SLOT(reject())); text_dlg.layout()->addWidget(&text_edit); text_dlg.layout()->addWidget(bbox); - actions_Z_up.setIcon(QIcon(":/icons/z-up.png")); actions_Z_up.setEnabled(false); - actions_Z_top.setIcon(QIcon(":/icons/z-top.png")); actions_Z_top.setEnabled(false); - actions_Z_down.setIcon(QIcon(":/icons/z-down.png")); actions_Z_down.setEnabled(false); - actions_Z_bottom.setIcon(QIcon(":/icons/z-bottom.png")); actions_Z_bottom.setEnabled(false); - actions_add << newAction(QIcon(":/icons/draw-rectangle.png"), 1) - << newAction(QIcon(":/icons/draw-ellipse.png"), 2) - << newAction(QIcon(":/icons/draw-line.png"), 4) - << newAction(QIcon(":/icons/draw-text.png"), 0) + actions_Z_up.setIcon(QIcon(":/icons/z-up.png")); + actions_Z_up.setEnabled(false); + actions_Z_top.setIcon(QIcon(":/icons/z-top.png")); + actions_Z_top.setEnabled(false); + actions_Z_down.setIcon(QIcon(":/icons/z-down.png")); + actions_Z_down.setEnabled(false); + actions_Z_bottom.setIcon(QIcon(":/icons/z-bottom.png")); + actions_Z_bottom.setEnabled(false); + actions_add << newAction(QIcon(":/icons/draw-rectangle.png"), 1) << newAction(QIcon(":/icons/draw-ellipse.png"), 2) + << newAction(QIcon(":/icons/draw-line.png"), 4) << newAction(QIcon(":/icons/draw-text.png"), 0) << newAction(QIcon(":/icons/view-preview.png"), 3); - buttons_align << ui->buttonAlignTL << ui->buttonAlignTC << ui->buttonAlignTR - << ui->buttonAlignCL << ui->buttonAlignCC << ui->buttonAlignCR - << ui->buttonAlignBL << ui->buttonAlignBC << ui->buttonAlignBR; - foreach (QAction * a, actions_add) { + buttons_align << ui->buttonAlignTL << ui->buttonAlignTC << ui->buttonAlignTR << ui->buttonAlignCL << ui->buttonAlignCC + << ui->buttonAlignCR << ui->buttonAlignBL << ui->buttonAlignBC << ui->buttonAlignBR; + foreach(QAction * a, actions_add) { connect(a, SIGNAL(toggled(bool)), this, SLOT(toggleNewItem(bool))); } - foreach (QToolButton * b, buttons_align) { + foreach(QToolButton * b, buttons_align) { connect(b, SIGNAL(clicked(bool)), this, SLOT(alignClicked())); } connect(ui->buttonImage, SIGNAL(clicked(bool)), this, SLOT(buttonImage_clicked())); @@ -328,8 +351,7 @@ DrawTools::~DrawTools() { void DrawTools::retranslate() { QStringList styles; - styles << tr("NoPen") << tr("Solid") << tr("Dash") - << tr("Dot") << tr("Dash-Dot") << tr("Dash-Dot-Dot"); + styles << tr("NoPen") << tr("Solid") << tr("Dash") << tr("Dot") << tr("Dash-Dot") << tr("Dash-Dot-Dot"); for (int i = 0; i < styles.size(); i++) { ui->comboLineStyle->setItemText(i, styles[i]); } @@ -380,7 +402,7 @@ bool DrawTools::eventFilter(QObject * o, QEvent * e) { delete new_item; new_item = nullptr; if (!me->modifiers().testFlag(Qt::ControlModifier)) { - foreach (QAction * a, actions_add) { + foreach(QAction * a, actions_add) { a->setChecked(false); } new_type = -1; @@ -388,26 +410,21 @@ bool DrawTools::eventFilter(QObject * o, QEvent * e) { } } new_item = nullptr; - pp = sp; + pp = sp; switch (new_type) { case 0: new_item = new AlignedTextItem(); qgraphicsitem_cast(new_item)->setText("Text"); qgraphicsitem_cast(new_item)->setPos(sp); break; - case 1: - new_item = new QGraphicsRectItem(); - break; - case 2: - new_item = new QGraphicsEllipseItem(); - break; + case 1: new_item = new QGraphicsRectItem(); break; + case 2: new_item = new QGraphicsEllipseItem(); break; case 3: new_item = new QGraphicsPixmapItem(QPixmap(":/icons/view-preview.png")); - qgraphicsitem_cast(new_item)->setPos(sp - QPointF(new_item->boundingRect().width() / 2, new_item->boundingRect().height() / 2)); - break; - case 4: - new_item = new QGraphicsLineItem(QLineF(sp, sp)); + qgraphicsitem_cast(new_item)->setPos( + sp - QPointF(new_item->boundingRect().width() / 2, new_item->boundingRect().height() / 2)); break; + case 4: new_item = new QGraphicsLineItem(QLineF(sp, sp)); break; }; if (new_item) { if (new_type == 1 || new_type == 2) { @@ -424,21 +441,14 @@ bool DrawTools::eventFilter(QObject * o, QEvent * e) { if (new_item) { mr = new_item->mapRectFromScene(QRectF(pp, sp).normalized()); switch (new_type) { - case 0: - qgraphicsitem_cast(new_item)->setPos(sp); - break; - case 1: - qgraphicsitem_cast(new_item)->setRect(mr); - break; - case 2: - qgraphicsitem_cast(new_item)->setRect(mr); - break; + case 0: qgraphicsitem_cast(new_item)->setPos(sp); break; + case 1: qgraphicsitem_cast(new_item)->setRect(mr); break; + case 2: qgraphicsitem_cast(new_item)->setRect(mr); break; case 3: - qgraphicsitem_cast(new_item)->setPos(sp - QPointF(new_item->boundingRect().width() / 2, new_item->boundingRect().height() / 2)); - break; - case 4: - qgraphicsitem_cast(new_item)->setLine(QLineF(pp, sp)); + qgraphicsitem_cast(new_item)->setPos( + sp - QPointF(new_item->boundingRect().width() / 2, new_item->boundingRect().height() / 2)); break; + case 4: qgraphicsitem_cast(new_item)->setLine(QLineF(pp, sp)); break; }; return true; } @@ -457,7 +467,7 @@ bool DrawTools::eventFilter(QObject * o, QEvent * e) { } new_item = nullptr; if (!me->modifiers().testFlag(Qt::ControlModifier)) { - foreach (QAction * a, actions_add) { + foreach(QAction * a, actions_add) { a->setChecked(false); } new_type = -1; @@ -497,8 +507,8 @@ QAction * DrawTools::newAction(const QIcon & icon, int type) { void DrawTools::toggleNewItem(bool on) { - QAction * sa = (QAction * )sender(); - foreach (QAction * a, actions_add) { + QAction * sa = (QAction *)sender(); + foreach(QAction * a, actions_add) { if (a != sa) a->setChecked(false); } if (!on) { @@ -512,12 +522,12 @@ void DrawTools::toggleNewItem(bool on) { void DrawTools::alignClicked() { - QToolButton * sb = (QToolButton * )sender(); - foreach (QToolButton * b, buttons_align) { + QToolButton * sb = (QToolButton *)sender(); + foreach(QToolButton * b, buttons_align) { if (b != sb) b->setChecked(false); } sb->setChecked(true); - align = Qt::Alignment(); + align = Qt::Alignment(); QString als = sb->objectName().right(2).toLower(); if (als[0] == 't') align |= Qt::AlignTop; if (als[0] == 'c') align |= Qt::AlignVCenter; @@ -563,7 +573,7 @@ void DrawTools::blockPropSignals(bool block_) { ui->actionHCenter->blockSignals(block_); ui->actionLeft->blockSignals(block_); ui->actionRight->blockSignals(block_); - foreach (QToolButton * b, buttons_align) { + foreach(QToolButton * b, buttons_align) { b->blockSignals(block_); } } @@ -571,8 +581,12 @@ void DrawTools::blockPropSignals(bool block_) { void DrawTools::actionAlignTrigger(bool vert, Qt::AlignmentFlag value) { blockPropSignals(true); - if (vert) foreach (QAction * a, menu_ver.actions()) a->setChecked(false); - else foreach (QAction * a, menu_hor.actions()) a->setChecked(false); + if (vert) + foreach(QAction * a, menu_ver.actions()) + a->setChecked(false); + else + foreach(QAction * a, menu_hor.actions()) + a->setChecked(false); align = align & (vert ? Qt::AlignHorizontal_Mask : Qt::AlignVertical_Mask); align |= value; qobject_cast(sender())->setChecked(true); @@ -583,7 +597,9 @@ void DrawTools::actionAlignTrigger(bool vert, Qt::AlignmentFlag value) { void DrawTools::emitZAvailabe(QGraphicsItem * item) { BlockView * view = nullptr; - if (item) if (item->scene()) if (!item->scene()->views().isEmpty()) view = qobject_cast(item->scene()->views()[0]); + if (item) + if (item->scene()) + if (!item->scene()->views().isEmpty()) view = qobject_cast(item->scene()->views()[0]); if (!view) { moveZUpAvailable(false); moveZDownAvailable(false); @@ -633,11 +649,11 @@ void DrawTools::selectionChanged() { return; } QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(cur_item); - AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); - QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); - QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); + QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); blockPropSignals(true); if (itext) { ui->stackedProperties->setCurrentIndex(0); @@ -658,20 +674,40 @@ void DrawTools::selectionChanged() { font_dlg.setCurrentFont(iatext->font()); font_dlg.blockSignals(false); setToolButtonsEnabled(true, false, false); - foreach (QAction * a, menu_hor.actions()) a->setChecked(false); - foreach (QAction * a, menu_ver.actions()) a->setChecked(false); + foreach(QAction * a, menu_hor.actions()) + a->setChecked(false); + foreach(QAction * a, menu_ver.actions()) + a->setChecked(false); align = iatext->alignment(); QString als; - if (align.testFlag(Qt::AlignTop)) {als += "T"; ui->actionTop->setChecked(true);} - if (align.testFlag(Qt::AlignVCenter)) {als += "C"; ui->actionVCenter->setChecked(true);} - if (align.testFlag(Qt::AlignBottom)) {als += "B"; ui->actionBottom->setChecked(true);} - if (align.testFlag(Qt::AlignLeft)) {als += "L"; ui->actionLeft->setChecked(true);} - if (align.testFlag(Qt::AlignHCenter)) {als += "C"; ui->actionHCenter->setChecked(true);} - if (align.testFlag(Qt::AlignRight)) {als += "R"; ui->actionRight->setChecked(true);} - foreach (QToolButton * b, buttons_align) { + if (align.testFlag(Qt::AlignTop)) { + als += "T"; + ui->actionTop->setChecked(true); + } + if (align.testFlag(Qt::AlignVCenter)) { + als += "C"; + ui->actionVCenter->setChecked(true); + } + if (align.testFlag(Qt::AlignBottom)) { + als += "B"; + ui->actionBottom->setChecked(true); + } + if (align.testFlag(Qt::AlignLeft)) { + als += "L"; + ui->actionLeft->setChecked(true); + } + if (align.testFlag(Qt::AlignHCenter)) { + als += "C"; + ui->actionHCenter->setChecked(true); + } + if (align.testFlag(Qt::AlignRight)) { + als += "R"; + ui->actionRight->setChecked(true); + } + foreach(QToolButton * b, buttons_align) { b->setChecked(false); } - foreach (QToolButton * b, buttons_align) { + foreach(QToolButton * b, buttons_align) { if (b->objectName().endsWith(als)) { b->setChecked(true); break; @@ -724,7 +760,7 @@ void DrawTools::selectionChanged() { void DrawTools::sizeChanged() { blockPropSignals(true); - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); if (irect || iell) { if (irect) { @@ -744,17 +780,17 @@ void DrawTools::sizeChanged() { void DrawTools::propertyChanged() { if (!cur_item) return; QGraphicsSimpleTextItem * itext = qgraphicsitem_cast(cur_item); - AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); - QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); - QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + AlignedTextItem * iatext = qgraphicsitem_cast(cur_item); + QGraphicsPixmapItem * ipixmap = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); if (itext) { QRectF obr = itext->boundingRect(); itext->setFont(font_dlg.currentFont()); itext->setText(ui->comboText->currentText()); QRectF nbr = itext->boundingRect(); - QSizeF ds = (obr.size() - nbr.size()) / 2.; + QSizeF ds = (obr.size() - nbr.size()) / 2.; itext->setPos(itext->pos() + QPointF(ds.width(), ds.height())); itext->setBrush(ui->colorButtonPen->color()); } else if (iatext) { @@ -764,8 +800,8 @@ void DrawTools::propertyChanged() { iatext->setAlignment(align); } else if (ipixmap) { QTransform t = ipixmap->transform(); - double det = sqrt(t.determinant()); - QSizeF os = ipixmap->boundingRect().size() * det; + double det = sqrt(t.determinant()); + QSizeF os = ipixmap->boundingRect().size() * det; if (det != 0.) t.scale(1. / det, 1. / det); det = ui->spinScale->value(); t.scale(det, det); @@ -797,9 +833,9 @@ void DrawTools::propertyChanged() { void DrawTools::comboLineStyleChanged() { if (!cur_item) return; - QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); + QGraphicsRectItem * irect = qgraphicsitem_cast(cur_item); QGraphicsEllipseItem * iell = qgraphicsitem_cast(cur_item); - QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); + QGraphicsLineItem * iline = qgraphicsitem_cast(cur_item); if (irect || iell) { QAbstractGraphicsShapeItem * ishape = nullptr; if (irect) ishape = irect; @@ -824,7 +860,7 @@ void DrawTools::buttonImage_clicked() { if (!pi) return; QList sif(QImageReader::supportedImageFormats()); QString f; - foreach (const QByteArray & i, sif) { + foreach(const QByteArray & i, sif) { if (!f.isEmpty()) f += " "; f += "*."; f += i; @@ -833,11 +869,11 @@ void DrawTools::buttonImage_clicked() { if (ret.isEmpty()) return; QImage im(ret); if (im.isNull()) return; - prev_dir = ret; + prev_dir = ret; QRectF obr = pi->boundingRect(); pi->setPixmap(QPixmap::fromImage(im)); QRectF nbr = pi->boundingRect(); - QSizeF ds = (obr.size() - nbr.size()) / 2.; + QSizeF ds = (obr.size() - nbr.size()) / 2.; pi->setPos(pi->pos() + QPointF(ds.width(), ds.height())); changeFinished(); } @@ -851,7 +887,7 @@ void DrawTools::buttonImagePaste_clicked() { QRectF obr = pi->boundingRect(); pi->setPixmap(pm); QRectF nbr = pi->boundingRect(); - QSizeF ds = (obr.size() - nbr.size()) / 2.; + QSizeF ds = (obr.size() - nbr.size()) / 2.; pi->setPos(pi->pos() + QPointF(ds.width(), ds.height())); changeFinished(); } @@ -860,7 +896,7 @@ void DrawTools::buttonImagePaste_clicked() { void DrawTools::buttonFont_clicked() { if (!cur_item) return; QGraphicsSimpleTextItem * ti = qgraphicsitem_cast(cur_item); - AlignedTextItem * ati = qgraphicsitem_cast(cur_item); + AlignedTextItem * ati = qgraphicsitem_cast(cur_item); if (!ti && !ati) return; QFont font_prev; if (ti) font_prev = ti->font(); @@ -892,28 +928,32 @@ void DrawTools::actionZ_triggered() { if (!cur_item) return; if (cur_item->data(bvidType).toInt() == bvitDecor) { BlockView * view = nullptr; - if (cur_item->scene()) if (!cur_item->scene()->views().isEmpty()) { - view = qobject_cast(cur_item->scene()->views()[0]); - } + if (cur_item->scene()) + if (!cur_item->scene()->views().isEmpty()) { + view = qobject_cast(cur_item->scene()->views()[0]); + } if (!view) return; - QGraphicsScene * scene = view->scene(); + QGraphicsScene * scene = view->scene(); QList dl = view->decors(); scene->blockSignals(true); - foreach (QGraphicsItem * d, dl) scene->removeItem(d); + foreach(QGraphicsItem * d, dl) + scene->removeItem(d); int ind = dl.indexOf(cur_item); dl.removeAt(ind); if (sender() == &actions_Z_up) dl.insert(ind + 1, cur_item); if (sender() == &actions_Z_top) dl.append(cur_item); if (sender() == &actions_Z_down) dl.insert(ind - 1, cur_item); if (sender() == &actions_Z_bottom) dl.prepend(cur_item); - foreach (QGraphicsItem * d, dl) scene->addItem(d); + foreach(QGraphicsItem * d, dl) + scene->addItem(d); scene->blockSignals(false); } if (cur_item->data(bvidBlockDecor).toBool()) { BlockItem * bi = qgraphicsitem_cast(cur_item->parentItem()); if (!bi) return; QList dl = bi->decors_; - foreach (QGraphicsItem * d, dl) d->setParentItem(nullptr); + foreach(QGraphicsItem * d, dl) + d->setParentItem(nullptr); int ind = dl.indexOf(cur_item); dl.removeAt(ind); if (sender() == &actions_Z_up) dl.insert(ind + 1, cur_item); @@ -921,7 +961,8 @@ void DrawTools::actionZ_triggered() { if (sender() == &actions_Z_down) dl.insert(ind - 1, cur_item); if (sender() == &actions_Z_bottom) dl.prepend(cur_item); bi->decors_ = dl; - foreach (QGraphicsItem * d, dl) d->setParentItem(bi); + foreach(QGraphicsItem * d, dl) + d->setParentItem(bi); } size_item.assignObject(cur_item); emitZAvailabe(cur_item); diff --git a/libs/blockview/drawtools.h b/libs/blockview/drawtools.h index 2746aaf..0fafe71 100644 --- a/libs/blockview/drawtools.h +++ b/libs/blockview/drawtools.h @@ -1,47 +1,48 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef DRAWTOOLS_H #define DRAWTOOLS_H -#include -#include -#include -#include -#include -#include #include "blockview.h" #include "qad_blockview_export.h" +#include +#include +#include +#include +#include +#include + class QComboBox; -class QAD_BLOCKVIEW_EXPORT _DTSizeItem: public QGraphicsObject -{ +class QAD_BLOCKVIEW_EXPORT _DTSizeItem: public QGraphicsObject { Q_OBJECT + public: _DTSizeItem(); ~_DTSizeItem(); - + void assignObject(QGraphicsItem * item); - + protected: void moveRects(); void applyRect(); @@ -51,7 +52,7 @@ protected: QRectF boundingRect() const; void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {} bool sceneEventFilter(QGraphicsItem * watched, QEvent * event); - + QGraphicsItem * cur_item; QGraphicsView * view_; QGraphicsRectItem rects[8]; @@ -59,55 +60,56 @@ protected: QRectF nrect; qreal grid; bool in_process, can_drag, is_line; - + signals: void sizeChanged(); void textEditRequest(); void pixmapEditRequest(); - }; namespace Ui { - class DrawTools; +class DrawTools; } -class QAD_BLOCKVIEW_EXPORT DrawTools: public QWidget -{ +class QAD_BLOCKVIEW_EXPORT DrawTools: public QWidget { Q_OBJECT Q_PROPERTY(bool resizeHandlesEnabled READ isResizeHandlesEnabled WRITE setResizeHandlesEnabled) + public: explicit DrawTools(BlockView * parent = 0); ~DrawTools(); - + void setBlockView(BlockView * v); - void resetSizeTool() {size_item.assignObject(0);} - bool isResizeHandlesEnabled() const {return resize_enabled;} + void resetSizeTool() { size_item.assignObject(0); } + bool isResizeHandlesEnabled() const { return resize_enabled; } void setAlignCompact(bool yes); - + QComboBox * textEditCombo() const; - QList actionsForAdd() const {return actions_add;} - QList actionsForZ() const {return QList() << &actions_Z_bottom << &actions_Z_down << &actions_Z_up << &actions_Z_top;} - QWidget * propertyWidget() const {return widget_props;} - + QList actionsForAdd() const { return actions_add; } + QList actionsForZ() const { + return QList() << &actions_Z_bottom << &actions_Z_down << &actions_Z_up << &actions_Z_top; + } + QWidget * propertyWidget() const { return widget_props; } + protected: bool eventFilter(QObject * o, QEvent * e); void changeEvent(QEvent * e); - + QAction * newAction(const QIcon & icon, int type); void setToolButtonsEnabled(bool pen, bool brush, bool wid_hei); void blockPropSignals(bool block_); void actionAlignTrigger(bool vert, Qt::AlignmentFlag value); void emitZAvailabe(QGraphicsItem * item = 0); - + QWidget * widget_props; Ui::DrawTools * ui; BlockView * view_; - QList actions_add; + QList actions_add; mutable QAction actions_Z_up, actions_Z_top, actions_Z_down, actions_Z_bottom; - QList buttons_align; - QGraphicsItem * new_item, * cur_item; + QList buttons_align; + QGraphicsItem *new_item, *cur_item; QFontDialog font_dlg; QPointF pp; QDialog text_dlg; @@ -118,7 +120,7 @@ protected: int new_type; bool resize_enabled; QString prev_dir; - + private slots: void toggleNewItem(bool on); void alignClicked(); @@ -126,32 +128,40 @@ private slots: void sizeChanged(); void propertyChanged(); void comboLineStyleChanged(); - void changeFinished() {if (cur_item) emit itemEdited(cur_item);} - void moveZUpAvailable(bool yes) {actions_Z_up.setEnabled(yes); actions_Z_top.setEnabled(yes);} - void moveZDownAvailable(bool yes) {actions_Z_down.setEnabled(yes); actions_Z_bottom.setEnabled(yes);} - + void changeFinished() { + if (cur_item) emit itemEdited(cur_item); + } + void moveZUpAvailable(bool yes) { + actions_Z_up.setEnabled(yes); + actions_Z_top.setEnabled(yes); + } + void moveZDownAvailable(bool yes) { + actions_Z_down.setEnabled(yes); + actions_Z_bottom.setEnabled(yes); + } + void buttonImage_clicked(); void buttonImagePaste_clicked(); void buttonFont_clicked(); void buttonTextEdit_clicked(); - - void actionTop_triggered(bool on) {actionAlignTrigger(true, Qt::AlignTop);} - void actionVCenter_triggered(bool on) {actionAlignTrigger(true, Qt::AlignVCenter);} - void actionBottom_triggered(bool on) {actionAlignTrigger(true, Qt::AlignBottom);} - void actionLeft_triggered(bool on) {actionAlignTrigger(false, Qt::AlignLeft);} - void actionHCenter_triggered(bool on) {actionAlignTrigger(false, Qt::AlignHCenter);} - void actionRight_triggered(bool on) {actionAlignTrigger(false, Qt::AlignRight);} + + void actionTop_triggered(bool on) { actionAlignTrigger(true, Qt::AlignTop); } + void actionVCenter_triggered(bool on) { actionAlignTrigger(true, Qt::AlignVCenter); } + void actionBottom_triggered(bool on) { actionAlignTrigger(true, Qt::AlignBottom); } + void actionLeft_triggered(bool on) { actionAlignTrigger(false, Qt::AlignLeft); } + void actionHCenter_triggered(bool on) { actionAlignTrigger(false, Qt::AlignHCenter); } + void actionRight_triggered(bool on) { actionAlignTrigger(false, Qt::AlignRight); } void actionZ_triggered(); - + public slots: void setResizeHandlesEnabled(bool on); - + signals: void itemCreated(QGraphicsItem * item); void itemAddConfirm(QGraphicsItem * item); void itemEdited(QGraphicsItem * item); void itemZChanged(QGraphicsItem * item); - + private: void retranslate(); }; diff --git a/libs/blockview/plugin/blockviewplugin.cpp b/libs/blockview/plugin/blockviewplugin.cpp index 4bd2d2a..5113c0c 100644 --- a/libs/blockview/plugin/blockviewplugin.cpp +++ b/libs/blockview/plugin/blockviewplugin.cpp @@ -1,5 +1,7 @@ -#include "blockview.h" #include "blockviewplugin.h" + +#include "blockview.h" + #include @@ -9,8 +11,7 @@ BlockViewPlugin::BlockViewPlugin(QObject * parent): QObject(parent) { void BlockViewPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString BlockViewPlugin::domXml() const { QString BlockViewPlugin::includeFile() const { return QLatin1String("blockview.h"); } - diff --git a/libs/blockview/plugin/blockviewplugin.h b/libs/blockview/plugin/blockviewplugin.h index 7a90ca3..4344b52 100644 --- a/libs/blockview/plugin/blockviewplugin.h +++ b/libs/blockview/plugin/blockviewplugin.h @@ -8,8 +8,9 @@ # include #endif -class BlockViewPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class BlockViewPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // BLOCKVIEWPLUGIN_H diff --git a/libs/blockview/plugin/qad_blockview.cpp b/libs/blockview/plugin/qad_blockview.cpp index 4bd984e..b6d0c1d 100644 --- a/libs/blockview/plugin/qad_blockview.cpp +++ b/libs/blockview/plugin/qad_blockview.cpp @@ -1,13 +1,13 @@ #include "qad_blockview.h" + #include "blockviewplugin.h" -QADBlockView::QADBlockView(QObject * parent): QObject(parent) -{ +QADBlockView::QADBlockView(QObject * parent): QObject(parent) { m_widgets.append(new BlockViewPlugin(this)); } -QList QADBlockView::customWidgets() const { +QList QADBlockView::customWidgets() const { return m_widgets; } diff --git a/libs/blockview/plugin/qad_blockview.h b/libs/blockview/plugin/qad_blockview.h index 2645d92..44ae4d1 100644 --- a/libs/blockview/plugin/qad_blockview.h +++ b/libs/blockview/plugin/qad_blockview.h @@ -1,23 +1,24 @@ #ifndef QAD_BLOCKVIEW_H #define QAD_BLOCKVIEW_H -#include #include +#include -class QADBlockView: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADBlockView + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.blockview") #endif + public: explicit QADBlockView(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_BLOCKVIEW_H diff --git a/libs/doc/markdown.cpp b/libs/doc/markdown.cpp index 57fee7d..e353b47 100644 --- a/libs/doc/markdown.cpp +++ b/libs/doc/markdown.cpp @@ -1,36 +1,36 @@ #include "markdown.h" -#include + #include +#include #ifndef NO_MARKDOWN extern "C" { -#include MARKDOWN_HEADER +# include MARKDOWN_HEADER } -#ifndef mkd_flags_are -# ifndef MKD_DLEXTRA -# define MKD_DLEXTRA 0x01000000 +# ifndef mkd_flags_are +# ifndef MKD_DLEXTRA +# define MKD_DLEXTRA 0x01000000 +# endif +# ifndef MKD_FENCEDCODE +# define MKD_FENCEDCODE 0x02000000 +# endif +# ifndef MKD_EXTRA_FOOTNOTE +# define MKD_EXTRA_FOOTNOTE 0x00200000 +# endif +# ifndef MKD_TOC +# define MKD_TOC 0x00001000 +# endif +# ifndef MKD_AUTOLINK +# define MKD_AUTOLINK 0x00004000 +# endif +# ifndef MKD_GITHUBTAGS +# define MKD_GITHUBTAGS 0x08000000 +# endif # endif -# ifndef MKD_FENCEDCODE -# define MKD_FENCEDCODE 0x02000000 -# endif -# ifndef MKD_EXTRA_FOOTNOTE -# define MKD_EXTRA_FOOTNOTE 0x00200000 -# endif -# ifndef MKD_TOC -# define MKD_TOC 0x00001000 -# endif -# ifndef MKD_AUTOLINK -# define MKD_AUTOLINK 0x00004000 -# endif -# ifndef MKD_GITHUBTAGS -# define MKD_GITHUBTAGS 0x08000000 -# endif -#endif -static QString markdown_css = "table { margin: 5px; background-color: #cccccc; }" - "table tr { background-color: white; }" - "table td { vertical-align: middle; padding: 5px;}" - "table th { padding: 5px; };" -; +static QString markdown_css = "table { margin: 5px; background-color: #cccccc; }" + "table tr { background-color: white; }" + "table td { vertical-align: middle; padding: 5px;}" + "table th { padding: 5px; };"; QString md2html(const QByteArray & src) { static bool _is_mkd_init = false; @@ -39,34 +39,34 @@ QString md2html(const QByteArray & src) { _is_mkd_init = true; mkd_initialize(); } -#ifdef _MARKDOWN_D +# ifdef _MARKDOWN_D DWORD flagm = (MKD_DLEXTRA | MKD_FENCEDCODE); Document -#endif -#ifdef _MKDIO_D - #ifdef mkd_flags_are - mkd_flag_t * flagm = mkd_flags(); - mkd_set_flag_num(flagm, MKD_DLEXTRA); - mkd_set_flag_num(flagm, MKD_FENCEDCODE); - #else - mkd_flag_t flagm = (MKD_DLEXTRA | MKD_FENCEDCODE | MKD_GITHUBTAGS | MKD_AUTOLINK); - #endif +# endif +# ifdef _MKDIO_D +# ifdef mkd_flags_are + mkd_flag_t * flagm = mkd_flags(); + mkd_set_flag_num(flagm, MKD_DLEXTRA); + mkd_set_flag_num(flagm, MKD_FENCEDCODE); +# else + mkd_flag_t flagm = (MKD_DLEXTRA | MKD_FENCEDCODE | MKD_GITHUBTAGS | MKD_AUTOLINK); +# endif MMIOT -#endif - * doc = mkd_string(src.constData(), src.size(), 0); +# endif + *doc = mkd_string(src.constData(), src.size(), 0); if (!doc) return QString(); mkd_compile(doc, flagm); char * html = 0; - int len = mkd_document(doc, &html); + int len = mkd_document(doc, &html); if (!html) { mkd_cleanup(doc); return QString(); } QString ret = QString::fromUtf8(html, len); mkd_cleanup(doc); - QString title = QTextStream(&ret, QIODevice::ReadOnly).readLine(); - title = title.mid(title.indexOf(">")+1); - title = title.left(title.indexOf("<")); + QString title = QTextStream(&ret, QIODevice::ReadOnly).readLine(); + title = title.mid(title.indexOf(">") + 1); + title = title.left(title.indexOf("<")); QString header = "\n" "\n\n" "\n" diff --git a/libs/doc/markdown.h b/libs/doc/markdown.h index 5d48ed5..4a412ca 100644 --- a/libs/doc/markdown.h +++ b/libs/doc/markdown.h @@ -1,28 +1,29 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QAD_MARKDOWN_H #define QAD_MARKDOWN_H -#include #include "qad_doc_export.h" +#include + QAD_DOC_EXPORT QString md2html(const QByteArray & src); diff --git a/libs/graphic/gif.h b/libs/graphic/gif.h index d89ffc3..ee09a33 100644 --- a/libs/graphic/gif.h +++ b/libs/graphic/gif.h @@ -29,10 +29,10 @@ #ifndef gif_h #define gif_h +#include // for bool macros +#include // for integer typedefs #include // for FILE* #include // for memcpy and bzero -#include // for integer typedefs -#include // for bool macros // Define these macros to hook into a custom memory allocator. // TEMP_MALLOC and TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs @@ -41,796 +41,775 @@ // is used to find changed pixels for delta-encoding.) #ifndef GIF_TEMP_MALLOC -#include -#define GIF_TEMP_MALLOC malloc +# include +# define GIF_TEMP_MALLOC malloc #endif #ifndef GIF_TEMP_FREE -#include -#define GIF_TEMP_FREE free +# include +# define GIF_TEMP_FREE free #endif #ifndef GIF_MALLOC -#include -#define GIF_MALLOC malloc +# include +# define GIF_MALLOC malloc #endif #ifndef GIF_FREE -#include -#define GIF_FREE free +# include +# define GIF_FREE free #endif const int kGifTransIndex = 0; -typedef struct -{ - int bitDepth; +typedef struct { + int bitDepth; - uint8_t r[256]; - uint8_t g[256]; - uint8_t b[256]; + uint8_t r[256]; + uint8_t g[256]; + uint8_t b[256]; - // k-d tree over RGB space, organized in heap fashion - // i.e. left child of node i is node i*2, right child is node i*2+1 - // nodes 256-511 are implicitly the leaves, containing a color - uint8_t treeSplitElt[256]; - uint8_t treeSplit[256]; + // k-d tree over RGB space, organized in heap fashion + // i.e. left child of node i is node i*2, right child is node i*2+1 + // nodes 256-511 are implicitly the leaves, containing a color + uint8_t treeSplitElt[256]; + uint8_t treeSplit[256]; } GifPalette; // max, min, and abs functions -int GifIMax(int l, int r) { return l>r?l:r; } -int GifIMin(int l, int r) { return l r ? l : r; +} +int GifIMin(int l, int r) { + return l < r ? l : r; +} +int GifIAbs(int i) { + return i < 0 ? -i : i; +} // walks the k-d tree to pick the palette entry for a desired color. // Takes as in/out parameters the current best color and its error - // only changes them if it finds a better color in its subtree. // this is the major hotspot in the code at the moment. -void GifGetClosestPaletteColor( GifPalette* pPal, int r, int g, int b, int* bestInd, int* bestDiff, int treeRoot ) -{ - // base case, reached the bottom of the tree - if(treeRoot > (1<bitDepth)-1) - { - int ind = treeRoot-(1<bitDepth); - if(ind == kGifTransIndex) return; +void GifGetClosestPaletteColor(GifPalette * pPal, int r, int g, int b, int * bestInd, int * bestDiff, int treeRoot) { + // base case, reached the bottom of the tree + if (treeRoot > (1 << pPal->bitDepth) - 1) { + int ind = treeRoot - (1 << pPal->bitDepth); + if (ind == kGifTransIndex) return; - // check whether this color is better than the current winner - int r_err = r - ((int32_t)pPal->r[ind]); - int g_err = g - ((int32_t)pPal->g[ind]); - int b_err = b - ((int32_t)pPal->b[ind]); - int diff = GifIAbs(r_err)+GifIAbs(g_err)+GifIAbs(b_err); + // check whether this color is better than the current winner + int r_err = r - ((int32_t)pPal->r[ind]); + int g_err = g - ((int32_t)pPal->g[ind]); + int b_err = b - ((int32_t)pPal->b[ind]); + int diff = GifIAbs(r_err) + GifIAbs(g_err) + GifIAbs(b_err); - if(diff < *bestDiff) - { - *bestInd = ind; - *bestDiff = diff; - } + if (diff < *bestDiff) { + *bestInd = ind; + *bestDiff = diff; + } - return; - } + return; + } - // take the appropriate color (r, g, or b) for this node of the k-d tree - int comps[3]; comps[0] = r; comps[1] = g; comps[2] = b; - int splitComp = comps[pPal->treeSplitElt[treeRoot]]; + // take the appropriate color (r, g, or b) for this node of the k-d tree + int comps[3]; + comps[0] = r; + comps[1] = g; + comps[2] = b; + int splitComp = comps[pPal->treeSplitElt[treeRoot]]; - int splitPos = pPal->treeSplit[treeRoot]; - if(splitPos > splitComp) - { - // check the left subtree - GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2); - if( *bestDiff > splitPos - splitComp ) - { - // cannot prove there's not a better value in the right subtree, check that too - GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1); - } - } - else - { - GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1); - if( *bestDiff > splitComp - splitPos ) - { - GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2); - } - } + int splitPos = pPal->treeSplit[treeRoot]; + if (splitPos > splitComp) { + // check the left subtree + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2); + if (*bestDiff > splitPos - splitComp) { + // cannot prove there's not a better value in the right subtree, check that too + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2 + 1); + } + } else { + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2 + 1); + if (*bestDiff > splitComp - splitPos) { + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2); + } + } } -void GifSwapPixels(uint8_t* image, int pixA, int pixB) -{ - uint8_t rA = image[pixA*4]; - uint8_t gA = image[pixA*4+1]; - uint8_t bA = image[pixA*4+2]; - uint8_t aA = image[pixA*4+3]; +void GifSwapPixels(uint8_t * image, int pixA, int pixB) { + uint8_t rA = image[pixA * 4]; + uint8_t gA = image[pixA * 4 + 1]; + uint8_t bA = image[pixA * 4 + 2]; + uint8_t aA = image[pixA * 4 + 3]; - uint8_t rB = image[pixB*4]; - uint8_t gB = image[pixB*4+1]; - uint8_t bB = image[pixB*4+2]; - uint8_t aB = image[pixA*4+3]; + uint8_t rB = image[pixB * 4]; + uint8_t gB = image[pixB * 4 + 1]; + uint8_t bB = image[pixB * 4 + 2]; + uint8_t aB = image[pixA * 4 + 3]; - image[pixA*4] = rB; - image[pixA*4+1] = gB; - image[pixA*4+2] = bB; - image[pixA*4+3] = aB; + image[pixA * 4] = rB; + image[pixA * 4 + 1] = gB; + image[pixA * 4 + 2] = bB; + image[pixA * 4 + 3] = aB; - image[pixB*4] = rA; - image[pixB*4+1] = gA; - image[pixB*4+2] = bA; - image[pixB*4+3] = aA; + image[pixB * 4] = rA; + image[pixB * 4 + 1] = gA; + image[pixB * 4 + 2] = bA; + image[pixB * 4 + 3] = aA; } // just the partition operation from quicksort -int GifPartition(uint8_t* image, const int left, const int right, const int elt, int pivotIndex) -{ - const int pivotValue = image[(pivotIndex)*4+elt]; - GifSwapPixels(image, pivotIndex, right-1); - int storeIndex = left; - bool split = 0; - for(int ii=left; ii neededCenter) - GifPartitionByMedian(image, left, pivotIndex, com, neededCenter); + // Only "sort" the section of the array that contains the median + if (pivotIndex > neededCenter) GifPartitionByMedian(image, left, pivotIndex, com, neededCenter); - if(pivotIndex < neededCenter) - GifPartitionByMedian(image, pivotIndex+1, right, com, neededCenter); - } + if (pivotIndex < neededCenter) GifPartitionByMedian(image, pivotIndex + 1, right, com, neededCenter); + } } // Builds a palette by creating a balanced k-d tree of all pixels in the image -void GifSplitPalette(uint8_t* image, int numPixels, int firstElt, int lastElt, int splitElt, int splitDist, int treeNode, bool buildForDither, GifPalette* pal) -{ - if(lastElt <= firstElt || numPixels == 0) - return; +void GifSplitPalette(uint8_t * image, + int numPixels, + int firstElt, + int lastElt, + int splitElt, + int splitDist, + int treeNode, + bool buildForDither, + GifPalette * pal) { + if (lastElt <= firstElt || numPixels == 0) return; - // base case, bottom of the tree - if(lastElt == firstElt+1) - { - if(buildForDither) - { - // Dithering needs at least one color as dark as anything - // in the image and at least one brightest color - - // otherwise it builds up error and produces strange artifacts - if( firstElt == 1 ) - { - // special case: the darkest color in the image - uint32_t r=255, g=255, b=255; - for(int ii=0; iir[firstElt] = (uint8_t)r; - pal->g[firstElt] = (uint8_t)g; - pal->b[firstElt] = (uint8_t)b; + pal->r[firstElt] = (uint8_t)r; + pal->g[firstElt] = (uint8_t)g; + pal->b[firstElt] = (uint8_t)b; - return; - } + return; + } - if( firstElt == (1 << pal->bitDepth)-1 ) - { - // special case: the lightest color in the image - uint32_t r=0, g=0, b=0; - for(int ii=0; iibitDepth) - 1) { + // special case: the lightest color in the image + uint32_t r = 0, g = 0, b = 0; + for (int ii = 0; ii < numPixels; ++ii) { + r = (uint32_t)GifIMax((int32_t)r, image[ii * 4 + 0]); + g = (uint32_t)GifIMax((int32_t)g, image[ii * 4 + 1]); + b = (uint32_t)GifIMax((int32_t)b, image[ii * 4 + 2]); + } - pal->r[firstElt] = (uint8_t)r; - pal->g[firstElt] = (uint8_t)g; - pal->b[firstElt] = (uint8_t)b; + pal->r[firstElt] = (uint8_t)r; + pal->g[firstElt] = (uint8_t)g; + pal->b[firstElt] = (uint8_t)b; - return; - } - } + return; + } + } - // otherwise, take the average of all colors in this subcube - uint64_t r=0, g=0, b=0; - for(int ii=0; iir[firstElt] = (uint8_t)r; - pal->g[firstElt] = (uint8_t)g; - pal->b[firstElt] = (uint8_t)b; + pal->r[firstElt] = (uint8_t)r; + pal->g[firstElt] = (uint8_t)g; + pal->b[firstElt] = (uint8_t)b; - return; - } + return; + } - // Find the axis with the largest range - int minR = 255, maxR = 0; - int minG = 255, maxG = 0; - int minB = 255, maxB = 0; - for(int ii=0; ii maxR) maxR = r; - if(r < minR) minR = r; + if (r > maxR) maxR = r; + if (r < minR) minR = r; - if(g > maxG) maxG = g; - if(g < minG) minG = g; + if (g > maxG) maxG = g; + if (g < minG) minG = g; - if(b > maxB) maxB = b; - if(b < minB) minB = b; - } + if (b > maxB) maxB = b; + if (b < minB) minB = b; + } - int rRange = maxR - minR; - int gRange = maxG - minG; - int bRange = maxB - minB; + int rRange = maxR - minR; + int gRange = maxG - minG; + int bRange = maxB - minB; - // and split along that axis. (incidentally, this means this isn't a "proper" k-d tree but I don't know what else to call it) - int splitCom = 1; - if(bRange > gRange) splitCom = 2; - if(rRange > bRange && rRange > gRange) splitCom = 0; + // and split along that axis. (incidentally, this means this isn't a "proper" k-d tree but I don't know what else to call it) + int splitCom = 1; + if (bRange > gRange) splitCom = 2; + if (rRange > bRange && rRange > gRange) splitCom = 0; - int subPixelsA = numPixels * (splitElt - firstElt) / (lastElt - firstElt); - int subPixelsB = numPixels-subPixelsA; + int subPixelsA = numPixels * (splitElt - firstElt) / (lastElt - firstElt); + int subPixelsB = numPixels - subPixelsA; - GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA); + GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA); - pal->treeSplitElt[treeNode] = (uint8_t)splitCom; - pal->treeSplit[treeNode] = image[subPixelsA*4+splitCom]; + pal->treeSplitElt[treeNode] = (uint8_t)splitCom; + pal->treeSplit[treeNode] = image[subPixelsA * 4 + splitCom]; - GifSplitPalette(image, subPixelsA, firstElt, splitElt, splitElt-splitDist, splitDist/2, treeNode*2, buildForDither, pal); - GifSplitPalette(image+subPixelsA*4, subPixelsB, splitElt, lastElt, splitElt+splitDist, splitDist/2, treeNode*2+1, buildForDither, pal); + GifSplitPalette(image, subPixelsA, firstElt, splitElt, splitElt - splitDist, splitDist / 2, treeNode * 2, buildForDither, pal); + GifSplitPalette(image + subPixelsA * 4, + subPixelsB, + splitElt, + lastElt, + splitElt + splitDist, + splitDist / 2, + treeNode * 2 + 1, + buildForDither, + pal); } // Finds all pixels that have changed from the previous image and // moves them to the fromt of th buffer. // This allows us to build a palette optimized for the colors of the // changed pixels only. -int GifPickChangedPixels( const uint8_t* lastFrame, uint8_t* frame, int numPixels ) -{ - int numChanged = 0; - uint8_t* writeIter = frame; +int GifPickChangedPixels(const uint8_t * lastFrame, uint8_t * frame, int numPixels) { + int numChanged = 0; + uint8_t * writeIter = frame; - for (int ii=0; iibitDepth = bitDepth; +void GifMakePalette(const uint8_t * lastFrame, + const uint8_t * nextFrame, + uint32_t width, + uint32_t height, + int bitDepth, + bool buildForDither, + GifPalette * pPal) { + pPal->bitDepth = bitDepth; - // SplitPalette is destructive (it sorts the pixels by color) so - // we must create a copy of the image for it to destroy - size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t)); - uint8_t* destroyableImage = (uint8_t*)GIF_TEMP_MALLOC(imageSize); - memcpy(destroyableImage, nextFrame, imageSize); + // SplitPalette is destructive (it sorts the pixels by color) so + // we must create a copy of the image for it to destroy + size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t)); + uint8_t * destroyableImage = (uint8_t *)GIF_TEMP_MALLOC(imageSize); + memcpy(destroyableImage, nextFrame, imageSize); - int numPixels = (int)(width * height); - if(lastFrame) - numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels); + int numPixels = (int)(width * height); + if (lastFrame) numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels); - const int lastElt = 1 << bitDepth; - const int splitElt = lastElt/2; - const int splitDist = splitElt/2; + const int lastElt = 1 << bitDepth; + const int splitElt = lastElt / 2; + const int splitDist = splitElt / 2; - GifSplitPalette(destroyableImage, numPixels, 1, lastElt, splitElt, splitDist, 1, buildForDither, pPal); + GifSplitPalette(destroyableImage, numPixels, 1, lastElt, splitElt, splitDist, 1, buildForDither, pPal); - GIF_TEMP_FREE(destroyableImage); + GIF_TEMP_FREE(destroyableImage); - // add the bottom node for the transparency index - pPal->treeSplit[1 << (bitDepth-1)] = 0; - pPal->treeSplitElt[1 << (bitDepth-1)] = 0; + // add the bottom node for the transparency index + pPal->treeSplit[1 << (bitDepth - 1)] = 0; + pPal->treeSplitElt[1 << (bitDepth - 1)] = 0; - pPal->r[0] = pPal->g[0] = pPal->b[0] = 0; + pPal->r[0] = pPal->g[0] = pPal->b[0] = 0; } // Implements Floyd-Steinberg dithering, writes palette value to alpha -void GifDitherImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal ) -{ - int numPixels = (int)(width * height); +void GifDitherImage(const uint8_t * lastFrame, + const uint8_t * nextFrame, + uint8_t * outFrame, + uint32_t width, + uint32_t height, + GifPalette * pPal) { + int numPixels = (int)(width * height); - // quantPixels initially holds color*256 for all pixels - // The extra 8 bits of precision allow for sub-single-color error values - // to be propagated - int32_t *quantPixels = (int32_t *)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4); + // quantPixels initially holds color*256 for all pixels + // The extra 8 bits of precision allow for sub-single-color error values + // to be propagated + int32_t * quantPixels = (int32_t *)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4); - for( int ii=0; iir[bestInd]) * 256; - int32_t g_err = nextPix[1] - (int32_t)(pPal->g[bestInd]) * 256; - int32_t b_err = nextPix[2] - (int32_t)(pPal->b[bestInd]) * 256; + // Write the result to the temp buffer + int32_t r_err = nextPix[0] - (int32_t)(pPal->r[bestInd]) * 256; + int32_t g_err = nextPix[1] - (int32_t)(pPal->g[bestInd]) * 256; + int32_t b_err = nextPix[2] - (int32_t)(pPal->b[bestInd]) * 256; - nextPix[0] = pPal->r[bestInd]; - nextPix[1] = pPal->g[bestInd]; - nextPix[2] = pPal->b[bestInd]; - nextPix[3] = bestInd; + nextPix[0] = pPal->r[bestInd]; + nextPix[1] = pPal->g[bestInd]; + nextPix[2] = pPal->b[bestInd]; + nextPix[3] = bestInd; - // Propagate the error to the four adjacent locations - // that we haven't touched yet - int quantloc_7 = (int)(yy * width + xx + 1); - int quantloc_3 = (int)(yy * width + width + xx - 1); - int quantloc_5 = (int)(yy * width + width + xx); - int quantloc_1 = (int)(yy * width + width + xx + 1); + // Propagate the error to the four adjacent locations + // that we haven't touched yet + int quantloc_7 = (int)(yy * width + xx + 1); + int quantloc_3 = (int)(yy * width + width + xx - 1); + int quantloc_5 = (int)(yy * width + width + xx); + int quantloc_1 = (int)(yy * width + width + xx + 1); - if(quantloc_7 < numPixels) - { - int32_t* pix7 = quantPixels+4*quantloc_7; - pix7[0] += GifIMax( -pix7[0], r_err * 7 / 16 ); - pix7[1] += GifIMax( -pix7[1], g_err * 7 / 16 ); - pix7[2] += GifIMax( -pix7[2], b_err * 7 / 16 ); - } + if (quantloc_7 < numPixels) { + int32_t * pix7 = quantPixels + 4 * quantloc_7; + pix7[0] += GifIMax(-pix7[0], r_err * 7 / 16); + pix7[1] += GifIMax(-pix7[1], g_err * 7 / 16); + pix7[2] += GifIMax(-pix7[2], b_err * 7 / 16); + } - if(quantloc_3 < numPixels) - { - int32_t* pix3 = quantPixels+4*quantloc_3; - pix3[0] += GifIMax( -pix3[0], r_err * 3 / 16 ); - pix3[1] += GifIMax( -pix3[1], g_err * 3 / 16 ); - pix3[2] += GifIMax( -pix3[2], b_err * 3 / 16 ); - } + if (quantloc_3 < numPixels) { + int32_t * pix3 = quantPixels + 4 * quantloc_3; + pix3[0] += GifIMax(-pix3[0], r_err * 3 / 16); + pix3[1] += GifIMax(-pix3[1], g_err * 3 / 16); + pix3[2] += GifIMax(-pix3[2], b_err * 3 / 16); + } - if(quantloc_5 < numPixels) - { - int32_t* pix5 = quantPixels+4*quantloc_5; - pix5[0] += GifIMax( -pix5[0], r_err * 5 / 16 ); - pix5[1] += GifIMax( -pix5[1], g_err * 5 / 16 ); - pix5[2] += GifIMax( -pix5[2], b_err * 5 / 16 ); - } + if (quantloc_5 < numPixels) { + int32_t * pix5 = quantPixels + 4 * quantloc_5; + pix5[0] += GifIMax(-pix5[0], r_err * 5 / 16); + pix5[1] += GifIMax(-pix5[1], g_err * 5 / 16); + pix5[2] += GifIMax(-pix5[2], b_err * 5 / 16); + } - if(quantloc_1 < numPixels) - { - int32_t* pix1 = quantPixels+4*quantloc_1; - pix1[0] += GifIMax( -pix1[0], r_err / 16 ); - pix1[1] += GifIMax( -pix1[1], g_err / 16 ); - pix1[2] += GifIMax( -pix1[2], b_err / 16 ); - } - } - } + if (quantloc_1 < numPixels) { + int32_t * pix1 = quantPixels + 4 * quantloc_1; + pix1[0] += GifIMax(-pix1[0], r_err / 16); + pix1[1] += GifIMax(-pix1[1], g_err / 16); + pix1[2] += GifIMax(-pix1[2], b_err / 16); + } + } + } - // Copy the palettized result to the output buffer - for( int ii=0; iir[bestInd]; - outFrame[1] = pPal->g[bestInd]; - outFrame[2] = pPal->b[bestInd]; - outFrame[3] = (uint8_t)bestInd; - } + // Write the resulting color to the output buffer + outFrame[0] = pPal->r[bestInd]; + outFrame[1] = pPal->g[bestInd]; + outFrame[2] = pPal->b[bestInd]; + outFrame[3] = (uint8_t)bestInd; + } - if(lastFrame) lastFrame += 4; - outFrame += 4; - nextFrame += 4; - } + if (lastFrame) lastFrame += 4; + outFrame += 4; + nextFrame += 4; + } } // Simple structure to write out the LZW-compressed portion of the image // one bit at a time -typedef struct -{ - uint8_t bitIndex; // how many bits in the partial byte written so far - uint8_t byte; // current partial byte +typedef struct { + uint8_t bitIndex; // how many bits in the partial byte written so far + uint8_t byte; // current partial byte - uint32_t chunkIndex; - uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file + uint32_t chunkIndex; + uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file } GifBitStatus; // insert a single bit -void GifWriteBit( GifBitStatus* stat, uint32_t bit ) -{ - bit = bit & 1; - bit = bit << stat->bitIndex; - stat->byte |= bit; +void GifWriteBit(GifBitStatus * stat, uint32_t bit) { + bit = bit & 1; + bit = bit << stat->bitIndex; + stat->byte |= bit; - ++stat->bitIndex; - if( stat->bitIndex > 7 ) - { - // move the newly-finished byte to the chunk buffer - stat->chunk[stat->chunkIndex++] = stat->byte; - // and start a new byte - stat->bitIndex = 0; - stat->byte = 0; - } + ++stat->bitIndex; + if (stat->bitIndex > 7) { + // move the newly-finished byte to the chunk buffer + stat->chunk[stat->chunkIndex++] = stat->byte; + // and start a new byte + stat->bitIndex = 0; + stat->byte = 0; + } } // write all bytes so far to the file -void GifWriteChunk( FILE* f, GifBitStatus* stat ) -{ - fputc((int)stat->chunkIndex, f); - fwrite(stat->chunk, 1, stat->chunkIndex, f); +void GifWriteChunk(FILE * f, GifBitStatus * stat) { + fputc((int)stat->chunkIndex, f); + fwrite(stat->chunk, 1, stat->chunkIndex, f); - stat->bitIndex = 0; - stat->byte = 0; - stat->chunkIndex = 0; + stat->bitIndex = 0; + stat->byte = 0; + stat->chunkIndex = 0; } -void GifWriteCode( FILE* f, GifBitStatus* stat, uint32_t code, uint32_t length ) -{ - for( uint32_t ii=0; ii> 1; +void GifWriteCode(FILE * f, GifBitStatus * stat, uint32_t code, uint32_t length) { + for (uint32_t ii = 0; ii < length; ++ii) { + GifWriteBit(stat, code); + code = code >> 1; - if( stat->chunkIndex == 255 ) - { - GifWriteChunk(f, stat); - } - } + if (stat->chunkIndex == 255) { + GifWriteChunk(f, stat); + } + } } // The LZW dictionary is a 256-ary tree constructed as the file is encoded, // this is one node -typedef struct -{ - uint16_t m_next[256]; +typedef struct { + uint16_t m_next[256]; } GifLzwNode; // write a 256-color (8-bit) image palette to the file -void GifWritePalette( const GifPalette* pPal, FILE* f ) -{ - fputc(0, f); // first color: transparency - fputc(0, f); - fputc(0, f); +void GifWritePalette(const GifPalette * pPal, FILE * f) { + fputc(0, f); // first color: transparency + fputc(0, f); + fputc(0, f); - for(int ii=1; ii<(1 << pPal->bitDepth); ++ii) - { - uint32_t r = pPal->r[ii]; - uint32_t g = pPal->g[ii]; - uint32_t b = pPal->b[ii]; + for (int ii = 1; ii < (1 << pPal->bitDepth); ++ii) { + uint32_t r = pPal->r[ii]; + uint32_t g = pPal->g[ii]; + uint32_t b = pPal->b[ii]; - fputc((int)r, f); - fputc((int)g, f); - fputc((int)b, f); - } + fputc((int)r, f); + fputc((int)g, f); + fputc((int)b, f); + } } // write the image header, LZW-compress and write out the image -void GifWriteLzwImage(FILE* f, uint8_t* image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette* pPal) -{ - // graphics control extension - fputc(0x21, f); - fputc(0xf9, f); - fputc(0x04, f); - fputc(0x05, f); // leave prev frame in place, this frame has transparency - fputc(delay & 0xff, f); - fputc((delay >> 8) & 0xff, f); - fputc(kGifTransIndex, f); // transparent color index - fputc(0, f); +void GifWriteLzwImage(FILE * f, + uint8_t * image, + uint32_t left, + uint32_t top, + uint32_t width, + uint32_t height, + uint32_t delay, + GifPalette * pPal) { + // graphics control extension + fputc(0x21, f); + fputc(0xf9, f); + fputc(0x04, f); + fputc(0x05, f); // leave prev frame in place, this frame has transparency + fputc(delay & 0xff, f); + fputc((delay >> 8) & 0xff, f); + fputc(kGifTransIndex, f); // transparent color index + fputc(0, f); - fputc(0x2c, f); // image descriptor block + fputc(0x2c, f); // image descriptor block - fputc(left & 0xff, f); // corner of image in canvas space - fputc((left >> 8) & 0xff, f); - fputc(top & 0xff, f); - fputc((top >> 8) & 0xff, f); + fputc(left & 0xff, f); // corner of image in canvas space + fputc((left >> 8) & 0xff, f); + fputc(top & 0xff, f); + fputc((top >> 8) & 0xff, f); - fputc(width & 0xff, f); // width and height of image - fputc((width >> 8) & 0xff, f); - fputc(height & 0xff, f); - fputc((height >> 8) & 0xff, f); + fputc(width & 0xff, f); // width and height of image + fputc((width >> 8) & 0xff, f); + fputc(height & 0xff, f); + fputc((height >> 8) & 0xff, f); - //fputc(0, f); // no local color table, no transparency - //fputc(0x80, f); // no local color table, but transparency + // fputc(0, f); // no local color table, no transparency + // fputc(0x80, f); // no local color table, but transparency - fputc(0x80 + pPal->bitDepth-1, f); // local color table present, 2 ^ bitDepth entries - GifWritePalette(pPal, f); + fputc(0x80 + pPal->bitDepth - 1, f); // local color table present, 2 ^ bitDepth entries + GifWritePalette(pPal, f); - const int minCodeSize = pPal->bitDepth; - const uint32_t clearCode = 1 << pPal->bitDepth; + const int minCodeSize = pPal->bitDepth; + const uint32_t clearCode = 1 << pPal->bitDepth; - fputc(minCodeSize, f); // min code size 8 bits + fputc(minCodeSize, f); // min code size 8 bits - GifLzwNode* codetree = (GifLzwNode*)GIF_TEMP_MALLOC(sizeof(GifLzwNode)*4096); + GifLzwNode * codetree = (GifLzwNode *)GIF_TEMP_MALLOC(sizeof(GifLzwNode) * 4096); - memset(codetree, 0, sizeof(GifLzwNode)*4096); - int32_t curCode = -1; - uint32_t codeSize = (uint32_t)minCodeSize + 1; - uint32_t maxCode = clearCode+1; + memset(codetree, 0, sizeof(GifLzwNode) * 4096); + int32_t curCode = -1; + uint32_t codeSize = (uint32_t)minCodeSize + 1; + uint32_t maxCode = clearCode + 1; - GifBitStatus stat; - stat.byte = 0; - stat.bitIndex = 0; - stat.chunkIndex = 0; + GifBitStatus stat; + stat.byte = 0; + stat.bitIndex = 0; + stat.chunkIndex = 0; - GifWriteCode(f, &stat, clearCode, codeSize); // start with a fresh LZW dictionary + GifWriteCode(f, &stat, clearCode, codeSize); // start with a fresh LZW dictionary - for(uint32_t yy=0; yy= (1ul << codeSize) ) - { - // dictionary entry count has broken a size barrier, - // we need more bits for codes - codeSize++; - } - if( maxCode == 4095 ) - { - // the dictionary is full, clear it out and begin anew - GifWriteCode(f, &stat, clearCode, codeSize); // clear tree + if (maxCode >= (1ul << codeSize)) { + // dictionary entry count has broken a size barrier, + // we need more bits for codes + codeSize++; + } + if (maxCode == 4095) { + // the dictionary is full, clear it out and begin anew + GifWriteCode(f, &stat, clearCode, codeSize); // clear tree - memset(codetree, 0, sizeof(GifLzwNode)*4096); - codeSize = (uint32_t)(minCodeSize + 1); - maxCode = clearCode+1; - } + memset(codetree, 0, sizeof(GifLzwNode) * 4096); + codeSize = (uint32_t)(minCodeSize + 1); + maxCode = clearCode + 1; + } - curCode = nextValue; - } - } - } + curCode = nextValue; + } + } + } - // compression footer - GifWriteCode(f, &stat, (uint32_t)curCode, codeSize); - GifWriteCode(f, &stat, clearCode, codeSize); - GifWriteCode(f, &stat, clearCode + 1, (uint32_t)minCodeSize + 1); + // compression footer + GifWriteCode(f, &stat, (uint32_t)curCode, codeSize); + GifWriteCode(f, &stat, clearCode, codeSize); + GifWriteCode(f, &stat, clearCode + 1, (uint32_t)minCodeSize + 1); - // write out the last partial chunk - while( stat.bitIndex ) GifWriteBit(&stat, 0); - if( stat.chunkIndex ) GifWriteChunk(f, &stat); + // write out the last partial chunk + while (stat.bitIndex) + GifWriteBit(&stat, 0); + if (stat.chunkIndex) GifWriteChunk(f, &stat); - fputc(0, f); // image block terminator + fputc(0, f); // image block terminator - GIF_TEMP_FREE(codetree); + GIF_TEMP_FREE(codetree); } -typedef struct -{ - FILE* f; - uint8_t* oldImage; - bool firstFrame; +typedef struct { + FILE * f; + uint8_t * oldImage; + bool firstFrame; } GifWriter; // Creates a gif file. // The input GIFWriter is assumed to be uninitialized. // The delay value is the time between frames in hundredths of a second - note that not all viewers pay much attention to this value. -bool GifBegin( GifWriter* writer, const char* filename, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth = 8, bool dither = false ) -{ - (void)bitDepth; (void)dither; // Mute "Unused argument" warnings +bool GifBegin(GifWriter * writer, + const char * filename, + uint32_t width, + uint32_t height, + uint32_t delay, + int32_t bitDepth = 8, + bool dither = false) { + (void)bitDepth; + (void)dither; // Mute "Unused argument" warnings #if defined(_MSC_VER) && (_MSC_VER >= 1400) writer->f = 0; - fopen_s(&writer->f, filename, "wb"); + fopen_s(&writer->f, filename, "wb"); #else - writer->f = fopen(filename, "wb"); + writer->f = fopen(filename, "wb"); #endif - if(!writer->f) return false; + if (!writer->f) return false; - writer->firstFrame = true; + writer->firstFrame = true; - // allocate - writer->oldImage = (uint8_t*)GIF_MALLOC(width*height*4); + // allocate + writer->oldImage = (uint8_t *)GIF_MALLOC(width * height * 4); - fputs("GIF89a", writer->f); + fputs("GIF89a", writer->f); - // screen descriptor - fputc(width & 0xff, writer->f); - fputc((width >> 8) & 0xff, writer->f); - fputc(height & 0xff, writer->f); - fputc((height >> 8) & 0xff, writer->f); + // screen descriptor + fputc(width & 0xff, writer->f); + fputc((width >> 8) & 0xff, writer->f); + fputc(height & 0xff, writer->f); + fputc((height >> 8) & 0xff, writer->f); - fputc(0xf0, writer->f); // there is an unsorted global color table of 2 entries - fputc(0, writer->f); // background color - fputc(0, writer->f); // pixels are square (we need to specify this because it's 1989) + fputc(0xf0, writer->f); // there is an unsorted global color table of 2 entries + fputc(0, writer->f); // background color + fputc(0, writer->f); // pixels are square (we need to specify this because it's 1989) - // now the "global" palette (really just a dummy palette) - // color 0: black - fputc(0, writer->f); - fputc(0, writer->f); - fputc(0, writer->f); - // color 1: also black - fputc(0, writer->f); - fputc(0, writer->f); - fputc(0, writer->f); + // now the "global" palette (really just a dummy palette) + // color 0: black + fputc(0, writer->f); + fputc(0, writer->f); + fputc(0, writer->f); + // color 1: also black + fputc(0, writer->f); + fputc(0, writer->f); + fputc(0, writer->f); - if( delay != 0 ) - { - // animation header - fputc(0x21, writer->f); // extension - fputc(0xff, writer->f); // application specific - fputc(11, writer->f); // length 11 - fputs("NETSCAPE2.0", writer->f); // yes, really - fputc(3, writer->f); // 3 bytes of NETSCAPE2.0 data + if (delay != 0) { + // animation header + fputc(0x21, writer->f); // extension + fputc(0xff, writer->f); // application specific + fputc(11, writer->f); // length 11 + fputs("NETSCAPE2.0", writer->f); // yes, really + fputc(3, writer->f); // 3 bytes of NETSCAPE2.0 data - fputc(1, writer->f); // JUST BECAUSE - fputc(0, writer->f); // loop infinitely (byte 0) - fputc(0, writer->f); // loop infinitely (byte 1) + fputc(1, writer->f); // JUST BECAUSE + fputc(0, writer->f); // loop infinitely (byte 0) + fputc(0, writer->f); // loop infinitely (byte 1) - fputc(0, writer->f); // block terminator - } + fputc(0, writer->f); // block terminator + } - return true; + return true; } // Writes out a new frame to a GIF in progress. // The GIFWriter should have been created by GIFBegin. // AFAIK, it is legal to use different bit depths for different frames of an image - // this may be handy to save bits in animations that don't change much. -bool GifWriteFrame( GifWriter* writer, const uint8_t* image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth = 8, bool dither = false ) -{ - if(!writer->f) return false; +bool GifWriteFrame(GifWriter * writer, + const uint8_t * image, + uint32_t width, + uint32_t height, + uint32_t delay, + int bitDepth = 8, + bool dither = false) { + if (!writer->f) return false; - const uint8_t* oldImage = writer->firstFrame? NULL : writer->oldImage; - writer->firstFrame = false; + const uint8_t * oldImage = writer->firstFrame ? NULL : writer->oldImage; + writer->firstFrame = false; - GifPalette pal; - GifMakePalette((dither? NULL : oldImage), image, width, height, bitDepth, dither, &pal); + GifPalette pal; + GifMakePalette((dither ? NULL : oldImage), image, width, height, bitDepth, dither, &pal); - if(dither) - GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal); - else - GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal); + if (dither) + GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal); + else + GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal); - GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal); + GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal); - return true; + return true; } // Writes the EOF code, closes the file handle, and frees temp memory used by a GIF. // Many if not most viewers will still display a GIF properly if the EOF code is missing, // but it's still a good idea to write it out. -bool GifEnd( GifWriter* writer ) -{ - if(!writer->f) return false; +bool GifEnd(GifWriter * writer) { + if (!writer->f) return false; - fputc(0x3b, writer->f); // end of file - fclose(writer->f); - GIF_FREE(writer->oldImage); + fputc(0x3b, writer->f); // end of file + fclose(writer->f); + GIF_FREE(writer->oldImage); - writer->f = NULL; - writer->oldImage = NULL; + writer->f = NULL; + writer->oldImage = NULL; - return true; + return true; } #endif diff --git a/libs/graphic/graphic.cpp b/libs/graphic/graphic.cpp index f10b848..b82c72a 100644 --- a/libs/graphic/graphic.cpp +++ b/libs/graphic/graphic.cpp @@ -1,19 +1,21 @@ #include "graphic.h" + +#include "gif.h" #include "qad_types.h" #include "uglwidget.h" #include "ui_graphic.h" #include "ui_graphic_conf.h" -#include -#include + +#include +#include #include -#include +#include #include #include -#include #include +#include #include -#include -#include "gif.h" +#include #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) # include #endif @@ -21,12 +23,12 @@ # define NO_BUTTONS #else # ifndef FORCE_NO_GL -# define HAS_GL +# define HAS_GL # endif #endif #ifdef HAS_GL # ifndef GL_MULTISAMPLE -# define GL_MULTISAMPLE 0x809D +# define GL_MULTISAMPLE 0x809D # endif #endif @@ -42,7 +44,7 @@ enum DateComponent { }; const char _button_prop_name_[] = "_button_"; -const double rad2deg_qpie = 45. / atan(1.); +const double rad2deg_qpie = 45. / atan(1.); __GraphicRegistrator__ __graphic_registrator__; @@ -61,6 +63,7 @@ public: w->setAutoFillBackground(false); } int minimum_hei; + protected: virtual QSize sizeHint() const { QSize ret; @@ -68,26 +71,24 @@ protected: ret = widget()->sizeHint(); return ret; } - virtual QSize minimumSizeHint() const { - return QSize(1, minimum_hei); - } + virtual QSize minimumSizeHint() const { return QSize(1, minimum_hei); } }; Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), line_x_max(this), line_y_min(this), line_y_max(this) { - canvas_gl = 0; + canvas_gl = 0; timer_pause = timer_record = 0; - gesture_angle = 45.; - leg_update = true; + gesture_angle = 45.; + leg_update = true; visible_update = fullscr = need_mouse_pan = m_fakeGL = false; gestures = #ifdef Q_OS_ANDROID - true; + true; #else - false; + false; #endif func_gridMarkX = func_gridMarkY = nullptr; - ui = new Ui::Graphic(); + ui = new Ui::Graphic(); ui->setupUi(this); ui->scrollLegend->layout()->addWidget(new LegendScrollArea(ui->widgetLegend)); ui->scrollLegend->hide(); @@ -95,21 +96,20 @@ Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), #ifdef NO_BUTTONS ui->widgetLeft->hide(); ui->widgetRight->hide(); - QList btnlist = { - ui->graphic_buttonAutofit, - ui->graphic_checkGrid, - ui->graphic_checkGuides, - ui->graphic_buttonFullscreen, - ui->graphic_checkBorderInputs, - ui->graphic_checkLegend, - ui->graphic_checkPause, - ui->graphic_buttonConfigure, - ui->graphic_buttonSave, - ui->graphic_buttonExport, - ui->graphic_buttonRecord, - ui->graphic_buttonClear, - ui->graphic_buttonClose}; - buttons_menu = new QMenu(this); + QList btnlist = {ui->graphic_buttonAutofit, + ui->graphic_checkGrid, + ui->graphic_checkGuides, + ui->graphic_buttonFullscreen, + ui->graphic_checkBorderInputs, + ui->graphic_checkLegend, + ui->graphic_checkPause, + ui->graphic_buttonConfigure, + ui->graphic_buttonSave, + ui->graphic_buttonExport, + ui->graphic_buttonRecord, + ui->graphic_buttonClear, + ui->graphic_buttonClose}; + buttons_menu = new QMenu(this); for (auto * b: btnlist) { auto * a = new QAction(this); connect(a, SIGNAL(triggered()), b, SLOT(click())); @@ -120,31 +120,31 @@ Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), } #endif QActionGroup * agroup = new QActionGroup(this); - agroup->addAction(ui->graphic_actionGuidesFree ); - agroup->addAction(ui->graphic_actionGuidesTrace ); + agroup->addAction(ui->graphic_actionGuidesFree); + agroup->addAction(ui->graphic_actionGuidesTrace); agroup->addAction(ui->graphic_actionGuidesTraceX); agroup->addAction(ui->graphic_actionGuidesTraceY); - ui->graphic_actionGuidesFree ->setProperty("_value", (int)Free ); - ui->graphic_actionGuidesTrace ->setProperty("_value", (int)TraceXY); - ui->graphic_actionGuidesTraceX->setProperty("_value", (int)TraceX ); - ui->graphic_actionGuidesTraceY->setProperty("_value", (int)TraceY ); + ui->graphic_actionGuidesFree->setProperty("_value", (int)Free); + ui->graphic_actionGuidesTrace->setProperty("_value", (int)TraceXY); + ui->graphic_actionGuidesTraceX->setProperty("_value", (int)TraceX); + ui->graphic_actionGuidesTraceY->setProperty("_value", (int)TraceY); ui->graphic_actionGuidesFree->setChecked(true); - connect(agroup, SIGNAL(triggered(QAction*)), this, SLOT(actionGuidesTriggered(QAction*))); - ui->graphic_checkGuides ->addAction(ui->graphic_actionGuidesFree ); - ui->graphic_checkGuides ->addAction(ui->graphic_actionGuidesTrace ); - ui->graphic_checkGuides ->addAction(ui->graphic_actionGuidesTraceX); - ui->graphic_checkGuides ->addAction(ui->graphic_actionGuidesTraceY); + connect(agroup, SIGNAL(triggered(QAction *)), this, SLOT(actionGuidesTriggered(QAction *))); + ui->graphic_checkGuides->addAction(ui->graphic_actionGuidesFree); + ui->graphic_checkGuides->addAction(ui->graphic_actionGuidesTrace); + ui->graphic_checkGuides->addAction(ui->graphic_actionGuidesTraceX); + ui->graphic_checkGuides->addAction(ui->graphic_actionGuidesTraceY); ui->graphic_buttonAutofit->addAction(ui->graphic_actionExpandX); ui->graphic_buttonAutofit->addAction(ui->graphic_actionExpandY); line_x_min.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); line_x_max.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - ((QBoxLayout * )ui->widgetLY->layout())->insertWidget(0, &line_y_min); - ((QBoxLayout * )ui->widgetLY->layout())->addWidget(&line_y_max); - ((QBoxLayout * )ui->widgetLX->layout())->insertWidget(0, &line_x_min); - ((QBoxLayout * )ui->widgetLX->layout())->addWidget(&line_x_max); + ((QBoxLayout *)ui->widgetLY->layout())->insertWidget(0, &line_y_min); + ((QBoxLayout *)ui->widgetLY->layout())->addWidget(&line_y_max); + ((QBoxLayout *)ui->widgetLX->layout())->insertWidget(0, &line_x_min); + ((QBoxLayout *)ui->widgetLX->layout())->addWidget(&line_x_max); tm.restart(); grid_numbers_x = grid_numbers_y = 1; - LN10 = qLn(10.); + LN10 = qLn(10.); line_x_min.setClearButtonVisible(true); line_x_max.setClearButtonVisible(true); line_y_min.setClearButtonVisible(true); @@ -153,12 +153,12 @@ Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), connect(&line_x_max, SIGNAL(valueChanged(double)), this, SLOT(lineXMaxChanged(double))); connect(&line_y_min, SIGNAL(valueChanged(double)), this, SLOT(lineYMinChanged(double))); connect(&line_y_max, SIGNAL(valueChanged(double)), this, SLOT(lineYMaxChanged(double))); - connect(ui->canvas_raster, SIGNAL(paintEvent(QPaintEvent * )), this, SLOT(canvasPaintEvent())); + connect(ui->canvas_raster, SIGNAL(paintEvent(QPaintEvent *)), this, SLOT(canvasPaintEvent())); prepareCanvas(ui->canvas_raster); - icon_exp_x = QIcon(":/icons/expand_x.png"); - icon_exp_y = QIcon(":/icons/expand_y.png"); - icon_exp_sx = QIcon(":/icons/expand_s_x.png"); - icon_exp_sy = QIcon(":/icons/expand_s_y.png"); + icon_exp_x = QIcon(":/icons/expand_x.png"); + icon_exp_y = QIcon(":/icons/expand_y.png"); + icon_exp_sx = QIcon(":/icons/expand_s_x.png"); + icon_exp_sy = QIcon(":/icons/expand_s_y.png"); icon_pause_b = QImage(":/icons/pause-back.png"); icon_pause_f = QImage(":/icons/pause-front.png"); aupdate = grid = isFit = navigation = true; @@ -167,17 +167,17 @@ Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), limit_.setCoords(-DBL_MAX, -DBL_MAX, DBL_MAX, DBL_MAX); eminx = eminy = DBL_MAX; emaxx = emaxy = DBL_MIN; - grad_x = grad_y = Auto; - axis_type_x = Numeric; + grad_x = grad_y = Auto; + axis_type_x = Numeric; floating_axis_type = Free; - min_repaint_int = 25; + min_repaint_int = 25; lastw = lasth = 0; - inc_x = 1.; - //buffer = 0; + inc_x = 1.; + // buffer = 0; gridx = gridy = 1.; - history = 5.; - visible_time = -1.; - thick = lineThickness(this); + history = 5.; + visible_time = -1.; + thick = lineThickness(this); #if QT_VERSION_MAJOR >= 5 thick *= devicePixelRatio(); #endif @@ -189,13 +189,13 @@ Graphic::Graphic(QWidget * parent): QFrame(parent), canvas(0), line_x_min(this), selbrush.setStyle(Qt::SolidPattern); selbrush.setColor(QColor(60, 175, 255, 100)); text_color = palette().color(QPalette::WindowText); - grid_pen = QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 0., Qt::DotLine); + grid_pen = QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 0., Qt::DotLine); graphics.append(GraphicType()); curGraphic = curTrace = 0; - selpen = palette().color(QPalette::WindowText); + selpen = palette().color(QPalette::WindowText); selpen.setStyle(Qt::DashLine); back_color = palette().color(QPalette::Base); - buttons_ = AllButtons; + buttons_ = AllButtons; setOpenGL(false); setButtonsPosition(Graphic::Left); setAntialiasing(false); @@ -215,7 +215,7 @@ Graphic::~Graphic() { delete buttons_menu; #endif delete conf; - //if (buffer != 0) delete buffer; + // if (buffer != 0) delete buffer; } @@ -232,7 +232,7 @@ void Graphic::changeEvent(QEvent * e) { void Graphic::resizeEvent(QResizeEvent *) { if (leg_update) #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) - QTimer::singleShot(0, this, [this](){updateLegend(false);}); + QTimer::singleShot(0, this, [this]() { updateLegend(false); }); #else updateLegend(false); #endif @@ -241,7 +241,7 @@ void Graphic::resizeEvent(QResizeEvent *) { void Graphic::showEvent(QShowEvent *) { if (need_createGL && !canvas_gl) { - //qDebug() << "create GL on show"; + // qDebug() << "create GL on show"; canvas_gl = new UGLWidget(); ui->layoutCanvas->addWidget(canvas_gl); connect(canvas_gl, SIGNAL(paintSignal()), this, SLOT(canvasPaintEvent())); @@ -257,8 +257,7 @@ void Graphic::showEvent(QShowEvent *) { void Graphic::timerEvent(QTimerEvent * e) { if (e->timerId() == timer_pause) { pause_phase += 0.02; - if (pause_phase > 1.) - pause_phase -= 1.; + if (pause_phase > 1.) pause_phase -= 1.; update(); } if (e->timerId() == timer_record) { @@ -274,16 +273,16 @@ bool Graphic::eventFilter(QObject * o, QEvent * e) { switch (e->type()) { case QEvent::Gesture: if (!navigation || !gestures) break; - foreach (QGesture * g, ((QGestureEvent*)e)->gestures()) + foreach(QGesture * g, ((QGestureEvent *)e)->gestures()) procGesture(g); break; case QEvent::KeyPress: { - int k = ((QKeyEvent*)e)->key(); + int k = ((QKeyEvent *)e)->key(); if ((k == Qt::Key_Back || k == Qt::Key_Escape) && fullscr) { leaveFullscreen(); return true; } - } break; + } break; case QEvent::TouchBegin: if (!navigation || !gestures) break; need_mouse_pan = true; @@ -292,9 +291,9 @@ bool Graphic::eventFilter(QObject * o, QEvent * e) { if (!navigation || !gestures) break; QList tpl = #if QT_VERSION_MAJOR <= 5 - ((QTouchEvent*)e)->touchPoints(); + ((QTouchEvent *)e)->touchPoints(); #else - ((QTouchEvent*)e)->points(); + ((QTouchEvent *)e)->points(); #endif if (tpl.size() == 2) { need_mouse_pan = false; @@ -306,7 +305,7 @@ bool Graphic::eventFilter(QObject * o, QEvent * e) { #endif gesture_angle = rad2deg_qpie * qAtan2(qAbs(dp.y()), qAbs(dp.x())); } - } break; + } break; default: break; } } @@ -315,13 +314,13 @@ bool Graphic::eventFilter(QObject * o, QEvent * e) { void Graphic::prepareCanvas(QWidget * w) { - connect(w, SIGNAL(mouseMoveEvent(QMouseEvent * )), this, SLOT(canvasMouseMoveEvent(QMouseEvent * ))); - connect(w, SIGNAL(mousePressEvent(QMouseEvent * )), this, SLOT(canvasMousePressEvent(QMouseEvent * ))); - connect(w, SIGNAL(mouseReleaseEvent(QMouseEvent * )), this, SLOT(canvasMouseReleaseEvent(QMouseEvent * ))); - connect(w, SIGNAL(mouseDoubleClickEvent(QMouseEvent*)), this, SLOT(canvasMouseDoubleClickEvent(QMouseEvent * ))); - connect(w, SIGNAL(wheelEvent(QWheelEvent * )), this, SLOT(canvasWheelEvent(QWheelEvent * ))); - connect(w, SIGNAL(leaveEvent(QEvent * )), this, SLOT(canvasLeaveEvent(QEvent * ))); - connect(w, SIGNAL(keyPressEvent(QKeyEvent * )), this, SLOT(canvasKeyPressEvent(QKeyEvent * ))); + connect(w, SIGNAL(mouseMoveEvent(QMouseEvent *)), this, SLOT(canvasMouseMoveEvent(QMouseEvent *))); + connect(w, SIGNAL(mousePressEvent(QMouseEvent *)), this, SLOT(canvasMousePressEvent(QMouseEvent *))); + connect(w, SIGNAL(mouseReleaseEvent(QMouseEvent *)), this, SLOT(canvasMouseReleaseEvent(QMouseEvent *))); + connect(w, SIGNAL(mouseDoubleClickEvent(QMouseEvent *)), this, SLOT(canvasMouseDoubleClickEvent(QMouseEvent *))); + connect(w, SIGNAL(wheelEvent(QWheelEvent *)), this, SLOT(canvasWheelEvent(QWheelEvent *))); + connect(w, SIGNAL(leaveEvent(QEvent *)), this, SLOT(canvasLeaveEvent(QEvent *))); + connect(w, SIGNAL(keyPressEvent(QKeyEvent *)), this, SLOT(canvasKeyPressEvent(QKeyEvent *))); w->grabGesture(Qt::TapAndHoldGesture); w->grabGesture(Qt::PanGesture); w->grabGesture(Qt::PinchGesture); @@ -335,15 +334,15 @@ void Graphic::procGesture(QGesture * g) { switch (g->gestureType()) { case Qt::PanGesture: { if (need_mouse_pan) break; - QPanGesture * pg = (QPanGesture*)g; - QPointF dp = -pg->delta(); + QPanGesture * pg = (QPanGesture *)g; + QPointF dp = -pg->delta(); dp.rx() /= getScaleX(); dp.ry() /= getScaleY(); selrect.translate(dp); totalUpdate(); - } break; + } break; case Qt::PinchGesture: { - QPinchGesture * pg = (QPinchGesture*)g; + QPinchGesture * pg = (QPinchGesture *)g; Qt::KeyboardModifiers km = Qt::NoModifier; if (gesture_angle <= 20.) km = Qt::ControlModifier; if (gesture_angle >= 70.) km = Qt::ShiftModifier; @@ -351,33 +350,33 @@ void Graphic::procGesture(QGesture * g) { if (!fullscr) cp = mapFromGlobal(cp); procZoom(cp, (pg->scaleFactor() - 1.) * 500., km); totalUpdate(); - } break; + } break; case Qt::TapAndHoldGesture: { - QTapAndHoldGesture * pg = (QTapAndHoldGesture*)g; + QTapAndHoldGesture * pg = (QTapAndHoldGesture *)g; if (pg->state() == Qt::GestureStarted) - QMetaObject::invokeMethod(this, [this](){showMenu();}, Qt::QueuedConnection); - } break; - default: - break; + QMetaObject::invokeMethod( + this, + [this]() { showMenu(); }, + Qt::QueuedConnection); + } break; + default: break; } } void Graphic::procZoom(QPointF view_center, double dzoom, Qt::KeyboardModifiers km) { - double scl, wid = canvas->width() - gridborder.x() - margins_.width() - margins_.left(), hei = canvas->height() - gridborder.y() - margins_.height() - margins_.top(); + double scl, wid = canvas->width() - gridborder.x() - margins_.width() - margins_.left(), + hei = canvas->height() - gridborder.y() - margins_.height() - margins_.top(); double px = view_center.x() - gridborder.x() - margins_.left(), py = hei - view_center.y() + margins_.height(); - px = px / wid * selrect.width() + selrect.x(); - py = py / hei * selrect.height() + selrect.y(); + px = px / wid * selrect.width() + selrect.x(); + py = py / hei * selrect.height() + selrect.y(); scl = 1. - dzoom / 500.; if (km == Qt::NoModifier) selrect.setRect(px - (px - selrect.x()) * scl, py - (py - selrect.y()) * scl, selrect.width() * scl, selrect.height() * scl); else { - if (km == Qt::ControlModifier) - selrect.setRect(px - (px - selrect.x()) * scl, selrect.y(), selrect.width() * scl, selrect.height()); - if (km == Qt::ShiftModifier) - selrect.setRect(selrect.x(), py - (py - selrect.y()) * scl, selrect.width(), selrect.height() * scl); - if (km == Qt::AltModifier) - selrect.translate((dzoom > 0. ? 1. : -1.) * selrect.width() / 2., 0.); + if (km == Qt::ControlModifier) selrect.setRect(px - (px - selrect.x()) * scl, selrect.y(), selrect.width() * scl, selrect.height()); + if (km == Qt::ShiftModifier) selrect.setRect(selrect.x(), py - (py - selrect.y()) * scl, selrect.width(), selrect.height() * scl); + if (km == Qt::AltModifier) selrect.translate((dzoom > 0. ? 1. : -1.) * selrect.width() / 2., 0.); } } @@ -392,23 +391,22 @@ void Graphic::totalUpdate() { void Graphic::canvasPaintEvent() { if (is_lines_update) return; - int wid = canvas->width (),hei = canvas->height(); + int wid = canvas->width(), hei = canvas->height(); if (canvas->isHidden() || wid <= 1 || hei <= 1) return; if (!buffer.isNull()) { - if (lastw != wid || lasth != hei) - buffer = QPixmap(); + if (lastw != wid || lasth != hei) buffer = QPixmap(); } if (buffer.isNull()) { #if QT_VERSION_MAJOR >= 5 const qreal dpr = canvas->devicePixelRatio(); - buffer = QPixmap(canvas->size() * dpr); + buffer = QPixmap(canvas->size() * dpr); buffer.setDevicePixelRatio(dpr); #else buffer = QPixmap(canvas->size()); #endif } - lastw = wid; - lasth = hei; + lastw = wid; + lasth = hei; font_sz = fontMetrics().size(0, "0"); font_sz.setHeight(font_sz.height() * 1.); #ifdef Q_OS_ANDROID @@ -452,13 +450,14 @@ void Graphic::canvasPaintEvent() { painter->setClipRect(QRect(gridborder.x(), 0, wid - gridborder.x(), hei - gridborder.y())); emit beforeGraphicPaintEvent(painter); painter->setClipping(false); - if (grid) - drawGrid(); + if (grid) drawGrid(); p.setRenderHint(QPainter::Antialiasing, aalias); #ifdef HAS_GL if (isOGL && !m_fakeGL) { - if (aalias) glEnable(GL_MULTISAMPLE); - else glDisable(GL_MULTISAMPLE); + if (aalias) + glEnable(GL_MULTISAMPLE); + else + glDisable(GL_MULTISAMPLE); } #endif fp_size.clear(); @@ -476,8 +475,8 @@ void Graphic::canvasPaintEvent() { void Graphic::canvasMouseMoveEvent(QMouseEvent * e) { - isHover = true; - curpos = e->pos(); + isHover = true; + curpos = e->pos(); curpos_r = canvas2real(curpos); QPointF dp; QString cursorstr = tr("Cursor: ") + pointCoords(curpos_r); @@ -491,38 +490,34 @@ void Graphic::canvasMouseMoveEvent(QMouseEvent * e) { if (gestures) { if (!need_mouse_pan) return; curaction = gaMove; - } else - if (curaction != gaMove && (e->buttons() & Qt::RightButton) == Qt::RightButton) return; + } else if (curaction != gaMove && (e->buttons() & Qt::RightButton) == Qt::RightButton) + return; switch (curaction) { - case gaZoomInRect: - ui->status->setText(tr("Selection") + ": " + pointCoords(startpos_r) + " -> " + - pointCoords(curpos_r) + ", " + tr("Size") + ": " + pointCoords(absPoint(curpos_r - startpos_r))); - repaintCanvas(true); + case gaZoomInRect: + ui->status->setText(tr("Selection") + ": " + pointCoords(startpos_r) + " -> " + pointCoords(curpos_r) + ", " + tr("Size") + ": " + + pointCoords(absPoint(curpos_r - startpos_r))); + repaintCanvas(true); break; - case gaZoomRangeX: - ui->status->setText(tr("Range") + ": " + QString::number(startpos_r.x(), 'f', 3) + - " -> " + QString::number(curpos_r.x(), 'f', 3) + ", " + tr("Length") + ": " + - QString::number(qAbs(curpos_r.x() - startpos_r.x()), 'f', 3)); - repaintCanvas(true); + case gaZoomRangeX: + ui->status->setText(tr("Range") + ": " + QString::number(startpos_r.x(), 'f', 3) + " -> " + QString::number(curpos_r.x(), 'f', 3) + + ", " + tr("Length") + ": " + QString::number(qAbs(curpos_r.x() - startpos_r.x()), 'f', 3)); + repaintCanvas(true); break; - case gaZoomRangeY: - ui->status->setText(tr("Range") + ": " + QString::number(startpos_r.y(), 'f', 3) + - " -> " + QString::number(curpos_r.y(), 'f', 3) + ", " + tr("Length") + ": " + - QString::number(qAbs(curpos_r.y() - startpos_r.y()), 'f', 3)); - repaintCanvas(true); + case gaZoomRangeY: + ui->status->setText(tr("Range") + ": " + QString::number(startpos_r.y(), 'f', 3) + " -> " + QString::number(curpos_r.y(), 'f', 3) + + ", " + tr("Length") + ": " + QString::number(qAbs(curpos_r.y() - startpos_r.y()), 'f', 3)); + repaintCanvas(true); break; - case gaMove: - dp = e->pos() - prevpos; - dp.rx() *= selrect.width() / double(gridborder.x() + 5 - lastw); - dp.ry() *= selrect.height() / double(lasth - gridborder.y() - 5); - if (e->modifiers() == Qt::ControlModifier) - dp.setY(0.); - if (e->modifiers() == Qt::ShiftModifier) - dp.setX(0.); - selrect.translate(dp); - totalUpdate(); + case gaMove: + dp = e->pos() - prevpos; + dp.rx() *= selrect.width() / double(gridborder.x() + 5 - lastw); + dp.ry() *= selrect.height() / double(lasth - gridborder.y() - 5); + if (e->modifiers() == Qt::ControlModifier) dp.setY(0.); + if (e->modifiers() == Qt::ShiftModifier) dp.setX(0.); + selrect.translate(dp); + totalUpdate(); break; - default: break; + default: break; } prevpos = e->pos(); } @@ -533,14 +528,14 @@ void Graphic::canvasMousePressEvent(QMouseEvent * e) { if (!navigation) return; if (gestures && !need_mouse_pan) return; setGuidesCursor(); - prevpos = e->pos(); - startpos = prevpos; + prevpos = e->pos(); + startpos = prevpos; startpos_r = canvas2real(startpos); if (cancel || gestures) return; if (e->button() == QT_MID_BUTTON) curaction = gaMove; if (e->button() == Qt::RightButton) { if (bufferActive) { - curpos = startpos; + curpos = startpos; curpos_r = canvas2real(curpos); repaintCanvas(true); swapToNormal(); @@ -553,16 +548,17 @@ void Graphic::canvasMousePressEvent(QMouseEvent * e) { } } if (e->button() == Qt::LeftButton) { - if (e->modifiers() == Qt::ControlModifier) curaction = gaZoomRangeX; - else if (e->modifiers() == Qt::ShiftModifier) curaction = gaZoomRangeY; - else curaction = gaZoomInRect; + if (e->modifiers() == Qt::ControlModifier) + curaction = gaZoomRangeX; + else if (e->modifiers() == Qt::ShiftModifier) + curaction = gaZoomRangeY; + else + curaction = gaZoomInRect; switch (curaction) { - case gaZoomInRect: - case gaZoomRangeX: - case gaZoomRangeY: - swapToBuffer(); - break; - default: break; + case gaZoomInRect: + case gaZoomRangeX: + case gaZoomRangeY: swapToBuffer(); break; + default: break; } } setCurrentAction(curaction); @@ -588,24 +584,24 @@ void Graphic::canvasMouseReleaseEvent(QMouseEvent * e) { } if (e->button() == Qt::LeftButton && (e->buttons() & Qt::RightButton) != Qt::RightButton) { if (curpos != startpos) { - tlp = canvas2real(sr.topLeft()); - brp = canvas2real(sr.bottomRight()); + tlp = canvas2real(sr.topLeft()); + brp = canvas2real(sr.bottomRight()); isFit = false; switch (curaction) { - case gaZoomInRect: - if (sr.width() <= 1 || sr.height() <= 1) break; - selrect.setCoords(tlp.x(), brp.y(), brp.x(), tlp.y()); - setRectToLines(); + case gaZoomInRect: + if (sr.width() <= 1 || sr.height() <= 1) break; + selrect.setCoords(tlp.x(), brp.y(), brp.x(), tlp.y()); + setRectToLines(); break; - case gaZoomRangeX: - if (sr.width() <= 1) break; - findGraphicsRect(tlp.x(), brp.x()); + case gaZoomRangeX: + if (sr.width() <= 1) break; + findGraphicsRect(tlp.x(), brp.x()); break; - case gaZoomRangeY: - if (sr.height() <= 1) break; - findGraphicsRect(0., 0., brp.y(), tlp.y()); + case gaZoomRangeY: + if (sr.height() <= 1) break; + findGraphicsRect(0., 0., brp.y(), tlp.y()); break; - default: return; + default: return; } } swapToNormal(); @@ -617,7 +613,7 @@ void Graphic::canvasMouseReleaseEvent(QMouseEvent * e) { } -void Graphic::canvasMouseDoubleClickEvent(QMouseEvent * ) { +void Graphic::canvasMouseDoubleClickEvent(QMouseEvent *) { if (!navigation) return; autofit(); } @@ -641,11 +637,15 @@ void Graphic::canvasWheelEvent(QWheelEvent * e) { void Graphic::zoom(float factor) { - double wid = canvas->width() - gridborder.x() - margins_.width() - margins_.left(), hei = canvas->height() - gridborder.y() - margins_.height() - margins_.top(); + double wid = canvas->width() - gridborder.x() - margins_.width() - margins_.left(), + hei = canvas->height() - gridborder.y() - margins_.height() - margins_.top(); double px = wid / 2, py = hei / 2; px = px / wid * selrect.width() + selrect.x(); py = py / hei * selrect.height() + selrect.y(); - selrect.setRect(px - (px - selrect.x()) * factor, py - (py - selrect.y()) * factor, selrect.width() * factor, selrect.height() * factor); + selrect.setRect(px - (px - selrect.x()) * factor, + py - (py - selrect.y()) * factor, + selrect.width() * factor, + selrect.height() * factor); isFit = false; update(true); setRectToLines(); @@ -653,12 +653,14 @@ void Graphic::zoom(float factor) { void Graphic::fullscreen() { - if (fullscr) leaveFullscreen(); - else enterFullscreen(); + if (fullscr) + leaveFullscreen(); + else + enterFullscreen(); } -void Graphic::canvasLeaveEvent(QEvent * ) { +void Graphic::canvasLeaveEvent(QEvent *) { isHover = false; if (guides) update(true); ui->status->setText(tr("Cursor") + ": ( ; )"); @@ -668,8 +670,8 @@ void Graphic::canvasLeaveEvent(QEvent * ) { void Graphic::canvasKeyPressEvent(QKeyEvent * e) { switch (e->key()) { - case Qt::Key_Escape: leaveFullscreen(); - default: break; + case Qt::Key_Escape: leaveFullscreen(); + default: break; }; } @@ -680,7 +682,7 @@ void Graphic::clear() { graphics[i].polyline_pause.clear(); graphics[i]._lod.clear(); graphics[i]._lod_pause.clear(); - graphics[i].max_x = 0.; + graphics[i].max_x = 0.; graphics[i].cvrect = QRectF(); } if (isFit) on_graphic_buttonAutofit_clicked(); @@ -725,8 +727,8 @@ void Graphic::setHistorySize(double val) { QPolygonF & pol(graphics[i].polyline); if (pol.isEmpty() || history <= 0.) continue; graphics[i].cvrect = QRectF(); - x = pol.back().x() - history; - for (int j = pol.size() - 2; j >= 0 ; --j) + x = pol.back().x() - history; + for (int j = pol.size() - 2; j >= 0; --j) if (pol[j].x() < x) { pol.erase(pol.begin(), pol.begin() + j); break; @@ -813,8 +815,8 @@ void Graphic::setButtons(Graphic::Buttons b) { ui->graphic_buttonClose->setVisible(b.testFlag(Close)); ui->graphic_checkPause->setVisible(b.testFlag(Pause)); ui->graphic_buttonRecord->setVisible(b.testFlag(Record)); - if (ui->graphic_buttonAutofit ->isVisible() || ui->graphic_checkGrid ->isVisible() || ui->graphic_checkGuides->isVisible() || - ui->graphic_buttonConfigure->isVisible() || ui->graphic_buttonSave->isVisible() || ui->graphic_checkPause ->isVisible()) + if (ui->graphic_buttonAutofit->isVisible() || ui->graphic_checkGrid->isVisible() || ui->graphic_checkGuides->isVisible() || + ui->graphic_buttonConfigure->isVisible() || ui->graphic_buttonSave->isVisible() || ui->graphic_checkPause->isVisible()) ui->verticalSpacer->changeSize(0, 30, QSizePolicy::Preferred, QSizePolicy::Preferred); else ui->verticalSpacer->changeSize(0, 0, QSizePolicy::Preferred, QSizePolicy::Preferred); @@ -830,13 +832,13 @@ void Graphic::setButtonsPosition(Graphic::Alignment a) { return; #endif switch (a) { - case Graphic::Left: - ui->widgetLeft->setLayout(ui->layoutButtons); - ui->widgetLeft->show(); + case Graphic::Left: + ui->widgetLeft->setLayout(ui->layoutButtons); + ui->widgetLeft->show(); break; - case Graphic::Right: - ui->widgetRight->setLayout(ui->layoutButtons); - ui->widgetRight->show(); + case Graphic::Right: + ui->widgetRight->setLayout(ui->layoutButtons); + ui->widgetRight->show(); break; } } @@ -862,7 +864,7 @@ void Graphic::addPoints(const QPolygonF & pts, int graphic, bool update_) { if (graphic >= graphics.size() || graphic < 0 || pts.isEmpty()) return; GraphicType & t(graphics[graphic]); if (!t.cvrect.isNull() && !pause_) { - for(const QPointF & p : pts) { + for (const QPointF & p: pts) { if (t.cvrect.top() < p.y()) t.cvrect.setTop(p.y()); if (t.cvrect.bottom() > p.y()) t.cvrect.setBottom(p.y()); if (t.cvrect.right() < p.x()) t.cvrect.setRight(p.x()); @@ -870,7 +872,8 @@ void Graphic::addPoints(const QPolygonF & pts, int graphic, bool update_) { } } if (t.polyline.size() == 0) t.max_x = pts.at(0).x(); - for(const QPointF & p : pts) if (t.max_x < p.x()) t.max_x = p.x(); + for (const QPointF & p: pts) + if (t.max_x < p.x()) t.max_x = p.x(); t.polyline << pts; tick(graphic, true, update_); } @@ -881,7 +884,8 @@ void Graphic::addPoints(const QVector & pts, int graphic, bool update_) ps.reserve(pts.size()); double stx = 0; if (!graphics[curGraphic].polyline.isEmpty()) stx = graphics[curGraphic].max_x; - for (int i=0; i & g, int graphic, bool updat } t.max_x = t.polyline[0].x(); for (int i = 1; i < t.polyline.size(); ++i) - if (t.max_x < t.polyline[i].x()) - t.max_x = t.polyline[i].x(); + if (t.max_x < t.polyline[i].x()) t.max_x = t.polyline[i].x(); tick(graphic, false, update_); } -void Graphic::setGraphicProperties(int graphic, const QString & name, const QColor& color, Qt::PenStyle style, double width, bool visible) { +void Graphic::setGraphicProperties(int graphic, + const QString & name, + const QColor & color, + Qt::PenStyle style, + double width, + bool visible) { if (graphic < 0 || graphic >= graphics.size()) return; graphics[graphic].name = name; graphics[graphic].pen.setColor(color); @@ -924,7 +932,7 @@ void Graphic::addGraphic(const QString & name, const QColor & color, Qt::PenStyl void Graphic::setVisualRect(const QRectF & rect) { selrect = rect; - isFit = false; + isFit = false; update(); } @@ -962,7 +970,7 @@ void Graphic::exportGraphics(QString filename, QChar decimal_point) { } ts << "\n"; bool has_data = true; - int ind = 0; + int ind = 0; QString line; while (has_data) { has_data = false; @@ -991,8 +999,7 @@ void Graphic::exportGraphics(QString filename, QChar decimal_point) { } ++ind; line += "\n"; - if (has_data) - ts << line; + if (has_data) ts << line; } QApplication::restoreOverrideCursor(); } @@ -1000,14 +1007,14 @@ void Graphic::exportGraphics(QString filename, QChar decimal_point) { void Graphic::setOpenGL(bool on) { #ifdef HAS_GL - isOGL = on; + isOGL = on; need_createGL = false; if (on && !m_fakeGL) { if (!canvas_gl) { if (!isVisible()) need_createGL = true; else { - //qDebug() << "create GL on setter"; + // qDebug() << "create GL on setter"; canvas_gl = new UGLWidget(); ui->layoutCanvas->addWidget(canvas_gl); connect(canvas_gl, SIGNAL(paintSignal()), this, SLOT(canvasPaintEvent())); @@ -1020,8 +1027,7 @@ void Graphic::setOpenGL(bool on) { canvas = canvas_gl; } } else { - if (canvas_gl) - canvas_gl->hide(); + if (canvas_gl) canvas_gl->hide(); ui->canvas_raster->show(); canvas = ui->canvas_raster; } @@ -1043,7 +1049,9 @@ void Graphic::setGraphicsCount(int arg, bool update) { if (arg < 0) return; while (graphics.size() < arg) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) - graphics.append(GraphicType(tr("y(x)"), QColor::fromHsv((graphics.size() * 55) % 360, 255, 255 - QRandomGenerator::global()->generate() % 115))); + graphics.append( + GraphicType(tr("y(x)"), + QColor::fromHsv((graphics.size() * 55) % 360, 255, 255 - QRandomGenerator::global()->generate() % 115))); #else graphics.append(GraphicType(tr("y(x)"), QColor::fromHsv((graphics.size() * 55) % 360, 255, 255 - qrand() % 115))); #endif @@ -1064,7 +1072,7 @@ void Graphic::removeGraphic(int arg, bool update) { } -void Graphic::setCustomGridMarkFuncs(std::function fx, std::function fy) { +void Graphic::setCustomGridMarkFuncs(std::function fx, std::function fy) { func_gridMarkX = fx; func_gridMarkY = fy; } @@ -1073,12 +1081,12 @@ void Graphic::setCustomGridMarkFuncs(std::function fx, std::fu void Graphic::findGraphicsRect(double start_x, double end_x, double start_y, double end_y) { double cx, cy, maxX, minX, maxY, minY, vx; bool isRangeX = (start_x != end_x), isRangeY = (start_y != end_y); - bool can_fast = (start_x == 0 && end_x == 0 && start_y == 0 && end_y == 0); + bool can_fast = (start_x == 0 && end_x == 0 && start_y == 0 && end_y == 0); bool anyVisible = false, isTimeLimit = (visible_time > 0.) && !(isRangeX || isRangeY); - vx = -DBL_MAX; + vx = -DBL_MAX; minY = minX = DBL_MAX; maxY = maxX = -DBL_MAX; - foreach (const GraphicType & t, graphics) { + foreach(const GraphicType & t, graphics) { if (!t.visible) continue; if (vx < (pause_ ? t.max_x_pause : t.max_x)) vx = (pause_ ? t.max_x_pause : t.max_x); } @@ -1130,8 +1138,14 @@ void Graphic::findGraphicsRect(double start_x, double end_x, double start_y, dou if (maxY < limit_.top()) maxY = limit_.top(); if (minX > maxX) qSwap(minX, maxX); if (minY > maxY) qSwap(minY, maxY); - if (qAbs(minX - maxX) < 1E-60) {minX -= defaultRect().width()/2; maxX += defaultRect().width()/2;} - if (qAbs(minY - maxY) < 1E-60) {minY -= defaultRect().height()/2; maxY += defaultRect().height()/2;} + if (qAbs(minX - maxX) < 1E-60) { + minX -= defaultRect().width() / 2; + maxX += defaultRect().width() / 2; + } + if (qAbs(minY - maxY) < 1E-60) { + minY -= defaultRect().height() / 2; + maxY += defaultRect().height() / 2; + } if (only_expand_x) { if (minX > eminx) minX = eminx; if (maxX < emaxx) maxX = emaxx; @@ -1140,16 +1154,20 @@ void Graphic::findGraphicsRect(double start_x, double end_x, double start_y, dou if (minY > eminy) minY = eminy; if (maxY < emaxy) maxY = emaxy; } - eminx = minX; emaxx = maxX; - eminy = minY; emaxy = maxY; - if (isRangeX) selrect.setRect(start_x, minY, end_x - start_x, maxY - minY); - else if (isRangeY) selrect.setRect(minX, start_y, maxX - minX, end_y - start_y); - else grect.setRect(minX, minY, maxX - minX, maxY - minY); + eminx = minX; + emaxx = maxX; + eminy = minY; + emaxy = maxY; + if (isRangeX) + selrect.setRect(start_x, minY, end_x - start_x, maxY - minY); + else if (isRangeY) + selrect.setRect(minX, start_y, maxX - minX, end_y - start_y); + else + grect.setRect(minX, minY, maxX - minX, maxY - minY); grect = grect.normalized(); if (isFit) { if (visible_time > 0.) { - if (grect.width() > visible_time) - grect.setLeft(grect.right() - visible_time); + if (grect.width() > visible_time) grect.setLeft(grect.right() - visible_time); } selrect = grect; } @@ -1158,28 +1176,29 @@ void Graphic::findGraphicsRect(double start_x, double end_x, double start_y, dou void Graphic::drawAction() { - int wid = canvas->width(), hei = canvas->height() - gridborder.y(), sx = startpos.x(), sy = startpos.y(), cx = curpos.x(), cy = curpos.y(); + int wid = canvas->width(), hei = canvas->height() - gridborder.y(), sx = startpos.x(), sy = startpos.y(), cx = curpos.x(), + cy = curpos.y(); painter->setPen(selpen); painter->setBrush(selbrush); switch (curaction) { - case gaZoomInRect: { - QSizeF rsz = QRectF(startpos_r, curpos_r).normalized().size(); - painter->drawRect(QRect(startpos, curpos)); - fp_size = " x " + pointCoords(QPointF(rsz.width(), rsz.height())); - } break; - case gaZoomRangeX: - painter->drawLine(sx, hei, sx, 0); - painter->drawLine(cx, hei, cx, 0); - painter->fillRect(sx, 0, cx - sx, hei, selbrush); - fp_size = " x " + pointCoords(QPointF(qAbs(startpos_r.x() - curpos_r.x()), 0.), true, false); - break; - case gaZoomRangeY: - painter->drawLine(gridborder.x(), sy, wid, sy); - painter->drawLine(gridborder.x(), cy, wid, cy); - painter->fillRect(gridborder.x(), sy, wid - gridborder.x(), cy - sy, selbrush); - fp_size = " x " + pointCoords(QPointF(0., qAbs(startpos_r.y() - curpos_r.y())), false, true); - break; - default: break; + case gaZoomInRect: { + QSizeF rsz = QRectF(startpos_r, curpos_r).normalized().size(); + painter->drawRect(QRect(startpos, curpos)); + fp_size = " x " + pointCoords(QPointF(rsz.width(), rsz.height())); + } break; + case gaZoomRangeX: + painter->drawLine(sx, hei, sx, 0); + painter->drawLine(cx, hei, cx, 0); + painter->fillRect(sx, 0, cx - sx, hei, selbrush); + fp_size = " x " + pointCoords(QPointF(qAbs(startpos_r.x() - curpos_r.x()), 0.), true, false); + break; + case gaZoomRangeY: + painter->drawLine(gridborder.x(), sy, wid, sy); + painter->drawLine(gridborder.x(), cy, wid, cy); + painter->fillRect(gridborder.x(), sy, wid - gridborder.x(), cy - sy, selbrush); + fp_size = " x " + pointCoords(QPointF(0., qAbs(startpos_r.y() - curpos_r.y())), false, true); + break; + default: break; } } @@ -1192,12 +1211,14 @@ void Graphic::drawGrid() { QPair str; range = selrect.bottom() - selrect.top(); - if (grad_y == Graphic::Auto) step = splitRange(range, hei / gridy / font_sz.height() / 1.4); - else step = gridy; + if (grad_y == Graphic::Auto) + step = splitRange(range, hei / gridy / font_sz.height() / 1.4); + else + step = gridy; start = roundTo(canvas2realY(-hei), step) - step; - py = start + step; - cy = 0; - cx = gbx - 5; + py = start + step; + cy = 0; + cx = gbx - 5; grid_pen.setWidth(qMax(qMax(qRound(thick / 1.4), 1), grid_pen.width())); #if QT_VERSION_MAJOR >= 5 grid_pen.setCosmetic(true); @@ -1257,10 +1278,12 @@ void Graphic::drawGrid() { range = selrect.right() - selrect.left(); QString df; if (axis_type_x == Graphic::Numeric) { - if (grad_x == Graphic::Auto) step = splitRange(range, wid / gridx / font_sz.width() * 1.4); - else step = gridx; + if (grad_x == Graphic::Auto) + step = splitRange(range, wid / gridx / font_sz.width() * 1.4); + else + step = gridx; start = roundTo(canvas2realX(right), step); - px = start + step; + px = start + step; if (step > 0.) { cnt = 1000; while (cnt-- > 0) { @@ -1300,10 +1323,12 @@ void Graphic::drawGrid() { } else { int dt_add[DateComponentCount]; int dt_add_lo[DateComponentCount]; - for (int i = 0; i < DateComponentCount; ++i) dt_add_lo[i] = dt_add[i] = 0; + for (int i = 0; i < DateComponentCount; ++i) + dt_add_lo[i] = dt_add[i] = 0; DateFormats formats; step = splitRangeDate(range, wid / gridx / font_sz.width() / 1.5, formats, dt_add); - for (int i = 0; i < DateComponentCount - 1; ++i) dt_add_lo[i + 1] = dt_add[i]; + for (int i = 0; i < DateComponentCount - 1; ++i) + dt_add_lo[i + 1] = dt_add[i]; bool is_years = formats.center.isEmpty(); if (step > 0.) { int up_y = cy - font_sz.height() * 2; @@ -1312,7 +1337,7 @@ void Graphic::drawGrid() { int ddx = 0, pcx = 0; QDateTime cd = QDateTime::fromMSecsSinceEpoch(canvas2realX(gbx) * grid_numbers_x), cdp, cdc, cdl, cdlp; QString ds; - //qDebug() << step << range << int(wid / gridx / font_sz.width() * 1.4) << cd; + // qDebug() << step << range << int(wid / gridx / font_sz.width() * 1.4) << cd; if (!is_years) { roundDateTime(cd, dt_add); cdp = cdl = cdlp = cd; @@ -1322,13 +1347,13 @@ void Graphic::drawGrid() { cd.setTime(QTime(0, 0, 0)); cd.setDate(QDate(roundTo(cd.date().year(), dt_add[6]) - dt_add[6], 1, 1)); } - //qDebug() << cd << cur_scl[0] << cur_scl[1] << cur_scl[2] << cur_scl[3] << cur_scl[4] << cur_scl[5] << cur_scl[6]; + // qDebug() << cd << cur_scl[0] << cur_scl[1] << cur_scl[2] << cur_scl[3] << cur_scl[4] << cur_scl[5] << cur_scl[6]; struct Anchor { int x_start, x_end; QDateTime date; }; QVector areas_ce, areas_lo; - cnt = 1000; + cnt = 1000; int area_start = gbx, area_start_lo = gbx; pcx = real2canvasX(cd.toMSecsSinceEpoch() / grid_numbers_x); while (cnt-- > 0) { @@ -1341,16 +1366,16 @@ void Graphic::drawGrid() { if (cx < gbx) continue; if (cdp != cdc) { int cxc = real2canvasX(cdc.toMSecsSinceEpoch() / grid_numbers_x); - //qDebug() << cx << cxc << ddx << pcx; + // qDebug() << cx << cxc << ddx << pcx; if ((qAbs(cxc - cx) < ddx) && (cx != cxc)) need_text = false; areas_ce << Anchor{area_start, qMin(cxc, right), cdp}; area_start = areas_ce.back().x_end; cd = cdl = cdp = cdc; - cx = cxc; + cx = cxc; roundDateTime(cdl, dt_add_lo); if (cdlp != cdl) { areas_lo << Anchor{area_start_lo, qMin(cxc, right), cdlp}; - cdlp = cdl; + cdlp = cdl; area_start_lo = areas_lo.back().x_end; } } else { @@ -1372,11 +1397,9 @@ void Graphic::drawGrid() { } } if (!is_years) { - if (area_start < right) - areas_ce << Anchor{area_start, right, cdc}; - if (area_start_lo < right) - areas_lo << Anchor{area_start_lo, right, cdl}; - //qDebug() << areas_lo.size() << formats.upper << areas_lo[0].date; + if (area_start < right) areas_ce << Anchor{area_start, right, cdc}; + if (area_start_lo < right) areas_lo << Anchor{area_start_lo, right, cdl}; + // qDebug() << areas_lo.size() << formats.upper << areas_lo[0].date; painter->setPen(grid_pen); for (const auto & a: areas_ce) { painter->drawLine(a.x_start, hei + 5, a.x_start, ce_y); @@ -1389,12 +1412,12 @@ void Graphic::drawGrid() { painter->setFont(nf); auto pfm = painter->fontMetrics(); for (const auto & a: areas_ce) { - ds = a.date.toString(formats.center); + ds = a.date.toString(formats.center); auto str_rect = pfm.boundingRect(ds); painter->drawText(a.x_start + (a.x_end - a.x_start - str_rect.width()) / 2, ce_y, ds); } for (const auto & a: areas_lo) { - ds = a.date.toString(formats.lower); + ds = a.date.toString(formats.lower); auto str_rect = pfm.boundingRect(ds); painter->drawText(a.x_start + (a.x_end - a.x_start - str_rect.width()) / 2, lo_y, ds); } @@ -1426,7 +1449,7 @@ QPair Graphic::gridMark(double v) const { v = 1.; p += 1; } - ret.first = QString::fromUtf8("%1·10").arg(v); + ret.first = QString::fromUtf8("%1·10").arg(v); ret.second = QString::number(p); } else ret.first = QString::number(v, 'g', 8); @@ -1437,31 +1460,30 @@ QPair Graphic::gridMark(double v) const { void Graphic::fillDateFormats() { date_formats.clear(); QString tr_ms = tr("ms"), tr_s = tr("s"), tr_m = tr("m"), tr_h = tr("h"); - auto trFunc = [&](const DateFormats & src)->DateFormats{ + auto trFunc = [&](const DateFormats & src) -> DateFormats { DateFormats ret; - ret.upper = QString(src.upper ).replace("%1", tr_ms).replace("%2", tr_s).replace("%3", tr_m).replace("%4", tr_h); + ret.upper = QString(src.upper).replace("%1", tr_ms).replace("%2", tr_s).replace("%3", tr_m).replace("%4", tr_h); ret.center = QString(src.center).replace("%1", tr_ms).replace("%2", tr_s).replace("%3", tr_m).replace("%4", tr_h); - ret.lower = QString(src.lower ).replace("%1", tr_ms).replace("%2", tr_s).replace("%3", tr_m).replace("%4", tr_h); + ret.lower = QString(src.lower).replace("%1", tr_ms).replace("%2", tr_s).replace("%3", tr_m).replace("%4", tr_h); return ret; }; date_formats << trFunc(DateFormats{"zzz '%1'", "h '%4' mm '%3' ss '%2'", "yyyy MMM dd(ddd)"}); - date_formats << trFunc(DateFormats{"ss '%2'" , "h '%4' mm '%3'" , "yyyy MMM dd(ddd)"}); - date_formats << trFunc(DateFormats{"mm '%3'" , "h '%4'" , "yyyy MMM dd(ddd)"}); - date_formats << trFunc(DateFormats{"h '%4'" , "dd(ddd)" , "yyyy MMM" }); - date_formats << trFunc(DateFormats{"dd(ddd)" , "MMM" , "yyyy" }); - date_formats << trFunc(DateFormats{"MMM" , "yyyy" , "" }); - date_formats << trFunc(DateFormats{"yyyy" , "" , "" }); + date_formats << trFunc(DateFormats{"ss '%2'", "h '%4' mm '%3'", "yyyy MMM dd(ddd)"}); + date_formats << trFunc(DateFormats{"mm '%3'", "h '%4'", "yyyy MMM dd(ddd)"}); + date_formats << trFunc(DateFormats{"h '%4'", "dd(ddd)", "yyyy MMM"}); + date_formats << trFunc(DateFormats{"dd(ddd)", "MMM", "yyyy"}); + date_formats << trFunc(DateFormats{"MMM", "yyyy", ""}); + date_formats << trFunc(DateFormats{"yyyy", "", ""}); } void Graphic::drawGraphics() { - if (isHover) - ui->status->setText(tr("Cursor: ") + pointCoords(canvas2real(QPointF(curpos)))); + if (isHover) ui->status->setText(tr("Cursor: ") + pointCoords(canvas2real(QPointF(curpos)))); QPointF srp = -selrect.topLeft(); double sclx, scly, wid = canvas->width(), hei = canvas->height(); int cwid = (wid - gridborder.x() - margins_.left() - margins_.width()); - sclx = cwid / selrect.width(); - scly = (hei - gridborder.y() - margins_.top() - margins_.height()) / selrect.height(); + sclx = cwid / selrect.width(); + scly = (hei - gridborder.y() - margins_.top() - margins_.height()) / selrect.height(); painter->setClipping(true); painter->setClipRect(QRect(gridborder.x(), 0, wid - gridborder.x(), hei - gridborder.y())); painter->translate(gridborder.x() + margins_.left(), hei - gridborder.y() - margins_.top()); @@ -1478,23 +1500,23 @@ void Graphic::drawGraphics() { QVector & src_lod(pause_ ? t._lod_pause : t._lod); int lod = 0; if (m_LODOptimization) { - int gpcnt = src_pol.size(); + int gpcnt = src_pol.size(); qreal range = src_pol.back().x() - src_pol.front().x(); - qreal ppp = (gpcnt * selrect.width() / qMax(range, 1.E-9) / cwid); - lod = qBound(0, qFloor(log2(ppp) - 1), src_lod.size()); - //qDebug() << "draw lod" << lod << src_lod[lod - 1].size(); + qreal ppp = (gpcnt * selrect.width() / qMax(range, 1.E-9) / cwid); + lod = qBound(0, qFloor(log2(ppp) - 1), src_lod.size()); + // qDebug() << "draw lod" << lod << src_lod[lod - 1].size(); } t.last_lod = lod; QPolygonF & rpol(lod == 0 ? src_pol : src_lod[lod - 1]); int ind_start = -1, ind_end = -1; if (m_LODOptimization) { qreal xs = selrect.left(), xe = selrect.right(), _offset = 2. / cwid * selrect.width(); - xs -= _offset; xe += _offset; + xs -= _offset; + xe += _offset; for (int i = 0; i < rpol.size(); ++i) { qreal px = rpol[i].x(); if (px < xs) continue; - if (ind_start < 0) - ind_start = qMax(0, i - 1); + if (ind_start < 0) ind_start = qMax(0, i - 1); if (px > xe && ind_end < 0) { ind_end = qMin(rpol.size(), i + 1); break; @@ -1502,10 +1524,10 @@ void Graphic::drawGraphics() { } if (ind_start < 0) ind_start = 0; if (ind_end < 0) ind_end = rpol.size(); - //qDebug() << "bound" << ind_start << ind_end << rpol.size(); + // qDebug() << "bound" << ind_start << ind_end << rpol.size(); } else { ind_start = 0; - ind_end = rpol.size(); + ind_end = rpol.size(); } int polsize = ind_end - ind_start; if (polsize > 0) { @@ -1513,13 +1535,15 @@ void Graphic::drawGraphics() { if (m_LODOptimization && polsize < rpol.size()) { cpol.resize(polsize); memcpy(cpol.data(), &(rpol[ind_start]), polsize * sizeof(QPointF)); - //qDebug() << "copy" << polsize; + // qDebug() << "copy" << polsize; } else { cpol = rpol; } pen = t.pen; - if (qRound(pen.widthF()) == pen.widthF()) pen.setWidth(pen.width()*thick); - else pen.setWidthF(pen.widthF()*thick); + if (qRound(pen.widthF()) == pen.widthF()) + pen.setWidth(pen.width() * thick); + else + pen.setWidthF(pen.widthF() * thick); pen.setCosmetic(true); if (t.lines) { painter->setPen(pen); @@ -1530,8 +1554,10 @@ void Graphic::drawGraphics() { painter->drawPolyline(mat.map(cpol)); } if (t.points) { - if (qRound(t.pointWidth) == t.pointWidth) pen.setWidth(qRound(t.pointWidth*thick)); - else pen.setWidthF(t.pointWidth*thick); + if (qRound(t.pointWidth) == t.pointWidth) + pen.setWidth(qRound(t.pointWidth * thick)); + else + pen.setWidthF(t.pointWidth * thick); painter->setPen(pen); painter->drawPoints(mat.map(cpol)); } @@ -1549,9 +1575,9 @@ QString Graphic::pointCoords(QPointF point, bool x, bool y) { else ret += #if QT_VERSION_MAJOR <= 5 - QDateTime::fromMSecsSinceEpoch(point.x()).toString(Qt::SystemLocaleShortDate); + QDateTime::fromMSecsSinceEpoch(point.x()).toString(Qt::SystemLocaleShortDate); #else - locale().toString(QDateTime::fromMSecsSinceEpoch(point.x()), QLocale::ShortFormat); + locale().toString(QDateTime::fromMSecsSinceEpoch(point.x()), QLocale::ShortFormat); #endif } if (y) { @@ -1575,11 +1601,11 @@ void Graphic::drawGuides() { painter->resetTransform(); painter->setClipping(true); painter->setClipRect(QRect(gridborder.x(), 0, wid - gridborder.x(), hei - gridborder.y())); - QPoint apos = curpos; + QPoint apos = curpos; QPointF rpos = canvas2real(apos); QString str; - str = pointCoords(rpos) + fp_size; - bool trace_found = false; + str = pointCoords(rpos) + fp_size; + bool trace_found = false; auto trace_axis_func = [&](bool on_x, double cursor) { if (curTrace >= 0 && curTrace < graphics.size()) { auto & t(graphics[curTrace]); @@ -1594,13 +1620,13 @@ void Graphic::drawGuides() { dist = qAbs((on_x ? pol[i].x() : pol[i].y()) - cursor); if (min_dist > dist || min_dist < 0) { min_dist = dist; - index = i; + index = i; } } if (index >= 0) { - rpos = pol[index]; - apos = real2canvas(rpos).toPoint(); - str = pointCoords(pol[index]) + fp_size; + rpos = pol[index]; + apos = real2canvas(rpos).toPoint(); + str = pointCoords(pol[index]) + fp_size; trace_found = true; emit graphicTraceEvent(curTrace, rpos); } @@ -1610,7 +1636,7 @@ void Graphic::drawGuides() { auto trace_free_func = [&](QPointF cursor) { double min_dist = -1; int gr = -1, mag_dist = fontHeight(this) * 2; - QPointF point, scale = getScale(), dp; + QPointF point, scale = getScale(), dp; for (int g = 0; g < graphics.size(); ++g) { auto & t(graphics[g]); if (t.visible) { @@ -1627,34 +1653,27 @@ void Graphic::drawGuides() { dist = QVector2D(dp).lengthSquared(); if (min_dist > dist || min_dist < 0) { min_dist = dist; - gr = g; - rpos = point; + gr = g; + rpos = point; } } } } } if (gr >= 0) { - apos = real2canvas(rpos).toPoint(); - str = " " + graphics[gr].name + ": " + pointCoords(rpos) + fp_size; + apos = real2canvas(rpos).toPoint(); + str = " " + graphics[gr].name + ": " + pointCoords(rpos) + fp_size; trace_found = true; emit graphicTraceEvent(gr, rpos); } }; switch (floating_axis_type) { - case TraceXY: - trace_free_func(rpos); - break; - case TraceX: - trace_axis_func(true, rpos.x()); - break; - case TraceY: - trace_axis_func(false, rpos.y()); - break; + case TraceXY: trace_free_func(rpos); break; + case TraceX: trace_axis_func(true, rpos.x()); break; + case TraceY: trace_axis_func(false, rpos.y()); break; default: break; } - if (was_trace && !trace_found) - emit graphicTraceEvent(-1, QPointF()); + if (was_trace && !trace_found) emit graphicTraceEvent(-1, QPointF()); was_trace = trace_found; painter->drawLine(0, apos.y(), wid, apos.y()); painter->drawLine(apos.x(), 0, apos.x(), hei); @@ -1678,7 +1697,7 @@ void Graphic::drawPause() { painter->resetTransform(); painter->translate(canvas->width() - icon_pause_b.width() - 6, 6); double o = (0.5 - pause_phase) * 2; - painter->setOpacity(o*o); + painter->setOpacity(o * o); painter->drawImage(0, 0, icon_pause_b); painter->setOpacity(1.); painter->drawImage(0, 0, icon_pause_f); @@ -1689,11 +1708,11 @@ void Graphic::drawPause() { double roundToSteps(double value, const QVector & steps) { double ret = value, min_err = -1.; for (double v: steps) { - double sv = qRound64(value / v) * v; + double sv = qRound64(value / v) * v; double err = qAbs(value - sv); if (min_err < 0 || min_err > err) { min_err = err; - ret = sv; + ret = sv; } } if (ret < steps[0]) ret = steps[0]; @@ -1706,7 +1725,7 @@ double roundToNearest(double value, const QVector & values) { double err = qAbs(value - v); if (min_err < 0 || min_err > err) { min_err = err; - ret = v; + ret = v; } } if (ret < values[0]) ret = values[0]; @@ -1717,13 +1736,13 @@ double roundToNearest(double value, const QVector & values) { double Graphic::splitRange(double range, int count) { double digits, step, tln; range = qAbs(range); - tln = qFloor(qLn(range) / LN10); + tln = qFloor(qLn(range) / LN10); for (int i = 0; i <= 5; ++i) { digits = qPow(10., tln - i); - step = qRound(range / count / digits); + step = qRound(range / count / digits); if (step > 0.) { digits = qPow(10., tln - i - 1); - step = qRound(range / count / digits); + step = qRound(range / count / digits); break; } } @@ -1733,22 +1752,32 @@ double Graphic::splitRange(double range, int count) { double Graphic::splitRangeDate(double range, int count, DateFormats & formats, int step[7]) { - static const qint64 - to_sec = 1000LL, - to_min = 1000LL * 60, - to_hour = 1000LL * 60 * 60, - to_day = 1000LL * 60 * 60 * 24, - to_month = 1000LL * 60 * 60 * 24 * 30, - to_year = 1000LL * 60 * 60 * 24 * 30 * 12; - double ret = splitRange(range, count); + static const qint64 to_sec = 1000LL, to_min = 1000LL * 60, to_hour = 1000LL * 60 * 60, to_day = 1000LL * 60 * 60 * 24, + to_month = 1000LL * 60 * 60 * 24 * 30, to_year = 1000LL * 60 * 60 * 24 * 30 * 12; + double ret = splitRange(range, count); int format_index = DateYears; - if (ret < to_sec / 1 ) {format_index = DateMSecs ; step[DateMSecs ] = qRound64(ret);} - else if (ret < to_min / 2 ) {format_index = DateSecs ; step[DateSecs ] = roundToNearest(ret / to_sec , {1, 2, 5, 10, 15, 20, 30});} - else if (ret < to_hour ) {format_index = DateMinutes; step[DateMinutes] = roundToNearest(ret / to_min , {1, 2, 5, 10, 15, 20, 30});} - else if (ret < to_day ) {format_index = DateHours ; step[DateHours ] = roundToNearest(ret / to_hour , {1, 2, 3, 4, 6, 8, 12});} - else if (ret < to_month / 1.6) {format_index = DateDays ; step[DateDays ] = roundToNearest(ret / to_day , {1, 2, 5, 10});} - else if (ret < to_year ) {format_index = DateMonths ; step[DateMonths ] = roundToNearest(ret / to_month, {1, 2, 3, 4, 6});} - else {format_index = DateYears ; step[DateYears ] = qRound64(ret / to_year);} + if (ret < to_sec / 1) { + format_index = DateMSecs; + step[DateMSecs] = qRound64(ret); + } else if (ret < to_min / 2) { + format_index = DateSecs; + step[DateSecs] = roundToNearest(ret / to_sec, {1, 2, 5, 10, 15, 20, 30}); + } else if (ret < to_hour) { + format_index = DateMinutes; + step[DateMinutes] = roundToNearest(ret / to_min, {1, 2, 5, 10, 15, 20, 30}); + } else if (ret < to_day) { + format_index = DateHours; + step[DateHours] = roundToNearest(ret / to_hour, {1, 2, 3, 4, 6, 8, 12}); + } else if (ret < to_month / 1.6) { + format_index = DateDays; + step[DateDays] = roundToNearest(ret / to_day, {1, 2, 5, 10}); + } else if (ret < to_year) { + format_index = DateMonths; + step[DateMonths] = roundToNearest(ret / to_month, {1, 2, 3, 4, 6}); + } else { + format_index = DateYears; + step[DateYears] = qRound64(ret / to_year); + } formats = date_formats[format_index]; return ret; } @@ -1761,25 +1790,35 @@ double Graphic::roundTo(double value, double round_to) { void Graphic::roundDateTime(QDateTime & dt, int * c) { - QDate d(dt.date()); QTime t(dt.time()); - if (c[DateMSecs ] != 0) t.setHMS(t.hour(), t.minute(), t.second()); - if (c[DateSecs ] != 0) t.setHMS(t.hour(), t.minute(), 0); + QDate d(dt.date()); + QTime t(dt.time()); + if (c[DateMSecs] != 0) t.setHMS(t.hour(), t.minute(), t.second()); + if (c[DateSecs] != 0) t.setHMS(t.hour(), t.minute(), 0); if (c[DateMinutes] != 0) t.setHMS(t.hour(), 0, 0); - if (c[DateHours ] != 0) {t.setHMS(0, 0, 0); d.setDate(d.year(), d.month(), d.day());} - if (c[DateDays ] != 0) {t.setHMS(0, 0, 0); d.setDate(d.year(), d.month(), 1);} - if (c[DateMonths ] != 0 || c[DateYears] != 0) {t.setHMS(0, 0, 0); d.setDate(d.year(), 1, 1);} + if (c[DateHours] != 0) { + t.setHMS(0, 0, 0); + d.setDate(d.year(), d.month(), d.day()); + } + if (c[DateDays] != 0) { + t.setHMS(0, 0, 0); + d.setDate(d.year(), d.month(), 1); + } + if (c[DateMonths] != 0 || c[DateYears] != 0) { + t.setHMS(0, 0, 0); + d.setDate(d.year(), 1, 1); + } dt = QDateTime(d, t); } void Graphic::addDateTime(QDateTime & dt, int * c, qint64 mul) { - if (c[DateMSecs ] != 0) dt = dt.addMSecs (mul * c[DateMSecs ]); - if (c[DateSecs ] != 0) dt = dt.addSecs (mul * c[DateSecs ]); - if (c[DateMinutes] != 0) dt = dt.addSecs (mul * c[DateMinutes] * 60); - if (c[DateHours ] != 0) dt = dt.addSecs (mul * c[DateHours ] * 60 * 60); - if (c[DateDays ] != 0) dt = dt.addDays (mul * c[DateDays ]); - if (c[DateMonths ] != 0) dt = dt.addMonths(mul * c[DateMonths ]); - if (c[DateYears ] != 0) dt = dt.addYears (mul * c[DateYears ]); + if (c[DateMSecs] != 0) dt = dt.addMSecs(mul * c[DateMSecs]); + if (c[DateSecs] != 0) dt = dt.addSecs(mul * c[DateSecs]); + if (c[DateMinutes] != 0) dt = dt.addSecs(mul * c[DateMinutes] * 60); + if (c[DateHours] != 0) dt = dt.addSecs(mul * c[DateHours] * 60 * 60); + if (c[DateDays] != 0) dt = dt.addDays(mul * c[DateDays]); + if (c[DateMonths] != 0) dt = dt.addMonths(mul * c[DateMonths]); + if (c[DateYears] != 0) dt = dt.addYears(mul * c[DateYears]); } @@ -1813,7 +1852,7 @@ double Graphic::real2canvasY(double py) const { QPolygonF Graphic::real2canvas(const QPolygonF & real_polygon) const { QPolygonF ret; - for (int i=0; icanvas_raster->setCursor(cursor); #ifdef HAS_GL - if (canvas_gl) - canvas_gl->setCursor(cursor); + if (canvas_gl) canvas_gl->setCursor(cursor); #endif } @@ -1883,28 +1911,42 @@ void Graphic::swapToBuffer() { void Graphic::setRectToLines() { is_lines_update = true; if (line_x_min.isVisible() && line_x_max.isVisible() && line_y_min.isVisible() && line_y_max.isVisible()) { - line_x_min.blockSignals(true); line_x_max.blockSignals(true); line_y_min.blockSignals(true); line_y_max.blockSignals(true); + line_x_min.blockSignals(true); + line_x_max.blockSignals(true); + line_y_min.blockSignals(true); + line_y_max.blockSignals(true); if (!line_x_min.hasFocus()) { - if (isFit) line_x_min.setValue(grect.left()); - else line_x_min.setValue(selrect.left()); + if (isFit) + line_x_min.setValue(grect.left()); + else + line_x_min.setValue(selrect.left()); } if (!line_x_max.hasFocus()) { - if(isFit) line_x_max.setValue(grect.right()); - else line_x_max.setValue(selrect.right()); + if (isFit) + line_x_max.setValue(grect.right()); + else + line_x_max.setValue(selrect.right()); } if (!line_y_min.hasFocus()) { - if(isFit) line_y_min.setValue(grect.bottom()); - else line_y_min.setValue(selrect.bottom()); + if (isFit) + line_y_min.setValue(grect.bottom()); + else + line_y_min.setValue(selrect.bottom()); } if (!line_y_max.hasFocus()) { - if(isFit) line_y_max.setValue(grect.top()); - else line_y_max.setValue(selrect.top()); + if (isFit) + line_y_max.setValue(grect.top()); + else + line_y_max.setValue(selrect.top()); } line_x_min.setDefaultText(QString::number(grect.left()).toUpper()); line_x_max.setDefaultText(QString::number(grect.right()).toUpper()); line_y_min.setDefaultText(QString::number(grect.bottom()).toUpper()); line_y_max.setDefaultText(QString::number(grect.top()).toUpper()); - line_x_min.blockSignals(false); line_x_max.blockSignals(false); line_y_min.blockSignals(false); line_y_max.blockSignals(false); + line_x_min.blockSignals(false); + line_x_max.blockSignals(false); + line_y_min.blockSignals(false); + line_y_max.blockSignals(false); } is_lines_update = false; } @@ -1925,10 +1967,8 @@ void Graphic::tick(int index, bool slide, bool update_) { /// TODO: [Graphic] fast autofit while addPoint(double y, ...) if (!t.cvrect.isNull()) { QPointF fp(t.polyline.first()); - if (qFuzzyCompare(t.cvrect.left(), fp.x()) || - qFuzzyCompare(t.cvrect.right(), fp.x()) || - qFuzzyCompare(t.cvrect.top(), fp.y()) || - qFuzzyCompare(t.cvrect.bottom(), fp.y())) { + if (qFuzzyCompare(t.cvrect.left(), fp.x()) || qFuzzyCompare(t.cvrect.right(), fp.x()) || + qFuzzyCompare(t.cvrect.top(), fp.y()) || qFuzzyCompare(t.cvrect.bottom(), fp.y())) { t.cvrect = QRectF(); } } @@ -1955,48 +1995,51 @@ void Graphic::calcLOD(int index) { GraphicType & t(graphics[index]); t._lod.clear(); int pcnt = t.polyline.size(); - //qDebug() << "calcLOD" << index; + // qDebug() << "calcLOD" << index; while (pcnt >= 10) { QPolygonF & pl(t._lod.isEmpty() ? t.polyline : t._lod.back()); t._lod.append(QPolygonF()); QPolygonF & cl(t._lod.back()); cl << pl.front(); - int qcnt = (pl.size() + 1) / 4; - pcnt = qcnt * 2 + 2; - int pc = 4; + int qcnt = (pl.size() + 1) / 4; + pcnt = qcnt * 2 + 2; + int pc = 4; qreal mx[2] = {0., 0.}, my[2] = {0., 0.}, my_x[2] = {0., 0.}, px, py; for (int i = 0; i < qcnt; ++i) { - int j = i*4 + 1; + int j = i * 4 + 1; if (i == qcnt - 1) pc = pl.size() - j - 1; - mx[0] = mx[1] = my_x[0] = my_x[1] = pl[j].x(); my[0] = my[1] = pl[j].y(); + mx[0] = mx[1] = my_x[0] = my_x[1] = pl[j].x(); + my[0] = my[1] = pl[j].y(); for (int k = 1; k < pc; ++k) { - px = pl[j + k].x(); py = pl[j + k].y(); - mx[0] = qMin(mx[0], px); mx[1] = qMax(mx[1], px); + px = pl[j + k].x(); + py = pl[j + k].y(); + mx[0] = qMin(mx[0], px); + mx[1] = qMax(mx[1], px); if (my[0] > py) { - my[0] = py; + my[0] = py; my_x[0] = px; } if (my[1] < py) { - my[1] = py; + my[1] = py; my_x[1] = px; } } - qreal dx =(mx[1] - mx[0]) / 4., cx = (mx[1] + mx[0]) / 2.; + qreal dx = (mx[1] - mx[0]) / 4., cx = (mx[1] + mx[0]) / 2.; if (my_x[1] >= my_x[0]) cl << QPointF(cx - dx, my[0]) << QPointF(cx + dx, my[1]); else cl << QPointF(cx - dx, my[1]) << QPointF(cx + dx, my[0]); } cl << pl.back(); - //qDebug() << "lod" << t._lod.size() << "->" << cl.size(); + // qDebug() << "lod" << t._lod.size() << "->" << cl.size(); } } void Graphic::on_graphic_buttonAutofit_clicked() { - isFit = true; + isFit = true; bool isEmpty = true; - foreach (const GraphicType & t, graphics) { + foreach(const GraphicType & t, graphics) { const QPolygonF & pol(pause_ ? t.polyline_pause : t.polyline); if (!pol.isEmpty()) { isEmpty = false; @@ -2046,23 +2089,29 @@ void Graphic::on_graphic_buttonConfigure_clicked() { grid_pen = QPen(conf->ui->colorGrid->color(), conf->ui->spinWidthGrid->value(), (Qt::PenStyle)conf->ui->comboStyleGrid->currentIndex()); back_color = conf->ui->colorBackground->color(); text_color = conf->ui->colorText->color(); - grad_x = conf->ui->checkGridAutoX->isChecked() ? Auto : Fixed; - grad_y = conf->ui->checkGridAutoY->isChecked() ? Auto : Fixed; - gridx = conf->ui->spinGridStepX->value(); - gridy = conf->ui->spinGridStepY->value(); + grad_x = conf->ui->checkGridAutoX->isChecked() ? Auto : Fixed; + grad_y = conf->ui->checkGridAutoY->isChecked() ? Auto : Fixed; + gridx = conf->ui->spinGridStepX->value(); + gridy = conf->ui->spinGridStepY->value(); setOpenGL(conf->ui->checkOGL->isChecked()); setAntialiasing(conf->ui->checkAAlias->isChecked()); setBorderInputsVisible(conf->ui->checkInputs->isChecked()); setStatusVisible(conf->ui->checkStatus->isChecked()); setLegendVisible(conf->ui->checkLegend->isChecked()); - setMargins(conf->ui->spinMarginL->value(), conf->ui->spinMarginR->value(), conf->ui->spinMarginT->value(), conf->ui->spinMarginB->value()); + setMargins(conf->ui->spinMarginL->value(), + conf->ui->spinMarginR->value(), + conf->ui->spinMarginT->value(), + conf->ui->spinMarginB->value()); updateLegend(); update(); } void Graphic::on_graphic_buttonSave_clicked() { - QString f = QFileDialog::getSaveFileName(this, tr("Save Image"), ppath, "PNG(*.png);;JPEG(*.jpg *.jpeg);;BMP(*.bmp);;TIFF(*.tiff *.tif);;PPM(*.ppm)"); + QString f = QFileDialog::getSaveFileName(this, + tr("Save Image"), + ppath, + "PNG(*.png);;JPEG(*.jpg *.jpeg);;BMP(*.bmp);;TIFF(*.tiff *.tif);;PPM(*.ppm)"); if (f.isEmpty()) return; saveImage(f); } @@ -2072,7 +2121,8 @@ void Graphic::on_graphic_buttonExport_clicked() { QString f = QFileDialog::getSaveFileName(this, tr("Export graphics"), ppath, "CSV(*.csv)"); if (f.isEmpty()) return; QStringList items; - items << "." << ","; + items << "." + << ","; bool ok; QString item = QInputDialog::getItem(this, tr("Select decimal point"), tr("Decimal point:"), items, 0, false, &ok); if (ok && !item.isEmpty()) exportGraphics(f, item.front()); @@ -2092,15 +2142,17 @@ void Graphic::on_graphic_buttonRecord_clicked(bool checked) { qApp->setOverrideCursor(Qt::BusyCursor); GifWriter gif_writer; int frame_delay = 10; - if (GifBegin(&gif_writer, f.toUtf8(), static_cast(record_imgs.first().width()), - static_cast(record_imgs.first().height()), - static_cast(frame_delay))) { - for (const QImage & im : record_imgs) { + if (GifBegin(&gif_writer, + f.toUtf8(), + static_cast(record_imgs.first().width()), + static_cast(record_imgs.first().height()), + static_cast(frame_delay))) { + for (const QImage & im: record_imgs) { if (!GifWriteFrame(&gif_writer, - im.convertToFormat(QImage::Format_RGBA8888).constBits(), - static_cast(im.width()), - static_cast(im.height()), - static_cast(frame_delay))) { + im.convertToFormat(QImage::Format_RGBA8888).constBits(), + static_cast(im.width()), + static_cast(im.height()), + static_cast(frame_delay))) { GifEnd(&gif_writer); qDebug() << "GifWriteFrame ERROR"; } @@ -2127,8 +2179,10 @@ void Graphic::updateLegend(bool es) { pix.fill(back_color); QPainter p(&pix); QPen pen = graphics[i].pen; - if (qRound(pen.widthF()) == pen.widthF()) pen.setWidth(pen.width()*thick); - else pen.setWidthF(pen.widthF()*thick); + if (qRound(pen.widthF()) == pen.widthF()) + pen.setWidth(pen.width() * thick); + else + pen.setWidthF(pen.widthF() * thick); p.setPen(pen); p.drawLine(0, pix.height() / 2, pix.width(), pix.height() / 2); p.end(); @@ -2139,7 +2193,7 @@ void Graphic::updateLegend(bool es) { return; } leg_update = false; - int ps = 100; + int ps = 100; for (int r = 0; r < ui->layoutLegend->rowCount(); ++r) for (int c = 0; c < ui->layoutLegend->columnCount(); ++c) { QLayoutItem * li = ui->layoutLegend->itemAtPosition(r, c); @@ -2167,33 +2221,36 @@ void Graphic::updateLegend(bool es) { if (cps > ps) ps = cps; } LegendScrollArea * leg_sa = (LegendScrollArea *)ui->scrollLegend->layout()->itemAt(0)->widget(); - int maxcol = qMax(leg_sa->width() / ps - 1, 1); + int maxcol = qMax(leg_sa->width() / ps - 1, 1); int row = 0, col = 0; bool lv = ui->scrollLegend->isVisibleTo(this); ui->scrollLegend->hide(); for (int i = 0; i < graphics.size(); i++) { - ui->layoutLegend->addWidget(graphics[i].pb,row,col); + ui->layoutLegend->addWidget(graphics[i].pb, row, col); QCheckBox * check = graphics[i].pb; check->show(); if (leg_sa->minimum_hei == 0) { leg_sa->minimum_hei = ui->widgetLegend->sizeHint().height(); -/*#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) - QTimer::singleShot(0, this, [this,leg_sa,check](){ - leg_sa->minimum_hei = check->sizeHint().height(); - leg_sa->updateGeometry(); - qDebug() << leg_sa->minimum_hei << ui->widgetLegend->sizeHint(); - }); -#else - leg_sa->minimum_hei = check->sizeHint().height(); -#endif*/ + /*#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) + QTimer::singleShot(0, this, [this,leg_sa,check](){ + leg_sa->minimum_hei = check->sizeHint().height(); + leg_sa->updateGeometry(); + qDebug() << leg_sa->minimum_hei << ui->widgetLegend->sizeHint(); + }); + #else + leg_sa->minimum_hei = check->sizeHint().height(); + #endif*/ } col++; - if (col > maxcol) {col = 0; row++;} + if (col > maxcol) { + col = 0; + row++; + } } ui->gridLayout->invalidate(); ui->scrollLegend->setVisible(lv); leg_sa->updateGeometry(); - //ui->gridLayout->invalidate(); + // ui->gridLayout->invalidate(); leg_update = true; if (es) emit graphicSettingsChanged(); } @@ -2212,24 +2269,30 @@ void Graphic::updateLegendChecks() { void Graphic::graphicVisibleChange(bool checked) { if (visible_update) return; - QCheckBox * cb = qobject_cast(sender()); - int i = cb->property("graphic_num").toInt(); + QCheckBox * cb = qobject_cast(sender()); + int i = cb->property("graphic_num").toInt(); graphics[i].visible = checked; - if (isFit) on_graphic_buttonAutofit_clicked(); - else {update();} + if (isFit) + on_graphic_buttonAutofit_clicked(); + else { + update(); + } emit graphicSettingsChanged(); } void Graphic::graphicAllVisibleChange(bool checked) { visible_update = true; - for (int i=0; isetChecked(checked); } visible_update = false; - if (isFit) on_graphic_buttonAutofit_clicked(); - else {update();} + if (isFit) + on_graphic_buttonAutofit_clicked(); + else { + update(); + } emit graphicSettingsChanged(); } @@ -2319,23 +2382,22 @@ bool Graphic::legendVisible() const { QByteArray Graphic::save() { -// QByteArray ba; -// QDataStream s(&ba, QIODevice::ReadWrite); -// s << openGL() << antialiasing() << borderInputsVisible() << statusVisible() << legendVisible(); -// s << graphics; -// return ba; + // QByteArray ba; + // QDataStream s(&ba, QIODevice::ReadWrite); + // s << openGL() << antialiasing() << borderInputsVisible() << statusVisible() << legendVisible(); + // s << graphics; + // return ba; -// version '2': + // version '2': ChunkStream cs; cs.add(1, antialiasing()).add(2, openGL()).add(3, borderInputsVisible()).add(4, statusVisible()).add(5, legendVisible()); cs.add(6, backgroundColor()).add(7, textColor()).add(8, margins()); cs.add(9, gridPen()).add(10, graduationX()).add(11, graduationY()).add(12, graduationStepX()).add(13, graduationStepY()); cs.add(14, graphics); cs.add(15, isFit).add(16, visualRect()); - if (backgroundColor() == palette().color(QPalette::Base) && - textColor() == palette().color(QPalette::WindowText) && - gridColor() == palette().color(QPalette::Disabled, QPalette::WindowText)) - cs.add(17, true); + if (backgroundColor() == palette().color(QPalette::Base) && textColor() == palette().color(QPalette::WindowText) && + gridColor() == palette().color(QPalette::Disabled, QPalette::WindowText)) + cs.add(17, true); return cs.data().prepend('2'); } @@ -2343,8 +2405,8 @@ QByteArray Graphic::save() { void Graphic::load(QByteArray ba) { if (ba.isEmpty()) return; char ver = ba[0]; - switch(ver) { - case '2': {// version '2': + switch (ver) { + case '2': { // version '2': ba.remove(0, 1); QRectF vrect; ChunkStream cs(ba); @@ -2356,35 +2418,47 @@ void Graphic::load(QByteArray ba) { case 3: setBorderInputsVisible(cs.getData()); break; case 4: setStatusVisible(cs.getData()); break; case 5: setLegendVisible(cs.getData()); break; - case 6: if (!def_colors) setBackgroundColor(cs.getData()); break; - case 7: if (!def_colors) setTextColor(cs.getData()); break; + case 6: + if (!def_colors) setBackgroundColor(cs.getData()); + break; + case 7: + if (!def_colors) setTextColor(cs.getData()); + break; case 8: setMargins(cs.getData()); break; - case 9: if (!def_colors) setGridPen(cs.getData()); break; + case 9: + if (!def_colors) setGridPen(cs.getData()); + break; case 10: setGraduationX(cs.getData()); break; case 11: setGraduationY(cs.getData()); break; case 12: setGraduationStepX(cs.getData()); break; case 13: setGraduationStepY(cs.getData()); break; - case 14: graphics = cs.getData >(); break; + case 14: graphics = cs.getData>(); break; case 15: isFit = cs.getData(); break; case 16: vrect = cs.getData(); break; - case 17: if(cs.getData()) { - setTextColor(palette().color(QPalette::WindowText)); - setGridPen(QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 0., Qt::DotLine)); - setBackgroundColor(palette().color(QPalette::Base)); - def_colors = true; - } break; + case 17: + if (cs.getData()) { + setTextColor(palette().color(QPalette::WindowText)); + setGridPen(QPen(palette().color(QPalette::Disabled, QPalette::WindowText), 0., Qt::DotLine)); + setBackgroundColor(palette().color(QPalette::Base)); + def_colors = true; + } + break; default: break; } } if (!isFit) setVisualRect(vrect); } break; - default: {// old version 0: + default: { // old version 0: QDataStream s(ba); bool a; - s >> a; setOpenGL(a); - s >> a; setAntialiasing(a); - s >> a; setBorderInputsVisible(a); - s >> a; setStatusVisible(a); + s >> a; + setOpenGL(a); + s >> a; + setAntialiasing(a); + s >> a; + setBorderInputsVisible(a); + s >> a; + setStatusVisible(a); s >> a; s >> graphics; setLegendVisible(a); @@ -2403,7 +2477,8 @@ void Graphic::setCaption(const QString & str) { void Graphic::setGraphicVisible(bool visible, int index) { graphics[index].visible = visible; updateLegendChecks(); - if (isFit) on_graphic_buttonAutofit_clicked(); + if (isFit) + on_graphic_buttonAutofit_clicked(); else if (aupdate) update(); } @@ -2431,7 +2506,7 @@ void Graphic::setLegendVisible(bool visible) { ui->scrollLegend->setVisible(visible); ui->graphic_checkLegend->setChecked(visible); #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) - QTimer::singleShot(0, this, [this](){updateLegend();}); + QTimer::singleShot(0, this, [this]() { updateLegend(); }); #else updateLegend(); #endif diff --git a/libs/graphic/graphic.h b/libs/graphic/graphic.h index 95c9a9d..04f9b96 100644 --- a/libs/graphic/graphic.h +++ b/libs/graphic/graphic.h @@ -1,46 +1,47 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef GRAPHIC_H #define GRAPHIC_H -#include -#include -#include -#include +#include "evalspinbox.h" +#include "graphic_conf.h" +#include "qad_graphic_export.h" + #include #include -#include -#include #include -#include +#include #include +#include #include -#include +#include +#include +#include +#include +#include #include -#include "graphic_conf.h" -#include "evalspinbox.h" -#include "qad_graphic_export.h" +#include namespace Ui { - class Graphic; +class Graphic; } @@ -51,8 +52,7 @@ class GraphicPlugin; Q_DECLARE_METATYPE(QVector) -class QAD_GRAPHIC_EXPORT Graphic: public QFrame -{ +class QAD_GRAPHIC_EXPORT Graphic: public QFrame { Q_OBJECT Q_FLAGS(Buttons) Q_ENUMS(Alignment Graduation AxisType FloatingAxisType) @@ -127,164 +127,262 @@ public: Graphic(QWidget * parent = 0); virtual ~Graphic(); - typedef QVector > GraphicsData; - enum GraphicAction {gaNone, gaZoomInRect, gaZoomRangeX, gaZoomRangeY, gaMove}; - enum Button {NoButtons = 0x0, - AllButtons = 0xFFFFFFFF, - Autofit = 0x01, - Grid = 0x02, - CursorAxis = 0x04, - Fullscreen = 0x20, - BorderInputs = 0x40, - Legend = 0x80, - Configure = 0x100, - Save = 0x200, - Export = 0x400, - Clear = 0x800, - Close = 0x1000, - Pause = 0x2000, - Record = 0x4000, - StandartButtons = 0x2BFF - }; - enum Alignment {Left, Right}; - enum Graduation {Auto, Fixed}; - enum AxisType {Numeric, DateTime}; - enum FloatingAxisType {Free, TraceXY, TraceX, TraceY}; + typedef QVector> GraphicsData; + enum GraphicAction { + gaNone, + gaZoomInRect, + gaZoomRangeX, + gaZoomRangeY, + gaMove + }; + enum Button { + NoButtons = 0x0, + AllButtons = 0xFFFFFFFF, + Autofit = 0x01, + Grid = 0x02, + CursorAxis = 0x04, + Fullscreen = 0x20, + BorderInputs = 0x40, + Legend = 0x80, + Configure = 0x100, + Save = 0x200, + Export = 0x400, + Clear = 0x800, + Close = 0x1000, + Pause = 0x2000, + Record = 0x4000, + StandartButtons = 0x2BFF + }; + enum Alignment { + Left, + Right + }; + enum Graduation { + Auto, + Fixed + }; + enum AxisType { + Numeric, + DateTime + }; + enum FloatingAxisType { + Free, + TraceXY, + TraceX, + TraceY + }; Q_DECLARE_FLAGS(Buttons, Button) QString caption() const; - QString labelX() const {return label_x;} - QString labelY() const {return label_y;} - QString graphicName() const {return graphics[curGraphic].name;} - QString graphicName(int index) const {return graphics[index].name;} - QColor backgroundColor() const {return back_color;} - QColor textColor() const {return text_color;} - QColor graphicColor() const {return graphics[curGraphic].pen.color();} - QColor graphicColor(int index) const {return graphics[index].pen.color();} - QColor gridColor() const {return grid_pen.color();} - QColor selectionColor() const {return selpen.color();} - Qt::PenStyle graphicStyle() const {return graphics[curGraphic].pen.style();} - Qt::PenStyle graphicStyle(int index) const {return graphics[index].pen.style();} - Qt::PenStyle gridStyle() const {return grid_pen.style();} - Qt::PenStyle selectionStyle() const {return selpen.style();} - double graphicLineWidth() const {return graphics[curGraphic].pen.widthF();} - double graphicLineWidth(int index) const {return graphics[index].pen.widthF();} - double graphicPointWidth() const {return graphics[curGraphic].pointWidth;} - double graphicPointWidth(int index) const {return graphics[index].pointWidth;} - QColor graphicFillColor() const {return graphics[curGraphic].fill_color;} - QColor graphicFillColor(int index) const {return graphics[index].fill_color;} - bool graphicVisible() const {return graphics[curGraphic].visible;} - bool graphicVisible(int index) const {return graphics[index].visible;} - bool graphicLinesEnabled() const {return graphics[curGraphic].lines;} - bool graphicLinesEnabled(int index) const {return graphics[index].lines;} - bool graphicPointsEnabled() const {return graphics[curGraphic].points;} - bool graphicPointsEnabled(int index) const {return graphics[index].points;} - bool graphicFillEnabled() const {return graphics[curGraphic].fill;} - bool graphicFillEnabled(int index) const {return graphics[index].fill;} - QPen graphicPen() const {return graphics[curGraphic].pen;} - QPen graphicPen(int index) const {return graphics[index].pen;} - QPen gridPen() const {return grid_pen;} - QPen selectionPen() const {return selpen;} - QBrush selectionBrush() const {return selbrush;} - bool navigationEnabled() const {return navigation;} - bool openGL() const {return isOGL;} - bool antialiasing() const {return aalias;} - bool autoUpdate() const {return aupdate;} - bool gridEnabled() const {return grid;} + QString labelX() const { return label_x; } + QString labelY() const { return label_y; } + QString graphicName() const { return graphics[curGraphic].name; } + QString graphicName(int index) const { return graphics[index].name; } + QColor backgroundColor() const { return back_color; } + QColor textColor() const { return text_color; } + QColor graphicColor() const { return graphics[curGraphic].pen.color(); } + QColor graphicColor(int index) const { return graphics[index].pen.color(); } + QColor gridColor() const { return grid_pen.color(); } + QColor selectionColor() const { return selpen.color(); } + Qt::PenStyle graphicStyle() const { return graphics[curGraphic].pen.style(); } + Qt::PenStyle graphicStyle(int index) const { return graphics[index].pen.style(); } + Qt::PenStyle gridStyle() const { return grid_pen.style(); } + Qt::PenStyle selectionStyle() const { return selpen.style(); } + double graphicLineWidth() const { return graphics[curGraphic].pen.widthF(); } + double graphicLineWidth(int index) const { return graphics[index].pen.widthF(); } + double graphicPointWidth() const { return graphics[curGraphic].pointWidth; } + double graphicPointWidth(int index) const { return graphics[index].pointWidth; } + QColor graphicFillColor() const { return graphics[curGraphic].fill_color; } + QColor graphicFillColor(int index) const { return graphics[index].fill_color; } + bool graphicVisible() const { return graphics[curGraphic].visible; } + bool graphicVisible(int index) const { return graphics[index].visible; } + bool graphicLinesEnabled() const { return graphics[curGraphic].lines; } + bool graphicLinesEnabled(int index) const { return graphics[index].lines; } + bool graphicPointsEnabled() const { return graphics[curGraphic].points; } + bool graphicPointsEnabled(int index) const { return graphics[index].points; } + bool graphicFillEnabled() const { return graphics[curGraphic].fill; } + bool graphicFillEnabled(int index) const { return graphics[index].fill; } + QPen graphicPen() const { return graphics[curGraphic].pen; } + QPen graphicPen(int index) const { return graphics[index].pen; } + QPen gridPen() const { return grid_pen; } + QPen selectionPen() const { return selpen; } + QBrush selectionBrush() const { return selbrush; } + bool navigationEnabled() const { return navigation; } + bool openGL() const { return isOGL; } + bool antialiasing() const { return aalias; } + bool autoUpdate() const { return aupdate; } + bool gridEnabled() const { return grid; } bool borderInputsVisible() const; bool statusVisible() const; bool legendVisible() const; - bool paused() const {return pause_;} - bool onlyExpandY() const {return only_expand_y;} - bool onlyExpandX() const {return only_expand_x;} - bool gesturesNavigation() const {return gestures;} - bool LODOptimization() const {return m_LODOptimization;} - bool isAutofitted() const {return isFit;} - int currentGraphic() const {return curGraphic;} - int currentTraceGraphic() const {return curTrace;} - int graphicsCount() const {return graphics.size();} - Graphic::Buttons buttons() const {return buttons_;} - Graphic::Alignment buttonsPosition() const {return align;} - double historySize() const {return history;} - double maxVisibleTime() const {return visible_time;} - double autoXIncrement() const {return inc_x;} - QRectF visualRect() const {return selrect;} - QRectF defaultRect() const {return def_rect;} - QRectF limit() const {return limit_;} - QRect margins() const {return margins_;} - int minimumRepaintInterval() const {return min_repaint_int;} - double gridNumbersMultiplierX() const {return grid_numbers_x;} - double gridNumbersMultiplierY() const {return grid_numbers_y;} - Graduation graduationX() const {return grad_x;} - Graduation graduationY() const {return grad_y;} - double graduationStepX() const {return gridx;} - double graduationStepY() const {return gridy;} - AxisType axisType() const {return axis_type_x;} - FloatingAxisType floatingAxisType() const {return floating_axis_type;} - QVector graphicData() const {return graphics[curGraphic].polyline;} - QVector graphicData(int index) const {return graphics[index].polyline;} + bool paused() const { return pause_; } + bool onlyExpandY() const { return only_expand_y; } + bool onlyExpandX() const { return only_expand_x; } + bool gesturesNavigation() const { return gestures; } + bool LODOptimization() const { return m_LODOptimization; } + bool isAutofitted() const { return isFit; } + int currentGraphic() const { return curGraphic; } + int currentTraceGraphic() const { return curTrace; } + int graphicsCount() const { return graphics.size(); } + Graphic::Buttons buttons() const { return buttons_; } + Graphic::Alignment buttonsPosition() const { return align; } + double historySize() const { return history; } + double maxVisibleTime() const { return visible_time; } + double autoXIncrement() const { return inc_x; } + QRectF visualRect() const { return selrect; } + QRectF defaultRect() const { return def_rect; } + QRectF limit() const { return limit_; } + QRect margins() const { return margins_; } + int minimumRepaintInterval() const { return min_repaint_int; } + double gridNumbersMultiplierX() const { return grid_numbers_x; } + double gridNumbersMultiplierY() const { return grid_numbers_y; } + Graduation graduationX() const { return grad_x; } + Graduation graduationY() const { return grad_y; } + double graduationStepX() const { return gridx; } + double graduationStepY() const { return gridy; } + AxisType axisType() const { return axis_type_x; } + FloatingAxisType floatingAxisType() const { return floating_axis_type; } + QVector graphicData() const { return graphics[curGraphic].polyline; } + QVector graphicData(int index) const { return graphics[index].polyline; } GraphicsData graphicsData() const; QByteArray graphicsDataRaw() const; - QWidget * viewport() const {return canvas;} + QWidget * viewport() const { return canvas; } QByteArray save(); void load(QByteArray ba); - GraphicType graphic(int arg) {if (arg < 0 || arg >= graphics.size()) return GraphicType(); return graphics[arg];} - const QVector & allGraphics() const {return graphics;} - void setAllGraphics(const QVector & g, bool update = true) {graphics = g; if (update) updateLegend();} + GraphicType graphic(int arg) { + if (arg < 0 || arg >= graphics.size()) return GraphicType(); + return graphics[arg]; + } + const QVector & allGraphics() const { return graphics; } + void setAllGraphics(const QVector & g, bool update = true) { + graphics = g; + if (update) updateLegend(); + } double canvas2realX(double px) const; double canvas2realY(double py) const; double real2canvasX(double px) const; double real2canvasY(double py) const; - QPointF canvas2real(QPointF canvas_point) const {return QPointF(canvas2realX(canvas_point.x()), canvas2realY(canvas_point.y()));} - QPointF real2canvas(QPointF real_point) const {return QPointF(real2canvasX(real_point.x()), real2canvasY(real_point.y()));} + QPointF canvas2real(QPointF canvas_point) const { return QPointF(canvas2realX(canvas_point.x()), canvas2realY(canvas_point.y())); } + QPointF real2canvas(QPointF real_point) const { return QPointF(real2canvasX(real_point.x()), real2canvasY(real_point.y())); } QPolygonF real2canvas(const QPolygonF & real_polygon) const; QPolygonF canvas2real(const QPolygonF & canvas_polygon) const; - double getScaleX() const {return real2canvasX(1.) - real2canvasX(0.);} - double getScaleY() const {return real2canvasY(1.) - real2canvasY(0.);} - QPointF getScale() const {return QPointF(getScaleX(), getScaleY());} + double getScaleX() const { return real2canvasX(1.) - real2canvasX(0.); } + double getScaleY() const { return real2canvasY(1.) - real2canvasY(0.); } + QPointF getScale() const { return QPointF(getScaleX(), getScaleY()); } public slots: void setCaption(const QString & str); - void setLabelX(const QString & str) {label_x = str; hasLblX = (str.length() > 0); if (aupdate) update();} - void setLabelY(const QString & str) {label_y = str; hasLblY = (str.length() > 0); if (aupdate) update();} - void setGraphicName(const QString & str, int index) {graphics[index].name = str; updateLegend(); if (aupdate) update();} - void setGraphicName(const QString & str) {graphics[curGraphic].name = str; updateLegend(); if (aupdate) update();} - void setBackgroundColor(const QColor & color) {back_color = color; if (aupdate) update(); updateLegend();} - void setTextColor(const QColor & color) {text_color = color; if (aupdate) update();} - void setGraphicColor(const QColor & color, int index) {graphics[index].pen.setColor(color); updateLegend(); if (aupdate) update();} - void setGraphicColor(const QColor & color) {setGraphicColor(color, curGraphic);} - void setGridColor(const QColor & color) {grid_pen.setColor(color); if (aupdate) update();} - void setSelectionColor(const QColor & color) {selpen.setColor(color);} - void setGraphicStyle(const Qt::PenStyle & style, int index) {graphics[index].pen.setStyle(style); updateLegend(); if (aupdate) update();} - void setGraphicStyle(const Qt::PenStyle & style) {setGraphicStyle(style, curGraphic);} - void setGridStyle(const Qt::PenStyle & style) {grid_pen.setStyle(style); if (aupdate) update();} - void setSelectionStyle(const Qt::PenStyle & style) {selpen.setStyle(style);} + void setLabelX(const QString & str) { + label_x = str; + hasLblX = (str.length() > 0); + if (aupdate) update(); + } + void setLabelY(const QString & str) { + label_y = str; + hasLblY = (str.length() > 0); + if (aupdate) update(); + } + void setGraphicName(const QString & str, int index) { + graphics[index].name = str; + updateLegend(); + if (aupdate) update(); + } + void setGraphicName(const QString & str) { + graphics[curGraphic].name = str; + updateLegend(); + if (aupdate) update(); + } + void setBackgroundColor(const QColor & color) { + back_color = color; + if (aupdate) update(); + updateLegend(); + } + void setTextColor(const QColor & color) { + text_color = color; + if (aupdate) update(); + } + void setGraphicColor(const QColor & color, int index) { + graphics[index].pen.setColor(color); + updateLegend(); + if (aupdate) update(); + } + void setGraphicColor(const QColor & color) { setGraphicColor(color, curGraphic); } + void setGridColor(const QColor & color) { + grid_pen.setColor(color); + if (aupdate) update(); + } + void setSelectionColor(const QColor & color) { selpen.setColor(color); } + void setGraphicStyle(const Qt::PenStyle & style, int index) { + graphics[index].pen.setStyle(style); + updateLegend(); + if (aupdate) update(); + } + void setGraphicStyle(const Qt::PenStyle & style) { setGraphicStyle(style, curGraphic); } + void setGridStyle(const Qt::PenStyle & style) { + grid_pen.setStyle(style); + if (aupdate) update(); + } + void setSelectionStyle(const Qt::PenStyle & style) { selpen.setStyle(style); } void setGraphicVisible(bool visible, int index); - void setGraphicVisible(bool visible) {setGraphicVisible(visible, curGraphic);} - void setGraphicLineWidth(double w, int index) {if (qRound(w) == w) graphics[index].pen.setWidth(qRound(w)); else graphics[index].pen.setWidthF(w); updateLegend(); if (aupdate) update();} - void setGraphicLineWidth(double w) {setGraphicLineWidth(w, curGraphic);} - void setGraphicPointWidth(double w, int index) {graphics[index].pointWidth = w; updateLegend(); if (aupdate) update();} - void setGraphicPointWidth(double w) {setGraphicPointWidth(w, curGraphic);} - void setGraphicFillColor(const QColor & w, int index) {graphics[index].fill_color = w; updateLegend(); if (aupdate) update();} - void setGraphicFillColor(const QColor & w) {setGraphicFillColor(w, curGraphic);} - void setGraphicLinesEnabled(bool w, int index) {graphics[index].lines = w; updateLegend(); if (aupdate) update();} - void setGraphicLinesEnabled(bool w) {setGraphicLinesEnabled(w, curGraphic);} - void setGraphicPointsEnabled(bool w, int index) {graphics[index].points = w; updateLegend(); if (aupdate) update();} - void setGraphicPointsEnabled(bool w) {setGraphicPointsEnabled(w, curGraphic);} - void setGraphicFillEnabled(bool w, int index) {graphics[index].fill = w; updateLegend(); if (aupdate) update();} - void setGraphicFillEnabled(bool w) {setGraphicFillEnabled(w, curGraphic);} - void setGraphicPen(const QPen & pen, int index) {graphics[index].pen = pen; updateLegend(); if (aupdate) update();} - void setGraphicPen(const QPen & pen) {setGraphicPen(pen, curGraphic);} - void setGridPen(const QPen & pen) {grid_pen = pen; if (aupdate) update();} - void setSelectionPen(const QPen & pen) {selpen = pen;} - void setSelectionBrush(const QBrush & brush) {selbrush = brush;} - void setNavigationEnabled(bool on) {navigation = on;} - void setLODOptimization(bool yes) {m_LODOptimization = yes;} + void setGraphicVisible(bool visible) { setGraphicVisible(visible, curGraphic); } + void setGraphicLineWidth(double w, int index) { + if (qRound(w) == w) + graphics[index].pen.setWidth(qRound(w)); + else + graphics[index].pen.setWidthF(w); + updateLegend(); + if (aupdate) update(); + } + void setGraphicLineWidth(double w) { setGraphicLineWidth(w, curGraphic); } + void setGraphicPointWidth(double w, int index) { + graphics[index].pointWidth = w; + updateLegend(); + if (aupdate) update(); + } + void setGraphicPointWidth(double w) { setGraphicPointWidth(w, curGraphic); } + void setGraphicFillColor(const QColor & w, int index) { + graphics[index].fill_color = w; + updateLegend(); + if (aupdate) update(); + } + void setGraphicFillColor(const QColor & w) { setGraphicFillColor(w, curGraphic); } + void setGraphicLinesEnabled(bool w, int index) { + graphics[index].lines = w; + updateLegend(); + if (aupdate) update(); + } + void setGraphicLinesEnabled(bool w) { setGraphicLinesEnabled(w, curGraphic); } + void setGraphicPointsEnabled(bool w, int index) { + graphics[index].points = w; + updateLegend(); + if (aupdate) update(); + } + void setGraphicPointsEnabled(bool w) { setGraphicPointsEnabled(w, curGraphic); } + void setGraphicFillEnabled(bool w, int index) { + graphics[index].fill = w; + updateLegend(); + if (aupdate) update(); + } + void setGraphicFillEnabled(bool w) { setGraphicFillEnabled(w, curGraphic); } + void setGraphicPen(const QPen & pen, int index) { + graphics[index].pen = pen; + updateLegend(); + if (aupdate) update(); + } + void setGraphicPen(const QPen & pen) { setGraphicPen(pen, curGraphic); } + void setGridPen(const QPen & pen) { + grid_pen = pen; + if (aupdate) update(); + } + void setSelectionPen(const QPen & pen) { selpen = pen; } + void setSelectionBrush(const QBrush & brush) { selbrush = brush; } + void setNavigationEnabled(bool on) { navigation = on; } + void setLODOptimization(bool yes) { m_LODOptimization = yes; } void setOpenGL(bool on); void setAntialiasing(bool enabled); - void setAutoUpdate(bool enabled) {aupdate = enabled;} + void setAutoUpdate(bool enabled) { aupdate = enabled; } void setGridEnabled(bool enabled); void setBorderInputsVisible(bool visible); void setStatusVisible(bool visible); @@ -294,66 +392,149 @@ public slots: void setButtonsPosition(Graphic::Alignment a); void setHistorySize(double val); void setMaxVisibleTime(double val); - void setAutoXIncrement(double val) {inc_x = val;} - void setLimit(const QRectF & val) {limit_ = val;} - void setMargins(const QRect & val) {margins_ = val; update();} - void setMargins(int left_, int right_, int top_, int bottom_) {setMargins(QRect(left_, bottom_, right_, top_));} - void setLeftMargin(int value) {margins_.moveLeft(value); setMargins(margins_);} - void setRightMargin(int value) {margins_.setWidth(value); setMargins(margins_);} - void setTopMargin(int value) {margins_.setHeight(value); setMargins(margins_);} - void setBottomMargin(int value) {margins_.moveTop(value); setMargins(margins_);} - void setMinimumRepaintInterval(const int & val) {min_repaint_int = val;} + void setAutoXIncrement(double val) { inc_x = val; } + void setLimit(const QRectF & val) { limit_ = val; } + void setMargins(const QRect & val) { + margins_ = val; + update(); + } + void setMargins(int left_, int right_, int top_, int bottom_) { setMargins(QRect(left_, bottom_, right_, top_)); } + void setLeftMargin(int value) { + margins_.moveLeft(value); + setMargins(margins_); + } + void setRightMargin(int value) { + margins_.setWidth(value); + setMargins(margins_); + } + void setTopMargin(int value) { + margins_.setHeight(value); + setMargins(margins_); + } + void setBottomMargin(int value) { + margins_.moveTop(value); + setMargins(margins_); + } + void setMinimumRepaintInterval(const int & val) { min_repaint_int = val; } void setOnlyExpandY(bool yes); void setOnlyExpandX(bool yes); void setGesturesNavigation(bool yes); void setGraphicsData(const GraphicsData & gd); void setGraphicsDataRaw(const QByteArray & ba); - void setGridNumbersMultiplierX(double value) {grid_numbers_x = value; updateGraphics();} - void setGridNumbersMultiplierY(double value) {grid_numbers_y = value; updateGraphics();} - void setGraduationX(Graduation value) {grad_x = value; if (aupdate) update();;} - void setGraduationY(Graduation value) {grad_y = value; if (aupdate) update();;} - void setGraduationStepX(double sx) {gridx = sx; if (aupdate) update();} - void setGraduationStepY(double sy) {gridy = sy; if (aupdate) update();} - void setGraduationSteps(double sx, double sy) {gridx = sx; gridy = sy; if (aupdate) update();} - void setAxisType(AxisType t) {axis_type_x = t; if (aupdate) update();} - void setFloatingAxisType(FloatingAxisType t) {floating_axis_type = t; setGuidesCursor(); if (aupdate) update();} + void setGridNumbersMultiplierX(double value) { + grid_numbers_x = value; + updateGraphics(); + } + void setGridNumbersMultiplierY(double value) { + grid_numbers_y = value; + updateGraphics(); + } + void setGraduationX(Graduation value) { + grad_x = value; + if (aupdate) update(); + ; + } + void setGraduationY(Graduation value) { + grad_y = value; + if (aupdate) update(); + ; + } + void setGraduationStepX(double sx) { + gridx = sx; + if (aupdate) update(); + } + void setGraduationStepY(double sy) { + gridy = sy; + if (aupdate) update(); + } + void setGraduationSteps(double sx, double sy) { + gridx = sx; + gridy = sy; + if (aupdate) update(); + } + void setAxisType(AxisType t) { + axis_type_x = t; + if (aupdate) update(); + } + void setFloatingAxisType(FloatingAxisType t) { + floating_axis_type = t; + setGuidesCursor(); + if (aupdate) update(); + } void setFloatingAxisEnabled(bool on); void addPoint(const QPointF & p, int graphic, bool update_ = true); - void addPoint(const QPointF & p, bool update = true) {addPoint(p, curGraphic, update);} - void addPoint(double x, double y, int graphic, bool update = true) {addPoint(QPointF(x, y), graphic, update);} - void addPoint(double x, double y, bool update = true) {addPoint(QPointF(x, y), update);} - void addPoint(double y, int graphic, bool update = true) {if (graphics[graphic].polyline.isEmpty()) addPoint(QPointF(0.0, y), graphic, update); else addPoint(QPointF(graphics[graphic].max_x + inc_x, y), graphic, update);} - void addPoint(double y, bool update = true) {if (graphics[curGraphic].polyline.isEmpty()) addPoint(QPointF(0.0, y), update); else addPoint(QPointF(graphics[curGraphic].max_x + inc_x, y), update);} + void addPoint(const QPointF & p, bool update = true) { addPoint(p, curGraphic, update); } + void addPoint(double x, double y, int graphic, bool update = true) { addPoint(QPointF(x, y), graphic, update); } + void addPoint(double x, double y, bool update = true) { addPoint(QPointF(x, y), update); } + void addPoint(double y, int graphic, bool update = true) { + if (graphics[graphic].polyline.isEmpty()) + addPoint(QPointF(0.0, y), graphic, update); + else + addPoint(QPointF(graphics[graphic].max_x + inc_x, y), graphic, update); + } + void addPoint(double y, bool update = true) { + if (graphics[curGraphic].polyline.isEmpty()) + addPoint(QPointF(0.0, y), update); + else + addPoint(QPointF(graphics[curGraphic].max_x + inc_x, y), update); + } void addPoints(const QPolygonF & pts, int graphic, bool update_ = true); - void addPoints(const QPolygonF & pts, bool update = true) {addPoints(pts, curGraphic, update);} + void addPoints(const QPolygonF & pts, bool update = true) { addPoints(pts, curGraphic, update); } void addPoints(const QVector & pts, int graphic, bool update_ = true); - void addPoints(const QVector & pts, bool update = true) {addPoints(pts, curGraphic, update);} + void addPoints(const QVector & pts, bool update = true) { addPoints(pts, curGraphic, update); } void setGraphicData(const QVector & g, int graphic, bool update_ = true); - void setGraphicData(const QVector & g) {setGraphicData(g, curGraphic);} - void setGraphicProperties(const QString & name, const QColor & color = Qt::darkRed, Qt::PenStyle style = Qt::SolidLine, double width = 0., bool visible = true) {setGraphicProperties(curGraphic, name, color, style, width, visible);} - void setGraphicProperties(int graphic, const QString & name, const QColor & color = Qt::darkRed, Qt::PenStyle style = Qt::SolidLine, double width = 0., bool visible = true); - void addGraphic(const QString & name, const QColor & color = Qt::darkRed, Qt::PenStyle style = Qt::SolidLine, double width = 0., bool visible = true); - void addGraphic(const GraphicType & gd, bool update = true) {graphics << gd; if (update) updateLegend();} + void setGraphicData(const QVector & g) { setGraphicData(g, curGraphic); } + void setGraphicProperties(const QString & name, + const QColor & color = Qt::darkRed, + Qt::PenStyle style = Qt::SolidLine, + double width = 0., + bool visible = true) { + setGraphicProperties(curGraphic, name, color, style, width, visible); + } + void setGraphicProperties(int graphic, + const QString & name, + const QColor & color = Qt::darkRed, + Qt::PenStyle style = Qt::SolidLine, + double width = 0., + bool visible = true); + void addGraphic(const QString & name, + const QColor & color = Qt::darkRed, + Qt::PenStyle style = Qt::SolidLine, + double width = 0., + bool visible = true); + void addGraphic(const GraphicType & gd, bool update = true) { + graphics << gd; + if (update) updateLegend(); + } void setVisualRect(const QRectF & rect); void setDefaultRect(const QRectF & rect); - void autofit() {on_graphic_buttonAutofit_clicked();} + void autofit() { on_graphic_buttonAutofit_clicked(); } void saveImage(QString filename); void exportGraphics(QString filename, QChar decimal_point); void clear(); void update(bool force); - void update() {update(false);} - void updateGraphics() {findGraphicsRect(); update();} - void setCurrentGraphic(int arg) {if (arg < 0 || arg >= graphics.size()) return; curGraphic = arg;} - void setTraceGraphic(int arg) {if (arg < 0 || arg >= graphics.size()) return; curTrace = arg;} + void update() { update(false); } + void updateGraphics() { + findGraphicsRect(); + update(); + } + void setCurrentGraphic(int arg) { + if (arg < 0 || arg >= graphics.size()) return; + curGraphic = arg; + } + void setTraceGraphic(int arg) { + if (arg < 0 || arg >= graphics.size()) return; + curTrace = arg; + } void setGraphicsCount(int arg, bool update = true); void removeGraphic(int arg, bool update = true); void setCustomGridMarkFuncs(std::function fx, std::function fy); void zoom(float factor); - void zoomIn() {zoom(1. / 1.2);} - void zoomOut() {zoom(1.2);} + void zoomIn() { zoom(1. / 1.2); } + void zoomOut() { zoom(1.2); } void fullscreen(); @@ -365,9 +546,9 @@ protected: }; void changeEvent(QEvent * e) override; - void resizeEvent(QResizeEvent * ) override; - void showEvent(QShowEvent * ) override; - QSize sizeHint() const override {return QSize(400, 300);} + void resizeEvent(QResizeEvent *) override; + void showEvent(QShowEvent *) override; + QSize sizeHint() const override { return QSize(400, 300); } void timerEvent(QTimerEvent * e) override; bool eventFilter(QObject * o, QEvent * e) override; @@ -379,7 +560,11 @@ protected: void findGraphicsRect(double start_x = 0., double end_x = 0., double start_y = 0., double end_y = 0.); void tick(int index, bool slide = true, bool update = true); void calcLOD(int index); - void repaintCanvas(bool force = false) {if (tm.elapsed() < min_repaint_int && !force) return; tm.restart(); canvas->update();} + void repaintCanvas(bool force = false) { + if (tm.elapsed() < min_repaint_int && !force) return; + tm.restart(); + canvas->update(); + } void drawGraphics(); void drawGrid(); void drawGuides(); @@ -390,7 +575,7 @@ protected: void setCanvasCursor(QCursor cursor); void setGuidesCursor(); void swapToBuffer(); - void swapToNormal() {bufferActive = false;} + void swapToNormal() { bufferActive = false; } void setRectToLines(); void checkLines(); double splitRange(double range, int count = 1); @@ -398,7 +583,7 @@ protected: double roundTo(double value, double round_to); void roundDateTime(QDateTime & dt, int * c); void addDateTime(QDateTime & dt, int * c, qint64 mul = 1); - QPointF absPoint(QPointF point) {return QPointF(qAbs(point.x()), qAbs(point.y()));} + QPointF absPoint(QPointF point) { return QPointF(qAbs(point.x()), qAbs(point.y())); } QString pointCoords(QPointF point, bool x = true, bool y = true); QPair gridMark(double v) const; void fillDateFormats(); @@ -438,56 +623,76 @@ protected: double eminx, eminy, emaxx, emaxy, pause_phase, gesture_angle; int lastw, lasth, min_repaint_int, thick; int timer_pause, timer_record; - bool aalias, aupdate, grid, guides, isFit, isOGL, isHover, bufferActive, cancel, pause_, gestures, m_LODOptimization, m_fakeGL, need_createGL; - bool hasLblX, hasLblY, navigation, only_expand_y, only_expand_x, is_lines_update, leg_update, visible_update, fullscr, need_mouse_pan, was_trace; + bool aalias, aupdate, grid, guides, isFit, isOGL, isHover, bufferActive, cancel, pause_, gestures, m_LODOptimization, m_fakeGL, + need_createGL; + bool hasLblX, hasLblY, navigation, only_expand_y, only_expand_x, is_lines_update, leg_update, visible_update, fullscr, need_mouse_pan, + was_trace; std::function func_gridMarkX, func_gridMarkY; QVector date_formats; QList record_imgs; protected slots: void canvasPaintEvent(); - void canvasMouseMoveEvent(QMouseEvent * ); - void canvasMousePressEvent(QMouseEvent * ); - void canvasMouseReleaseEvent(QMouseEvent * ); - void canvasMouseDoubleClickEvent(QMouseEvent * ); - void canvasWheelEvent(QWheelEvent * ); - void canvasLeaveEvent(QEvent * ); - void canvasKeyPressEvent(QKeyEvent * ); + void canvasMouseMoveEvent(QMouseEvent *); + void canvasMousePressEvent(QMouseEvent *); + void canvasMouseReleaseEvent(QMouseEvent *); + void canvasMouseDoubleClickEvent(QMouseEvent *); + void canvasWheelEvent(QWheelEvent *); + void canvasLeaveEvent(QEvent *); + void canvasKeyPressEvent(QKeyEvent *); void graphicVisibleChange(bool checked); void graphicAllVisibleChange(bool checked); - void lineXMinChanged(double value) {selrect.setLeft(value); checkLines();} - void lineXMaxChanged(double value) {selrect.setRight(value); checkLines();} - void lineYMinChanged(double value) {selrect.setBottom(value); checkLines();} - void lineYMaxChanged(double value) {selrect.setTop(value); checkLines();} - void on_graphic_buttonClose_clicked() {emit closeRequest(this);} - void on_graphic_buttonClear_clicked() {clear(); emit cleared();} + void lineXMinChanged(double value) { + selrect.setLeft(value); + checkLines(); + } + void lineXMaxChanged(double value) { + selrect.setRight(value); + checkLines(); + } + void lineYMinChanged(double value) { + selrect.setBottom(value); + checkLines(); + } + void lineYMaxChanged(double value) { + selrect.setTop(value); + checkLines(); + } + void on_graphic_buttonClose_clicked() { emit closeRequest(this); } + void on_graphic_buttonClear_clicked() { + clear(); + emit cleared(); + } void on_graphic_buttonAutofit_clicked(); void on_graphic_buttonConfigure_clicked(); - void on_graphic_buttonFullscreen_clicked() {fullscreen();} + void on_graphic_buttonFullscreen_clicked() { fullscreen(); } void on_graphic_buttonSave_clicked(); void on_graphic_buttonExport_clicked(); void on_graphic_buttonRecord_clicked(bool checked); - void on_graphic_checkGrid_toggled(bool checked) {grid = checked; update();} + void on_graphic_checkGrid_toggled(bool checked) { + grid = checked; + update(); + } void on_graphic_checkGuides_toggled(bool checked); void on_graphic_actionExpandX_triggered(bool checked); void on_graphic_actionExpandY_triggered(bool checked); - void on_graphic_checkBorderInputs_toggled(bool checked) {setBorderInputsVisible(checked);} - void on_graphic_checkLegend_toggled(bool checked) {setLegendVisible(checked);} - void on_graphic_checkPause_toggled(bool checked) {setPaused(checked);} + void on_graphic_checkBorderInputs_toggled(bool checked) { setBorderInputsVisible(checked); } + void on_graphic_checkLegend_toggled(bool checked) { setLegendVisible(checked); } + void on_graphic_checkPause_toggled(bool checked) { setPaused(checked); } void actionGuidesTriggered(QAction * a); void enterFullscreen(); void leaveFullscreen(); void showMenu(); signals: - void beforeGraphicPaintEvent(QPainter * ); - void graphicPaintEvent(QPainter * ); + void beforeGraphicPaintEvent(QPainter *); + void graphicPaintEvent(QPainter *); void graphicMouseMoveEvent(QPointF point, int buttons); void graphicMousePressEvent(QPointF point, int buttons); void graphicMouseReleaseEvent(QPointF point, int buttons); void graphicWheelEvent(QPointF point, int delta); void graphicTraceEvent(int graphic, QPointF point); - void closeRequest(QWidget * ); + void closeRequest(QWidget *); void cleared(); void visualRectChanged(); void graphicSettingsChanged(); @@ -499,14 +704,20 @@ Q_DECLARE_METATYPE(Graphic::GraphicsData) Q_DECLARE_OPERATORS_FOR_FLAGS(Graphic::Buttons) -inline QDataStream & operator <<(QDataStream & s, const Graphic::Graduation & v) {s << (int)v; return s;} -inline QDataStream & operator >>(QDataStream & s, Graphic::Graduation & v) {s >> *((int*)(&v)); return s;} +inline QDataStream & operator<<(QDataStream & s, const Graphic::Graduation & v) { + s << (int)v; + return s; +} +inline QDataStream & operator>>(QDataStream & s, Graphic::Graduation & v) { + s >> *((int *)(&v)); + return s; +} class QAD_GRAPHIC_EXPORT __GraphicRegistrator__ { public: __GraphicRegistrator__() { - qRegisterMetaType >("QVector"); + qRegisterMetaType>("QVector"); qRegisterMetaType("Graphic::GraphicsData"); #if QT_VERSION_MAJOR <= 5 qRegisterMetaTypeStreamOperators("Graphic::GraphicsData"); diff --git a/libs/graphic/graphic_conf.cpp b/libs/graphic/graphic_conf.cpp index e0c94fb..c875ec2 100644 --- a/libs/graphic/graphic_conf.cpp +++ b/libs/graphic/graphic_conf.cpp @@ -1,4 +1,5 @@ #include "graphic_conf.h" + #include "qad_types.h" #include "ui_graphic_conf.h" @@ -7,11 +8,10 @@ GraphicConf::GraphicConf(QVector & graphics_, QWidget * parent): QD ui = new Ui::GraphicConf(); ui->setupUi(this); QStringList styles; - int fh = qMax(fontMetrics().size(0, "0").height(), 22); + int fh = qMax(fontMetrics().size(0, "0").height(), 22); int thick = lineThickness(this); QSize sz(fh * 2.5, fh); - styles << tr("NoPen") << tr("Solid") << tr("Dash") - << tr("Dot") << tr("Dash-Dot") << tr("Dash-Dot-Dot"); + styles << tr("NoPen") << tr("Solid") << tr("Dash") << tr("Dot") << tr("Dash-Dot") << tr("Dash-Dot-Dot"); ui->comboStyleGrid->setIconSize(sz); ui->comboStyleGraphic->setIconSize(sz); ui->cbGraphicNames->setIconSize(sz); @@ -72,8 +72,10 @@ void GraphicConf::on_comboStyleGraphic_currentIndexChanged(int index) { void GraphicConf::on_spinLineWidthGraphic_valueChanged(double value) { if (graphicItems.isEmpty()) return; - if (qRound(value) == value) graphics[ui->cbGraphicNames->currentIndex()].pen.setWidth(qRound(value)); - else graphics[ui->cbGraphicNames->currentIndex()].pen.setWidthF(value); + if (qRound(value) == value) + graphics[ui->cbGraphicNames->currentIndex()].pen.setWidth(qRound(value)); + else + graphics[ui->cbGraphicNames->currentIndex()].pen.setWidthF(value); } diff --git a/libs/graphic/graphic_conf.h b/libs/graphic/graphic_conf.h index 1146eb3..a6a6624 100644 --- a/libs/graphic/graphic_conf.h +++ b/libs/graphic/graphic_conf.h @@ -1,54 +1,61 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef GRAPHIC_CONF_H #define GRAPHIC_CONF_H -#include -#include -#include -#include #include "qad_graphic_export.h" +#include +#include +#include +#include + namespace Ui { - class GraphicConf; +class GraphicConf; } struct QAD_GRAPHIC_EXPORT GraphicType { - GraphicType(QString name_ = "y(x)", QColor color = Qt::red, Qt::PenStyle style = Qt::SolidLine, double width = 0., bool visible_ = true) { + GraphicType(QString name_ = "y(x)", + QColor color = Qt::red, + Qt::PenStyle style = Qt::SolidLine, + double width = 0., + bool visible_ = true) { pen.setColor(color); pen.setStyle(style); - lines = true; - points = false; - fill = false; + lines = true; + points = false; + fill = false; fill_color = Qt::yellow; - if (qRound(width) == width) pen.setWidth(qRound(width)); - else pen.setWidthF(width); + if (qRound(width) == width) + pen.setWidth(qRound(width)); + else + pen.setWidthF(width); pen.setWidth(1); pen.setCosmetic(true); - max_x = 0.; - name = name_; - visible = visible_; + max_x = 0.; + name = name_; + visible = visible_; pointWidth = 2.; - pb = new QCheckBox(name); + pb = new QCheckBox(name); } //~GraphicType() {delete pb;} QString name; @@ -72,14 +79,20 @@ struct QAD_GRAPHIC_EXPORT GraphicType { }; -inline QDataStream & operator <<(QDataStream & s, const GraphicType & v) {s << v.name << v.pen << v.fill_color << v.lines << v.points << v.fill << v.pointWidth << v.visible; return s;} -inline QDataStream & operator >>(QDataStream & s, GraphicType & v) {s >> v.name >> v.pen >> v.fill_color >> v.lines >> v.points >> v.fill >> v.pointWidth >> v.visible; return s;} +inline QDataStream & operator<<(QDataStream & s, const GraphicType & v) { + s << v.name << v.pen << v.fill_color << v.lines << v.points << v.fill << v.pointWidth << v.visible; + return s; +} +inline QDataStream & operator>>(QDataStream & s, GraphicType & v) { + s >> v.name >> v.pen >> v.fill_color >> v.lines >> v.points >> v.fill >> v.pointWidth >> v.visible; + return s; +} -class QAD_GRAPHIC_EXPORT GraphicConf: public QDialog -{ +class QAD_GRAPHIC_EXPORT GraphicConf: public QDialog { Q_OBJECT friend class Graphic; + public: explicit GraphicConf(QVector & graphics_, QWidget * parent = 0); diff --git a/libs/graphic/plugin/graphicplugin.cpp b/libs/graphic/plugin/graphicplugin.cpp index 4a0afc2..707f984 100644 --- a/libs/graphic/plugin/graphicplugin.cpp +++ b/libs/graphic/plugin/graphicplugin.cpp @@ -1,5 +1,7 @@ -#include "graphic.h" #include "graphicplugin.h" + +#include "graphic.h" + #include @@ -10,8 +12,7 @@ GraphicPlugin::GraphicPlugin(QObject * parent): QObject(parent) { void GraphicPlugin::initialize(QDesignerFormEditorInterface * /* core */) { m_designer = true; - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -26,8 +27,7 @@ bool GraphicPlugin::isInitialized() const { QWidget * GraphicPlugin::createWidget(QWidget * parent) { auto ret = new Graphic(parent); - if (m_designer) - ret->m_fakeGL = true; + if (m_designer) ret->m_fakeGL = true; return ret; } @@ -48,7 +48,7 @@ QIcon GraphicPlugin::icon() const { QString GraphicPlugin::toolTip() const { - return QLatin1String("");//QLatin1String("Widget for display any math graphics with grid and navigation"); + return QLatin1String(""); // QLatin1String("Widget for display any math graphics with grid and navigation"); } @@ -70,4 +70,3 @@ QString GraphicPlugin::domXml() const { QString GraphicPlugin::includeFile() const { return QLatin1String("graphic.h"); } - diff --git a/libs/graphic/plugin/graphicplugin.h b/libs/graphic/plugin/graphicplugin.h index 58af1a4..3c813ab 100644 --- a/libs/graphic/plugin/graphicplugin.h +++ b/libs/graphic/plugin/graphicplugin.h @@ -8,8 +8,9 @@ # include #endif -class GraphicPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class GraphicPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized, m_designer; - }; #endif diff --git a/libs/graphic/plugin/qad_graphic.cpp b/libs/graphic/plugin/qad_graphic.cpp index 4dd23cd..344842c 100644 --- a/libs/graphic/plugin/qad_graphic.cpp +++ b/libs/graphic/plugin/qad_graphic.cpp @@ -1,13 +1,13 @@ #include "qad_graphic.h" + #include "graphicplugin.h" -QADGraphic::QADGraphic(QObject * parent): QObject(parent) -{ +QADGraphic::QADGraphic(QObject * parent): QObject(parent) { m_widgets.append(new GraphicPlugin(this)); } -QList QADGraphic::customWidgets() const { +QList QADGraphic::customWidgets() const { return m_widgets; } diff --git a/libs/graphic/plugin/qad_graphic.h b/libs/graphic/plugin/qad_graphic.h index 07098fa..23c2000 100644 --- a/libs/graphic/plugin/qad_graphic.h +++ b/libs/graphic/plugin/qad_graphic.h @@ -1,23 +1,24 @@ #ifndef QAD_GRAPHIC_H #define QAD_GRAPHIC_H -#include #include +#include -class QADGraphic: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADGraphic + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.graphic") #endif + public: explicit QADGraphic(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_GRAPHIC_H diff --git a/libs/graphic/uglwidget.h b/libs/graphic/uglwidget.h index 9a20903..b3dae85 100644 --- a/libs/graphic/uglwidget.h +++ b/libs/graphic/uglwidget.h @@ -1,8 +1,8 @@ #ifndef UGLWIDGET_H #define UGLWIDGET_H -#include #include +#include #if QT_VERSION >= 0x050400 # include typedef QOpenGLWidget __GLWidget__; @@ -10,32 +10,37 @@ typedef QOpenGLWidget __GLWidget__; # include typedef QGLWidget __GLWidget__; # ifndef GL_MULTISAMPLE -# define GL_MULTISAMPLE 0x809D +# define GL_MULTISAMPLE 0x809D # endif #endif #include "qad_graphic_export.h" -class QAD_GRAPHIC_EXPORT UGLWidget: public __GLWidget__ -{ +class QAD_GRAPHIC_EXPORT UGLWidget: public __GLWidget__ { Q_OBJECT + public: #if QT_VERSION >= 0x050400 - UGLWidget(QWidget * parent = 0): __GLWidget__(parent) {QSurfaceFormat sf = format(); sf.setSamples(8); setFormat(sf);} + UGLWidget(QWidget * parent = 0): __GLWidget__(parent) { + QSurfaceFormat sf = format(); + sf.setSamples(8); + setFormat(sf); + } #else - UGLWidget(QWidget * parent = 0): __GLWidget__(QGLFormat(QGL::DoubleBuffer | QGL::AlphaChannel | QGL::DirectRendering | QGL::SampleBuffers), parent) {} + UGLWidget(QWidget * parent = 0) + : __GLWidget__(QGLFormat(QGL::DoubleBuffer | QGL::AlphaChannel | QGL::DirectRendering | QGL::SampleBuffers), parent) {} #endif - //UGLWidget(QGLContext * context, QWidget * parent = 0): __GLWidget__(context, parent) {} + // UGLWidget(QGLContext * context, QWidget * parent = 0): __GLWidget__(context, parent) {} #if QT_VERSION >= 0x050400 - QImage grabFrameBuffer() {return grabFramebuffer();} + QImage grabFrameBuffer() { return grabFramebuffer(); } #endif protected: #if QT_VERSION >= 0x050400 - virtual void paintGL() {emit paintSignal();} + virtual void paintGL() { emit paintSignal(); } #else - virtual void paintEvent(QPaintEvent * ) {emit paintSignal();} + virtual void paintEvent(QPaintEvent *) { emit paintSignal(); } #endif virtual void resizeEvent(QResizeEvent * e) { __GLWidget__::resizeEvent(e); @@ -63,7 +68,6 @@ signals: void wheelEvent(QWheelEvent * e); void resizeSignal(); void paintSignal(); - }; #endif diff --git a/libs/graphic/uwidget.h b/libs/graphic/uwidget.h index 6c6b44c..926647d 100644 --- a/libs/graphic/uwidget.h +++ b/libs/graphic/uwidget.h @@ -1,20 +1,21 @@ #ifndef UWIDGET_H #define UWIDGET_H -#include +#include "qad_graphic_export.h" + +#include #include #include #include -#include -#include "qad_graphic_export.h" +#include -class QAD_GRAPHIC_EXPORT UWidget: public QWidget -{ +class QAD_GRAPHIC_EXPORT UWidget: public QWidget { Q_OBJECT + public: UWidget(QWidget * parent = 0): QWidget(parent) {} - + private: virtual bool event(QEvent * e) { if (e->type() != QEvent::Paint) return QWidget::event(e); @@ -27,7 +28,7 @@ private: #endif QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); - emit paintEvent((QPaintEvent * )e); + emit paintEvent((QPaintEvent *)e); return true; } @@ -51,7 +52,6 @@ signals: void showEvent(QShowEvent * e); void wheelEvent(QWheelEvent * e); void paintEvent(QPaintEvent * e); - }; #endif diff --git a/libs/piqt/piqt.cpp b/libs/piqt/piqt.cpp index 5481a12..b4e0954 100644 --- a/libs/piqt/piqt.cpp +++ b/libs/piqt/piqt.cpp @@ -1,14 +1,16 @@ #include "piqt.h" + #include "qvariantedit.h" #ifdef PIQT_HAS_GEOPOSITION -# include # include "pigeoposition.h" + +# include #endif const QAD::Enum PI2QADEnum(const PIVariantTypes::Enum & el) { QAD::Enum ret; - piForeachC (PIVariantTypes::Enumerator & e, el.enum_list) + piForeachC(PIVariantTypes::Enumerator & e, el.enum_list) ret << QAD::Enumerator(e.value, PI2QString(e.name)); ret.selectValue(el.selectedValue()); return ret; @@ -17,7 +19,7 @@ const QAD::Enum PI2QADEnum(const PIVariantTypes::Enum & el) { const PIVariantTypes::Enum QAD2PIEnum(const QAD::Enum & el) { PIVariantTypes::Enum ret; - foreach (const QAD::Enumerator & e, el.enum_list) + foreach(const QAD::Enumerator & e, el.enum_list) ret << PIVariantTypes::Enumerator(e.value, Q2PIString(e.name)); ret.selectValue(el.selectedValue()); return ret; @@ -54,7 +56,7 @@ const QVariant PI2QVariant(const PIVariant & v) { case PIVariant::pivIODevice: return QVariant::fromValue(PI2QADIODevice(v.toIODevice())); case PIVariant::pivMathVector: return QVariant::fromValue(PI2QMathVector(v.toMathVector())); case PIVariant::pivMathMatrix: return QVariant::fromValue(PI2QMathMatrix(v.toMathMatrix())); - //case PIVariant::pivSystemTime: return QVariant(v.to()); + // case PIVariant::pivSystemTime: return QVariant(v.to()); default: return QVariant(); } return QVariant(); @@ -168,13 +170,13 @@ const PIVariant Q2PIVariant(const QVariant & v) { case QMetaType::QLine: case QMetaType::QLineF: #endif - return PIVariant(Q2PILine(v.toLineF())); + return PIVariant(Q2PILine(v.toLineF())); default: break; } if (v.canConvert()) return PIVariant(v.value()); if (v.canConvert()) return PIVariant(QAD2PIEnum(v.value())); if (v.canConvert()) return PIVariant(QAD2PIFile(v.value())); - if (v.canConvert()) return PIVariant(QAD2PIDir(v.value())); + if (v.canConvert()) return PIVariant(QAD2PIDir(v.value())); if (v.canConvert()) return PIVariant(QAD2PIIODevice(v.value())); if (v.canConvert()) return PIVariant(Q2PIMathVector(v.value())); if (v.canConvert()) return PIVariant(Q2PIMathMatrix(v.value())); @@ -185,8 +187,8 @@ const PIVariant Q2PIVariant(const QVariant & v) { const PIVariantTypes::IODevice QAD2PIIODevice(const QAD::IODevice & v) { PIVariantTypes::IODevice d; d.set(Q2PIPropertyStorage(v.props)); - d.prefix = Q2PIString(v.prefix); - d.mode = v.mode; + d.prefix = Q2PIString(v.prefix); + d.mode = v.mode; d.options = v.options; return d; } diff --git a/libs/piqt/piqt.h b/libs/piqt/piqt.h index 3d47cb1..994a62a 100644 --- a/libs/piqt/piqt.h +++ b/libs/piqt/piqt.h @@ -1,43 +1,43 @@ /* - PIQt - PIP <-> Qt convertions + PIQt - PIP <-> Qt convertions - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef PIQT_H #define PIQT_H -#include -#include -#include -#include -#include - #include "pimathmatrix.h" #include "pipropertystorage.h" -#include "qad_types.h" #include "piqt_macros.h" +#include "qad_types.h" + +#include +#include +#include +#include +#include #if QT_VERSION_MAJOR == 5 # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) -# define PIQT_HAS_GEOPOSITION +# define PIQT_HAS_GEOPOSITION # endif #endif #if QT_VERSION_MAJOR == 6 # if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) -# define PIQT_HAS_GEOPOSITION +# define PIQT_HAS_GEOPOSITION # endif #endif #ifdef PIQT_HAS_GEOPOSITION @@ -50,114 +50,187 @@ class PIGeoPosition; QAD_PIQT_EXPORT const QVariant PI2QVariant(const PIVariant & v); QAD_PIQT_EXPORT const PIVariant Q2PIVariant(const QVariant & v); -//inline const QString PI2QString(const PIString & v) {return QString::fromLocal8Bit(v.data());} -inline const QString PI2QString(const PIString & v) {return QString::fromUtf8(v.dataUTF8());} -#if PIP_VERSION >= PIP_MAKE_VERSION(2,38,0) -inline const QString PI2QString(const PIConstChars & v) {return QString::fromLatin1(v.data(), v.length());} +// inline const QString PI2QString(const PIString & v) {return QString::fromLocal8Bit(v.data());} +inline const QString PI2QString(const PIString & v) { + return QString::fromUtf8(v.dataUTF8()); +} +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 38, 0) +inline const QString PI2QString(const PIConstChars & v) { + return QString::fromLatin1(v.data(), v.length()); +} #endif -//inline const PIString Q2PIString(const QString & v) {return PIString(v.toLocal8Bit().data());} -inline const PIString Q2PIString(const QString & v) {return PIString::fromUTF8(v.toUtf8().data());} +// inline const PIString Q2PIString(const QString & v) {return PIString(v.toLocal8Bit().data());} +inline const PIString Q2PIString(const QString & v) { + return PIString::fromUTF8(v.toUtf8().data()); +} -inline const QStringList PI2QStringList(const PIStringList & v) {QStringList ret; piForeachC (PIString & s, v) ret << PI2QString(s); return ret;} +inline const QStringList PI2QStringList(const PIStringList & v) { + QStringList ret; + piForeachC(PIString & s, v) + ret << PI2QString(s); + return ret; +} -inline const PIStringList Q2PIStringList(const QStringList & v) {PIStringList ret; foreach (const QString & s, v) ret << Q2PIString(s); return ret;} +inline const PIStringList Q2PIStringList(const QStringList & v) { + PIStringList ret; + foreach(const QString & s, v) + ret << Q2PIString(s); + return ret; +} -inline const QByteArray PI2QByteArray(const PIByteArray & v) {return QByteArray((const char *)(v.data()), v.size_s());} +inline const QByteArray PI2QByteArray(const PIByteArray & v) { + return QByteArray((const char *)(v.data()), v.size_s()); +} -inline const PIByteArray Q2PIByteArray(const QByteArray & v) {return PIByteArray(v.constData(), v.size());} +inline const PIByteArray Q2PIByteArray(const QByteArray & v) { + return PIByteArray(v.constData(), v.size()); +} -inline const QPointF PI2QVector2(const PIMathVectorT2d & v) {return QPointF(v[0], v[1]);} -inline const QVector3D PI2QVector3(const PIMathVectorT3d & v) {return QVector3D(v[0], v[1], v[2]);} +inline const QPointF PI2QVector2(const PIMathVectorT2d & v) { + return QPointF(v[0], v[1]); +} +inline const QVector3D PI2QVector3(const PIMathVectorT3d & v) { + return QVector3D(v[0], v[1], v[2]); +} -inline const PIMathVectorT2d Q2PIVector2(const QPointF & v) {return PIMathVectorT2d({double(v.x()), double(v.y())});} -inline const PIMathVectorT3d Q2PIVector3(const QVector3D & v) {return PIMathVectorT3d({double(v.x()), double(v.y()), double(v.z())});} +inline const PIMathVectorT2d Q2PIVector2(const QPointF & v) { + return PIMathVectorT2d({double(v.x()), double(v.y())}); +} +inline const PIMathVectorT3d Q2PIVector3(const QVector3D & v) { + return PIMathVectorT3d({double(v.x()), double(v.y()), double(v.z())}); +} -inline const QPointF PI2QPoint(const PIPointd & v) {return QPointF(v.x, v.y);} -inline const PIPointd Q2PIPoint(const QPointF & v) {return PIPointd(v.x(), v.y());} +inline const QPointF PI2QPoint(const PIPointd & v) { + return QPointF(v.x, v.y); +} +inline const PIPointd Q2PIPoint(const QPointF & v) { + return PIPointd(v.x(), v.y()); +} -inline const QRectF PI2QRect(const PIRectd & v) {return QRectF(v.left(), v.bottom(), v.width(), v.height());} -inline const PIRectd Q2PIRect(const QRectF & v) {return PIRectd(v.left(), v.top(), v.width(), v.height());} +inline const QRectF PI2QRect(const PIRectd & v) { + return QRectF(v.left(), v.bottom(), v.width(), v.height()); +} +inline const PIRectd Q2PIRect(const QRectF & v) { + return PIRectd(v.left(), v.top(), v.width(), v.height()); +} -inline const QLineF PI2QLine(const PILined & v) {return QLineF(PI2QPoint(v.p0), PI2QPoint(v.p1));} -inline const PILined Q2PILine(const QLineF & v) {return PILined(Q2PIPoint(v.p1()), Q2PIPoint(v.p2()));} +inline const QLineF PI2QLine(const PILined & v) { + return QLineF(PI2QPoint(v.p0), PI2QPoint(v.p1)); +} +inline const PILined Q2PILine(const QLineF & v) { + return PILined(Q2PIPoint(v.p1()), Q2PIPoint(v.p2())); +} inline const QAD::MathVector PI2QMathVector(const PIMathVectord & v) { QVector q = QVector(v.size()); - memcpy(q.data(), v.data(), q.size()*sizeof(double)); + memcpy(q.data(), v.data(), q.size() * sizeof(double)); return QAD::MathVector(q); } inline const PIMathVectord Q2PIMathVector(const QAD::MathVector & v) { PIMathVectord p = PIMathVectord(v.v.size()); - memcpy(p.data(), v.v.data(), p.size()*sizeof(double)); + memcpy(p.data(), v.v.data(), p.size() * sizeof(double)); return p; } inline const QAD::MathMatrix PI2QMathMatrix(const PIMathMatrixd & v) { - PIVector > p = v.toVectors(); - QVector > q = QVector >(p.size()); + PIVector> p = v.toVectors(); + QVector> q = QVector>(p.size()); for (int i = 0; i < q.size(); ++i) { q[i].resize(p[i].size()); - memcpy(q[i].data(), p[i].data(), q[i].size()*sizeof(double)); + memcpy(q[i].data(), p[i].data(), q[i].size() * sizeof(double)); } return QAD::MathMatrix(q); } inline const PIMathMatrixd Q2PIMathMatrix(const QAD::MathMatrix & v) { - PIVector > p = PIVector >(v.m.size()); + PIVector> p = PIVector>(v.m.size()); for (int i = 0; i < v.m.size(); ++i) { p[i].resize(v.m[i].size()); - memcpy(p[i].data(), v.m[i].data(), p[i].size()*sizeof(double)); + memcpy(p[i].data(), v.m[i].data(), p[i].size() * sizeof(double)); } return PIMathMatrixd(p); } -inline const QDate PI2QDate(const PIDate & v) {return QDate(v.year, v.month, v.day);} -inline const QTime PI2QTime(const PITime & v) {return QTime(v.hours, v.minutes, v.seconds, v.milliseconds);} -inline const QDateTime PI2QDateTime(const PIDateTime & v) {return QDateTime(PI2QDate(v.date()), PI2QTime(v.time()));} +inline const QDate PI2QDate(const PIDate & v) { + return QDate(v.year, v.month, v.day); +} +inline const QTime PI2QTime(const PITime & v) { + return QTime(v.hours, v.minutes, v.seconds, v.milliseconds); +} +inline const QDateTime PI2QDateTime(const PIDateTime & v) { + return QDateTime(PI2QDate(v.date()), PI2QTime(v.time())); +} -inline const PIDate Q2PIDate(const QDate & v) {return PIDate(v.year(), v.month(), v.day());} -inline const PITime Q2PITime(const QTime & v) {return PITime(v.hour(), v.minute(), v.second(), v.msec());} -inline const PIDateTime Q2PIDateTime(const QDateTime & v) {return PIDateTime(Q2PIDate(v.date()), Q2PITime(v.time()));} +inline const PIDate Q2PIDate(const QDate & v) { + return PIDate(v.year(), v.month(), v.day()); +} +inline const PITime Q2PITime(const QTime & v) { + return PITime(v.hour(), v.minute(), v.second(), v.msec()); +} +inline const PIDateTime Q2PIDateTime(const QDateTime & v) { + return PIDateTime(Q2PIDate(v.date()), Q2PITime(v.time())); +} -inline const QColor PI2QColor(const PIVariantTypes::Color & v) {return QColor::fromRgba(v.rgba);} -inline const PIVariantTypes::Color Q2PIColor(const QColor & v) {return PIVariantTypes::Color(v.rgba());} +inline const QColor PI2QColor(const PIVariantTypes::Color & v) { + return QColor::fromRgba(v.rgba); +} +inline const PIVariantTypes::Color Q2PIColor(const QColor & v) { + return PIVariantTypes::Color(v.rgba()); +} template -inline const QVector PI2QVector(const PIVector & v) {QVector ret; ret.reserve(v.size_s()); for (int i = 0; i < v.size_s(); ++i) ret << v[i]; return ret;} +inline const QVector PI2QVector(const PIVector & v) { + QVector ret; + ret.reserve(v.size_s()); + for (int i = 0; i < v.size_s(); ++i) + ret << v[i]; + return ret; +} template -inline const PIVector Q2PIVector(const QVector & v) {if (v.isEmpty()) return PIVector(); return PIVector(v.constData(), (size_t)v.size());} +inline const PIVector Q2PIVector(const QVector & v) { + if (v.isEmpty()) return PIVector(); + return PIVector(v.constData(), (size_t)v.size()); +} -template +template inline QMap PI2QMap(const PIMap & v) { QMap ret; auto it = v.makeIterator(); - while (it.hasNext()) {it.next(); ret[it.key()] = it.value();} - return ret;} -template + while (it.hasNext()) { + it.next(); + ret[it.key()] = it.value(); + } + return ret; +} +template inline PIMap Q2PIMap(const QMap & v) { PIMap ret; ret.reserve((size_t)v.size()); QMapIterator it(v); - while (it.hasNext()) {it.next(); ret[it.key()] = it.value();} - return ret;} + while (it.hasNext()) { + it.next(); + ret[it.key()] = it.value(); + } + return ret; +} inline PIPropertyStorage Q2PIPropertyStorage(const PropertyStorage & props) { PIPropertyStorage ret; - foreach (const PropertyStorage::Property & p, props) + foreach(const PropertyStorage::Property & p, props) ret.addProperty(Q2PIString(p.name), Q2PIVariant(p.value), Q2PIString(p.comment), p.flags); return ret; } inline PropertyStorage PI2QPropertyStorage(const PIPropertyStorage & props) { PropertyStorage ret; - piForeachC (PIPropertyStorage::Property & p, props) + piForeachC(PIPropertyStorage::Property & p, props) ret.addProperty(PI2QString(p.name), PI2QVariant(p.value), PI2QString(p.comment), p.flags); return ret; } @@ -172,186 +245,451 @@ QAD_PIQT_EXPORT const PIVariantTypes::File QAD2PIFile(const QAD::File & v); QAD_PIQT_EXPORT const PIVariantTypes::Dir QAD2PIDir(const QAD::Dir & v); QAD_PIQT_EXPORT const PIVariantTypes::IODevice QAD2PIIODevice(const QAD::IODevice & v); -//inline const PIVariant QString2PIVariant(const QString & v) {return PIVariant::readFromString(QString2PIString(v));} +// inline const PIVariant QString2PIVariant(const QString & v) {return PIVariant::readFromString(QString2PIString(v));} #ifdef PIQT_HAS_GEOPOSITION QAD_PIQT_EXPORT const QGeoCoordinate PI2QGeoPosition(const PIGeoPosition & v); QAD_PIQT_EXPORT const PIGeoPosition Q2PIGeoPosition(const QGeoCoordinate & v); #endif -template +template class __PIQtConverter { public: __PIQtConverter(const From & v): val(v) {} - template operator To() {return To();} + template + operator To() { + return To(); + } From val; }; -template inline __PIQtConverter __PIQtConvert(const From & f) {return __PIQtConverter(f);} +template +inline __PIQtConverter __PIQtConvert(const From & f) { + return __PIQtConverter(f); +} -#define _PIQt_CONVERT(ft, tt, ftc, tfc) \ -template<> template<> inline __PIQtConverter::operator tt() {return ftc(val);} \ -template<> template<> inline __PIQtConverter::operator ft() {return tfc(val);} +#define _PIQt_CONVERT(ft, tt, ftc, tfc) \ + template<> \ + template<> \ + inline __PIQtConverter::operator tt() { \ + return ftc(val); \ + } \ + template<> \ + template<> \ + inline __PIQtConverter::operator ft() { \ + return tfc(val); \ + } #define _PIQt_CONVERT_S(t) _PIQt_CONVERT(PI##t, Q##t, PI2Q##t, Q2PI##t) -_PIQt_CONVERT_S(String) -_PIQt_CONVERT_S(ByteArray) -_PIQt_CONVERT_S(Time) -_PIQt_CONVERT_S(Date) -_PIQt_CONVERT_S(DateTime) -_PIQt_CONVERT(PIMathVectorT2d, QPointF, PI2QVector2, Q2PIVector2) -_PIQt_CONVERT(PIMathVectorT3d, QVector3D, PI2QVector3, Q2PIVector3) - +_PIQt_CONVERT_S(String) _PIQt_CONVERT_S(ByteArray) _PIQt_CONVERT_S(Time) _PIQt_CONVERT_S(Date) _PIQt_CONVERT_S(DateTime) + _PIQt_CONVERT(PIMathVectorT2d, QPointF, PI2QVector2, Q2PIVector2) _PIQt_CONVERT(PIMathVectorT3d, QVector3D, PI2QVector3, Q2PIVector3) #define piqt __PIQtConvert #define qtpi __PIQtConvert - - #ifndef PIP_BINARY_STREAM -inline PIByteArray & operator <<(PIByteArray & s, const QString & v) {s << Q2PIString(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QString & v) {PIString t; s >> t; v = PI2QString(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QStringList & v) {s << Q2PIStringList(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QStringList & v) {PIStringList t; s >> t; v = PI2QStringList(t); return s;} -template inline PIByteArray & operator <<(PIByteArray & s, const QVector & v) {s << PIVector(v.constData(), (size_t)v.size()); return s;} -template inline PIByteArray & operator >>(PIByteArray & s, QVector & v) { - PIVector t; s >> t; - v.resize(t.size_s()); - for (int i = 0; i < t.size_s(); ++i) - v[i] = t[i]; - return s;} -template inline PIByteArray & operator <<(PIByteArray & s, const QMap & v) { - PIMap t; - t.reserve(v.size()); - QMapIterator it(v); - while (it.hasNext()) {it.next(); t[it.key()] = it.value();} - s << t; - return s;} -template inline PIByteArray & operator >>(PIByteArray & s, QMap & v) { - v.clear(); - PIMap t; s >> t; - auto it = t.makeIterator(); - while (it.hasNext()) {it.next(); v[it.key()] = it.value();} - return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QPolygonF & v) {s << (QVector)v; return s;} -inline PIByteArray & operator >>(PIByteArray & s, QPolygonF & v) {QVector t; s >> t; v = t; return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QByteArray & v) {s << Q2PIByteArray(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QByteArray & v) {PIByteArray t; s >> t; v = PI2QByteArray(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QDate & v) {s << Q2PIDate(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QDate & v) {PIDate t; s >> t; v = PI2QDate(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QTime & v) {s << Q2PITime(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QTime & v) {PITime t; s >> t; v = PI2QTime(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QDateTime & v) {s << Q2PIDateTime(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QDateTime & v) {PIDateTime t; s >> t; v = PI2QDateTime(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QVariant & v) {s << Q2PIVariant(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QVariant & v) {PIVariant t; s >> t; v = PI2QVariant(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const PropertyStorage & v) {s << Q2PIPropertyStorage(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, PropertyStorage & v) {PIPropertyStorage t; s >> t; v = PI2QPropertyStorage(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QColor & v) {s << Q2PIColor(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QColor & v) {PIVariantTypes::Color t; s >> t; v = PI2QColor(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QAD::Enum & v) {s << QAD2PIEnum(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QAD::Enum & v) {PIVariantTypes::Enum t; s >> t; v = PI2QADEnum(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QAD::File & v) {s << QAD2PIFile(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QAD::File & v) {PIVariantTypes::File t; s >> t; v = PI2QADFile(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QAD::Dir & v) {s << QAD2PIDir(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QAD::Dir & v) {PIVariantTypes::Dir t; s >> t; v = PI2QADDir(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QAD::IODevice & v) {s << QAD2PIIODevice(v); return s;} -inline PIByteArray & operator >>(PIByteArray & s, QAD::IODevice & v) {PIVariantTypes::IODevice t; s >> t; v = PI2QADIODevice(t); return s;} -inline PIByteArray & operator <<(PIByteArray & s, const QImage & v) { - QByteArray ba; QBuffer buf(&ba); - v.save(&buf, "png"); - s << Q2PIByteArray(ba); - return s;} -inline PIByteArray & operator >>(PIByteArray & s, QImage & v) { - PIByteArray pba; s >> pba; - QByteArray ba = PI2QByteArray(pba); - if (!v.loadFromData(ba, "png")) - v = QImage(); - return s;} - -#else - -template inline PIBinaryStream

& operator <<(PIBinaryStream

& s, const QVector & v) { + inline PIByteArray & + operator<<(PIByteArray & s, const QString & v) { + s << Q2PIString(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QString & v) { + PIString t; + s >> t; + v = PI2QString(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QStringList & v) { + s << Q2PIStringList(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QStringList & v) { + PIStringList t; + s >> t; + v = PI2QStringList(t); + return s; +} +template +inline PIByteArray & operator<<(PIByteArray & s, const QVector & v) { s << PIVector(v.constData(), (size_t)v.size()); return s; } -template inline PIBinaryStream

& operator >>(PIBinaryStream

& s, QVector & v) { - PIVector t; s >> t; +template +inline PIByteArray & operator>>(PIByteArray & s, QVector & v) { + PIVector t; + s >> t; + v.resize(t.size_s()); + for (int i = 0; i < t.size_s(); ++i) + v[i] = t[i]; + return s; +} +template +inline PIByteArray & operator<<(PIByteArray & s, const QMap & v) { + PIMap t; + t.reserve(v.size()); + QMapIterator it(v); + while (it.hasNext()) { + it.next(); + t[it.key()] = it.value(); + } + s << t; + return s; +} +template +inline PIByteArray & operator>>(PIByteArray & s, QMap & v) { + v.clear(); + PIMap t; + s >> t; + auto it = t.makeIterator(); + while (it.hasNext()) { + it.next(); + v[it.key()] = it.value(); + } + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QPolygonF & v) { + s << (QVector)v; + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QPolygonF & v) { + QVector t; + s >> t; + v = t; + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QByteArray & v) { + s << Q2PIByteArray(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QByteArray & v) { + PIByteArray t; + s >> t; + v = PI2QByteArray(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QDate & v) { + s << Q2PIDate(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QDate & v) { + PIDate t; + s >> t; + v = PI2QDate(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QTime & v) { + s << Q2PITime(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QTime & v) { + PITime t; + s >> t; + v = PI2QTime(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QDateTime & v) { + s << Q2PIDateTime(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QDateTime & v) { + PIDateTime t; + s >> t; + v = PI2QDateTime(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QVariant & v) { + s << Q2PIVariant(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QVariant & v) { + PIVariant t; + s >> t; + v = PI2QVariant(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const PropertyStorage & v) { + s << Q2PIPropertyStorage(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, PropertyStorage & v) { + PIPropertyStorage t; + s >> t; + v = PI2QPropertyStorage(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QColor & v) { + s << Q2PIColor(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QColor & v) { + PIVariantTypes::Color t; + s >> t; + v = PI2QColor(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QAD::Enum & v) { + s << QAD2PIEnum(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QAD::Enum & v) { + PIVariantTypes::Enum t; + s >> t; + v = PI2QADEnum(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QAD::File & v) { + s << QAD2PIFile(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QAD::File & v) { + PIVariantTypes::File t; + s >> t; + v = PI2QADFile(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QAD::Dir & v) { + s << QAD2PIDir(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QAD::Dir & v) { + PIVariantTypes::Dir t; + s >> t; + v = PI2QADDir(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QAD::IODevice & v) { + s << QAD2PIIODevice(v); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QAD::IODevice & v) { + PIVariantTypes::IODevice t; + s >> t; + v = PI2QADIODevice(t); + return s; +} +inline PIByteArray & operator<<(PIByteArray & s, const QImage & v) { + QByteArray ba; + QBuffer buf(&ba); + v.save(&buf, "png"); + s << Q2PIByteArray(ba); + return s; +} +inline PIByteArray & operator>>(PIByteArray & s, QImage & v) { + PIByteArray pba; + s >> pba; + QByteArray ba = PI2QByteArray(pba); + if (!v.loadFromData(ba, "png")) v = QImage(); + return s; +} + +#else + + template + inline PIBinaryStream

& operator<<(PIBinaryStream

& s, const QVector & v) { + s << PIVector(v.constData(), (size_t)v.size()); + return s; +} +template +inline PIBinaryStream

& operator>>(PIBinaryStream

& s, QVector & v) { + PIVector t; + s >> t; v.resize(t.size_s()); for (int i = 0; i < t.size_s(); ++i) v[i] = t[i]; return s; } -template inline PIBinaryStream

& operator <<(PIBinaryStream

& s, const QMap & v) { +template +inline PIBinaryStream

& operator<<(PIBinaryStream

& s, const QMap & v) { PIMap t; t.reserve(v.size()); QMapIterator it(v); - while (it.hasNext()) {it.next(); t[it.key()] = it.value();} + while (it.hasNext()) { + it.next(); + t[it.key()] = it.value(); + } s << t; return s; } -template inline PIBinaryStream

& operator >>(PIBinaryStream

& s, QMap & v) { +template +inline PIBinaryStream

& operator>>(PIBinaryStream

& s, QMap & v) { v.clear(); - PIMap t; s >> t; + PIMap t; + s >> t; auto it = t.makeIterator(); - while (it.hasNext()) {it.next(); v[it.key()] = it.value();} + while (it.hasNext()) { + it.next(); + v[it.key()] = it.value(); + } return s; } -BINARY_STREAM_WRITE(QString) {s << Q2PIString(v); return s;} -BINARY_STREAM_READ (QString) {PIString t; s >> t; v = PI2QString(t); return s;} +BINARY_STREAM_WRITE(QString) { + s << Q2PIString(v); + return s; +} +BINARY_STREAM_READ(QString) { + PIString t; + s >> t; + v = PI2QString(t); + return s; +} -BINARY_STREAM_WRITE(QStringList) {s << Q2PIStringList(v); return s;} -BINARY_STREAM_READ (QStringList) {PIStringList t; s >> t; v = PI2QStringList(t); return s;} +BINARY_STREAM_WRITE(QStringList) { + s << Q2PIStringList(v); + return s; +} +BINARY_STREAM_READ(QStringList) { + PIStringList t; + s >> t; + v = PI2QStringList(t); + return s; +} -BINARY_STREAM_WRITE(QPolygonF) {s << (QVector)v; return s;} -BINARY_STREAM_READ (QPolygonF) {QVector t; s >> t; v = t; return s;} +BINARY_STREAM_WRITE(QPolygonF) { + s << (QVector)v; + return s; +} +BINARY_STREAM_READ(QPolygonF) { + QVector t; + s >> t; + v = t; + return s; +} -BINARY_STREAM_WRITE(QByteArray) {s << Q2PIByteArray(v); return s;} -BINARY_STREAM_READ (QByteArray) {PIByteArray t; s >> t; v = PI2QByteArray(t); return s;} +BINARY_STREAM_WRITE(QByteArray) { + s << Q2PIByteArray(v); + return s; +} +BINARY_STREAM_READ(QByteArray) { + PIByteArray t; + s >> t; + v = PI2QByteArray(t); + return s; +} -BINARY_STREAM_WRITE(QDate) {s << Q2PIDate(v); return s;} -BINARY_STREAM_READ (QDate) {PIDate t; s >> t; v = PI2QDate(t); return s;} +BINARY_STREAM_WRITE(QDate) { + s << Q2PIDate(v); + return s; +} +BINARY_STREAM_READ(QDate) { + PIDate t; + s >> t; + v = PI2QDate(t); + return s; +} -BINARY_STREAM_WRITE(QTime) {s << Q2PITime(v); return s;} -BINARY_STREAM_READ (QTime) {PITime t; s >> t; v = PI2QTime(t); return s;} +BINARY_STREAM_WRITE(QTime) { + s << Q2PITime(v); + return s; +} +BINARY_STREAM_READ(QTime) { + PITime t; + s >> t; + v = PI2QTime(t); + return s; +} -BINARY_STREAM_WRITE(QDateTime) {s << Q2PIDateTime(v); return s;} -BINARY_STREAM_READ (QDateTime) {PIDateTime t; s >> t; v = PI2QDateTime(t); return s;} +BINARY_STREAM_WRITE(QDateTime) { + s << Q2PIDateTime(v); + return s; +} +BINARY_STREAM_READ(QDateTime) { + PIDateTime t; + s >> t; + v = PI2QDateTime(t); + return s; +} -BINARY_STREAM_WRITE(QVariant) {s << Q2PIVariant(v); return s;} -BINARY_STREAM_READ (QVariant) {PIVariant t; s >> t; v = PI2QVariant(t); return s;} +BINARY_STREAM_WRITE(QVariant) { + s << Q2PIVariant(v); + return s; +} +BINARY_STREAM_READ(QVariant) { + PIVariant t; + s >> t; + v = PI2QVariant(t); + return s; +} -BINARY_STREAM_WRITE(PropertyStorage) {s << Q2PIPropertyStorage(v); return s;} -BINARY_STREAM_READ (PropertyStorage) {PIPropertyStorage t; s >> t; v = PI2QPropertyStorage(t); return s;} +BINARY_STREAM_WRITE(PropertyStorage) { + s << Q2PIPropertyStorage(v); + return s; +} +BINARY_STREAM_READ(PropertyStorage) { + PIPropertyStorage t; + s >> t; + v = PI2QPropertyStorage(t); + return s; +} -BINARY_STREAM_WRITE(QColor) {s << Q2PIColor(v); return s;} -BINARY_STREAM_READ (QColor) {PIVariantTypes::Color t; s >> t; v = PI2QColor(t); return s;} +BINARY_STREAM_WRITE(QColor) { + s << Q2PIColor(v); + return s; +} +BINARY_STREAM_READ(QColor) { + PIVariantTypes::Color t; + s >> t; + v = PI2QColor(t); + return s; +} -BINARY_STREAM_WRITE(QAD::Enum) {s << QAD2PIEnum(v); return s;} -BINARY_STREAM_READ (QAD::Enum) {PIVariantTypes::Enum t; s >> t; v = PI2QADEnum(t); return s;} +BINARY_STREAM_WRITE(QAD::Enum) { + s << QAD2PIEnum(v); + return s; +} +BINARY_STREAM_READ(QAD::Enum) { + PIVariantTypes::Enum t; + s >> t; + v = PI2QADEnum(t); + return s; +} -BINARY_STREAM_WRITE(QAD::File) {s << QAD2PIFile(v); return s;} -BINARY_STREAM_READ (QAD::File) {PIVariantTypes::File t; s >> t; v = PI2QADFile(t); return s;} +BINARY_STREAM_WRITE(QAD::File) { + s << QAD2PIFile(v); + return s; +} +BINARY_STREAM_READ(QAD::File) { + PIVariantTypes::File t; + s >> t; + v = PI2QADFile(t); + return s; +} -BINARY_STREAM_WRITE(QAD::Dir) {s << QAD2PIDir(v); return s;} -BINARY_STREAM_READ (QAD::Dir) {PIVariantTypes::Dir t; s >> t; v = PI2QADDir(t); return s;} +BINARY_STREAM_WRITE(QAD::Dir) { + s << QAD2PIDir(v); + return s; +} +BINARY_STREAM_READ(QAD::Dir) { + PIVariantTypes::Dir t; + s >> t; + v = PI2QADDir(t); + return s; +} -BINARY_STREAM_WRITE(QAD::IODevice) {s << QAD2PIIODevice(v); return s;} -BINARY_STREAM_READ (QAD::IODevice) {PIVariantTypes::IODevice t; s >> t; v = PI2QADIODevice(t); return s;} +BINARY_STREAM_WRITE(QAD::IODevice) { + s << QAD2PIIODevice(v); + return s; +} +BINARY_STREAM_READ(QAD::IODevice) { + PIVariantTypes::IODevice t; + s >> t; + v = PI2QADIODevice(t); + return s; +} BINARY_STREAM_WRITE(QImage) { - QByteArray ba; QBuffer buf(&ba); + QByteArray ba; + QBuffer buf(&ba); v.save(&buf, "png"); s << Q2PIByteArray(ba); return s; } -BINARY_STREAM_READ (QImage) { - PIByteArray pba; s >> pba; +BINARY_STREAM_READ(QImage) { + PIByteArray pba; + s >> pba; QByteArray ba = PI2QByteArray(pba); - if (!v.loadFromData(ba, "png")) - v = QImage(); + if (!v.loadFromData(ba, "png")) v = QImage(); return s; } @@ -360,7 +698,8 @@ BINARY_STREAM_READ (QImage) { /// pure Qt -template QByteArray qSerialize(const T & value, int version = -1) { +template +QByteArray qSerialize(const T & value, int version = -1) { QByteArray ret; QDataStream s(&ret, QIODevice::ReadWrite); if (version > 0) s.setVersion((QDataStream::Version)version); @@ -368,7 +707,8 @@ template QByteArray qSerialize(const T & value, int version = -1) { return ret; } -template T qDeserialize(const QByteArray & data, int version = -1) { +template +T qDeserialize(const QByteArray & data, int version = -1) { T ret; if (!data.isEmpty()) { QDataStream s(data); @@ -382,13 +722,15 @@ template T qDeserialize(const QByteArray & data, int version = -1) /// PIP with QByteArray -template QByteArray piqSerialize(const T & value) { +template +QByteArray piqSerialize(const T & value) { PIByteArray ret; ret << value; return PI2QByteArray(ret); } -template T piqDeserialize(const QByteArray & data) { +template +T piqDeserialize(const QByteArray & data) { T ret; if (!data.isEmpty()) { PIByteArray ba = Q2PIByteArray(data); diff --git a/libs/piqt/piqt_macros.h b/libs/piqt/piqt_macros.h index 86a0e27..7704849 100644 --- a/libs/piqt/piqt_macros.h +++ b/libs/piqt/piqt_macros.h @@ -1,78 +1,89 @@ -/* - PIQt - PIP <-> Qt convertions - - Ivan Pelipenko peri4ko@yandex.ru - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . -*/ - -#ifndef PIQT_MACROS_H -#define PIQT_MACROS_H - -#include -#include -#include "qad_piqt_export.h" - - -/// connect PIP event "event" of object "src" directly to Qt slot "slot" of object "tgt" -/// e.g. PIQCONNECT(&pip_obj, someEvent, &qt_obj, someSlot) -#define PIQCONNECT(src, event, tgt, slot) \ - PIQt::piqConnect(src, #event, &(src)->__stat_eh_##event##__, tgt, &decltype(PIQt::removePtr(tgt))::slot); - -/// connect PIP event "event" of object "src" to Qt slot "slot" of object "tgt" via Qt::QueuedConnection -/// Note! All argument types must be registered in Qt meta-system! -/// e.g. PIQCONNECT_QUEUED(&pip_obj, someEvent, &qt_obj, someSlot) -#define PIQCONNECT_QUEUED(src, event, tgt, slot) \ - PIQt::piqConnectQ(src, #event, &(src)->__stat_eh_##event##__, tgt, #slot); - - -/// connect Qt signal "sig" of object "src" directly to PIP event handler "handler" of object "tgt" -/// e.g. QPICONNECT(&qt_obj, someSignal, &pip_obj, someHandler) -/// Returns QMetaObject::Connection -#define QPICONNECT(src, sig, tgt, handler) \ - PIQt::qpiConnect(src, &decltype(PIQt::removePtr(src))::sig, tgt, &(tgt)->__stat_eh_##handler##__); - - -namespace PIQt { - -template T removePtr(T*) {} -template QArgument qargument(const T & v) { - return QArgument( -#if QT_VERSION_MAJOR <= 5 - QMetaType::typeName(qMetaTypeId()) -#else - QMetaType::fromType().name() -#endif - , v);} - -template -void piqConnect(PIObject * source, const char * event, void(*func)(void*,ARGS...), O * target, SR(O::*slot)(ARGS...)) { - PIObject::piConnectLS(source, PIStringAscii(event), PIObject::__newFunctor(func, [target,slot](ARGS... args){(target->*slot)(args...);}), LOCATION); -} - -template -void piqConnectQ(PIObject * source, const char * event, void(*func)(void*,ARGS...), QObject * target, const char * slot) { - PIObject::piConnectLS(source, PIStringAscii(event), PIObject::__newFunctor(func, [target,slot](ARGS... args){ - QMetaObject::invokeMethod(target, slot, Qt::QueuedConnection, qargument(args)...); - }), LOCATION); -} - -template -QMetaObject::Connection qpiConnect(O * source, SR(O::*signal)(ARGS...), PIObject * target, void(*handler)(void*,ARGS...)) { - return QObject::connect(source, signal, source, [target,handler](ARGS... args){handler(target, args...);}); -} - -} - -#endif // PIQT_MACROS_H +/* + PIQt - PIP <-> Qt convertions + + Ivan Pelipenko peri4ko@yandex.ru + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . +*/ + +#ifndef PIQT_MACROS_H +#define PIQT_MACROS_H + +#include "qad_piqt_export.h" + +#include +#include + + +/// connect PIP event "event" of object "src" directly to Qt slot "slot" of object "tgt" +/// e.g. PIQCONNECT(&pip_obj, someEvent, &qt_obj, someSlot) +#define PIQCONNECT(src, event, tgt, slot) \ + PIQt::piqConnect(src, #event, &(src)->__stat_eh_##event##__, tgt, &decltype(PIQt::removePtr(tgt))::slot); + +/// connect PIP event "event" of object "src" to Qt slot "slot" of object "tgt" via Qt::QueuedConnection +/// Note! All argument types must be registered in Qt meta-system! +/// e.g. PIQCONNECT_QUEUED(&pip_obj, someEvent, &qt_obj, someSlot) +#define PIQCONNECT_QUEUED(src, event, tgt, slot) PIQt::piqConnectQ(src, #event, &(src)->__stat_eh_##event##__, tgt, #slot); + + +/// connect Qt signal "sig" of object "src" directly to PIP event handler "handler" of object "tgt" +/// e.g. QPICONNECT(&qt_obj, someSignal, &pip_obj, someHandler) +/// Returns QMetaObject::Connection +#define QPICONNECT(src, sig, tgt, handler) \ + PIQt::qpiConnect(src, &decltype(PIQt::removePtr(src))::sig, tgt, &(tgt)->__stat_eh_##handler##__); + + +namespace PIQt { + +template +T removePtr(T *) {} +template +QArgument qargument(const T & v) { + return QArgument( +#if QT_VERSION_MAJOR <= 5 + QMetaType::typeName(qMetaTypeId()) +#else + QMetaType::fromType().name() +#endif + , + v); +} + +template +void piqConnect(PIObject * source, const char * event, void (*func)(void *, ARGS...), O * target, SR (O::*slot)(ARGS...)) { + PIObject::piConnectLS(source, + PIStringAscii(event), + PIObject::__newFunctor(func, [target, slot](ARGS... args) { (target->*slot)(args...); }), + LOCATION); +} + +template +void piqConnectQ(PIObject * source, const char * event, void (*func)(void *, ARGS...), QObject * target, const char * slot) { + PIObject::piConnectLS(source, + PIStringAscii(event), + PIObject::__newFunctor(func, + [target, slot](ARGS... args) { + QMetaObject::invokeMethod(target, slot, Qt::QueuedConnection, qargument(args)...); + }), + LOCATION); +} + +template +QMetaObject::Connection qpiConnect(O * source, SR (O::*signal)(ARGS...), PIObject * target, void (*handler)(void *, ARGS...)) { + return QObject::connect(source, signal, source, [target, handler](ARGS... args) { handler(target, args...); }); +} + +} // namespace PIQt + +#endif // PIQT_MACROS_H diff --git a/libs/piqt/qpiconnection.cpp b/libs/piqt/qpiconnection.cpp index 754eaa2..a625a29 100644 --- a/libs/piqt/qpiconnection.cpp +++ b/libs/piqt/qpiconnection.cpp @@ -18,13 +18,19 @@ bool QPIConnection::loadFromCMFile(const QString & file) { void QPIConnection::piDataRec(const PIString & from, const PIByteArray & data) { - //piCout << from << PICoutManipulators::Hex << data; - QMetaObject::invokeMethod(this, "qDataReceivedEvent", Qt::QueuedConnection, - Q_ARG(QString, PI2QString(from)), Q_ARG(QByteArray, PI2QByteArray(data))); + // piCout << from << PICoutManipulators::Hex << data; + QMetaObject::invokeMethod(this, + "qDataReceivedEvent", + Qt::QueuedConnection, + Q_ARG(QString, PI2QString(from)), + Q_ARG(QByteArray, PI2QByteArray(data))); } void QPIConnection::piPacketRec(const PIString & from, const PIByteArray & data) { - QMetaObject::invokeMethod(this, "qPacketReceivedEvent", Qt::QueuedConnection, - Q_ARG(QString, PI2QString(from)), Q_ARG(QByteArray, PI2QByteArray(data))); + QMetaObject::invokeMethod(this, + "qPacketReceivedEvent", + Qt::QueuedConnection, + Q_ARG(QString, PI2QString(from)), + Q_ARG(QByteArray, PI2QByteArray(data))); } diff --git a/libs/piqt/qpiconnection.h b/libs/piqt/qpiconnection.h index 46dc5aa..7101304 100644 --- a/libs/piqt/qpiconnection.h +++ b/libs/piqt/qpiconnection.h @@ -1,56 +1,59 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONNECTION_H #define QPICONNECTION_H -#include -#include #include "piconnection.h" -#include "qpiconfig.h" #include "piqt.h" #include "qad_piqt_export.h" +#include "qpiconfig.h" + +#include +#include -class QAD_PIQT_EXPORT QPIConnection: public QObject, public PIConnection { +class QAD_PIQT_EXPORT QPIConnection + : public QObject + , public PIConnection { Q_OBJECT PIOBJECT_SUBCLASS(QPIConnection, PIConnection); + public: QPIConnection(const QString & name = QString()); - + bool loadFromCMFile(const QString & file); - + protected: -#if PIP_VERSION >= PIP_MAKE_VERSION(2,38,0) - void propertyChanged(const char *) override {setObjectName(PI2QString(name()));} +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 38, 0) + void propertyChanged(const char *) override { setObjectName(PI2QString(name())); } #else - void propertyChanged(const PIString &) override {setObjectName(PI2QString(name()));} + void propertyChanged(const PIString &) override { setObjectName(PI2QString(name())); } #endif EVENT_HANDLER2(void, piDataRec, const PIString &, from, const PIByteArray &, data); EVENT_HANDLER2(void, piPacketRec, const PIString &, from, const PIByteArray &, data); - + public slots: - + signals: void qDataReceivedEvent(QString from, QByteArray data); void qPacketReceivedEvent(QString from, QByteArray data); - }; #endif // QPICONNECTION_H diff --git a/libs/piqt_widgets/piqt_connection_edit.cpp b/libs/piqt_widgets/piqt_connection_edit.cpp index 04e4025..97cf053 100644 --- a/libs/piqt_widgets/piqt_connection_edit.cpp +++ b/libs/piqt_widgets/piqt_connection_edit.cpp @@ -1,9 +1,11 @@ -#include "ui_piqt_connection_edit.h" #include "piqt_connection_edit.h" + +#include "picodeinfo.h" +#include "piqt.h" #include "piqt_connection_view.h" #include "piqt_highlighter.h" -#include "piqt.h" -#include "picodeinfo.h" +#include "ui_piqt_connection_edit.h" + #include #include @@ -13,14 +15,15 @@ ConnectionEdit::ConnectionEdit(QWidget * parent): QDialog(parent) { ui->setupUi(this); new ConfigHighlighter(ui->codeEdit->document()); loading = false; - connect(ui->blockView, SIGNAL(schemeAction(BlockItemBase::Action,QList)), this, SLOT(recreateRequest())); + connect(ui->blockView, SIGNAL(schemeAction(BlockItemBase::Action, QList)), this, SLOT(recreateRequest())); connect(ui->blockView->scene(), SIGNAL(selectionChanged()), this, SLOT(selectionChanged())); - conn = 0; + conn = 0; PICodeInfo::EnumInfo * ei = PICodeInfo::enumsInfo->value("PIIODevice::DeviceMode"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) - ui->comboMode->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) + ui->comboMode->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), + QVariant::fromValue(e.value)); #else ui->comboMode->addItem(PI2QString(e.name + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); #endif @@ -28,9 +31,9 @@ ConnectionEdit::ConnectionEdit(QWidget * parent): QDialog(parent) { ui->comboMode->setCurrentIndex(ui->comboMode->count() - 1); ei = PICodeInfo::enumsInfo->value("PIIODevice::DeviceOption"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) { + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) { QCheckBox * cb = new QCheckBox(); -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) cb->setText(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")")); #else cb->setText(PI2QString(e.name + " (" + PIString::fromNumber(e.value) + ")")); @@ -41,9 +44,10 @@ ConnectionEdit::ConnectionEdit(QWidget * parent): QDialog(parent) { } ei = PICodeInfo::enumsInfo->value("PIPacketExtractor::SplitMode"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) - ui->comboSplit->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) + ui->comboSplit->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), + QVariant::fromValue(e.value)); #else ui->comboSplit->addItem(PI2QString(e.name + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); #endif @@ -61,13 +65,15 @@ ConnectionEdit::~ConnectionEdit() { void ConnectionEdit::accept() { - //bool ok = false; - QList bl = ui->blockView->allDevices(); - foreach (BlockItem * i, bl) - foreach (BlockItem * j, bl) + // bool ok = false; + QList bl = ui->blockView->allDevices(); + foreach(BlockItem * i, bl) + foreach(BlockItem * j, bl) if (i != j) - if (((DeviceItem*)i)->name() == ((DeviceItem*)j)->name()) { - QMessageBox::critical(this, windowTitle() + " - " + tr("error") + "!", tr("Equal devices names: \"%1\"!").arg(((DeviceItem*)i)->name())); + if (((DeviceItem *)i)->name() == ((DeviceItem *)j)->name()) { + QMessageBox::critical(this, + windowTitle() + " - " + tr("error") + "!", + tr("Equal devices names: \"%1\"!").arg(((DeviceItem *)i)->name())); return; } QDialog::accept(); @@ -85,21 +91,19 @@ QByteArray ConnectionEdit::model() const { QDataStream s(&ret, QIODevice::ReadWrite); QString cn = PI2QString(conn ? conn->name() : PIString()); s << cn; - QList busl = ui->blockView->buses(); + QList busl = ui->blockView->buses(); s << busl.size(); - foreach (BlockBusItem * b, busl) + foreach(BlockBusItem * b, busl) s << b->save(); - QList blockl = ui->blockView->blocks(); + QList blockl = ui->blockView->blocks(); s << blockl.size(); - foreach (BlockItem * b, blockl) { + foreach(BlockItem * b, blockl) { int type = b->propertyByName("__type").value.toInt(); s << type; switch (type) { case __CV_Device: case __CV_Filter: - case __CV_Sender: - s << b->save(); - break; + case __CV_Sender: s << b->save(); break; } } return ret; @@ -136,7 +140,9 @@ void ConnectionEdit::setModel(const QByteArray & m) { s >> sz; for (int i = 0; i < sz; ++i) { BlockBusItem * b = new BlockBusItem(); - QByteArray ba; s >> ba; b->load(ba); + QByteArray ba; + s >> ba; + b->load(ba); ui->blockView->addItem(b); } s >> sz; @@ -148,26 +154,26 @@ void ConnectionEdit::setModel(const QByteArray & m) { switch (type) { case __CV_Device: b = new DeviceItem(); - s >> ba; b->load(ba); - if (!b->isPropertyExists("bufferSize")) - ((DeviceItem*)b)->setBufferSize(4096); - ((DeviceItem*)b)->rename(); + s >> ba; + b->load(ba); + if (!b->isPropertyExists("bufferSize")) ((DeviceItem *)b)->setBufferSize(4096); + ((DeviceItem *)b)->rename(); break; case __CV_Filter: b = new FilterItem(); - s >> ba; b->load(ba); - if (!b->isPropertyExists("bufferSize")) - ((FilterItem*)b)->setBufferSize(65536); - ((FilterItem*)b)->rename(); + s >> ba; + b->load(ba); + if (!b->isPropertyExists("bufferSize")) ((FilterItem *)b)->setBufferSize(65536); + ((FilterItem *)b)->rename(); break; case __CV_Sender: b = new SenderItem(); - s >> ba; b->load(ba); - ((SenderItem*)b)->rename(); + s >> ba; + b->load(ba); + ((SenderItem *)b)->rename(); break; } - if (b) - ui->blockView->addItem(b); + if (b) ui->blockView->addItem(b); } ui->blockView->reconnectAll(); loading = false; @@ -176,18 +182,18 @@ void ConnectionEdit::setModel(const QByteArray & m) { void ConnectionEdit::selectionChanged() { - QList si = ui->blockView->scene()->selectedItems(); + QList si = ui->blockView->scene()->selectedItems(); ui->buttonRemove->setEnabled(!si.isEmpty()); ui->buttonDeviceModify->setEnabled(false); ui->buttonFilterModify->setEnabled(false); ui->buttonSenderModify->setEnabled(false); if (si.size() != 1) return; - BlockItem * b = qgraphicsitem_cast(si[0]); + BlockItem * b = qgraphicsitem_cast(si[0]); if (!b) return; int type = b->propertyByName("__type").value.toInt(); if (type == __CV_Device) { ui->tabWidget->setCurrentIndex(0); - DeviceItem * di = (DeviceItem*)b; + DeviceItem * di = (DeviceItem *)b; ui->buttonDeviceModify->setEnabled(true); for (int i = 0; i < ui->comboMode->count(); ++i) if (ui->comboMode->itemData(i).toInt() == di->mode()) { @@ -202,7 +208,7 @@ void ConnectionEdit::selectionChanged() { } if (type == __CV_Filter) { ui->tabWidget->setCurrentIndex(1); - FilterItem * fi = (FilterItem*)b; + FilterItem * fi = (FilterItem *)b; ui->buttonFilterModify->setEnabled(true); for (int i = 0; i < ui->comboSplit->count(); ++i) if (ui->comboSplit->itemData(i).toInt() == fi->mode()) { @@ -219,13 +225,12 @@ void ConnectionEdit::selectionChanged() { } if (type == __CV_Sender) { ui->tabWidget->setCurrentIndex(2); - SenderItem * si = (SenderItem*)b; + SenderItem * si = (SenderItem *)b; ui->buttonSenderModify->setEnabled(true); ui->lineSender->setText(si->name()); ui->lineData->setText(si->data()); ui->spinFrequency->setValue(si->frequency()); } - } @@ -268,10 +273,9 @@ void ConnectionEdit::applySender(SenderItem * b) { int ConnectionEdit::getOptions() const { int ret(0); for (int i = 0; i < ui->layoutOptions->count(); ++i) { - QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); + QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); if (!cb) continue; - if (cb->isChecked()) - ret |= cb->property("__value").toInt(); + if (cb->isChecked()) ret |= cb->property("__value").toInt(); } return ret; } @@ -279,27 +283,29 @@ int ConnectionEdit::getOptions() const { void ConnectionEdit::setOptions(int o) { for (int i = 0; i < ui->layoutOptions->count(); ++i) { - QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); + QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); if (!cb) continue; int cbf = cb->property("__value").toInt(); - //qDebug() << cbf; + // qDebug() << cbf; cb->setChecked((o & cbf) == cbf); } } void ConnectionEdit::recreateConnection() { - //qDebug() << "recreate"; + // qDebug() << "recreate"; if (loading) return; ui->blockView->reconnectAll(); if (conn) delete conn; PIString cn = Q2PIString(ui->lineName->text()); - if (cn.isEmpty()) conn = new PIConnection(); - else conn = new PIConnection(cn); - QList devs = ui->blockView->allDevices(); - foreach (BlockItem * b, devs) { - DeviceItem * di = (DeviceItem*)b; - //qDebug() << di->path(); + if (cn.isEmpty()) + conn = new PIConnection(); + else + conn = new PIConnection(cn); + QList devs = ui->blockView->allDevices(); + foreach(BlockItem * b, devs) { + DeviceItem * di = (DeviceItem *)b; + // qDebug() << di->path(); PIIODevice * dev = conn->addDevice(Q2PIString(di->path()), di->mode()); if (!dev) continue; dev->setOptions(di->options()); @@ -308,35 +314,35 @@ void ConnectionEdit::recreateConnection() { PIDiagnostics * diag = conn->diagnostic(dev); if (diag) diag->setDisconnectTimeout(di->disconnectTimeout()); } - foreach (BlockItem * b, devs) { - DeviceItem * di = (DeviceItem*)b; + foreach(BlockItem * b, devs) { + DeviceItem * di = (DeviceItem *)b; PIIODevice * dev = conn->deviceByName(Q2PIString(di->name())); if (!dev) continue; BlockItemPin * p = b->pinByText("read"); if (!p) continue; - QList buses = p->connectedBuses(), nbuses; - QSet pbuses; + QList buses = p->connectedBuses(), nbuses; + QSet pbuses; while (!buses.isEmpty()) { nbuses.clear(); - foreach (BlockBusItem * bus, buses) { - QList cb = bus->connectedBlocks(); + foreach(BlockBusItem * bus, buses) { + QList cb = bus->connectedBlocks(); if (cb.size() != 2) continue; FilterItem * fi_t(0); BlockItem * bi_f(0); if (cb[0]->pinAtBus(bus)->text() == "in") { - fi_t = (FilterItem*)(cb[0]); + fi_t = (FilterItem *)(cb[0]); bi_f = (cb[1]); } else if (cb[1]->pinAtBus(bus)->text() == "in") { - fi_t = (FilterItem*)(cb[1]); + fi_t = (FilterItem *)(cb[1]); bi_f = (cb[0]); } if (!fi_t || !bi_f) continue; PIString name_from; int type = bi_f->propertyByName("__type").value.toInt(); - if (type == __CV_Device) name_from = Q2PIString(((DeviceItem*)bi_f)->name()); - if (type == __CV_Filter) name_from = Q2PIString(((FilterItem*)bi_f)->name()); + if (type == __CV_Device) name_from = Q2PIString(((DeviceItem *)bi_f)->name()); + if (type == __CV_Filter) name_from = Q2PIString(((FilterItem *)bi_f)->name()); if (name_from.isEmpty()) continue; - PIPacketExtractor * pe = conn->addFilter(Q2PIString(fi_t->name()),conn->deviceByName(name_from), fi_t->mode()); + PIPacketExtractor * pe = conn->addFilter(Q2PIString(fi_t->name()), conn->deviceByName(name_from), fi_t->mode()); if (!pe) continue; pe->setHeader(PIByteArray::fromUserInput(Q2PIString(fi_t->header()))); pe->setFooter(PIByteArray::fromUserInput(Q2PIString(fi_t->footer()))); @@ -345,8 +351,8 @@ void ConnectionEdit::recreateConnection() { pe->setThreadedReadBufferSize(fi_t->bufferSize()); PIDiagnostics * diag = conn->diagnostic(pe); if (diag) diag->setDisconnectTimeout(fi_t->disconnectTimeout()); - QList nb = fi_t->pinByText("out")->connectedBuses(); - foreach (BlockBusItem * b_, nb) + QList nb = fi_t->pinByText("out")->connectedBuses(); + foreach(BlockBusItem * b_, nb) if (!pbuses.contains(b_)) { pbuses << b_; nbuses << b_; @@ -355,34 +361,34 @@ void ConnectionEdit::recreateConnection() { buses = nbuses; } } - foreach (BlockItem * b, devs) { + foreach(BlockItem * b, devs) { BlockItemPin * p = b->pinByText("write"); if (!p) continue; - QList buses = p->connectedBuses(); - foreach (BlockBusItem * bus, buses) { - QList cb = bus->connectedBlocks(); + QList buses = p->connectedBuses(); + foreach(BlockBusItem * bus, buses) { + QList cb = bus->connectedBlocks(); if (cb.size() != 2) continue; BlockItem * bi_f(0); DeviceItem * di_t(0); if (cb[0]->pinAtBus(bus)->text() == "write") { - di_t = (DeviceItem*)(cb[0]); + di_t = (DeviceItem *)(cb[0]); bi_f = (cb[1]); } else if (cb[1]->pinAtBus(bus)->text() == "write") { - di_t = (DeviceItem*)(cb[1]); + di_t = (DeviceItem *)(cb[1]); bi_f = (cb[0]); } if (!bi_f || !di_t) continue; QString name_from; int type = bi_f->propertyByName("__type").value.toInt(); if (type == __CV_Sender) { - SenderItem * si = ((SenderItem*)bi_f); + SenderItem * si = ((SenderItem *)bi_f); si->name(); conn->addSender(Q2PIString(si->name()), Q2PIString(di_t->path()), si->frequency()); if (!si->data().isEmpty()) conn->setSenderFixedData(Q2PIString(si->name()), PIByteArray::fromUserInput(Q2PIString(si->data()))); } else { - if (type == __CV_Device) name_from = ((DeviceItem*)bi_f)->name(); - if (type == __CV_Filter) name_from = ((FilterItem*)bi_f)->name(); + if (type == __CV_Device) name_from = ((DeviceItem *)bi_f)->name(); + if (type == __CV_Filter) name_from = ((FilterItem *)bi_f)->name(); if (name_from.isEmpty()) continue; conn->addChannel(Q2PIString(name_from), Q2PIString(di_t->name())); } @@ -411,12 +417,11 @@ void ConnectionEdit::on_buttonFilterAdd_clicked() { void ConnectionEdit::on_buttonFilterModify_clicked() { - QList si = ui->blockView->scene()->selectedItems(); + QList si = ui->blockView->scene()->selectedItems(); if (si.isEmpty()) return; - if (!qgraphicsitem_cast(si[0])) return; - if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Filter) - return; - applyFilter(qgraphicsitem_cast(si[0])); + if (!qgraphicsitem_cast(si[0])) return; + if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Filter) return; + applyFilter(qgraphicsitem_cast(si[0])); } @@ -435,12 +440,11 @@ void ConnectionEdit::on_buttonDeviceAdd_clicked() { void ConnectionEdit::on_buttonDeviceModify_clicked() { - QList si = ui->blockView->scene()->selectedItems(); + QList si = ui->blockView->scene()->selectedItems(); if (si.isEmpty()) return; - if (!qgraphicsitem_cast(si[0])) return; - if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Device) - return; - applyDevice(qgraphicsitem_cast(si[0])); + if (!qgraphicsitem_cast(si[0])) return; + if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Device) return; + applyDevice(qgraphicsitem_cast(si[0])); } @@ -451,12 +455,11 @@ void ConnectionEdit::on_buttonSenderAdd_clicked() { void ConnectionEdit::on_buttonSenderModify_clicked() { - QList si = ui->blockView->scene()->selectedItems(); + QList si = ui->blockView->scene()->selectedItems(); if (si.isEmpty()) return; - if (!qgraphicsitem_cast(si[0])) return; - if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Sender) - return; - applySender(qgraphicsitem_cast(si[0])); + if (!qgraphicsitem_cast(si[0])) return; + if (qgraphicsitem_cast(si[0])->propertyByName("__type").value.toInt() != __CV_Sender) return; + applySender(qgraphicsitem_cast(si[0])); } diff --git a/libs/piqt_widgets/piqt_connection_edit.h b/libs/piqt_widgets/piqt_connection_edit.h index e189ca6..8e2ae00 100644 --- a/libs/piqt_widgets/piqt_connection_edit.h +++ b/libs/piqt_widgets/piqt_connection_edit.h @@ -1,32 +1,33 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CONNECTION_EDIT_H #define CONNECTION_EDIT_H -#include #include "piconnection.h" #include "qad_piqt_utils_export.h" +#include + namespace Ui { - class ConnectionEdit; +class ConnectionEdit; } class FilterItem; @@ -35,18 +36,19 @@ class SenderItem; class QAD_PIQT_UTILS_EXPORT ConnectionEdit: public QDialog { Q_OBJECT + public: explicit ConnectionEdit(QWidget * parent = 0); ~ConnectionEdit(); - + QString configuration() const; QByteArray model() const; QString name() const; - + void setName(const QString & name); void addDevice(const QString & name, const QString & path); void setModel(const QByteArray & m); - + private: void accept(); void keyPressEvent(QKeyEvent *) {} @@ -55,14 +57,16 @@ private: void applySender(SenderItem * b); int getOptions() const; void setOptions(int o); - + Ui::ConnectionEdit * ui; PIConnection * conn; bool loading; int udevicenum; - + private slots: - void recreateRequest() {if (!loading) QMetaObject::invokeMethod(this, "recreateConnection", Qt::QueuedConnection);} + void recreateRequest() { + if (!loading) QMetaObject::invokeMethod(this, "recreateConnection", Qt::QueuedConnection); + } void on_buttonRemove_clicked(); void on_buttonClear_clicked(); void on_buttonFilterAdd_clicked(); @@ -73,10 +77,9 @@ private slots: void on_buttonSenderModify_clicked(); void on_comboSplit_currentIndexChanged(int index); void selectionChanged(); - + public slots: void recreateConnection(); - }; #endif // CONNECTION_EDIT_H diff --git a/libs/piqt_widgets/piqt_connection_view.cpp b/libs/piqt_widgets/piqt_connection_view.cpp index fe44203..eaa0d30 100644 --- a/libs/piqt_widgets/piqt_connection_view.cpp +++ b/libs/piqt_widgets/piqt_connection_view.cpp @@ -1,6 +1,8 @@ #include "piqt_connection_view.h" + #include "picodeinfo.h" #include "piqt.h" + #include @@ -11,7 +13,8 @@ DeviceItem::DeviceItem(): BlockItem() { setColor(QColor(192, 192, 255)); text_name = new AlignedTextItem(); text_path = new AlignedTextItem(); - QFont fnt(text_name->font()); fnt.setBold(true); + QFont fnt(text_name->font()); + fnt.setBold(true); text_name->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); text_name->setFont(fnt); text_name->setPos(0., -size().height() / 2.); @@ -29,19 +32,29 @@ DeviceItem::DeviceItem(): BlockItem() { void DeviceItem::rename() { QString ms; - BlockItemPin * pr = pinByText("read"), * pw = pinByText("write"); + BlockItemPin *pr = pinByText("read"), *pw = pinByText("write"); switch (mode()) { - case PIIODevice::ReadOnly: ms = "ro"; pr->show(); pw->hide(); break; - case PIIODevice::WriteOnly: ms = "wo"; pr->hide(); pw->show(); break; - case PIIODevice::ReadWrite: ms = "rw"; pr->show(); pw->show(); break; + case PIIODevice::ReadOnly: + ms = "ro"; + pr->show(); + pw->hide(); + break; + case PIIODevice::WriteOnly: + ms = "wo"; + pr->hide(); + pw->show(); + break; + case PIIODevice::ReadWrite: + ms = "rw"; + pr->show(); + pw->show(); + break; } text_name->setText(name() + " (" + ms + ")"); text_path->setText(path()); } - - FilterItem::FilterItem(): BlockItem() { addProperty(BlockItem::Property("__type", "", __CV_Filter)); addProperty(BlockItem::Property("bufferSize", "", 65536)); @@ -50,7 +63,8 @@ FilterItem::FilterItem(): BlockItem() { setColor(QColor(192, 255, 192)); text_name = new AlignedTextItem(); text_mode = new AlignedTextItem(); - QFont fnt(text_name->font()); fnt.setBold(true); + QFont fnt(text_name->font()); + fnt.setBold(true); text_name->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); text_name->setFont(fnt); text_name->setPos(0., -size().height() / 2.); @@ -71,9 +85,9 @@ void FilterItem::rename() { QString ms; PICodeInfo::EnumInfo * ei = PICodeInfo::enumsInfo->value("PIPacketExtractor::SplitMode", 0); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & i, ei->members) + piForeachC(PICodeInfo::EnumeratorInfo & i, ei->members) if (i.value == mode()) { -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) ms = PI2QString(i.name.toString()); #else ms = PI2QString(i.name); @@ -82,20 +96,18 @@ void FilterItem::rename() { } } text_mode->setText(ms); - } - - SenderItem::SenderItem(): BlockItem() { addProperty(BlockItem::Property("__type", "", __CV_Sender)); setSize(140, 80); setPos(-200, 0); setColor(QColor(255, 192, 192)); - text_name = new AlignedTextItem(); + text_name = new AlignedTextItem(); text_frequency = new AlignedTextItem(); - QFont fnt(text_name->font()); fnt.setBold(true); + QFont fnt(text_name->font()); + fnt.setBold(true); text_name->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); text_name->setFont(fnt); text_name->setPos(0., -size().height() / 2.); @@ -116,14 +128,10 @@ void SenderItem::rename() { } +ConnectionView::ConnectionView(QWidget * parent): BlockView(parent) {} -ConnectionView::ConnectionView(QWidget * parent): BlockView(parent) { -} - - -ConnectionView::~ConnectionView() { -} +ConnectionView::~ConnectionView() {} DeviceItem * ConnectionView::addDevice(const QString & name, const QString & path) { @@ -166,10 +174,9 @@ SenderItem * ConnectionView::addSender(const QString & name) { DeviceItem * ConnectionView::findDevice(const QString & name) const { - QList blockl = blocks(); - foreach (BlockItem * b, blockl) - if ((b->propertyByName("name").value == name) && (b->propertyByName("__type").value.toInt() == __CV_Device)) - return (DeviceItem*)b; + QList blockl = blocks(); + foreach(BlockItem * b, blockl) + if ((b->propertyByName("name").value == name) && (b->propertyByName("__type").value.toInt() == __CV_Device)) return (DeviceItem *)b; return 0; } @@ -179,14 +186,14 @@ void ConnectionView::loadBus(BlockBusItem * bus) { } -void ConnectionView::placeBlock(BlockItem * b, QList coll) { +void ConnectionView::placeBlock(BlockItem * b, QList coll) { if (coll.isEmpty()) return; QList collr; - foreach (BlockItem * i, coll) + foreach(BlockItem * i, coll) collr << i->sceneBoundingRect(); while (true) { QRectF br = b->sceneBoundingRect(); - bool ok = true; + bool ok = true; for (int i = 0; i < collr.size(); ++i) if (br.intersects(collr[i])) { ok = false; @@ -199,10 +206,9 @@ void ConnectionView::placeBlock(BlockItem * b, QList coll) { } -QList ConnectionView::allByType(int type_) const { - QList blockl = blocks(), ret; - foreach (BlockItem * b, blockl) - if (b->propertyByName("__type").value.toInt() == type_) - ret << b; +QList ConnectionView::allByType(int type_) const { + QList blockl = blocks(), ret; + foreach(BlockItem * b, blockl) + if (b->propertyByName("__type").value.toInt() == type_) ret << b; return ret; } diff --git a/libs/piqt_widgets/piqt_connection_view.h b/libs/piqt_widgets/piqt_connection_view.h index 76e9618..a63dcf5 100644 --- a/libs/piqt_widgets/piqt_connection_view.h +++ b/libs/piqt_widgets/piqt_connection_view.h @@ -1,20 +1,20 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CONNECTION_VIEW_H @@ -32,102 +32,150 @@ const int __CV_Sender = 3; class QAD_PIQT_UTILS_EXPORT DeviceItem: public BlockItem { public: DeviceItem(); - - void setName(const QString & n) {addProperty(BlockItem::Property("name", "", n)); rename();} - void setPath(const QString & p) {addProperty(BlockItem::Property("device", "", p)); rename();} - void setMode(PIIODevice::DeviceMode m) {addProperty(BlockItem::Property("mode", "", int(m))); rename();} - void setOptions(PIIODevice::DeviceOptions o) {addProperty(BlockItem::Property("options", "", int(o))); rename();} - void setDisconnectTimeout(double v) {addProperty(BlockItem::Property("disconnectTimeout", "", v)); rename();} - void setBufferSize(int v) {addProperty(BlockItem::Property("bufferSize", "", v)); rename();} - - QString name() const {return propertyByName("name").value.toString();} - QString path() const {return propertyByName("device").value.toString();} - PIIODevice::DeviceMode mode() const {return PIIODevice::DeviceMode(propertyByName("mode").value.toInt());} - PIIODevice::DeviceOptions options() const {return PIIODevice::DeviceOptions(propertyByName("options").value.toInt());} - double disconnectTimeout() const {return propertyByName("disconnectTimeout").value.toDouble();} - int bufferSize() const {return propertyByName("bufferSize").value.toInt();} - + + void setName(const QString & n) { + addProperty(BlockItem::Property("name", "", n)); + rename(); + } + void setPath(const QString & p) { + addProperty(BlockItem::Property("device", "", p)); + rename(); + } + void setMode(PIIODevice::DeviceMode m) { + addProperty(BlockItem::Property("mode", "", int(m))); + rename(); + } + void setOptions(PIIODevice::DeviceOptions o) { + addProperty(BlockItem::Property("options", "", int(o))); + rename(); + } + void setDisconnectTimeout(double v) { + addProperty(BlockItem::Property("disconnectTimeout", "", v)); + rename(); + } + void setBufferSize(int v) { + addProperty(BlockItem::Property("bufferSize", "", v)); + rename(); + } + + QString name() const { return propertyByName("name").value.toString(); } + QString path() const { return propertyByName("device").value.toString(); } + PIIODevice::DeviceMode mode() const { return PIIODevice::DeviceMode(propertyByName("mode").value.toInt()); } + PIIODevice::DeviceOptions options() const { return PIIODevice::DeviceOptions(propertyByName("options").value.toInt()); } + double disconnectTimeout() const { return propertyByName("disconnectTimeout").value.toDouble(); } + int bufferSize() const { return propertyByName("bufferSize").value.toInt(); } + void rename(); - + protected: - AlignedTextItem * text_name, * text_path; - + AlignedTextItem *text_name, *text_path; }; class QAD_PIQT_UTILS_EXPORT FilterItem: public BlockItem { public: FilterItem(); - - void setName(const QString & n) {addProperty(BlockItem::Property("name", "", n)); rename();} - void setMode(PIPacketExtractor::SplitMode m) {addProperty(BlockItem::Property("mode", "", int(m))); rename();} - void setHeader(const QString & v) {addProperty(BlockItem::Property("header", "", v)); rename();} - void setFooter(const QString & v) {addProperty(BlockItem::Property("footer", "", v)); rename();} - void setTimeout(double v) {addProperty(BlockItem::Property("timeout", "", v)); rename();} - void setPacketSize(int v) {addProperty(BlockItem::Property("size", "", v)); rename();} - void setDisconnectTimeout(double v) {addProperty(BlockItem::Property("disconnectTimeout", "", v)); rename();} - void setBufferSize(int v) {addProperty(BlockItem::Property("bufferSize", "", v)); rename();} - QString name() const {return propertyByName("name").value.toString();} - PIPacketExtractor::SplitMode mode() const {return PIPacketExtractor::SplitMode(propertyByName("mode").value.toInt());} - QString header() const {return propertyByName("header").value.toString();} - QString footer() const {return propertyByName("footer").value.toString();} - double timeout() const {return propertyByName("timeout").value.toDouble();} - int packetSize() const {return propertyByName("size").value.toInt();} - double disconnectTimeout() const {return propertyByName("disconnectTimeout").value.toDouble();} - int bufferSize() const {return propertyByName("bufferSize").value.toInt();} + void setName(const QString & n) { + addProperty(BlockItem::Property("name", "", n)); + rename(); + } + void setMode(PIPacketExtractor::SplitMode m) { + addProperty(BlockItem::Property("mode", "", int(m))); + rename(); + } + void setHeader(const QString & v) { + addProperty(BlockItem::Property("header", "", v)); + rename(); + } + void setFooter(const QString & v) { + addProperty(BlockItem::Property("footer", "", v)); + rename(); + } + void setTimeout(double v) { + addProperty(BlockItem::Property("timeout", "", v)); + rename(); + } + void setPacketSize(int v) { + addProperty(BlockItem::Property("size", "", v)); + rename(); + } + void setDisconnectTimeout(double v) { + addProperty(BlockItem::Property("disconnectTimeout", "", v)); + rename(); + } + void setBufferSize(int v) { + addProperty(BlockItem::Property("bufferSize", "", v)); + rename(); + } + + QString name() const { return propertyByName("name").value.toString(); } + PIPacketExtractor::SplitMode mode() const { return PIPacketExtractor::SplitMode(propertyByName("mode").value.toInt()); } + QString header() const { return propertyByName("header").value.toString(); } + QString footer() const { return propertyByName("footer").value.toString(); } + double timeout() const { return propertyByName("timeout").value.toDouble(); } + int packetSize() const { return propertyByName("size").value.toInt(); } + double disconnectTimeout() const { return propertyByName("disconnectTimeout").value.toDouble(); } + int bufferSize() const { return propertyByName("bufferSize").value.toInt(); } void rename(); - + protected: - AlignedTextItem * text_name, * text_mode; - + AlignedTextItem *text_name, *text_mode; }; class QAD_PIQT_UTILS_EXPORT SenderItem: public BlockItem { public: SenderItem(); - - void setName(const QString & n) {addProperty(BlockItem::Property("name", "", n)); rename();} - void setData(const QString & p) {addProperty(BlockItem::Property("data", "", p)); rename();} - void setFrequency(double m) {addProperty(BlockItem::Property("frequency", "", m)); rename();} - - QString name() const {return propertyByName("name").value.toString();} - QString data() const {return propertyByName("data").value.toString();} - double frequency() const {return propertyByName("frequency").value.toDouble();} - + + void setName(const QString & n) { + addProperty(BlockItem::Property("name", "", n)); + rename(); + } + void setData(const QString & p) { + addProperty(BlockItem::Property("data", "", p)); + rename(); + } + void setFrequency(double m) { + addProperty(BlockItem::Property("frequency", "", m)); + rename(); + } + + QString name() const { return propertyByName("name").value.toString(); } + QString data() const { return propertyByName("data").value.toString(); } + double frequency() const { return propertyByName("frequency").value.toDouble(); } + void rename(); - + protected: - AlignedTextItem * text_name, * text_frequency; - + AlignedTextItem *text_name, *text_frequency; }; class QAD_PIQT_UTILS_EXPORT ConnectionView: public BlockView { Q_OBJECT + public: explicit ConnectionView(QWidget * parent = 0); ~ConnectionView(); - + DeviceItem * addDevice(const QString & name, const QString & path); FilterItem * addFilter(const QString & name); SenderItem * addSender(const QString & name); DeviceItem * findDevice(const QString & name) const; - QList allDevices() const {return allByType(__CV_Device);} - QList allFilters() const {return allByType(__CV_Filter);} - QList allSenders() const {return allByType(__CV_Sender);} - + QList allDevices() const { return allByType(__CV_Device); } + QList allFilters() const { return allByType(__CV_Filter); } + QList allSenders() const { return allByType(__CV_Sender); } + private: - QSize sizeHint() const {return QSize(800, 600);} + QSize sizeHint() const { return QSize(800, 600); } void loadBus(BlockBusItem * bus); - void placeBlock(BlockItem * b, QList coll); - - QList allByType(int type_) const; - + void placeBlock(BlockItem * b, QList coll); + + QList allByType(int type_) const; + private slots: - }; #endif // CONNECTION_VIEW_H diff --git a/libs/piqt_widgets/piqt_highlighter.cpp b/libs/piqt_widgets/piqt_highlighter.cpp index da94d1d..c42f6f7 100644 --- a/libs/piqt_widgets/piqt_highlighter.cpp +++ b/libs/piqt_widgets/piqt_highlighter.cpp @@ -6,30 +6,30 @@ ConfigHighlighter::ConfigHighlighter(QTextDocument * parent): QSyntaxHighlighter valueNameFormat.setForeground(QColor(0, 64, 154)); rule.pattern = QRegularExpression("[^=]"); //"\\b[A-Za-z0-9_]+(?=\\()"); - rule.format = valueNameFormat; + rule.format = valueNameFormat; highlightingRules.append(rule); valueFormat.setForeground(QColor(192, 0, 0)); rule.pattern = QRegularExpression("=[^\n]*"); - rule.format = valueFormat; + rule.format = valueFormat; highlightingRules.append(rule); equalFormat.setFontWeight(QFont::Bold); equalFormat.setForeground(QColor(96, 126, 0)); rule.pattern = QRegularExpression("="); - rule.format = equalFormat; + rule.format = equalFormat; highlightingRules.append(rule); sectionFormat.setFontWeight(QFont::Bold); sectionFormat.setForeground(QColor(0, 32, 64)); rule.pattern = QRegularExpression("\\[.*\\]"); - rule.format = sectionFormat; + rule.format = sectionFormat; highlightingRules.append(rule); substFormat.setForeground(QColor(192, 0, 192)); rule.pattern = QRegularExpression("\\$\\{.*\\}+"); - //rule.pattern.setMinimal(true); - rule.format = substFormat; + // rule.pattern.setMinimal(true); + rule.format = substFormat; highlightingRules.append(rule); rule.pattern = QRegularExpression("\\$\\{[^\\{]*\\}+"); highlightingRules.append(rule); @@ -37,18 +37,18 @@ ConfigHighlighter::ConfigHighlighter(QTextDocument * parent): QSyntaxHighlighter singleLineCommentFormat.setFontItalic(true); singleLineCommentFormat.setForeground(QColor(128, 128, 128)); rule.pattern = QRegularExpression("#[^\n]*"); - rule.format = singleLineCommentFormat; + rule.format = singleLineCommentFormat; highlightingRules.append(rule); spaceFormat.setForeground(QColor(210, 210, 210)); - - //commentStartExpression = QRegExp("/\\*"); - //commentEndExpression = QRegExp("\\*/"); + + // commentStartExpression = QRegExp("/\\*"); + // commentEndExpression = QRegExp("\\*/"); } void ConfigHighlighter::highlightBlock(const QString & text) { - foreach (const HighlightingRule &rule, highlightingRules) { + foreach(const HighlightingRule & rule, highlightingRules) { QRegularExpression expression(rule.pattern); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QRegularExpressionMatchIterator i = expression.globalMatch(text); @@ -66,7 +66,7 @@ void ConfigHighlighter::highlightBlock(const QString & text) { #endif } setCurrentBlockState(0); - + QRegularExpression expression("[ |\t]"); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QRegularExpressionMatchIterator i = expression.globalMatch(text); diff --git a/libs/piqt_widgets/piqt_highlighter.h b/libs/piqt_widgets/piqt_highlighter.h index 557ced3..20c06c0 100644 --- a/libs/piqt_widgets/piqt_highlighter.h +++ b/libs/piqt_widgets/piqt_highlighter.h @@ -1,49 +1,49 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CONF_HIGHLIGHTER_H #define CONF_HIGHLIGHTER_H #include -#include #include +#include #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) # include #else # include - typedef QRegExp QRegularExpression; +typedef QRegExp QRegularExpression; #endif #include "qad_piqt_utils_export.h" class QTextDocument; -class QAD_PIQT_UTILS_EXPORT ConfigHighlighter : public QSyntaxHighlighter -{ +class QAD_PIQT_UTILS_EXPORT ConfigHighlighter: public QSyntaxHighlighter { Q_OBJECT + public: - ConfigHighlighter(QTextDocument *parent = 0); + ConfigHighlighter(QTextDocument * parent = 0); QTextCursor cursor; private: - void highlightBlock(const QString &text); - + void highlightBlock(const QString & text); + struct QAD_PIQT_UTILS_EXPORT HighlightingRule { QRegularExpression pattern; QTextCharFormat format; diff --git a/libs/piqt_widgets/piqt_iodevice_edit.cpp b/libs/piqt_widgets/piqt_iodevice_edit.cpp index 1eb8355..bfb9a66 100644 --- a/libs/piqt_widgets/piqt_iodevice_edit.cpp +++ b/libs/piqt_widgets/piqt_iodevice_edit.cpp @@ -1,17 +1,19 @@ #include "piqt_iodevice_edit.h" + #include "piqt_iodevice_edit_dialog.h" #include "qvariantedit_custom.h" + +#include #include #include -#include -#include #include +#include IODeviceEdit::IODeviceEdit(QWidget * parent): QWidget(parent) { - dlg = new IODeviceEditDialog(); + dlg = new IODeviceEditDialog(); line = new QLineEdit(); - btn = new QToolButton(); + btn = new QToolButton(); setLayout(new QBoxLayout(QBoxLayout::LeftToRight)); layout()->setContentsMargins(0, 0, 0, 0); layout()->addWidget(line); @@ -65,11 +67,10 @@ void IODeviceEdit::buttonDlg_clicked() { } - class Factory: public QVariantEditorFactoryBase { public: Factory() {} - virtual QWidget * createEditor() {return new IODeviceEdit();} + virtual QWidget * createEditor() { return new IODeviceEdit(); } }; @@ -81,11 +82,11 @@ __IODeviceEditRegistrator__::__IODeviceEditRegistrator__() { void QAD_IODevice_toString(const QVariant & v, QString & r) { PIVariantTypes::IODevice sd = Q2PIVariant(v).toIODevice(); -// piCout << sd; - PIIODevice * rd = PIIODevice::createFromVariant(sd); + // piCout << sd; + PIIODevice * rd = PIIODevice::createFromVariant(sd); if (rd) { PIString ps = rd->constructFullPath(); - r = PI2QString(ps); + r = PI2QString(ps); } else { piCout << "error in " << sd; } diff --git a/libs/piqt_widgets/piqt_iodevice_edit.h b/libs/piqt_widgets/piqt_iodevice_edit.h index 9da0496..19560f1 100644 --- a/libs/piqt_widgets/piqt_iodevice_edit.h +++ b/libs/piqt_widgets/piqt_iodevice_edit.h @@ -1,28 +1,29 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef PIQT_IODEVICE_EDIT_H #define PIQT_IODEVICE_EDIT_H -#include -#include "qad_types.h" #include "qad_piqt_utils_export.h" +#include "qad_types.h" + +#include class QLineEdit; class QToolButton; @@ -33,13 +34,14 @@ class QAD_PIQT_UTILS_EXPORT IODeviceEdit: public QWidget { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + public: explicit IODeviceEdit(QWidget * parent = 0); ~IODeviceEdit(); - + QVariant value() const; bool isReadOnly() const; - + private: void setDevice(const QAD::IODevice & d); @@ -47,7 +49,7 @@ private: QToolButton * btn; IODeviceEditDialog * dlg; QAD::IODevice dev; - + public slots: void setValue(const QVariant & v); void setReadOnly(bool yes); @@ -57,7 +59,6 @@ private slots: signals: void valueChanged(); - }; diff --git a/libs/piqt_widgets/piqt_iodevice_edit_dialog.cpp b/libs/piqt_widgets/piqt_iodevice_edit_dialog.cpp index 4100cd2..0f5644e 100644 --- a/libs/piqt_widgets/piqt_iodevice_edit_dialog.cpp +++ b/libs/piqt_widgets/piqt_iodevice_edit_dialog.cpp @@ -1,8 +1,10 @@ -#include "ui_piqt_iodevice_edit_dialog.h" #include "piqt_iodevice_edit_dialog.h" -#include "piqt.h" + #include "picodeinfo.h" #include "piiodevice.h" +#include "piqt.h" +#include "ui_piqt_iodevice_edit_dialog.h" + #include @@ -11,9 +13,10 @@ IODeviceEditDialog::IODeviceEditDialog(QWidget * parent): QDialog(parent) { ui->setupUi(this); PICodeInfo::EnumInfo * ei = PICodeInfo::enumsInfo->value("PIIODevice::DeviceMode"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) - ui->comboMode->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) + ui->comboMode->addItem(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")"), + QVariant::fromValue(e.value)); #else ui->comboMode->addItem(PI2QString(e.name + " (" + PIString::fromNumber(e.value) + ")"), QVariant::fromValue(e.value)); #endif @@ -21,9 +24,9 @@ IODeviceEditDialog::IODeviceEditDialog(QWidget * parent): QDialog(parent) { ui->comboMode->setCurrentIndex(ui->comboMode->count() - 1); ei = PICodeInfo::enumsInfo->value("PIIODevice::DeviceOption"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) { + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) { QCheckBox * cb = new QCheckBox(); -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) cb->setText(PI2QString(e.name.toString() + " (" + PIString::fromNumber(e.value) + ")")); #else cb->setText(PI2QString(e.name + " (" + PIString::fromNumber(e.value) + ")")); @@ -33,23 +36,21 @@ IODeviceEditDialog::IODeviceEditDialog(QWidget * parent): QDialog(parent) { } } PIStringList pl = PIIODevice::availablePrefixes(); - piForeachC (PIString & p, pl) { + piForeachC(PIString & p, pl) { ui->comboType->addItem(PI2QString(p)); } } -IODeviceEditDialog::~IODeviceEditDialog() { -} +IODeviceEditDialog::~IODeviceEditDialog() {} int IODeviceEditDialog::getOptions() const { int ret = 0; for (int i = 0; i < ui->layoutOptions->count(); ++i) { - QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); + QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); if (!cb) continue; - if (cb->isChecked()) - ret |= cb->property("__value").toInt(); + if (cb->isChecked()) ret |= cb->property("__value").toInt(); } return ret; } @@ -57,7 +58,7 @@ int IODeviceEditDialog::getOptions() const { void IODeviceEditDialog::setOptions(int o) { for (int i = 0; i < ui->layoutOptions->count(); ++i) { - QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); + QCheckBox * cb = qobject_cast(ui->layoutOptions->itemAt(i)->widget()); if (!cb) continue; int cbf = cb->property("__value").toInt(); cb->setChecked((o & cbf) == cbf); @@ -67,7 +68,7 @@ void IODeviceEditDialog::setOptions(int o) { void IODeviceEditDialog::on_comboType_currentIndexChanged(int index) { PIString prefix = Q2PIString(ui->comboType->currentText()); - auto * d = PIIODevice::createFromFullPath(prefix + "://"); + auto * d = PIIODevice::createFromFullPath(prefix + "://"); if (d) { ps = PI2QPropertyStorage(d->constructVariant().get()); ui->widgetProperties->setStorage(&ps); @@ -78,8 +79,7 @@ void IODeviceEditDialog::on_comboType_currentIndexChanged(int index) { QAD::IODevice IODeviceEditDialog::getIODevice(const QAD::IODevice & d) { setValue(d); - if (QDialog::exec() != QDialog::Accepted) - return QAD::IODevice(); + if (QDialog::exec() != QDialog::Accepted) return QAD::IODevice(); return value(); } @@ -87,10 +87,10 @@ QAD::IODevice IODeviceEditDialog::getIODevice(const QAD::IODevice & d) { QAD::IODevice IODeviceEditDialog::value() const { QAD::IODevice d; ui->widgetProperties->applyProperties(); - d.prefix = ui->comboType->currentText(); - d.mode = ui->comboMode->itemData(ui->comboMode->currentIndex()).toInt(); + d.prefix = ui->comboType->currentText(); + d.mode = ui->comboMode->itemData(ui->comboMode->currentIndex()).toInt(); d.options = getOptions(); - d.props = ps; + d.props = ps; return d; } diff --git a/libs/piqt_widgets/piqt_iodevice_edit_dialog.h b/libs/piqt_widgets/piqt_iodevice_edit_dialog.h index 89eb3d8..f278759 100644 --- a/libs/piqt_widgets/piqt_iodevice_edit_dialog.h +++ b/libs/piqt_widgets/piqt_iodevice_edit_dialog.h @@ -1,40 +1,42 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef PIQT_IODEVICE_EDIT_DIALOG_H #define PIQT_IODEVICE_EDIT_DIALOG_H -#include -#include "qad_types.h" #include "propertystorage.h" #include "qad_piqt_utils_export.h" +#include "qad_types.h" + +#include namespace Ui { - class IODeviceEditDialog; +class IODeviceEditDialog; } class QAD_PIQT_UTILS_EXPORT IODeviceEditDialog: public QDialog { Q_OBJECT + public: explicit IODeviceEditDialog(QWidget * parent = 0); ~IODeviceEditDialog(); - + QAD::IODevice getIODevice(const QAD::IODevice & d); private: @@ -45,10 +47,9 @@ private: PropertyStorage ps; Ui::IODeviceEditDialog * ui; - + private slots: void on_comboType_currentIndexChanged(int index); - }; #endif // PIQT_IODEVICE_EDIT_DIALOG_H diff --git a/libs/piqt_widgets/pivaluetree_edit.cpp b/libs/piqt_widgets/pivaluetree_edit.cpp index d50e82b..d1be70a 100644 --- a/libs/piqt_widgets/pivaluetree_edit.cpp +++ b/libs/piqt_widgets/pivaluetree_edit.cpp @@ -104,7 +104,7 @@ void PIValueTreeEdit::build() { widget_array = new QWidget(); ui_array->setupUi(widget_array); ui_array->spinCount->setRange(source.attribute(PIValueTree::attributeArrayMinCount, 0).toInt(), - source.attribute(PIValueTree::attributeArrayMaxCount, 65536).toInt()); + source.attribute(PIValueTree::attributeArrayMaxCount, 65536).toInt()); ui_array->spinCount->setValue(source.children().size_s()); ui_array->widgetEdit->setVisible(source.attribute(PIValueTree::attributeArrayResize, false).toBool()); ui_array->layoutArray->addWidget(grid); diff --git a/libs/piqt_widgets/pivaluetree_edit.h b/libs/piqt_widgets/pivaluetree_edit.h index 967a3b3..ec38c57 100644 --- a/libs/piqt_widgets/pivaluetree_edit.h +++ b/libs/piqt_widgets/pivaluetree_edit.h @@ -1,20 +1,20 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef pivaluetree_edit_H diff --git a/libs/piqt_widgets/pivariant_edit.h b/libs/piqt_widgets/pivariant_edit.h index 013d157..3787014 100644 --- a/libs/piqt_widgets/pivariant_edit.h +++ b/libs/piqt_widgets/pivariant_edit.h @@ -1,20 +1,20 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef pivariant_edit_H diff --git a/libs/piqt_widgets/pivariant_edit_widgets.cpp b/libs/piqt_widgets/pivariant_edit_widgets.cpp index 3f6cde0..a4c3c03 100644 --- a/libs/piqt_widgets/pivariant_edit_widgets.cpp +++ b/libs/piqt_widgets/pivariant_edit_widgets.cpp @@ -36,7 +36,7 @@ PIVariantMap PIVariantEditors::Int::defaultAttributes() const { void PIVariantEditors::Int::applyAttributes(const PIVariantMap & a) { widget->setRange(a.value(PIValueTree::attributeMinimum, widget->minimum()).toInt(), - a.value(PIValueTree::attributeMaximum, widget->maximum()).toInt()); + a.value(PIValueTree::attributeMaximum, widget->maximum()).toInt()); widget->setSingleStep(a.value(PIValueTree::attributeSingleStep, widget->singleStep()).toInt()); widget->setPrefix(PI2QString(a.value(PIValueTree::attributePrefix, Q2PIString(widget->prefix())).toString())); widget->setSuffix(PI2QString(a.value(PIValueTree::attributeSuffix, Q2PIString(widget->suffix())).toString())); @@ -60,7 +60,7 @@ PIVariantMap PIVariantEditors::Double::defaultAttributes() const { void PIVariantEditors::Double::applyAttributes(const PIVariantMap & a) { widget->setRange(a.value(PIValueTree::attributeMinimum, widget->minimum()).toDouble(), - a.value(PIValueTree::attributeMaximum, widget->maximum()).toDouble()); + a.value(PIValueTree::attributeMaximum, widget->maximum()).toDouble()); widget->setSingleStep(a.value(PIValueTree::attributeSingleStep, widget->singleStep()).toDouble()); widget->setDecimals(a.value(PIValueTree::attributeDecimals, widget->decimals()).toInt()); widget->setPrefix(PI2QString(a.value(PIValueTree::attributePrefix, Q2PIString(widget->prefix())).toString())); diff --git a/libs/piqt_widgets/pivariant_edit_widgets.h b/libs/piqt_widgets/pivariant_edit_widgets.h index a39d9bf..e4adff3 100644 --- a/libs/piqt_widgets/pivariant_edit_widgets.h +++ b/libs/piqt_widgets/pivariant_edit_widgets.h @@ -1,20 +1,20 @@ /* - PIQt Utils - Qt utilites for PIP + PIQt Utils - Qt utilites for PIP - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef pivariant_edit_widgets_H diff --git a/libs/qglview/glcamera.cpp b/libs/qglview/glcamera.cpp index 78f4b1f..9b43af4 100644 --- a/libs/qglview/glcamera.cpp +++ b/libs/qglview/glcamera.cpp @@ -1,6 +1,6 @@ /* QGLView - Ivan Pelipenko peri4ko@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -21,20 +21,20 @@ Camera::Camera() { - type_ = glCamera; - fov_ = 60.; + type_ = glCamera; + fov_ = 60.; angle_limit_lower_xy = 0.f; angle_limit_upper_xy = 360.f; angles_.setY(270.f); depth_start = 0.1f; - depth_end = 1000.f; + depth_end = 1000.f; mirror_x = mirror_y = false; } void Camera::anglesFromPoints() { QVector3D dv = aim_ - pos_, tv; - tv = QVector3D(dv.x(), dv.y(), 0.); + tv = QVector3D(dv.x(), dv.y(), 0.); angles_.setZ(atan2f(tv.x(), tv.y()) * rad2deg); angles_.setY(piClamp(atan2f(tv.length(), dv.z()) * rad2deg, angle_limit_lower_xy, angle_limit_upper_xy) + 180.f); } @@ -42,12 +42,11 @@ void Camera::anglesFromPoints() { void Camera::apply(const GLfloat & aspect) { glMatrixMode(GL_PROJECTION); - if (aspect <= 1.f) - glScalef(aspect, aspect, 1.f); + if (aspect <= 1.f) glScalef(aspect, aspect, 1.f); QMatrix4x4 pm = glMatrixPerspective(fov_, aspect, depth_start, depth_end); - //pm.perspective(fov_, aspect, depth_start, depth_end); - //qDebug() << pm;// << glMatrixPerspective(fov_, aspect, depth_start, depth_end); - //qDebug() << pm; + // pm.perspective(fov_, aspect, depth_start, depth_end); + // qDebug() << pm;// << glMatrixPerspective(fov_, aspect, depth_start, depth_end); + // qDebug() << pm; setGLMatrix(pm); glMatrixMode(GL_MODELVIEW); pm.setToIdentity(); @@ -55,17 +54,17 @@ void Camera::apply(const GLfloat & aspect) { pm.rotate(angles_.y(), 1., 0., 0.); pm.rotate(angles_.x(), 0., 1., 0.); pm.rotate(angles_.z(), 0., 0., 1.); - //pm.translate(-aim_); + // pm.translate(-aim_); if (parent_) { QMatrix4x4 pmat = parent_->worldTransform(); - offset_ = pmat.column(3).toVector3D(); + offset_ = pmat.column(3).toVector3D(); pmat(0, 3) = pmat(1, 3) = pmat(2, 3) = 0.; pmat.translate(aim_); pm *= pmat.inverted(); - //qDebug() << pmat; + // qDebug() << pmat; } setGLMatrix(pm); - //qDebug() << angles_; + // qDebug() << angles_; } @@ -77,65 +76,65 @@ QMatrix4x4 Camera::offsetMatrix() const { /* void Camera::localTransform(QMatrix4x4 & m) { - return; - if (parent_) - m *= parent_->worldTransform(); - QMatrix4x4 ret; - //qDebug() << "local camera"; - ret.translate(0., 0., -distance()); - ret.rotate(angles_.y(), 1., 0., 0.); - ret.rotate(angles_.x(), 0., 1., 0.); - ret.rotate(angles_.z(), 0., 0., 1.); - //m *= ret.inverted(); + return; + if (parent_) + m *= parent_->worldTransform(); + QMatrix4x4 ret; + //qDebug() << "local camera"; + ret.translate(0., 0., -distance()); + ret.rotate(angles_.y(), 1., 0., 0.); + ret.rotate(angles_.x(), 0., 1., 0.); + ret.rotate(angles_.z(), 0., 0., 1.); + //m *= ret.inverted(); } */ void Camera::assign(const Camera & c) { - pos_ = c.pos_; - aim_ = c.aim_; - fov_ = c.fov_; - angles_ = c.angles_; + pos_ = c.pos_; + aim_ = c.aim_; + fov_ = c.fov_; + angles_ = c.angles_; angle_limit_lower_xy = c.angle_limit_lower_xy; angle_limit_upper_xy = c.angle_limit_upper_xy; - mirror_x = c.mirror_x; - mirror_y = c.mirror_y; - depth_start = c.depth_start; - depth_end = c.depth_end; + mirror_x = c.mirror_x; + mirror_y = c.mirror_y; + depth_start = c.depth_start; + depth_end = c.depth_end; buildTransform(); } GLObjectBase * Camera::clone(bool withChildren) { Camera * o = new Camera(*this); - //GLObjectBase::clone(withChildren); + // GLObjectBase::clone(withChildren); o->is_init = false; - o->name_ = name_ + "_copy"; - o->view_ = nullptr; + o->name_ = name_ + "_copy"; + o->view_ = nullptr; o->children_.clear(); if (withChildren) { for (int i = 0; i < children_.size(); ++i) o->addChild(children_[i]->clone(withChildren)); } - o->pos_ = pos_; - o->aim_ = aim_; - o->fov_ = fov_; - o->angles_ = angles_; + o->pos_ = pos_; + o->aim_ = aim_; + o->fov_ = fov_; + o->angles_ = angles_; o->angle_limit_lower_xy = angle_limit_lower_xy; o->angle_limit_upper_xy = angle_limit_upper_xy; - o->mirror_x = mirror_x; - o->mirror_y = mirror_y; - o->depth_start = depth_start; - o->depth_end = depth_end; - o->meta = meta; + o->mirror_x = mirror_x; + o->mirror_y = mirror_y; + o->depth_start = depth_start; + o->depth_end = depth_end; + o->meta = meta; return o; } void Camera::panZ(const float & a) { QVector3D dv = aim_ - pos_; - float tl = QVector2D(dv.x(), dv.y()).length(); + float tl = QVector2D(dv.x(), dv.y()).length(); angles_.setZ(angles_.z() + a); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); aim_ = pos_ + dv; buildTransform(); } @@ -143,11 +142,11 @@ void Camera::panZ(const float & a) { void Camera::panXY(const float & a) { QVector3D dv = aim_ - pos_; - float tl = dv.length(), tc; + float tl = dv.length(), tc; angles_.setY(angles_.y() + a); angles_.setY(piClamp(angles_.y(), angle_limit_lower_xy, angle_limit_upper_xy)); - tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + tc = -sinf(angles_.y() * deg2rad); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); aim_ = pos_ + dv * tl; buildTransform(); } @@ -155,9 +154,9 @@ void Camera::panXY(const float & a) { void Camera::rotateZ(const float & a) { QVector3D dv = aim_ - pos_; - float tl = QVector2D(dv.x(), dv.y()).length(); + float tl = QVector2D(dv.x(), dv.y()).length(); angles_.setZ(angles_.z() + a); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); aim_ = pos_ + dv; buildTransform(); } @@ -165,11 +164,11 @@ void Camera::rotateZ(const float & a) { void Camera::rotateXY(const float & a) { QVector3D dv = aim_ - pos_; - float tl = dv.length(), tc; + float tl = dv.length(), tc; angles_.setY(angles_.y() + a); angles_.setY(piClamp(angles_.y(), angle_limit_lower_xy, angle_limit_upper_xy)); - tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + tc = -sinf(angles_.y() * deg2rad); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); aim_ = pos_ + dv * tl; buildTransform(); } @@ -177,9 +176,9 @@ void Camera::rotateXY(const float & a) { void Camera::orbitZ(const float & a) { QVector3D dv = aim_ - pos_; - float tl = QVector2D(dv.x(), dv.y()).length(); + float tl = QVector2D(dv.x(), dv.y()).length(); angles_.setZ(angles_.z() + a); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); pos_ = aim_ - dv; buildTransform(); } @@ -187,11 +186,11 @@ void Camera::orbitZ(const float & a) { void Camera::orbitXY(const float & a) { QVector3D dv = aim_ - pos_; - float tl = dv.length(), tc; + float tl = dv.length(), tc; angles_.setY(angles_.y() + a); angles_.setY(piClamp(angles_.y(), angle_limit_lower_xy, angle_limit_upper_xy)); - tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + tc = -sinf(angles_.y() * deg2rad); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); pos_ = aim_ - dv * tl; buildTransform(); } @@ -199,9 +198,9 @@ void Camera::orbitXY(const float & a) { void Camera::setAngleZ(const float & a) { QVector3D dv = aim_ - pos_; - float tl = QVector2D(dv.x(), dv.y()).length(); + float tl = QVector2D(dv.x(), dv.y()).length(); angles_.setZ(a); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tl, cosf(angles_.z() * deg2rad) * tl, dv.z()); aim_ = pos_ + dv; buildTransform(); } @@ -209,21 +208,21 @@ void Camera::setAngleZ(const float & a) { void Camera::setAngleXY(const float & a) { QVector3D dv = aim_ - pos_; - float tl = dv.length(), tc; + float tl = dv.length(), tc; angles_.setY(a); - tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); - //pos_ = aim_ - dv; + tc = -sinf(angles_.y() * deg2rad); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + // pos_ = aim_ - dv; aim_ = pos_ + dv * tl; buildTransform(); - //anglesFromPoints(); + // anglesFromPoints(); } void Camera::moveForward(const float & x, bool withZ) { - QVector3D dv;// = aim_ - pos_; + QVector3D dv; // = aim_ - pos_; float tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, 0.); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, 0.); if (withZ) dv.setZ(-cosf(angles_.y() * deg2rad)); dv.normalize(); dv *= x; @@ -234,9 +233,9 @@ void Camera::moveForward(const float & x, bool withZ) { void Camera::moveLeft(const float & x, bool withZ) { - QVector3D dv;// = aim_ - pos_; + QVector3D dv; // = aim_ - pos_; float tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad - float(M_PI_2)) * tc, cosf(angles_.z() * deg2rad - float(M_PI_2)) * tc, 0.f); + dv = QVector3D(sinf(angles_.z() * deg2rad - float(M_PI_2)) * tc, cosf(angles_.z() * deg2rad - float(M_PI_2)) * tc, 0.f); if (withZ) dv.setZ(-sinf(angles_.x() * deg2rad)); dv.normalize(); dv *= x; @@ -252,7 +251,7 @@ void Camera::moveUp(const float & x, bool onlyZ) { dv = QVector3D(0., 0., x); else { float tc = cosf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -sinf(angles_.y() * deg2rad)); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -sinf(angles_.y() * deg2rad)); dv.normalize(); dv *= x; } @@ -265,7 +264,7 @@ void Camera::moveUp(const float & x, bool onlyZ) { void Camera::flyCloser(const float & s) { QVector3D dv = aim_ - pos_; float tl = dv.length() / (1.f + s), tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); pos_ = aim_ - dv * tl; buildTransform(); } @@ -274,7 +273,7 @@ void Camera::flyCloser(const float & s) { void Camera::flyFarer(const float & s) { QVector3D dv = aim_ - pos_; float tl = dv.length() * (1.f + s), tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); pos_ = aim_ - dv * tl; buildTransform(); } @@ -282,9 +281,8 @@ void Camera::flyFarer(const float & s) { void Camera::flyToDistance(const float & d) { QVector3D dv = aim_ - pos_; - float tc = -sinf(angles_.y() * deg2rad); - dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); - pos_ = aim_ - dv * d; + float tc = -sinf(angles_.y() * deg2rad); + dv = QVector3D(sinf(angles_.z() * deg2rad) * tc, cosf(angles_.z() * deg2rad) * tc, -cosf(angles_.y() * deg2rad)); + pos_ = aim_ - dv * d; buildTransform(); } - diff --git a/libs/qglview/glcamera.h b/libs/qglview/glcamera.h index 8adeb74..46fe177 100644 --- a/libs/qglview/glcamera.h +++ b/libs/qglview/glcamera.h @@ -1,6 +1,6 @@ /* QGLView - Ivan Pelipenko peri4ko@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -23,66 +23,101 @@ class Camera; -//extern QMatrix4x4 globCameraMatrix; -//extern Camera * currentCamera; +// extern QMatrix4x4 globCameraMatrix; +// extern Camera * currentCamera; -class Camera: public GLObjectBase -{ +class Camera: public GLObjectBase { friend class QGLView; friend class GLParticlesSystem; - friend QDataStream & operator <<(QDataStream & s, const GLObjectBase * p); - friend QDataStream & operator >>(QDataStream & s, GLObjectBase *& p); + friend QDataStream & operator<<(QDataStream & s, const GLObjectBase * p); + friend QDataStream & operator>>(QDataStream & s, GLObjectBase *& p); + public: Camera(); - void setPos(const QVector3D & p) {pos_ = p; anglesFromPoints(); buildTransform();} - void setAim(const QVector3D & p) {aim_ = p; anglesFromPoints(); buildTransform();} - void move(const QVector3D & p) {pos_ += p; aim_ += p; buildTransform();} - void move(const float & x, const float & y = 0., const float & z = 0.) {pos_ += QVector3D(x, y, z); aim_ += QVector3D(x, y, z); buildTransform();} + void setPos(const QVector3D & p) { + pos_ = p; + anglesFromPoints(); + buildTransform(); + } + void setAim(const QVector3D & p) { + aim_ = p; + anglesFromPoints(); + buildTransform(); + } + void move(const QVector3D & p) { + pos_ += p; + aim_ += p; + buildTransform(); + } + void move(const float & x, const float & y = 0., const float & z = 0.) { + pos_ += QVector3D(x, y, z); + aim_ += QVector3D(x, y, z); + buildTransform(); + } void moveForward(const float & x, bool withZ = true); - void moveBackward(const float & x, bool withZ = true) {moveForward(-x, withZ);} + void moveBackward(const float & x, bool withZ = true) { moveForward(-x, withZ); } void moveLeft(const float & x, bool withZ = true); - void moveRight(const float & x, bool withZ = true) {moveLeft(-x, withZ);} + void moveRight(const float & x, bool withZ = true) { moveLeft(-x, withZ); } void moveUp(const float & x, bool onlyZ = false); - void moveDown(const float & x, bool onlyZ = false) {moveUp(-x, onlyZ);} + void moveDown(const float & x, bool onlyZ = false) { moveUp(-x, onlyZ); } void rotateZ(const float & a); void rotateXY(const float & a); - void rotateRoll(const float & a) {angles_.setX(angles_.x() + a); buildTransform();} + void rotateRoll(const float & a) { + angles_.setX(angles_.x() + a); + buildTransform(); + } void orbitZ(const float & a); void orbitXY(const float & a); void panZ(const float & a); void panXY(const float & a); - void setFOV(const float & f) {fov_ = f;} - void setAngles(const QVector3D & a) {setRotation(a);} + void setFOV(const float & f) { fov_ = f; } + void setAngles(const QVector3D & a) { setRotation(a); } void setAngleZ(const float & a); void setAngleXY(const float & a); - void setAngleRoll(const float & a) {angles_.setX(a); buildTransform();} - void setAngleLowerLimitXY(const float & a) {angle_limit_lower_xy = a; buildTransform();} - void setAngleUpperLimitXY(const float & a) {angle_limit_upper_xy = a; buildTransform();} - void setAngleLimitsXY(const float & lower, const float & upper) {angle_limit_lower_xy = lower; angle_limit_upper_xy = upper; buildTransform();} - void setDepthStart(const float & d) {depth_start = d;} - void setDepthEnd(const float & d) {depth_end = d;} - void setMirrorX(bool yes) {mirror_x = yes;} - void setMirrorY(bool yes) {mirror_y = yes;} + void setAngleRoll(const float & a) { + angles_.setX(a); + buildTransform(); + } + void setAngleLowerLimitXY(const float & a) { + angle_limit_lower_xy = a; + buildTransform(); + } + void setAngleUpperLimitXY(const float & a) { + angle_limit_upper_xy = a; + buildTransform(); + } + void setAngleLimitsXY(const float & lower, const float & upper) { + angle_limit_lower_xy = lower; + angle_limit_upper_xy = upper; + buildTransform(); + } + void setDepthStart(const float & d) { depth_start = d; } + void setDepthEnd(const float & d) { depth_end = d; } + void setMirrorX(bool yes) { mirror_x = yes; } + void setMirrorY(bool yes) { mirror_y = yes; } void flyCloser(const float & s); void flyFarer(const float & s); void flyToDistance(const float & d); - QVector3D aim() const {return aim_;} - QVector3D angles() const {return rotation();} - QVector3D direction() const {return (aim_ - pos_).normalized();} - QVector3D directionXY() const {QVector3D tv = aim_ - pos_; return QVector3D(tv.x(), tv.y(), 0.).normalized();} - float FOV() const {return fov_;} - float distance() const {return (pos_ - aim_).length();} - float angleZ() const {return angles_.z();} - float angleXY() const {return angles_.y();} - float angleRoll() const {return angles_.x();} - float angleLowerLimitXY() const {return angle_limit_lower_xy;} - float angleUpperLimitXY() const {return angle_limit_upper_xy;} - float depthStart() const {return depth_start;} - float depthEnd() const {return depth_end;} - bool isMirrorX() const {return mirror_x;} - bool isMirrorY() const {return mirror_y;} + QVector3D aim() const { return aim_; } + QVector3D angles() const { return rotation(); } + QVector3D direction() const { return (aim_ - pos_).normalized(); } + QVector3D directionXY() const { + QVector3D tv = aim_ - pos_; + return QVector3D(tv.x(), tv.y(), 0.).normalized(); + } + float FOV() const { return fov_; } + float distance() const { return (pos_ - aim_).length(); } + float angleZ() const { return angles_.z(); } + float angleXY() const { return angles_.y(); } + float angleRoll() const { return angles_.x(); } + float angleLowerLimitXY() const { return angle_limit_lower_xy; } + float angleUpperLimitXY() const { return angle_limit_upper_xy; } + float depthStart() const { return depth_start; } + float depthEnd() const { return depth_end; } + bool isMirrorX() const { return mirror_x; } + bool isMirrorY() const { return mirror_y; } void anglesFromPoints(); void apply(const GLfloat & aspect = 1.); void assign(const Camera & c); @@ -100,7 +135,6 @@ private: GLfloat angle_limit_upper_xy; bool mirror_x; bool mirror_y; - }; #endif // GLCAMERA_H diff --git a/libs/qglview/glframebuffer.cpp b/libs/qglview/glframebuffer.cpp index 16060b8..dc3921c 100644 --- a/libs/qglview/glframebuffer.cpp +++ b/libs/qglview/glframebuffer.cpp @@ -20,13 +20,13 @@ GLFramebuffer::GLFramebuffer(int colorAttachments_, bool withDepth, GLenum colorFormat_, GLenum target__) { - is_depth = withDepth; + is_depth = withDepth; color_format = colorFormat_; - target_ = target__; + target_ = target__; colors.fill(0, colorAttachments_); fbo = drbo = 0; - tex_d = 0; - wid = hei = 0; + tex_d = 0; + wid = hei = 0; is_changed = false; } @@ -80,8 +80,8 @@ void GLFramebuffer::resize(int width, int height, bool force) { QImage GLFramebuffer::grab() const { - //glReadPixels(0, 0, wid, hei, GL_RGBA, ); - //QImage ret(); + // glReadPixels(0, 0, wid, hei, GL_RGBA, ); + // QImage ret(); return QImage(); } @@ -90,17 +90,17 @@ void GLFramebuffer::bind() { if (is_changed) resize(wid, hei); if (fbo == 0) return; initializeOpenGLFunctions(); - //glFlush(); + // glFlush(); glGetIntegerv(GL_VIEWPORT, prev_view); - //glClearError(); + // glClearError(); glBindFramebuffer(GL_FRAMEBUFFER, fbo); - //qDebug() << QString::number(glGetError(), 16); + // qDebug() << QString::number(glGetError(), 16); QVector buffers; for (int i = 0; i < colors.size(); ++i) buffers << GL_COLOR_ATTACHMENT0 + i; glDrawBuffers(buffers.size(), buffers.constData()); glReadBuffer(GL_COLOR_ATTACHMENT0); - //glDrawBuffer(GL_COLOR_ATTACHMENT0); + // glDrawBuffer(GL_COLOR_ATTACHMENT0); glViewport(0, 0, wid, hei); } @@ -108,17 +108,17 @@ void GLFramebuffer::bind() { void GLFramebuffer::release() { is_changed = false; if (fbo == 0) return; - //glFlush(); + // glFlush(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(prev_view[0], prev_view[1], prev_view[2], prev_view[3]); } void GLFramebuffer::setWriteBuffer(int index) { - //QVector buffers; buffers << GL_COLOR_ATTACHMENT0 + index; + // QVector buffers; buffers << GL_COLOR_ATTACHMENT0 + index; GLenum e = GL_COLOR_ATTACHMENT0 + index; glDrawBuffer(e); - //glDrawBuffers(1, &e); + // glDrawBuffers(1, &e); } diff --git a/libs/qglview/glframebuffer.h b/libs/qglview/glframebuffer.h index a613af1..12df712 100644 --- a/libs/qglview/glframebuffer.h +++ b/libs/qglview/glframebuffer.h @@ -19,48 +19,56 @@ #ifndef GLFRAMEBUFFER_H #define GLFRAMEBUFFER_H -#include #include "gltypes.h" +#include -class GLFramebuffer : protected QOpenGLExtraFunctions -{ + +class GLFramebuffer: protected QOpenGLExtraFunctions { public: GLFramebuffer(int colorAttachments = 1, bool withDepth = true, GLenum colorFormat = GL_RGBA8, GLenum target = GL_TEXTURE_2D); virtual ~GLFramebuffer(); - GLuint id() const {return fbo;} - GLuint colorTexture(int index = 0) const {return colors[index];} - GLenum colorFormat() const {return color_format;} - GLuint depthTexture() const {return tex_d;} - GLenum target() const {return target_;} - int width() const {return wid;} - int height() const {return hei;} - QSize size() const {return QSize(wid, hei);} + GLuint id() const { return fbo; } + GLuint colorTexture(int index = 0) const { return colors[index]; } + GLenum colorFormat() const { return color_format; } + GLuint depthTexture() const { return tex_d; } + GLenum target() const { return target_; } + int width() const { return wid; } + int height() const { return hei; } + QSize size() const { return QSize(wid, hei); } QImage grab() const; void resize(int width, int height, bool force = false); void bind(); void release(); - void setReadBuffer(int index) {glReadBuffer(GL_COLOR_ATTACHMENT0 + index);} + void setReadBuffer(int index) { glReadBuffer(GL_COLOR_ATTACHMENT0 + index); } void setWriteBuffer(int index); void setWriteBuffers(int * indeces, int count); - void setColorFormat(GLenum format) {color_format = format; is_changed = true;} + void setColorFormat(GLenum format) { + color_format = format; + is_changed = true; + } - void copyDepthFrom(GLuint tex) {;} + void copyDepthFrom(GLuint tex) { ; } void bindColorTextures(); void bindDepthTexture(int channel); private: - void deleteGLRenderbuffer(GLuint & drbo) {if (drbo != 0) glDeleteRenderbuffers(1, &drbo); drbo = 0;} - void deleteGLFramebuffer(GLuint & fbo) {if (fbo != 0) glDeleteFramebuffers(1, &fbo); fbo = 0;} + void deleteGLRenderbuffer(GLuint & drbo) { + if (drbo != 0) glDeleteRenderbuffers(1, &drbo); + drbo = 0; + } + void deleteGLFramebuffer(GLuint & fbo) { + if (fbo != 0) glDeleteFramebuffers(1, &fbo); + fbo = 0; + } bool is_depth, is_changed; QVector colors; GLenum color_format, target_; GLuint fbo, drbo, tex_d; GLint prev_view[4], wid, hei; - }; #endif // GLFRAMEBUFFER_H diff --git a/libs/qglview/glmaterial.cpp b/libs/qglview/glmaterial.cpp index 815a87c..62ed188 100644 --- a/libs/qglview/glmaterial.cpp +++ b/libs/qglview/glmaterial.cpp @@ -23,24 +23,24 @@ QStringList GLTextureManagerBase::search_pathes("."); bool GLCubeTexture::create() { - //qDebug("create"); + // qDebug("create"); destroy(); glGenTextures(1, &id_); glBindTexture(GL_TEXTURE_CUBE_MAP, id_); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR/*_MIPMAP_LINEAR*/); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR /*_MIPMAP_LINEAR*/); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); - //glClearError(); + // glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); + // glClearError(); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, format_, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); - //qDebug() << glGetError(); + // qDebug() << glGetError(); changed_ = false; return id_ > 0; } @@ -59,28 +59,41 @@ void GLCubeTexture::load() { void GLCubeTexture::loadFromDirectory(const QString & dir) { - QDir d(dir); QFileInfoList sl; - sl = d.entryInfoList(QStringList("front.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadFront(sl[0].absoluteFilePath()); - sl = d.entryInfoList(QStringList("back.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadBack(sl[0].absoluteFilePath()); - sl = d.entryInfoList(QStringList("left.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadLeft(sl[0].absoluteFilePath()); - sl = d.entryInfoList(QStringList("right.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadRight(sl[0].absoluteFilePath()); - sl = d.entryInfoList(QStringList("top.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadTop(sl[0].absoluteFilePath()); - sl = d.entryInfoList(QStringList("bottom.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) loadBottom(sl[0].absoluteFilePath()); + QDir d(dir); + QFileInfoList sl; + sl = d.entryInfoList(QStringList("front.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadFront(sl[0].absoluteFilePath()); + sl = d.entryInfoList(QStringList("back.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadBack(sl[0].absoluteFilePath()); + sl = d.entryInfoList(QStringList("left.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadLeft(sl[0].absoluteFilePath()); + sl = d.entryInfoList(QStringList("right.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadRight(sl[0].absoluteFilePath()); + sl = d.entryInfoList(QStringList("top.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadTop(sl[0].absoluteFilePath()); + sl = d.entryInfoList(QStringList("bottom.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) loadBottom(sl[0].absoluteFilePath()); } void GLCubeTexture::loadPathesFromDirectory(const QString & dir) { - QDir d(dir); QFileInfoList sl; - sl = d.entryInfoList(QStringList("front.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[0] = sl[0].absoluteFilePath(); - sl = d.entryInfoList(QStringList("back.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[1] = sl[0].absoluteFilePath(); - sl = d.entryInfoList(QStringList("left.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[2] = sl[0].absoluteFilePath(); - sl = d.entryInfoList(QStringList("right.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[3] = sl[0].absoluteFilePath(); - sl = d.entryInfoList(QStringList("top.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[4] = sl[0].absoluteFilePath(); - sl = d.entryInfoList(QStringList("bottom.*"), QDir::Files | QDir::NoDotAndDotDot); if (!sl.isEmpty()) pathes[5] = sl[0].absoluteFilePath(); + QDir d(dir); + QFileInfoList sl; + sl = d.entryInfoList(QStringList("front.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[0] = sl[0].absoluteFilePath(); + sl = d.entryInfoList(QStringList("back.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[1] = sl[0].absoluteFilePath(); + sl = d.entryInfoList(QStringList("left.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[2] = sl[0].absoluteFilePath(); + sl = d.entryInfoList(QStringList("right.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[3] = sl[0].absoluteFilePath(); + sl = d.entryInfoList(QStringList("top.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[4] = sl[0].absoluteFilePath(); + sl = d.entryInfoList(QStringList("bottom.*"), QDir::Files | QDir::NoDotAndDotDot); + if (!sl.isEmpty()) pathes[5] = sl[0].absoluteFilePath(); } - QString GLTextureManagerBase::findFile(const QString & path) { return ::findFile(path, search_pathes); } @@ -91,16 +104,16 @@ GLuint GLTextureManagerBase::loadTexture(const QString & path, bool ownership, b if (p.isEmpty()) return 0; int tid = textureID(p, bump); if (tid > 0) { - //qDebug() << "[TextureManager] Found" << path << "as" << tid; + // qDebug() << "[TextureManager] Found" << path << "as" << tid; return tid; } QImage image(p); if (bump) convertToNormal(image); - //qDebug() << p << image.width() << image.height() << image.format() << bump; - ///tid = currentQGLView->bindTexture(image, GL_TEXTURE_2D/*, GL_RGBA, __GLContext__::MipmapBindOption*/); - //GLuint tid = 0; + // qDebug() << p << image.width() << image.height() << image.format() << bump; + /// tid = currentQGLView->bindTexture(image, GL_TEXTURE_2D/*, GL_RGBA, __GLContext__::MipmapBindOption*/); + // GLuint tid = 0; GLuint _tid = tid; - createGLTexture(_tid, image);///currentQGLView->bindTexture(image, GL_TEXTURE_2D); + createGLTexture(_tid, image); /// currentQGLView->bindTexture(image, GL_TEXTURE_2D); tid = _tid; if (tid == 0) { qDebug() << "[TextureManager] Can`t load" << p; @@ -117,12 +130,12 @@ GLuint GLTextureManagerBase::loadTexture(const QImage & im, bool ownership, bool QImage image(im); if (bump) convertToNormal(image); GLuint tid = 0; - createGLTexture(tid, im);///currentQGLView->bindTexture(image, GL_TEXTURE_2D); + createGLTexture(tid, im); /// currentQGLView->bindTexture(image, GL_TEXTURE_2D); if (tid == 0) { qDebug() << "[TextureManager] Can`t load image"; return tid; } - //qDebug() << "[TextureManager] Loaded image as" << tid; + // qDebug() << "[TextureManager] Loaded image as" << tid; if (ownership) tex_ids[bump ? 1 : 0].insert(QString(), tid); return tid; } @@ -150,21 +163,24 @@ void GLTextureManagerBase::reloadTexture(GLuint tid, const QImage & im) { Vector3d colorVector(QRgb c) { - return Vector3d(((uchar*)(&c))[0] / 255., ((uchar*)(&c))[1] / 255., ((uchar*)(&c))[2] / 255.); + return Vector3d(((uchar *)(&c))[0] / 255., ((uchar *)(&c))[1] / 255., ((uchar *)(&c))[2] / 255.); } void GLTextureManagerBase::convertToNormal(QImage & im) { if (im.isNull()) return; - QImage sim = im.convertToFormat(QImage::Format_ARGB32); - float sum[3] = {0., 0., 0.}; - llong a = 0; + QImage sim = im.convertToFormat(QImage::Format_ARGB32); + float sum[3] = {0., 0., 0.}; + llong a = 0; const uchar * sd = sim.constBits(); for (int i = 0; i < sim.height(); i++) { for (int j = 0; j < sim.width(); j++) { - sum[2] += sd[a] / 255.f - 0.5f; ++a; - sum[1] += sd[a] / 255.f - 0.5f; ++a; - sum[0] += sd[a] / 255.f - 0.5f; ++a; + sum[2] += sd[a] / 255.f - 0.5f; + ++a; + sum[1] += sd[a] / 255.f - 0.5f; + ++a; + sum[0] += sd[a] / 255.f - 0.5f; + ++a; ++a; } } @@ -178,7 +194,7 @@ void GLTextureManagerBase::convertToNormal(QImage & im) { qDebug() << "convert to bump"; QImage dim = QImage(sim.width(), sim.height(), QImage::Format_ARGB32); int tx, ty, w = sim.width(), h = sim.height(); - a = 0; + a = 0; uchar * dd = dim.bits(); for (int i = 0; i < sim.height(); i++) { for (int j = 0; j < sim.width(); j++) { @@ -187,40 +203,42 @@ void GLTextureManagerBase::convertToNormal(QImage & im) { ty = i - 1; ty = ty < 0 ? h + ty : ty % h; Vector3d p[3], res; - p[0] = colorVector(sim.pixel(j, i)); - p[1] = colorVector(sim.pixel(j, ty)); - p[2] = colorVector(sim.pixel(tx, i)); + p[0] = colorVector(sim.pixel(j, i)); + p[1] = colorVector(sim.pixel(j, ty)); + p[2] = colorVector(sim.pixel(tx, i)); res.y = piClamp(0.5f + (p[0].length() - p[1].length()) / 2.f, 0.f, 1.f); res.x = piClamp(0.5f + (p[0].length() - p[2].length()) / 2.f, 0.f, 1.f); - tx = (j + 1) % w; - ty = (i + 1) % h; - p[1] = colorVector(sim.pixel(j, ty)); - p[2] = colorVector(sim.pixel(tx, i)); + tx = (j + 1) % w; + ty = (i + 1) % h; + p[1] = colorVector(sim.pixel(j, ty)); + p[2] = colorVector(sim.pixel(tx, i)); res.y = piClamp(0.5f + (p[0].length() - p[1].length()) / 2.f, 0.f, 1.f); res.x = piClamp(0.5f + (p[0].length() - p[2].length()) / 2.f, 0.f, 1.f); res.z = 1.; - dd[a] = res.z * 255; ++a; - dd[a] = res.x * 255; ++a; - dd[a] = res.y * 255; ++a; - dd[a] = 255; ++a; + dd[a] = res.z * 255; + ++a; + dd[a] = res.x * 255; + ++a; + dd[a] = res.y * 255; + ++a; + dd[a] = 255; + ++a; } } im = dim; - //im.save("_bump.png"); + // im.save("_bump.png"); } - - Material::Material(): map_reflection(512) { color_diffuse = color_specular = Qt::white; - color_self_illumination = Qt::black; - glass = false; - transparency = reflectivity = 0.f; + color_self_illumination = Qt::black; + glass = false; + transparency = reflectivity = 0.f; map_specularity.color_amount = 0.5f; - map_specular.color_amount = 1.f; - iof = 1.f; - dispersion = 0.05f; + map_specular.color_amount = 1.f; + iof = 1.f; + dispersion = 0.05f; } @@ -228,24 +246,24 @@ void Material::apply(QOpenGLShaderProgram * prog) { if (prog) { setUniformMaterial(prog, *this); } else { - GLfloat mat_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f}; + GLfloat mat_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat mat_specular[4] = {0.9f, 0.9f, 0.9f, 1.0f}; GLfloat mat_emission[4] = {0.f, 0.f, 0.f, 1.0f}; - mat_diffuse[0] = map_diffuse.color_amount * color_diffuse.redF(); - mat_diffuse[1] = map_diffuse.color_amount * color_diffuse.greenF(); - mat_diffuse[2] = map_diffuse.color_amount * color_diffuse.blueF(); - mat_diffuse[3] = map_diffuse.color_amount * color_diffuse.alphaF() * (1.f - transparency); - mat_specular[0] = map_specular.color_amount * color_specular.redF(); - mat_specular[1] = map_specular.color_amount * color_specular.greenF(); - mat_specular[2] = map_specular.color_amount * color_specular.blueF(); - mat_emission[0] = map_self_illumination.color_amount * color_self_illumination.redF(); - mat_emission[1] = map_self_illumination.color_amount * color_self_illumination.greenF(); - mat_emission[2] = map_self_illumination.color_amount * color_self_illumination.blueF(); + mat_diffuse[0] = map_diffuse.color_amount * color_diffuse.redF(); + mat_diffuse[1] = map_diffuse.color_amount * color_diffuse.greenF(); + mat_diffuse[2] = map_diffuse.color_amount * color_diffuse.blueF(); + mat_diffuse[3] = map_diffuse.color_amount * color_diffuse.alphaF() * (1.f - transparency); + mat_specular[0] = map_specular.color_amount * color_specular.redF(); + mat_specular[1] = map_specular.color_amount * color_specular.greenF(); + mat_specular[2] = map_specular.color_amount * color_specular.blueF(); + mat_emission[0] = map_self_illumination.color_amount * color_self_illumination.redF(); + mat_emission[1] = map_self_illumination.color_amount * color_self_illumination.greenF(); + mat_emission[2] = map_self_illumination.color_amount * color_self_illumination.blueF(); glColor4f(mat_diffuse[0], mat_diffuse[1], mat_diffuse[2], mat_diffuse[3]); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); - //qDebug() << (map_specularity.color_amount)*128.; - glMaterialf(GL_FRONT, GL_SHININESS, (map_specularity.color_amount)*128.f); + // qDebug() << (map_specularity.color_amount)*128.; + glMaterialf(GL_FRONT, GL_SHININESS, (map_specularity.color_amount) * 128.f); glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_diffuse); } @@ -253,7 +271,7 @@ void Material::apply(QOpenGLShaderProgram * prog) { void Material::loadTextures(GLTextureManagerBase * tm) { - //qDebug() << "load textures"; + // qDebug() << "load textures"; if (!tm) return; if (!map_diffuse.bitmap_path.isEmpty()) map_diffuse.bitmap_id = tm->loadTexture(map_diffuse.bitmap_path); if (!map_normal.bitmap_path.isEmpty()) map_normal.bitmap_id = tm->loadTexture(map_normal.bitmap_path, true, true); @@ -261,6 +279,6 @@ void Material::loadTextures(GLTextureManagerBase * tm) { if (!map_specularity.bitmap_path.isEmpty()) map_specularity.bitmap_id = tm->loadTexture(map_specularity.bitmap_path); if (!map_specular.bitmap_path.isEmpty()) map_specular.bitmap_id = tm->loadTexture(map_specular.bitmap_path); if (!map_self_illumination.bitmap_path.isEmpty()) map_self_illumination.bitmap_id = tm->loadTexture(map_self_illumination.bitmap_path); - //if (!map_diffuse_2.bitmap_path.isEmpty()) map_diffuse_2.bitmap_id = tm->loadTexture(map_diffuse_2.bitmap_path); + // if (!map_diffuse_2.bitmap_path.isEmpty()) map_diffuse_2.bitmap_id = tm->loadTexture(map_diffuse_2.bitmap_path); map_reflection.load(); } diff --git a/libs/qglview/glmaterial.h b/libs/qglview/glmaterial.h index 7235c66..813f930 100644 --- a/libs/qglview/glmaterial.h +++ b/libs/qglview/glmaterial.h @@ -1,39 +1,55 @@ /* - QGLView - Ivan Pelipenko peri4ko@yandex.ru + QGLView + Ivan Pelipenko peri4ko@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef GLMATERIAL_H #define GLMATERIAL_H -#include "gltypes.h" #include "chunkstream.h" +#include "gltypes.h" class GLTexture { public: - GLTexture(int _width, int _height, const GLenum & _format = GL_RGBA8, const GLenum & _target = GL_TEXTURE_2D) {wid = _width; hei = _height; format_ = _format; target_ = _target; id_ = 0;} - bool create() {destroy(); createGLTexture(id_, wid, hei, format_, target_); return id_ > 0;} - void destroy() {if (id_ > 0) glDeleteTextures(1, &id_); id_ = 0;} - void bind() {if (id_ > 0) glBindTexture(target_, id_);} - void release() {glBindTexture(target_, 0);} - int width() const {return wid;} - int height() const {return hei;} - GLenum format() const {return format_;} - GLenum target() const {return target_;} - GLuint id() const {return id_;} + GLTexture(int _width, int _height, const GLenum & _format = GL_RGBA8, const GLenum & _target = GL_TEXTURE_2D) { + wid = _width; + hei = _height; + format_ = _format; + target_ = _target; + id_ = 0; + } + bool create() { + destroy(); + createGLTexture(id_, wid, hei, format_, target_); + return id_ > 0; + } + void destroy() { + if (id_ > 0) glDeleteTextures(1, &id_); + id_ = 0; + } + void bind() { + if (id_ > 0) glBindTexture(target_, id_); + } + void release() { glBindTexture(target_, 0); } + int width() const { return wid; } + int height() const { return hei; } + GLenum format() const { return format_; } + GLenum target() const { return target_; } + GLuint id() const { return id_; } + private: int wid, hei; GLenum format_, target_; @@ -43,27 +59,95 @@ private: class GLCubeTexture { public: - GLCubeTexture(int _size, const GLenum & _format = GL_RGBA8) {size = _size; format_ = _format; id_ = 0; changed_ = false; pathes.resize(6);} + GLCubeTexture(int _size, const GLenum & _format = GL_RGBA8) { + size = _size; + format_ = _format; + id_ = 0; + changed_ = false; + pathes.resize(6); + } bool create(); - void destroy() {if (id_ > 0) glDeleteTextures(1, &id_); id_ = 0;} - void bind() {if (changed_) {changed_ = false; create();} if (id_ > 0) glBindTexture(GL_TEXTURE_CUBE_MAP, id_);} - void release() {glBindTexture(GL_TEXTURE_CUBE_MAP, 0);} - void resize(int _size) {size = _size; changed_ = true;} + void destroy() { + if (id_ > 0) glDeleteTextures(1, &id_); + id_ = 0; + } + void bind() { + if (changed_) { + changed_ = false; + create(); + } + if (id_ > 0) glBindTexture(GL_TEXTURE_CUBE_MAP, id_); + } + void release() { glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } + void resize(int _size) { + size = _size; + changed_ = true; + } void loadFromDirectory(const QString & dir); - void loadFront(const QString & path) {bind(); pathes[0] = path; createGLTexture(id_, rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_POSITIVE_X);} - void loadBack(const QString & path) {bind(); pathes[1] = path; createGLTexture(id_, rotateQImageRight(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_NEGATIVE_X);} - void loadLeft(const QString & path) {bind(); pathes[2] = path; createGLTexture(id_, QImage(path).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y);} - void loadRight(const QString & path) {bind(); pathes[3] = path; createGLTexture(id_, rotateQImage180(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_POSITIVE_Y);} - void loadTop(const QString & path) {bind(); pathes[4] = path; createGLTexture(id_, rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);} - void loadBottom(const QString & path) {bind(); pathes[5] = path; createGLTexture(id_, rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), format_, GL_TEXTURE_CUBE_MAP_POSITIVE_Z);} + void loadFront(const QString & path) { + bind(); + pathes[0] = path; + createGLTexture(id_, + rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_POSITIVE_X); + } + void loadBack(const QString & path) { + bind(); + pathes[1] = path; + createGLTexture(id_, + rotateQImageRight(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_NEGATIVE_X); + } + void loadLeft(const QString & path) { + bind(); + pathes[2] = path; + createGLTexture(id_, + QImage(path).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Y); + } + void loadRight(const QString & path) { + bind(); + pathes[3] = path; + createGLTexture(id_, + rotateQImage180(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_POSITIVE_Y); + } + void loadTop(const QString & path) { + bind(); + pathes[4] = path; + createGLTexture(id_, + rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); + } + void loadBottom(const QString & path) { + bind(); + pathes[5] = path; + createGLTexture(id_, + rotateQImageLeft(QImage(path)).scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + format_, + GL_TEXTURE_CUBE_MAP_POSITIVE_Z); + } void load(); - bool isEmpty() const {foreach (const QString & i, pathes) if (!i.isEmpty()) return false; return true;} - GLenum format() const {return format_;} - void setFormat(GLenum f) {format_ = f; changed_ = true;} - GLuint id() const {return id_;} - const QString & path(int side) const {return pathes[side];} - void setPath(int side, const QString & p) {pathes[side] = p;} + bool isEmpty() const { + foreach(const QString & i, pathes) + if (!i.isEmpty()) return false; + return true; + } + GLenum format() const { return format_; } + void setFormat(GLenum f) { + format_ = f; + changed_ = true; + } + GLuint id() const { return id_; } + const QString & path(int side) const { return pathes[side]; } + void setPath(int side, const QString & p) { pathes[side] = p; } void loadPathesFromDirectory(const QString & dir); + private: bool changed_; int size; @@ -78,28 +162,33 @@ class GLTextureManagerBase { public: GLTextureManagerBase() {} virtual ~GLTextureManagerBase() {} - void addSearchPath(const QString & path) {search_pathes << path;} - static QStringList searchPathes() {return search_pathes;} + void addSearchPath(const QString & path) { search_pathes << path; } + static QStringList searchPathes() { return search_pathes; } QString findFile(const QString & path); GLuint loadTexture(const QString & path, bool ownership = true, bool bump = false); GLuint loadTexture(const QImage & image, bool ownership = true, bool bump = false); void reloadTexture(GLuint tid, const QString & path); void reloadTexture(GLuint tid, const QImage & image); - int textureID(const QString & path, bool bump = false) {return tex_ids[bump ? 1 : 0][path];} - virtual void addTexture(const QString & path) = 0; + int textureID(const QString & path, bool bump = false) { return tex_ids[bump ? 1 : 0][path]; } + virtual void addTexture(const QString & path) = 0; virtual void addAnimation(const QString & dir, const QString & name) = 0; - virtual bool loadTextures() = 0; + virtual bool loadTextures() = 0; protected: static void convertToNormal(QImage & im); static QStringList search_pathes; QMap tex_ids[2]; - }; class Map { public: - Map() {bitmap_id = 0; color_amount = 1.f; color_offset = 0.f; animation_frame_rate = -1.f; bitmap_scale = QPointF(1., 1.);} + Map() { + bitmap_id = 0; + color_amount = 1.f; + color_offset = 0.f; + animation_frame_rate = -1.f; + bitmap_scale = QPointF(1., 1.); + } QString bitmap_path; GLuint bitmap_id; QPointF bitmap_offset; @@ -137,12 +226,18 @@ public: }; -inline QDataStream & operator <<(QDataStream & s, const Map & m) { +inline QDataStream & operator<<(QDataStream & s, const Map & m) { ChunkStream cs; - cs.add(1, m.bitmap_path).add(2, m.color_amount).add(3, m.color_offset).add(4, m.animation).add(5, m.animation_frame_rate).add(6, m.bitmap_scale); - s << cs.data(); return s; + cs.add(1, m.bitmap_path) + .add(2, m.color_amount) + .add(3, m.color_offset) + .add(4, m.animation) + .add(5, m.animation_frame_rate) + .add(6, m.bitmap_scale); + s << cs.data(); + return s; } -inline QDataStream & operator >>(QDataStream & s, Map & m) { +inline QDataStream & operator>>(QDataStream & s, Map & m) { ChunkStream cs(s); while (!cs.atEnd()) { switch (cs.read()) { @@ -157,14 +252,25 @@ inline QDataStream & operator >>(QDataStream & s, Map & m) { return s; } -inline QDataStream & operator <<(QDataStream & s, const Material & m) { +inline QDataStream & operator<<(QDataStream & s, const Material & m) { ChunkStream cs; - cs.add(1, m.name).add(2, m.color_diffuse).add(3, m.color_specular).add(4, m.color_self_illumination) - .add(5, m.transparency).add(6, m.reflectivity).add(7, m.glass).add(8, m.map_diffuse).add(9, m.map_normal) - .add(10, m.map_relief).add(11, m.map_specular).add(12, m.map_specularity).add(13, m.map_self_illumination); - s << qCompress(cs.data()); return s; + cs.add(1, m.name) + .add(2, m.color_diffuse) + .add(3, m.color_specular) + .add(4, m.color_self_illumination) + .add(5, m.transparency) + .add(6, m.reflectivity) + .add(7, m.glass) + .add(8, m.map_diffuse) + .add(9, m.map_normal) + .add(10, m.map_relief) + .add(11, m.map_specular) + .add(12, m.map_specularity) + .add(13, m.map_self_illumination); + s << qCompress(cs.data()); + return s; } -inline QDataStream & operator >>(QDataStream & s, Material & m) { +inline QDataStream & operator>>(QDataStream & s, Material & m) { QByteArray ba; s >> ba; ba = qUncompress(ba); diff --git a/libs/qglview/globject.cpp b/libs/qglview/globject.cpp index 0e7f1a3..e93c10c 100644 --- a/libs/qglview/globject.cpp +++ b/libs/qglview/globject.cpp @@ -17,34 +17,35 @@ */ #include "globject.h" + #include "glcamera.h" #include "qglview.h" GLObjectBase::GLObjectBase() { - type_ = glMesh; + type_ = glMesh; render_mode = View; - pass_ = Solid; - geom_prim = Triangles; - scale_ = QVector3D(1., 1., 1.); - parent_ = nullptr; + pass_ = Solid; + geom_prim = Triangles; + scale_ = QVector3D(1., 1., 1.); + parent_ = nullptr; is_root = is_init = is_tex_loaded = selected_ = false; visible_ = accept_fog = accept_light = cast_shadow = rec_shadow = select_ = true; - line_width = -1.; - blend_src = GL_SRC_ALPHA; - blend_dest = GL_ONE_MINUS_SRC_ALPHA; - type_ = glMesh; - raw_matrix = false; + line_width = -1.; + blend_src = GL_SRC_ALPHA; + blend_dest = GL_ONE_MINUS_SRC_ALPHA; + type_ = glMesh; + raw_matrix = false; mat_.setToIdentity(); view_ = nullptr; } GLObjectBase::~GLObjectBase() { - //qDebug() << "del" << name() << view_; + // qDebug() << "del" << name() << view_; if (parent_) parent_->children_.removeAll(this); - if (view_) ((QGLView*)view_)->objectDeleted(this); - foreach (GLObjectBase * c, children_) { + if (view_) ((QGLView *)view_)->objectDeleted(this); + foreach(GLObjectBase * c, children_) { c->parent_ = nullptr; delete c; } @@ -52,37 +53,37 @@ GLObjectBase::~GLObjectBase() { GLObjectBase * GLObjectBase::clone(bool withChildren) { - GLObjectBase * o = new GLObjectBase(); - o->pass_ = pass_; - o->is_init = false; - o->accept_light = accept_light; - o->accept_fog = accept_fog; - o->visible_ = visible_; - o->type_ = type_; - o->raw_matrix = raw_matrix; - o->mat_ = mat_; - o->pos_ = pos_; - o->angles_ = angles_; - o->scale_ = scale_; - o->itransform_ = itransform_; - o->bound = bound; - o->name_ = name_ + "_copy"; - o->blend_src = blend_src; - o->blend_dest = blend_dest; - o->material_ = material_; - o->pos_h = pos_h; - o->points = points; - o->puvws = puvws; - o->faces = faces; - o->uvws = uvws; - o->norms = norms; - o->normals = normals; - o->vbo.vertices_ = vbo.vertices_; - o->vbo.normals_ = vbo.normals_; + GLObjectBase * o = new GLObjectBase(); + o->pass_ = pass_; + o->is_init = false; + o->accept_light = accept_light; + o->accept_fog = accept_fog; + o->visible_ = visible_; + o->type_ = type_; + o->raw_matrix = raw_matrix; + o->mat_ = mat_; + o->pos_ = pos_; + o->angles_ = angles_; + o->scale_ = scale_; + o->itransform_ = itransform_; + o->bound = bound; + o->name_ = name_ + "_copy"; + o->blend_src = blend_src; + o->blend_dest = blend_dest; + o->material_ = material_; + o->pos_h = pos_h; + o->points = points; + o->puvws = puvws; + o->faces = faces; + o->uvws = uvws; + o->norms = norms; + o->normals = normals; + o->vbo.vertices_ = vbo.vertices_; + o->vbo.normals_ = vbo.normals_; o->vbo.texcoords_ = vbo.texcoords_; - o->vbo.colors_ = vbo.colors_; - o->meta = meta; - o->view_ = nullptr; + o->vbo.colors_ = vbo.colors_; + o->meta = meta; + o->view_ = nullptr; o->children_.clear(); if (withChildren) { for (int i = 0; i < children_.size(); ++i) @@ -96,8 +97,8 @@ void GLObjectBase::init() { calculateBoundingBox(); vbo.init(); vbo.rebuffer(); - //material_.reflection.create(); - //qDebug() << "init" << vbo.buffer_; + // material_.reflection.create(); + // qDebug() << "init" << vbo.buffer_; is_init = true; } @@ -105,42 +106,41 @@ void GLObjectBase::init() { void GLObjectBase::draw(QOpenGLShaderProgram * prog, bool simplest) { vbo.draw(geom_prim, prog, simplest); /*if (!d_vertices.isEmpty()) { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glVertexPointer(3, GL_FLOAT, 0, d_vertices.constData()); - glTexCoordPointer(2, GL_FLOAT, 0, d_uvs.constData()); - //glColorPointer(4, GL_FLOAT, 0, d_colors.constData()); - glNormalPointer(GL_FLOAT, 0, d_normals.constData()); - glDrawArrays(geom_prim, 0, d_vertices.size() / 3);*/ - /*if (pass_ == Reflection) { - glActiveTexture(GL_TEXTURE1); - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP); - }*/ + glBindBuffer(GL_ARRAY_BUFFER, 0); + glVertexPointer(3, GL_FLOAT, 0, d_vertices.constData()); + glTexCoordPointer(2, GL_FLOAT, 0, d_uvs.constData()); + //glColorPointer(4, GL_FLOAT, 0, d_colors.constData()); + glNormalPointer(GL_FLOAT, 0, d_normals.constData()); + glDrawArrays(geom_prim, 0, d_vertices.size() / 3);*/ + /*if (pass_ == Reflection) { + glActiveTexture(GL_TEXTURE1); + glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP); + glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP); + }*/ //} } void GLObjectBase::setView(QGLView * v) { view_ = v; - foreach (GLObjectBase * c, children_) + foreach(GLObjectBase * c, children_) c->setView(v); } void GLObjectBase::addChild(GLObjectBase * o) { if (o == this) return; - if (o->parent_) - o->parent_->children_.removeAll(o); + if (o->parent_) o->parent_->children_.removeAll(o); children_ << o; o->parent_ = this; - o->setView((QGLView*)view_); + o->setView((QGLView *)view_); o->buildTransform(); if (view_) { view_->collectLights(); - QList cl = o->children(true); + QList cl = o->children(true); cl << o; - foreach (GLObjectBase * i, cl) { - emit ((QGLView*)view_)->objectAdded(i); + foreach(GLObjectBase * i, cl) { + emit((QGLView *)view_)->objectAdded(i); } } } @@ -164,8 +164,8 @@ void GLObjectBase::removeChild(int index) { void GLObjectBase::clearChildren(bool deleteAll) { - foreach (GLObjectBase * i, children_) { - i->view_ = nullptr; + foreach(GLObjectBase * i, children_) { + i->view_ = nullptr; i->parent_ = nullptr; i->clearChildren(deleteAll); if (deleteAll) { @@ -186,7 +186,7 @@ GLObjectBase * GLObjectBase::child(int index) { GLObjectBase * GLObjectBase::child(const QString & name) { - foreach (GLObjectBase * i, children_) + foreach(GLObjectBase * i, children_) if (i->name_ == name) return i; return nullptr; } @@ -199,15 +199,15 @@ const GLObjectBase * GLObjectBase::child(int index) const { const GLObjectBase * GLObjectBase::child(const QString & name) const { - foreach (GLObjectBase * i, children_) + foreach(GLObjectBase * i, children_) if (i->name_ == name) return i; return nullptr; } -QList GLObjectBase::children(bool all_) { +QList GLObjectBase::children(bool all_) { if (!all_) return children_; - QList cl; + QList cl; addChildren(cl, this); return cl; } @@ -230,8 +230,10 @@ void GLObjectBase::rotateY(GLfloat a) { void GLObjectBase::rotateZ(GLfloat a) { raw_matrix = false; angles_.setZ(angles_.z() + a); - while (angles_.z() < -360.f) angles_.setZ(angles_.z() + 360.f); - while (angles_.z() > 360.f) angles_.setZ(angles_.z() - 360.f); + while (angles_.z() < -360.f) + angles_.setZ(angles_.z() + 360.f); + while (angles_.z() > 360.f) + angles_.setZ(angles_.z() - 360.f); buildTransform(); } @@ -253,28 +255,30 @@ void GLObjectBase::setRotationY(GLfloat a) { void GLObjectBase::setRotationZ(GLfloat a) { raw_matrix = false; angles_.setZ(a); - while (angles_.z() < -360.f) angles_.setZ(angles_.z() + 360.f); - while (angles_.z() > 360.f) angles_.setZ(angles_.z() - 360.f); + while (angles_.z() < -360.f) + angles_.setZ(angles_.z() + 360.f); + while (angles_.z() > 360.f) + angles_.setZ(angles_.z() - 360.f); buildTransform(); } void GLObjectBase::setRotation(const QVector3D & a) { raw_matrix = false; - angles_= a; + angles_ = a; buildTransform(); } void GLObjectBase::resetRotation() { raw_matrix = false; - angles_ = QVector3D(0., 0., 0.); + angles_ = QVector3D(0., 0., 0.); buildTransform(); } -void GLObjectBase::addChildren(QList & list, GLObjectBase * where) { - foreach (GLObjectBase * i, where->children_) { +void GLObjectBase::addChildren(QList & list, GLObjectBase * where) { + foreach(GLObjectBase * i, where->children_) { list << i; addChildren(list, i); } @@ -284,21 +288,22 @@ void GLObjectBase::addChildren(QList & list, GLObjectBase * whe void GLObjectBase::loadTextures(bool with_children) { material_.loadTextures(view_->textureManager()); if (with_children) - foreach (GLObjectBase * i, children_) i->loadTextures(); + foreach(GLObjectBase * i, children_) + i->loadTextures(); is_tex_loaded = true; checkPass(); } void GLObjectBase::calculateBoundingBox() { - bound = vbo.boundingBox(); + bound = vbo.boundingBox(); QVector c = bound.corners(), tc; - //QMatrix4x4 mat = itransform_.inverted(); - //qDebug() << itransform_ << mat_ << mat; - foreach (QVector3D p, c) + // QMatrix4x4 mat = itransform_.inverted(); + // qDebug() << itransform_ << mat_ << mat; + foreach(QVector3D p, c) tc << (itransform_ * QVector4D(p, 1)).toVector3D(); bound = Box3D(tc); - foreach (GLObjectBase * i, children_) { + foreach(GLObjectBase * i, children_) { i->calculateBoundingBox(); bound |= i->boundingBox(); } @@ -328,25 +333,25 @@ void GLObjectBase::removeProperty(const QString & pn) { void GLObjectBase::setTransform(const QMatrix4x4 & t) { raw_matrix = true; - mat_ = t; - pos_ = mat_.column(3).toVector3D(); + mat_ = t; + pos_ = mat_.column(3).toVector3D(); mat_.setColumn(3, QVector4D(0., 0., 0., 1.)); buildTransform(); } void GLObjectBase::select() { - //qDebug() << "select" << name() << view_; + // qDebug() << "select" << name() << view_; selected_ = true; - if (view_) - ((QGLView*)view_)->selectObject(this); + if (view_) ((QGLView *)view_)->selectObject(this); } void GLObjectBase::setMaterial(const Material & m, bool with_children) { material_ = m; if (with_children) - foreach (GLObjectBase * i, children_) i->setMaterial(m, true); + foreach(GLObjectBase * i, children_) + i->setMaterial(m, true); checkPass(); is_tex_loaded = false; } @@ -355,16 +360,15 @@ void GLObjectBase::setMaterial(const Material & m, bool with_children) { void GLObjectBase::buildTransform() { itransform_.setToIdentity(); GLObjectBase * p = parent_; - if (p) - itransform_ = p->itransform_; + if (p) itransform_ = p->itransform_; if (raw_matrix) { itransform_.translate(pos_); itransform_ *= mat_; - //qDebug() << "raw_matrix" << itransform_; + // qDebug() << "raw_matrix" << itransform_; } else localTransform(itransform_); - //qDebug() << name_ << itransform_; - foreach (GLObjectBase * i, children_) + // qDebug() << name_ << itransform_; + foreach(GLObjectBase * i, children_) i->buildTransform(); } @@ -372,7 +376,8 @@ void GLObjectBase::buildTransform() { void GLObjectBase::initInternal() { init(); loadTextures(); - foreach (GLObjectBase * i, children_) i->initInternal(); + foreach(GLObjectBase * i, children_) + i->initInternal(); } @@ -386,8 +391,10 @@ void GLObjectBase::localTransform(QMatrix4x4 & m) { void GLObjectBase::checkPass() { - if (float(material_.color_diffuse.alphaF()) * (1.f - material_.transparency) < 1.f) pass_ = Transparent; - else pass_ = Solid; + if (float(material_.color_diffuse.alphaF()) * (1.f - material_.transparency) < 1.f) + pass_ = Transparent; + else + pass_ = Solid; } @@ -406,30 +413,28 @@ QMatrix4x4 GLObjectBase::worldMatrix(QMatrix4x4 parent) const { } -void GLObjectBase::render(int * id, QMap * ids, int sh_id_loc) { +void GLObjectBase::render(int * id, QMap * ids, int sh_id_loc) { if (!visible_) return; - //glPushMatrix(); - ///qglMultMatrix TODO + // glPushMatrix(); + /// qglMultMatrix TODO material_.apply(nullptr); if (id != nullptr) { ++(*id); ids->insert(*id, this); - //glVertexAttrib1f(sh_id_loc, (*id) / 255.f); - //qDebug() << "assign to" << sh_id_loc << (*id) / 255.f; + // glVertexAttrib1f(sh_id_loc, (*id) / 255.f); + // qDebug() << "assign to" << sh_id_loc << (*id) / 255.f; } draw(nullptr); - foreach (GLObjectBase * i, children_) + foreach(GLObjectBase * i, children_) i->render(id, ids, sh_id_loc); - //glPopMatrix(); + // glPopMatrix(); } - - Light::Light(): GLObjectBase(), shadow_map(0, true, GL_R16F) { - type_ = glLight; - light_type = Omni; - intensity = 1.; + type_ = glLight; + light_type = Omni; + intensity = 1.; angle_start = angle_end = 180.; decay_linear = decay_quadratic = decay_start = 0.; decay_const = decay_end = 1.; @@ -438,10 +443,10 @@ Light::Light(): GLObjectBase(), shadow_map(0, true, GL_R16F) { Light::Light(const QVector3D & p, const QColor & c, float i): GLObjectBase(), shadow_map(0, true, GL_R16F) { - type_ = glLight; - light_type = Omni; - pos_ = p; - intensity = i; + type_ = glLight; + light_type = Omni; + pos_ = p; + intensity = i; /*color_ = c;*/ angle_start = angle_end = 180.; decay_linear = decay_quadratic = decay_start = 0.; @@ -451,25 +456,25 @@ Light::Light(const QVector3D & p, const QColor & c, float i): GLObjectBase(), sh GLObjectBase * Light::clone(bool withChildren) { - Light * o = new Light(*this); - //GLObjectBase::clone(withChildren); + Light * o = new Light(*this); + // GLObjectBase::clone(withChildren); o->is_init = false; - o->name_ = name_ + "_copy"; - o->view_ = nullptr; + o->name_ = name_ + "_copy"; + o->view_ = nullptr; o->children_.clear(); if (withChildren) { for (int i = 0; i < children_.size(); ++i) o->addChild(children_[i]->clone(withChildren)); } - o->light_type = light_type; - o->direction = direction; - o->angle_start = angle_start; - o->angle_end = angle_end; - o->intensity = intensity; - o->decay_const = decay_const; - o->decay_linear = decay_linear; + o->light_type = light_type; + o->direction = direction; + o->angle_start = angle_start; + o->angle_end = angle_end; + o->intensity = intensity; + o->decay_const = decay_const; + o->decay_linear = decay_linear; o->decay_quadratic = decay_quadratic; - o->meta = meta; + o->meta = meta; return o; } @@ -486,8 +491,7 @@ void Light::draw(QOpenGLShaderProgram * prog, bool simplest) { if (light_type != Omni) { glBegin(GL_LINES); QVector4D dir = QVector4D(direction); - if (raw_matrix) - dir = transform().inverted() * dir; + if (raw_matrix) dir = transform().inverted() * dir; glVertex3f(0., 0., 0.); glVertex3f(dir.x() * s, dir.y() * s, dir.z() * s); glEnd(); @@ -496,102 +500,174 @@ void Light::draw(QOpenGLShaderProgram * prog, bool simplest) { } -QDataStream & operator <<(QDataStream & s, const GLObjectBase * p) { +QDataStream & operator<<(QDataStream & s, const GLObjectBase * p) { ChunkStream cs; - //qDebug() << "place" << p->name() << "..."; + // qDebug() << "place" << p->name() << "..."; cs << cs.chunk(1, int(p->type_)) << cs.chunk(2, p->accept_light) << cs.chunk(3, p->accept_fog) << cs.chunk(4, p->visible_) - << cs.chunk(5, p->cast_shadow) << cs.chunk(6, p->rec_shadow) << cs.chunk(7, p->raw_matrix) << cs.chunk(8, p->line_width) - << cs.chunk(9, int(p->render_mode)) << cs.chunk(10, p->material_) << cs.chunk(11, p->pos_) << cs.chunk(12, p->angles_) - << cs.chunk(13, p->scale_) << cs.chunk(14, p->mat_) << cs.chunk(15, p->vbo) << cs.chunk(16, p->children_.size()) - << cs.chunk(17, p->name_) << cs.chunk(18, p->meta); - //qDebug() << "place self done"; + << cs.chunk(5, p->cast_shadow) << cs.chunk(6, p->rec_shadow) << cs.chunk(7, p->raw_matrix) << cs.chunk(8, p->line_width) + << cs.chunk(9, int(p->render_mode)) << cs.chunk(10, p->material_) << cs.chunk(11, p->pos_) << cs.chunk(12, p->angles_) + << cs.chunk(13, p->scale_) << cs.chunk(14, p->mat_) << cs.chunk(15, p->vbo) << cs.chunk(16, p->children_.size()) + << cs.chunk(17, p->name_) << cs.chunk(18, p->meta); + // qDebug() << "place self done"; if (p->type_ == GLObjectBase::glLight) { - //qDebug() << "place light ..."; - const Light * l = (const Light*)p; + // qDebug() << "place light ..."; + const Light * l = (const Light *)p; cs << cs.chunk(100, l->direction) << cs.chunk(101, l->angle_start) << cs.chunk(102, l->angle_end) << cs.chunk(103, l->intensity) - << cs.chunk(104, l->decay_const) << cs.chunk(105, l->decay_linear) << cs.chunk(106, l->decay_quadratic) - << cs.chunk(107, l->decay_start) << cs.chunk(108, l->decay_end) << cs.chunk(109, int(l->light_type)); + << cs.chunk(104, l->decay_const) << cs.chunk(105, l->decay_linear) << cs.chunk(106, l->decay_quadratic) + << cs.chunk(107, l->decay_start) << cs.chunk(108, l->decay_end) << cs.chunk(109, int(l->light_type)); } if (p->type_ == GLObjectBase::glCamera) { - //qDebug() << "place camera ..."; - const Camera * c = (const Camera*)p; + // qDebug() << "place camera ..."; + const Camera * c = (const Camera *)p; cs << cs.chunk(200, c->aim_) << cs.chunk(201, c->fov_) << cs.chunk(202, c->depth_start) << cs.chunk(203, c->depth_end) - << cs.chunk(204, c->angle_limit_lower_xy) << cs.chunk(205, c->angle_limit_upper_xy) - << cs.chunk(206, c->mirror_x) << cs.chunk(207, c->mirror_y); + << cs.chunk(204, c->angle_limit_lower_xy) << cs.chunk(205, c->angle_limit_upper_xy) << cs.chunk(206, c->mirror_x) + << cs.chunk(207, c->mirror_y); } - //qDebug() << "place" << p->name() << cs.data().size() << s.device()->size(); + // qDebug() << "place" << p->name() << cs.data().size() << s.device()->size(); s << cs.data(); - foreach (const GLObjectBase * c, p->children_) + foreach(const GLObjectBase * c, p->children_) s << c; return s; } -QDataStream & operator >>(QDataStream & s, GLObjectBase *& p) { +QDataStream & operator>>(QDataStream & s, GLObjectBase *& p) { ChunkStream cs(s); - p = nullptr; - int ccnt = 0; - Light * l = nullptr; + p = nullptr; + int ccnt = 0; + Light * l = nullptr; Camera * c = nullptr; QVector3D cam_angles; - //qDebug() << "read obj ..."; + // qDebug() << "read obj ..."; while (!cs.atEnd()) { switch (cs.read()) { - case 1: - { + case 1: { GLObjectBase::Type type = (GLObjectBase::Type)cs.getData(); switch (type) { case GLObjectBase::glMesh: p = new GLObjectBase(); break; - case GLObjectBase::glLight: p = new Light(); l = (Light*)p; break; - case GLObjectBase::glCamera: p = new Camera(); c = (Camera*)p; break; - default : break; + case GLObjectBase::glLight: + p = new Light(); + l = (Light *)p; + break; + case GLObjectBase::glCamera: + p = new Camera(); + c = (Camera *)p; + break; + default: break; } if (p) p->type_ = type; - } + } break; + case 2: + if (p) p->accept_light = cs.getData(); + break; + case 3: + if (p) p->accept_fog = cs.getData(); + break; + case 4: + if (p) p->visible_ = cs.getData(); + break; + case 5: + if (p) p->cast_shadow = cs.getData(); + break; + case 6: + if (p) p->rec_shadow = cs.getData(); + break; + case 7: + if (p) p->raw_matrix = cs.getData(); + break; + case 8: + if (p) p->line_width = cs.getData(); + break; + case 9: + if (p) p->render_mode = (GLObjectBase::RenderMode)cs.getData(); + break; + case 10: + if (p) p->material_ = cs.getData(); + break; + case 11: + if (p) p->pos_ = cs.getData(); break; - case 2: if (p) p->accept_light = cs.getData(); break; - case 3: if (p) p->accept_fog = cs.getData(); break; - case 4: if (p) p->visible_ = cs.getData(); break; - case 5: if (p) p->cast_shadow = cs.getData(); break; - case 6: if (p) p->rec_shadow = cs.getData(); break; - case 7: if (p) p->raw_matrix = cs.getData(); break; - case 8: if (p) p->line_width = cs.getData(); break; - case 9: if (p) p->render_mode = (GLObjectBase::RenderMode)cs.getData(); break; - case 10: if (p) p->material_ = cs.getData(); break; - case 11: if (p) p->pos_ = cs.getData(); break; case 12: if (p) p->angles_ = cs.getData(); if (c) { c->setAngles(cs.getData()); cam_angles = c->angles(); } - break; - case 13: if (p) p->scale_ = cs.getData(); break; - case 14: if (p) p->mat_ = cs.getData(); break; - case 15: if (p) p->vbo = cs.getData(); break; - case 16: if (p) ccnt = cs.getData(); break; - case 17: if (p) p->name_ = cs.getData(); break; - case 18: if (p) p->meta = cs.getData(); break; - case 100: if (l) l->direction = cs.getData(); break; - case 101: if (l) l->angle_start = cs.getData(); break; - case 102: if (l) l->angle_end = cs.getData(); break; - case 103: if (l) l->intensity = cs.getData(); break; - case 104: if (l) l->decay_const = cs.getData(); break; - case 105: if (l) l->decay_linear = cs.getData(); break; - case 106: if (l) l->decay_quadratic = cs.getData(); break; - case 107: if (l) l->decay_start = cs.getData(); break; - case 108: if (l) l->decay_end = cs.getData(); break; - case 109: if (l) l->light_type = (Light::Type)cs.getData(); break; - case 200: if (c) c->setAim(cs.getData()); break; - case 201: if (c) c->setFOV(cs.getData()); break; - case 202: if (c) c->setDepthStart(cs.getData()); break; - case 203: if (c) c->setDepthEnd(cs.getData()); break; - case 204: if (c) c->setAngleLowerLimitXY(cs.getData()); break; - case 205: if (c) c->setAngleUpperLimitXY(cs.getData()); break; - case 206: if (c) c->mirror_x = cs.getData(); break; - case 207: if (c) c->mirror_y = cs.getData(); break; + break; + case 13: + if (p) p->scale_ = cs.getData(); + break; + case 14: + if (p) p->mat_ = cs.getData(); + break; + case 15: + if (p) p->vbo = cs.getData(); + break; + case 16: + if (p) ccnt = cs.getData(); + break; + case 17: + if (p) p->name_ = cs.getData(); + break; + case 18: + if (p) p->meta = cs.getData(); + break; + case 100: + if (l) l->direction = cs.getData(); + break; + case 101: + if (l) l->angle_start = cs.getData(); + break; + case 102: + if (l) l->angle_end = cs.getData(); + break; + case 103: + if (l) l->intensity = cs.getData(); + break; + case 104: + if (l) l->decay_const = cs.getData(); + break; + case 105: + if (l) l->decay_linear = cs.getData(); + break; + case 106: + if (l) l->decay_quadratic = cs.getData(); + break; + case 107: + if (l) l->decay_start = cs.getData(); + break; + case 108: + if (l) l->decay_end = cs.getData(); + break; + case 109: + if (l) l->light_type = (Light::Type)cs.getData(); + break; + case 200: + if (c) c->setAim(cs.getData()); + break; + case 201: + if (c) c->setFOV(cs.getData()); + break; + case 202: + if (c) c->setDepthStart(cs.getData()); + break; + case 203: + if (c) c->setDepthEnd(cs.getData()); + break; + case 204: + if (c) c->setAngleLowerLimitXY(cs.getData()); + break; + case 205: + if (c) c->setAngleUpperLimitXY(cs.getData()); + break; + case 206: + if (c) c->mirror_x = cs.getData(); + break; + case 207: + if (c) c->mirror_y = cs.getData(); + break; } } if (c) c->setAngles(cam_angles); - //qDebug() << p->name() << ccnt; + // qDebug() << p->name() << ccnt; for (int i = 0; i < ccnt; ++i) { GLObjectBase * c = nullptr; s >> c; diff --git a/libs/qglview/globject.h b/libs/qglview/globject.h index 88e812d..408d246 100644 --- a/libs/qglview/globject.h +++ b/libs/qglview/globject.h @@ -19,101 +19,158 @@ #ifndef GLOBJECT_H #define GLOBJECT_H -#include "glvbo.h" #include "glframebuffer.h" #include "glmaterial.h" +#include "glvbo.h" class Camera; class QGLView; -class GLObjectBase -{ +class GLObjectBase { friend class QGLView; friend class GLRendererBase; - friend QDataStream & operator <<(QDataStream & s, const GLObjectBase * p); - friend QDataStream & operator >>(QDataStream & s, GLObjectBase *& p); + friend QDataStream & operator<<(QDataStream & s, const GLObjectBase * p); + friend QDataStream & operator>>(QDataStream & s, GLObjectBase *& p); friend GLObjectBase * loadFromQGLFile(const QString & filepath); + public: - enum Type {glMesh, glLight, glCamera, glParticlesSystem}; - enum Pass {Solid, Transparent, Reflection, User}; - enum GeomPrimitives {Triangles = GL_TRIANGLES, Quads = GL_QUADS}; - enum RenderMode {View = 0, Point = GL_POINT, Line = GL_LINE, Fill = GL_FILL}; + enum Type { + glMesh, + glLight, + glCamera, + glParticlesSystem + }; + enum Pass { + Solid, + Transparent, + Reflection, + User + }; + enum GeomPrimitives { + Triangles = GL_TRIANGLES, + Quads = GL_QUADS + }; + enum RenderMode { + View = 0, + Point = GL_POINT, + Line = GL_LINE, + Fill = GL_FILL + }; explicit GLObjectBase(); virtual ~GLObjectBase(); virtual GLObjectBase * clone(bool withChildren = true); - QString name() const {return name_;} - void setName(const QString & name) {name_ = name;} - //virtual GLuint hList() {return list;} + QString name() const { return name_; } + void setName(const QString & name) { name_ = name; } + // virtual GLuint hList() {return list;} virtual void init(); virtual void draw(QOpenGLShaderProgram * prog, bool simplest = false); virtual void update() {} - bool isInit() const {return is_init;} - bool isTexturesLoaded() const {return is_tex_loaded;} - Type type() const {return type_;} + bool isInit() const { return is_init; } + bool isTexturesLoaded() const { return is_tex_loaded; } + Type type() const { return type_; } - RenderMode renderMode() const {return render_mode;} - void setRenderMode(RenderMode mode) {render_mode = mode;} + RenderMode renderMode() const { return render_mode; } + void setRenderMode(RenderMode mode) { render_mode = mode; } - float lineWidth() const {return line_width;} - void setLineWidth(const float & width) {line_width = width;} + float lineWidth() const { return line_width; } + void setLineWidth(const float & width) { line_width = width; } - GLObjectBase * parent() {return parent_;} - void setParent(GLObjectBase * o) {parent_ = o;} - bool hasParent() const {return parent_ != nullptr;} - bool hasChildren() const {return children_.size() != 0;} + GLObjectBase * parent() { return parent_; } + void setParent(GLObjectBase * o) { parent_ = o; } + bool hasParent() const { return parent_ != nullptr; } + bool hasChildren() const { return children_.size() != 0; } void setView(QGLView * v); void addChild(GLObjectBase * o); void removeChild(GLObjectBase * o); void removeChild(int index); void clearChildren(bool deleteAll = false); - int childCount() const {return children_.size();} + int childCount() const { return children_.size(); } GLObjectBase * child(int index); GLObjectBase * child(const QString & name); const GLObjectBase * child(int index) const; const GLObjectBase * child(const QString & name) const; - QList children(bool all_ = false); + QList children(bool all_ = false); - bool isVisible() const {return visible_;} - bool isHidden() const {return !visible_;} - void setVisible(bool v) {visible_ = v;} - void setHidden(bool v) {visible_ = !v;} - void show() {visible_ = true;} - void hide() {visible_ = false;} + bool isVisible() const { return visible_; } + bool isHidden() const { return !visible_; } + void setVisible(bool v) { visible_ = v; } + void setHidden(bool v) { visible_ = !v; } + void show() { visible_ = true; } + void hide() { visible_ = false; } - bool isReceiveShadows() const {return rec_shadow;} - bool isCastShadows() const {return cast_shadow;} - void setReceiveShadows(bool on) {rec_shadow = on;} - void setCastShadows(bool on) {cast_shadow = on;} + bool isReceiveShadows() const { return rec_shadow; } + bool isCastShadows() const { return cast_shadow; } + void setReceiveShadows(bool on) { rec_shadow = on; } + void setCastShadows(bool on) { cast_shadow = on; } - void move(const QVector3D & dv) {pos_ += dv; buildTransform();} - void moveTo(const QVector3D & dv) {pos_ = dv; buildTransform();} - void move(GLfloat dx, GLfloat dy, GLfloat dz = 0.) {move(QVector3D(dx, dy, dz)); buildTransform();} - void moveTo(GLfloat dx, GLfloat dy, GLfloat dz = 0.) {moveTo(QVector3D(dx, dy, dz)); buildTransform();} - void moveX(GLfloat o) {pos_.setX(pos_.x() + o); buildTransform();} - void moveY(GLfloat o) {pos_.setY(pos_.y() + o); buildTransform();} - void moveZ(GLfloat o) {pos_.setZ(pos_.z() + o); buildTransform();} - void setPosX(GLfloat o) {pos_.setX(o); buildTransform();} - void setPosY(GLfloat o) {pos_.setY(o); buildTransform();} - void setPosZ(GLfloat o) {pos_.setZ(o); buildTransform();} - void setPos(GLfloat x, GLfloat y, GLfloat z) {pos_ = QVector3D(x, y, z); buildTransform();} - void setPos(const QVector3D & p) {pos_ = p; buildTransform();} - void resetPos() {pos_ = QVector3D(0., 0., 0.); buildTransform();} + void move(const QVector3D & dv) { + pos_ += dv; + buildTransform(); + } + void moveTo(const QVector3D & dv) { + pos_ = dv; + buildTransform(); + } + void move(GLfloat dx, GLfloat dy, GLfloat dz = 0.) { + move(QVector3D(dx, dy, dz)); + buildTransform(); + } + void moveTo(GLfloat dx, GLfloat dy, GLfloat dz = 0.) { + moveTo(QVector3D(dx, dy, dz)); + buildTransform(); + } + void moveX(GLfloat o) { + pos_.setX(pos_.x() + o); + buildTransform(); + } + void moveY(GLfloat o) { + pos_.setY(pos_.y() + o); + buildTransform(); + } + void moveZ(GLfloat o) { + pos_.setZ(pos_.z() + o); + buildTransform(); + } + void setPosX(GLfloat o) { + pos_.setX(o); + buildTransform(); + } + void setPosY(GLfloat o) { + pos_.setY(o); + buildTransform(); + } + void setPosZ(GLfloat o) { + pos_.setZ(o); + buildTransform(); + } + void setPos(GLfloat x, GLfloat y, GLfloat z) { + pos_ = QVector3D(x, y, z); + buildTransform(); + } + void setPos(const QVector3D & p) { + pos_ = p; + buildTransform(); + } + void resetPos() { + pos_ = QVector3D(0., 0., 0.); + buildTransform(); + } - QVector3D pos() const {return pos_;} - float posX() const {return pos_.x();} - float posY() const {return pos_.y();} - float posZ() const {return pos_.z();} - QVector3D worldPos() const {return (itransform_ * QVector4D(0, 0, 0, 1.)).toVector3D();} - QMatrix4x4 worldTransform() const {return itransform_;} + QVector3D pos() const { return pos_; } + float posX() const { return pos_.x(); } + float posY() const { return pos_.y(); } + float posZ() const { return pos_.z(); } + QVector3D worldPos() const { return (itransform_ * QVector4D(0, 0, 0, 1.)).toVector3D(); } + QMatrix4x4 worldTransform() const { return itransform_; } - QVector3D rotation() const {return angles_;} - float rotationX() const {return angles_.x();} - float rotationY() const {return angles_.y();} - float rotationZ() const {return angles_.z();} + QVector3D rotation() const { return angles_; } + float rotationX() const { return angles_.x(); } + float rotationY() const { return angles_.y(); } + float rotationZ() const { return angles_.z(); } void rotateX(GLfloat a); void rotateY(GLfloat a); void rotateZ(GLfloat a); @@ -123,58 +180,113 @@ public: void setRotation(const QVector3D & a); void resetRotation(); - QVector3D scale() {return scale_;} - float scaleX() {return scale_.x();} - float scaleY() {return scale_.y();} - float scaleZ() {return scale_.z();} - void scale(const QVector3D & sv) {raw_matrix = false; scale_ *= sv; buildTransform();} - void scale(GLfloat sx, GLfloat sy, GLfloat sz) {raw_matrix = false; scale(QVector3D(sx, sy, sz)); buildTransform();} - void scale(GLfloat sx, GLfloat sy) {raw_matrix = false; scale(QVector3D(sx, sy, sy)); buildTransform();} - void scale(GLfloat sx) {raw_matrix = false; scale(QVector3D(sx, sx, sx)); buildTransform();} - void scaleX(GLfloat a) {raw_matrix = false; scale_.setX(scale_.x() + a); buildTransform();} - void scaleY(GLfloat a) {raw_matrix = false; scale_.setY(scale_.y() + a); buildTransform();} - void scaleZ(GLfloat a) {raw_matrix = false; scale_.setZ(scale_.z() + a); buildTransform();} - void setScale(const QVector3D & a) {raw_matrix = false; scale_ = a; buildTransform();} - void setScale(GLfloat a) {raw_matrix = false; scale_ = QVector3D(a, a, a); buildTransform();} - void setScaleX(GLfloat a) {raw_matrix = false; scale_.setX(a); buildTransform();} - void setScaleY(GLfloat a) {raw_matrix = false; scale_.setY(a); buildTransform();} - void setScaleZ(GLfloat a) {raw_matrix = false; scale_.setZ(a); buildTransform();} - void resetScale() {raw_matrix = false; scale_ = QVector3D(1., 1., 1.); buildTransform();} - - QMatrix4x4 transform() {return mat_;} + QVector3D scale() { return scale_; } + float scaleX() { return scale_.x(); } + float scaleY() { return scale_.y(); } + float scaleZ() { return scale_.z(); } + void scale(const QVector3D & sv) { + raw_matrix = false; + scale_ *= sv; + buildTransform(); + } + void scale(GLfloat sx, GLfloat sy, GLfloat sz) { + raw_matrix = false; + scale(QVector3D(sx, sy, sz)); + buildTransform(); + } + void scale(GLfloat sx, GLfloat sy) { + raw_matrix = false; + scale(QVector3D(sx, sy, sy)); + buildTransform(); + } + void scale(GLfloat sx) { + raw_matrix = false; + scale(QVector3D(sx, sx, sx)); + buildTransform(); + } + void scaleX(GLfloat a) { + raw_matrix = false; + scale_.setX(scale_.x() + a); + buildTransform(); + } + void scaleY(GLfloat a) { + raw_matrix = false; + scale_.setY(scale_.y() + a); + buildTransform(); + } + void scaleZ(GLfloat a) { + raw_matrix = false; + scale_.setZ(scale_.z() + a); + buildTransform(); + } + void setScale(const QVector3D & a) { + raw_matrix = false; + scale_ = a; + buildTransform(); + } + void setScale(GLfloat a) { + raw_matrix = false; + scale_ = QVector3D(a, a, a); + buildTransform(); + } + void setScaleX(GLfloat a) { + raw_matrix = false; + scale_.setX(a); + buildTransform(); + } + void setScaleY(GLfloat a) { + raw_matrix = false; + scale_.setY(a); + buildTransform(); + } + void setScaleZ(GLfloat a) { + raw_matrix = false; + scale_.setZ(a); + buildTransform(); + } + void resetScale() { + raw_matrix = false; + scale_ = QVector3D(1., 1., 1.); + buildTransform(); + } + + QMatrix4x4 transform() { return mat_; } void setTransform(const QMatrix4x4 & t); - bool isRawMatrix() {return raw_matrix;} + bool isRawMatrix() { return raw_matrix; } - bool isAcceptLight() const {return accept_light;} - void setAcceptLight(bool yes) {accept_light = yes;} + bool isAcceptLight() const { return accept_light; } + void setAcceptLight(bool yes) { accept_light = yes; } - bool isAcceptFog() const {return accept_fog;} - void setAcceptFog(bool yes) {accept_fog = yes;} + bool isAcceptFog() const { return accept_fog; } + void setAcceptFog(bool yes) { accept_fog = yes; } - bool isSelected() const {return selected_;} - void setSelected(bool yes) {selected_ = yes;} + bool isSelected() const { return selected_; } + void setSelected(bool yes) { selected_ = yes; } void select(); - void deselect() {selected_ = false;} + void deselect() { selected_ = false; } - bool isSelectable() const {return select_;} - void setSelectable(bool yes) {select_ = yes;} + bool isSelectable() const { return select_; } + void setSelectable(bool yes) { select_ = yes; } /* bool isWriteDepth() const {return write_depth_;} void setWriteDepth(bool yes) {write_depth_ = yes;}*/ - QColor color() const {return material_.color_diffuse;} - void setColor(const QColor & c) {material_.color_diffuse = c; checkPass();} + QColor color() const { return material_.color_diffuse; } + void setColor(const QColor & c) { + material_.color_diffuse = c; + checkPass(); + } - GLenum srcAlpha() const {return blend_src;} - GLenum destAlpha() const {return blend_dest;} - void setSrcAlpha(GLenum mode) {blend_src = mode;} - void setDestAlpha(GLenum mode) {blend_dest = mode;} + GLenum srcAlpha() const { return blend_src; } + GLenum destAlpha() const { return blend_dest; } + void setSrcAlpha(GLenum mode) { blend_src = mode; } + void setDestAlpha(GLenum mode) { blend_dest = mode; } void setMaterial(const Material & m, bool with_children = false); - Material & material() {return material_;} + Material & material() { return material_; } - const Box3D & boundingBox(bool withChildren = true) const {return bound;} - GLVBO & VBO() {return vbo;} + const Box3D & boundingBox(bool withChildren = true) const { return bound; } + GLVBO & VBO() { return vbo; } void calculateBoundingBox(); @@ -188,21 +300,22 @@ public: QVector faces, uvws, norms; QVector normals; - //QVector d_vertices, d_normals, d_uvs; + // QVector d_vertices, d_normals, d_uvs; protected: - void addChildren(QList & list, GLObjectBase * where); + void addChildren(QList & list, GLObjectBase * where); void loadTextures(bool with_children = false); - //void deleteTextures() {foreach (GLuint i, textures) currentQGLView->deleteTexture(i); textures.clear();} + // void deleteTextures() {foreach (GLuint i, textures) currentQGLView->deleteTexture(i); textures.clear();} void buildTransform(); void initInternal(); - void render(int * id = nullptr, QMap * ids = nullptr, int sh_id_loc = 0); + void render(int * id = nullptr, QMap * ids = nullptr, int sh_id_loc = 0); void checkPass(); virtual void localTransform(QMatrix4x4 & m); QMatrix4x4 worldMatrix(QMatrix4x4 parent) const; int pass_; // Pass - bool is_init, is_tex_loaded, accept_light, accept_fog, /*write_depth_,*/ visible_, cast_shadow, rec_shadow, select_, selected_, raw_matrix; + bool is_init, is_tex_loaded, accept_light, accept_fog, /*write_depth_,*/ visible_, cast_shadow, rec_shadow, select_, selected_, + raw_matrix; bool is_root; float line_width; Type type_; @@ -211,31 +324,40 @@ protected: Material material_; Box3D bound; QVector3D pos_, angles_, scale_; - QList children_; + QList children_; QList textures; QMatrix4x4 itransform_, mat_; - //QColor color_; + // QColor color_; QString name_; GLenum blend_src, blend_dest; GLObjectBase * parent_; QGLViewBase * view_; GLVBO vbo; QVariantMap meta; - }; -inline bool operator <(const GLObjectBase & f, const GLObjectBase & s) {return f.pos_h.z() < s.pos_h.z();} +inline bool operator<(const GLObjectBase & f, const GLObjectBase & s) { + return f.pos_h.z() < s.pos_h.z(); +} class Light: public GLObjectBase { friend class QGLView; friend class GLRendererBase; + public: - enum Type {Omni, Directional, Cone}; + enum Type { + Omni, + Directional, + Cone + }; Light(); Light(const QVector3D & p, const QColor & c = Qt::white, float i = 1.); virtual GLObjectBase * clone(bool withChildren = true); - virtual void init() {shadow_map.resize(512, 512); is_init = true;} + virtual void init() { + shadow_map.resize(512, 512); + is_init = true; + } virtual void draw(QOpenGLShaderProgram * prog, bool simplest = false); QVector3D direction, dir0, dir1; @@ -252,17 +374,20 @@ public: QMatrix4x4 shadow_matrix; protected: - }; -template -inline T globject_cast(GLObjectBase * object) {return reinterpret_cast(object);} +template +inline T globject_cast(GLObjectBase * object) { + return reinterpret_cast(object); +} -template -inline T globject_cast(const GLObjectBase * object) {return reinterpret_cast(object);} +template +inline T globject_cast(const GLObjectBase * object) { + return reinterpret_cast(object); +} -QDataStream & operator <<(QDataStream & s, const GLObjectBase * p); -QDataStream & operator >>(QDataStream & s, GLObjectBase *& p); +QDataStream & operator<<(QDataStream & s, const GLObjectBase * p); +QDataStream & operator>>(QDataStream & s, GLObjectBase *& p); #endif // GLOBJECT_H diff --git a/libs/qglview/globject_editor.cpp b/libs/qglview/globject_editor.cpp index 30263e8..4392254 100644 --- a/libs/qglview/globject_editor.cpp +++ b/libs/qglview/globject_editor.cpp @@ -17,8 +17,9 @@ */ #include "globject_editor.h" -#include "ui_globject_editor.h" + #include "glcamera.h" +#include "ui_globject_editor.h" GLObjectEditor::GLObjectEditor(QWidget * parent): QWidget(parent) { @@ -37,11 +38,8 @@ GLObjectEditor::GLObjectEditor(QWidget * parent): QWidget(parent) { void GLObjectEditor::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } @@ -76,8 +74,8 @@ void GLObjectEditor::setObject(GLObjectBase * o) { ui->groupLight->setEnabled(object->type() == GLObjectBase::glLight); ui->groupLight->setVisible(object->type() == GLObjectBase::glLight); if (object->type() == GLObjectBase::glLight) { - Light * l = globject_cast(object); - //bool is_dir = l->light_type == Light::Directional, is_cone = l->light_type == Light::Cone; + Light * l = globject_cast(object); + // bool is_dir = l->light_type == Light::Directional, is_cone = l->light_type == Light::Cone; ui->buttonLightColor->setColor(l->color()); ui->comboLightType->setCurrentIndex(l->light_type); ui->spinLightIntensity->setValue(l->intensity); @@ -93,7 +91,7 @@ void GLObjectEditor::setObject(GLObjectBase * o) { ui->groupCamera->setEnabled(object->type() == GLObjectBase::glCamera); ui->groupCamera->setVisible(object->type() == GLObjectBase::glCamera); if (object->type() == GLObjectBase::glCamera) { - Camera * c = globject_cast(object); + Camera * c = globject_cast(object); ui->checkCameraMirrorX->setChecked(c->isMirrorX()); ui->checkCameraMirrorY->setChecked(c->isMirrorY()); ui->spinCameraFOV->setValue(c->FOV()); @@ -125,20 +123,21 @@ void GLObjectEditor::objectChanged() { object->setReceiveShadows(ui->checkReceiveShadows->isChecked()); object->setRenderMode((GLObjectBase::RenderMode)rmodes[ui->comboRenderMode->currentIndex()]); if (object->type() == GLObjectBase::glLight) { - Light * l = globject_cast(object); - //bool is_dir = l->light_type == Light::Directional, is_cone = l->light_type == Light::Cone; + Light * l = globject_cast(object); + // bool is_dir = l->light_type == Light::Directional, is_cone = l->light_type == Light::Cone; l->setColor(ui->buttonLightColor->color()); - l->light_type = (Light::Type)ui->comboLightType->currentIndex(); - l->intensity = ui->spinLightIntensity->value(); - l->decay_const = ui->spinLightDecayConst->value(); - l->decay_linear = ui->spinLightDecayLinear->value(); + l->light_type = (Light::Type)ui->comboLightType->currentIndex(); + l->intensity = ui->spinLightIntensity->value(); + l->decay_const = ui->spinLightDecayConst->value(); + l->decay_linear = ui->spinLightDecayLinear->value(); l->decay_quadratic = ui->spinLightDecayQuadratic->value(); - l->angle_start = ui->spinLightAngleStart->value(); - l->angle_end = ui->spinLightAngleEnd->value(); - l->direction = QVector3D(ui->spinLightDirectionX->value(), ui->spinLightDirectionY->value(), ui->spinLightDirectionZ->value()).normalized(); + l->angle_start = ui->spinLightAngleStart->value(); + l->angle_end = ui->spinLightAngleEnd->value(); + l->direction = + QVector3D(ui->spinLightDirectionX->value(), ui->spinLightDirectionY->value(), ui->spinLightDirectionZ->value()).normalized(); } if (object->type() == GLObjectBase::glCamera) { - Camera * c = globject_cast(object); + Camera * c = globject_cast(object); c->setMirrorX(ui->checkCameraMirrorX->isChecked()); c->setMirrorY(ui->checkCameraMirrorY->isChecked()); c->setFOV(ui->spinCameraFOV->value()); @@ -150,14 +149,12 @@ void GLObjectEditor::objectChanged() { void GLObjectEditor::on_spinLightAngleStart_valueChanged(double v) { - if (ui->spinLightAngleEnd->value() < v) - ui->spinLightAngleEnd->setValue(v); + if (ui->spinLightAngleEnd->value() < v) ui->spinLightAngleEnd->setValue(v); } void GLObjectEditor::on_spinLightAngleEnd_valueChanged(double v) { - if (ui->spinLightAngleStart->value() > v) - ui->spinLightAngleStart->setValue(v); + if (ui->spinLightAngleStart->value() > v) ui->spinLightAngleStart->setValue(v); } diff --git a/libs/qglview/globject_editor.h b/libs/qglview/globject_editor.h index 2b38baa..f367638 100644 --- a/libs/qglview/globject_editor.h +++ b/libs/qglview/globject_editor.h @@ -22,17 +22,17 @@ #include "globject.h" namespace Ui { - class GLObjectEditor; +class GLObjectEditor; }; -class GLObjectEditor: public QWidget -{ +class GLObjectEditor: public QWidget { Q_OBJECT + public: explicit GLObjectEditor(QWidget * parent = 0); void setObject(GLObjectBase * o); - GLObjectBase * getObject() {return object;} + GLObjectBase * getObject() { return object; } protected: void changeEvent(QEvent * e); @@ -50,7 +50,6 @@ private slots: signals: void changed(); - }; #endif // GLOBJECT_EDITOR_H diff --git a/libs/qglview/glparticles_system.cpp b/libs/qglview/glparticles_system.cpp index e2409fd..99ec527 100644 --- a/libs/qglview/glparticles_system.cpp +++ b/libs/qglview/glparticles_system.cpp @@ -20,17 +20,17 @@ GLParticlesSystem::GLParticlesSystem(const QVector3D & pos): GLObjectBase() { - pass_ = GLObjectBase::Transparent; - freq = 40.f; - birthRate_ = 10.f; - lifeDuration_ = 2.f; - fade_time = 0.5f; - size_ = 1.f; + pass_ = GLObjectBase::Transparent; + freq = 40.f; + birthRate_ = 10.f; + lifeDuration_ = 2.f; + fade_time = 0.5f; + size_ = 1.f; additionalSpeed = 0.f; - initialSpeed_ = 1.f; - need_birth = -1.f; + initialSpeed_ = 1.f; + need_birth = -1.f; tex_rect.setRect(0., 0., 1., 1.); - tex_scale = QSizeF(); + tex_scale = QSizeF(); emitterPosition_ = pos; emitterDirection_.setZ(1.); speedDirection_.setZ(1.); @@ -38,64 +38,65 @@ GLParticlesSystem::GLParticlesSystem(const QVector3D & pos): GLObjectBase() { lifeDurationJitter_ = speedJitter_ = speedDirectionJitter_ = sizeJitter_ = angleJitter_ = 0.f; active_ = birthEnabled_ = true; is_diffuse_anim = add_vert_face = false; - emitterType_ = Cone; - tick_life = 1.f / freq; - tick_birth = birthRate_ / freq; + emitterType_ = Cone; + tick_life = 1.f / freq; + tick_birth = birthRate_ / freq; } void GLParticlesSystem::update() { - //qDebug() << "update" << need_birth << tick_birth; + // qDebug() << "update" << need_birth << tick_birth; if (!active_) return; - //QMutexLocker locker(&mutex); + // QMutexLocker locker(&mutex); Particle cp(lifeDuration_); if (birthEnabled_) need_birth += tick_birth; qDebug() << "update" << particles.size(); if (need_birth >= 1.f) { - cp.pos = emitterPosition_; - //qDebug() << "speed" << cp.speed; + cp.pos = emitterPosition_; + // qDebug() << "speed" << cp.speed; cp.speedDecay = 1.f + speedDecay_; for (int i = 0; i < floor(need_birth); ++i) { cp.lifeDuration = lifeDuration_ + urand(lifeDurationJitter_); switch (emitterType_) { - case Omni: - cp.speed = QVector3D(urand(), urand(), urand()).normalized() * initialSpeed_ * (1.f + urand(speedJitter_)); - break; - case Cone: case Box: + case Omni: cp.speed = QVector3D(urand(), urand(), urand()).normalized() * initialSpeed_ * (1.f + urand(speedJitter_)); break; + case Cone: + case Box: cp.speed = emitterDirection_ * initialSpeed_ * (1.f + urand(speedJitter_)); cp.speed += orthToVector(cp.speed, speedDirectionJitter_); break; } - if (emitterType_ == Box) - cp.pos = emitterRect_.randomPoint(); - //qDebug() << "before" << cp.speed.length(); + if (emitterType_ == Box) cp.pos = emitterRect_.randomPoint(); + // qDebug() << "before" << cp.speed.length(); lengthenVector(cp.speed, additionalSpeed); - //qDebug() << "after" << cp.speed.length(); - cp.size = size_ + urand(sizeJitter_); - cp.angle = initialAngle_ + urand(angleJitter_); + // qDebug() << "after" << cp.speed.length(); + cp.size = size_ + urand(sizeJitter_); + cp.angle = initialAngle_ + urand(angleJitter_); cp.enlargeSpeed = (enlargeSpeed_ + urand(enlargeSpeedJitter_)) * tick_life; /*if (is_diffuse_anim) { - if (material_.diffuse.animation_frame_rate < 0 && animation->bitmaps.size() > 0) - cp.animationFrameRate = animation->bitmaps.size() / cp.lifeDuration; - else - cp.animationFrameRate = material_.diffuse.animation_frame_rate; + if (material_.diffuse.animation_frame_rate < 0 && animation->bitmaps.size() > 0) + cp.animationFrameRate = animation->bitmaps.size() / cp.lifeDuration; + else + cp.animationFrameRate = material_.diffuse.animation_frame_rate; }*/ - if (tex_scale.isEmpty()) cp.tex_rect.setSize(tex_rect.size()); - else cp.tex_rect.setSize(tex_rect.size() * tex_scale); - cp.tex_rect.moveTopLeft(tex_rect.topLeft() + QPointF(uprand(tex_rect.width() - cp.tex_rect.width()), uprand(tex_rect.height() - cp.tex_rect.height()))); - //cp.tex_rect = tex_rect; + if (tex_scale.isEmpty()) + cp.tex_rect.setSize(tex_rect.size()); + else + cp.tex_rect.setSize(tex_rect.size() * tex_scale); + cp.tex_rect.moveTopLeft(tex_rect.topLeft() + QPointF(uprand(tex_rect.width() - cp.tex_rect.width()), + uprand(tex_rect.height() - cp.tex_rect.height()))); + // cp.tex_rect = tex_rect; particles.push_back(cp); } need_birth -= floor(need_birth); } for (int i = 0; i < particles.size(); ++i) { Particle & c(particles[i]); - foreach (const QVector3D & f, forces) + foreach(const QVector3D & f, forces) c.speed += f; c.lifeCurrent += tick_life; - //qDebug() << "life" << c.lifeCurrent << c.lifeDuration; + // qDebug() << "life" << c.lifeCurrent << c.lifeDuration; if (c.lifeCurrent > c.lifeDuration) { - //qDebug() << "remove" << i; + // qDebug() << "remove" << i; particles.remove(i); i--; continue; @@ -103,7 +104,7 @@ void GLParticlesSystem::update() { c.pos += c.speed * tick_life; c.speed /= c.speedDecay; c.size += c.enlargeSpeed; - //if (c.lifeCurrent > 1.) c.angle += urand(5.); + // if (c.lifeCurrent > 1.) c.angle += urand(5.); } } @@ -114,31 +115,30 @@ void GLParticlesSystem::draw(QOpenGLShaderProgram * prog, bool) { pass_ = GLObjectBase::Transparent; Camera * camera(view_->camera()); QVector3D apos = camera->pos(), dir = camera->direction(); - //qDebug() << dir; - //qDebug() << camera.angles(); - //qDebug() << camera.angle_xy; + // qDebug() << dir; + // qDebug() << camera.angles(); + // qDebug() << camera.angle_xy; GLfloat cxyc, czs, czc; - GLfloat dx, dy, cdx, cdy, cdz, a, tr_r = material_.color_diffuse.redF(), - tr_g = material_.color_diffuse.greenF(), + GLfloat dx, dy, cdx, cdy, cdz, a, tr_r = material_.color_diffuse.redF(), tr_g = material_.color_diffuse.greenF(), tr_b = material_.color_diffuse.blueF(), tr_a = material_.color_diffuse.alphaF() * (1.f - material_.transparency); - //cxys = sin(camera.angle_xy * deg2rad); - cxyc = cosf(camera->angles_.y() * deg2rad); - czs = sinf(camera->angles_.z() * deg2rad); - czc = cosf(camera->angles_.z() * deg2rad); + // cxys = sin(camera.angle_xy * deg2rad); + cxyc = cosf(camera->angles_.y() * deg2rad); + czs = sinf(camera->angles_.z() * deg2rad); + czc = cosf(camera->angles_.z() * deg2rad); - dx = -czc; - dy = czs; + dx = -czc; + dy = czs; vertices.clear(); texcoords.clear(); colors.clear(); for (int i = 0; i < particles.size(); ++i) - //particles[i].pos_h.setZ((particles[i].pos - apos).lengthSquared()); + // particles[i].pos_h.setZ((particles[i].pos - apos).lengthSquared()); particles[i].pos_h.setZ(particles[i].pos.distanceToPlane(apos, dir)); std::sort(particles.begin(), particles.end()); glBegin(GL_POINTS); - foreach (const Particle & i, particles) { - //glVertex3f(i.pos.x(), i.pos.y(), i.pos.z()); + foreach(const Particle & i, particles) { + // glVertex3f(i.pos.x(), i.pos.y(), i.pos.z()); a = (i.lifeDuration - i.lifeCurrent) / fade_time; if (a > 1.f) a = 1.f; a *= tr_a; @@ -182,12 +182,12 @@ void GLParticlesSystem::draw(QOpenGLShaderProgram * prog, bool) { } } glEnd(); - //bool cae = glIsEnabled(GL_COLOR_ARRAY), nae = glIsEnabled(GL_NORMAL_ARRAY); + // bool cae = glIsEnabled(GL_COLOR_ARRAY), nae = glIsEnabled(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); - //glNormal3f(vn.x(), vn.y(), vn.z()); + // glNormal3f(vn.x(), vn.y(), vn.z()); glNormal3f(0., 0., 1.); glDepthMask(false); glEnable(GL_COLOR_ARRAY); @@ -195,21 +195,20 @@ void GLParticlesSystem::draw(QOpenGLShaderProgram * prog, bool) { glVertexPointer(3, GL_FLOAT, 0, vertices.constData()); glTexCoordPointer(2, GL_FLOAT, 0, texcoords.constData()); glColorPointer(4, GL_FLOAT, 0, colors.constData()); - //glEnable(GL_ALPHA_TEST); - //glAlphaFunc(); + // glEnable(GL_ALPHA_TEST); + // glAlphaFunc(); glDrawArrays(GL_QUADS, 0, vertices.size() / 3); glDepthMask(true); - //glDisable(GL_ALPHA_TEST); - //if (!cae) glDisable(GL_COLOR_ARRAY); - //if (nae) glEnable(GL_NORMAL_ARRAY); + // glDisable(GL_ALPHA_TEST); + // if (!cae) glDisable(GL_COLOR_ARRAY); + // if (nae) glEnable(GL_NORMAL_ARRAY); } - GLParticlesSystem::Particle::Particle(float life_dur) { - size = 1.; + size = 1.; angle = lifeCurrent = 0.; - speedDecay = 0.; - lifeDuration = life_dur; - tex_rect = QRectF(0, 0, 1, 1); + speedDecay = 0.; + lifeDuration = life_dur; + tex_rect = QRectF(0, 0, 1, 1); } diff --git a/libs/qglview/glparticles_system.h b/libs/qglview/glparticles_system.h index 1fe3e5e..1cc7098 100644 --- a/libs/qglview/glparticles_system.h +++ b/libs/qglview/glparticles_system.h @@ -19,13 +19,16 @@ #ifndef GLPARTICLES_SYSTEM_H #define GLPARTICLES_SYSTEM_H -#include -#include "gltexture_manager.h" -#include "globject.h" #include "glcamera.h" +#include "globject.h" +#include "gltexture_manager.h" -class GLParticlesSystem: public QObject, public GLObjectBase, protected QOpenGLFunctions -{ +#include + +class GLParticlesSystem + : public QObject + , public GLObjectBase + , protected QOpenGLFunctions { Q_OBJECT Q_PROPERTY(float birthRate READ birthRate WRITE setBirthRate) Q_PROPERTY(float lifeDuration READ lifeDuration WRITE setLifeDuration) @@ -47,11 +50,16 @@ class GLParticlesSystem: public QObject, public GLObjectBase, protected QOpenGLF Q_PROPERTY(bool active READ isActive WRITE setActive) Q_PROPERTY(bool birthEnabled READ isBirthEnabled WRITE setBirthEnabled) Q_PROPERTY(float fadeTime READ fadeTime WRITE setFadeTime) + public: GLParticlesSystem(const QVector3D & pos = QVector3D()); - ~GLParticlesSystem() {;} + ~GLParticlesSystem() { ; } - enum Type {Cone, Omni, Box}; + enum Type { + Cone, + Omni, + Box + }; struct Particle { Particle(float life_dur = 40.); @@ -71,62 +79,65 @@ public: void update(); void draw(QOpenGLShaderProgram * prog, bool); - float birthRate() const {return birthRate_;} - float lifeDuration() const {return lifeDuration_;} - float size() const {return size_;} - float enlargeSpeed() const {return enlargeSpeed_;} - float initialAngle() const {return initialAngle_;} - float initialSpeed() const {return initialSpeed_;} - float speedDecay() const {return speedDecay_;} - float baseAngle() const {return baseAngle_;} - QVector3D speedDirection() const {return speedDirection_;} - QVector3D emitterPosition() const {return emitterPosition_;} - QVector3D emitterDirection() const {return emitterDirection_;} - Box3D emitterRect() const {return emitterRect_;} - float lifeDurationJitter() const {return lifeDurationJitter_;} - float speedJitter() const {return speedJitter_;} - float speedDirectionJitter() const {return speedDirectionJitter_;} - float sizeJitter() const {return sizeJitter_;} - float enlargeSpeedJitter() const {return enlargeSpeedJitter_;} - float angleJitter() const {return angleJitter_;} - bool isActive() const {return active_;} - bool isBirthEnabled() const {return birthEnabled_;} - GLParticlesSystem::Type emitterType() const {return emitterType_;} - float fadeTime() const {return fade_time;} - bool isAddVerticalFaceEnabled() const {return add_vert_face;} + float birthRate() const { return birthRate_; } + float lifeDuration() const { return lifeDuration_; } + float size() const { return size_; } + float enlargeSpeed() const { return enlargeSpeed_; } + float initialAngle() const { return initialAngle_; } + float initialSpeed() const { return initialSpeed_; } + float speedDecay() const { return speedDecay_; } + float baseAngle() const { return baseAngle_; } + QVector3D speedDirection() const { return speedDirection_; } + QVector3D emitterPosition() const { return emitterPosition_; } + QVector3D emitterDirection() const { return emitterDirection_; } + Box3D emitterRect() const { return emitterRect_; } + float lifeDurationJitter() const { return lifeDurationJitter_; } + float speedJitter() const { return speedJitter_; } + float speedDirectionJitter() const { return speedDirectionJitter_; } + float sizeJitter() const { return sizeJitter_; } + float enlargeSpeedJitter() const { return enlargeSpeedJitter_; } + float angleJitter() const { return angleJitter_; } + bool isActive() const { return active_; } + bool isBirthEnabled() const { return birthEnabled_; } + GLParticlesSystem::Type emitterType() const { return emitterType_; } + float fadeTime() const { return fade_time; } + bool isAddVerticalFaceEnabled() const { return add_vert_face; } - void setBirthRate(const float & arg) {birthRate_ = arg; tick_birth = birthRate_ / freq;} - void setLifeDuration(const float & arg) {lifeDuration_ = arg;} - void setSize(const float & arg) {size_ = arg;} - void setEnlargeSpeed(const float & arg) {enlargeSpeed_ = arg;} - void setInitialAngle(const float & arg) {initialAngle_ = arg;} - void setInitialSpeed(const float & arg) {initialSpeed_ = arg;} - void setBaseAngle(const float & arg) {baseAngle_ = arg;} - void setSpeedDecay(const float & arg) {speedDecay_ = arg;} - void setSpeedDirection(const QVector3D & arg) {speedDirection_ = arg;} - void setEmitterPosition(const QVector3D & arg) {emitterPosition_ = arg;} - void setEmitterDirection(const QVector3D & arg) {emitterDirection_ = arg.normalized();} - void setEmitterRect(const Box3D & arg) {emitterRect_ = arg;} - void setLifeDurationJitter(const float & arg) {lifeDurationJitter_ = arg;} - void setSpeedJitter(const float & arg) {speedJitter_ = arg;} - void setSpeedDirectionJitter(const float & arg) {speedDirectionJitter_ = arg;} - void setSizeJitter(const float & arg) {sizeJitter_ = arg;} - void setEnlargeSpeedJitter(const float & arg) {enlargeSpeedJitter_ = arg;} - void setActive(const bool & arg) {active_ = arg;} - void setAngleJitter(const float & arg) {angleJitter_ = arg;} - void setBirthEnabled(const bool & arg) {birthEnabled_ = arg;} - void setEmitterType(const GLParticlesSystem::Type & arg) {emitterType_ = arg;} - void setFadeTime(const float & arg) {fade_time = arg;} - void setAddVerticalFaceEnabled(const bool & arg) {add_vert_face = arg;} - void setTextureRect(const QRectF & arg) {tex_rect = arg;} - void setTextureScale(const float & x, const float & y) {tex_scale = QSizeF(x, y);} - void setTextureScale(const QSizeF & arg) {tex_scale = arg;} + void setBirthRate(const float & arg) { + birthRate_ = arg; + tick_birth = birthRate_ / freq; + } + void setLifeDuration(const float & arg) { lifeDuration_ = arg; } + void setSize(const float & arg) { size_ = arg; } + void setEnlargeSpeed(const float & arg) { enlargeSpeed_ = arg; } + void setInitialAngle(const float & arg) { initialAngle_ = arg; } + void setInitialSpeed(const float & arg) { initialSpeed_ = arg; } + void setBaseAngle(const float & arg) { baseAngle_ = arg; } + void setSpeedDecay(const float & arg) { speedDecay_ = arg; } + void setSpeedDirection(const QVector3D & arg) { speedDirection_ = arg; } + void setEmitterPosition(const QVector3D & arg) { emitterPosition_ = arg; } + void setEmitterDirection(const QVector3D & arg) { emitterDirection_ = arg.normalized(); } + void setEmitterRect(const Box3D & arg) { emitterRect_ = arg; } + void setLifeDurationJitter(const float & arg) { lifeDurationJitter_ = arg; } + void setSpeedJitter(const float & arg) { speedJitter_ = arg; } + void setSpeedDirectionJitter(const float & arg) { speedDirectionJitter_ = arg; } + void setSizeJitter(const float & arg) { sizeJitter_ = arg; } + void setEnlargeSpeedJitter(const float & arg) { enlargeSpeedJitter_ = arg; } + void setActive(const bool & arg) { active_ = arg; } + void setAngleJitter(const float & arg) { angleJitter_ = arg; } + void setBirthEnabled(const bool & arg) { birthEnabled_ = arg; } + void setEmitterType(const GLParticlesSystem::Type & arg) { emitterType_ = arg; } + void setFadeTime(const float & arg) { fade_time = arg; } + void setAddVerticalFaceEnabled(const bool & arg) { add_vert_face = arg; } + void setTextureRect(const QRectF & arg) { tex_rect = arg; } + void setTextureScale(const float & x, const float & y) { tex_scale = QSizeF(x, y); } + void setTextureScale(const QSizeF & arg) { tex_scale = arg; } - void addForce(const QVector3D & f) {forces << f;} - void birthParticles(int count) {need_birth += count;} + void addForce(const QVector3D & f) { forces << f; } + void birthParticles(int count) { need_birth += count; } - float frequency() const {return freq;} - void setFrequency(const float & f) {freq = f;} + float frequency() const { return freq; } + void setFrequency(const float & f) { freq = f; } float additionalSpeed; @@ -145,9 +156,10 @@ private: float lifeDurationJitter_, speedJitter_, speedDirectionJitter_, sizeJitter_, angleJitter_, initialAngle_; float enlargeSpeed_, enlargeSpeedJitter_, baseAngle_; bool active_, birthEnabled_, is_diffuse_anim, add_vert_face; - }; -inline bool operator <(const GLParticlesSystem::Particle & f, const GLParticlesSystem::Particle & s) {return f.pos_h.z() > s.pos_h.z();} +inline bool operator<(const GLParticlesSystem::Particle & f, const GLParticlesSystem::Particle & s) { + return f.pos_h.z() > s.pos_h.z(); +} #endif // GLPARTICLES_SYSTEM_H diff --git a/libs/qglview/glprimitives.cpp b/libs/qglview/glprimitives.cpp index 0f9dbf9..15fb139 100644 --- a/libs/qglview/glprimitives.cpp +++ b/libs/qglview/glprimitives.cpp @@ -28,7 +28,6 @@ void GLPrimitivePoint::draw(QOpenGLShaderProgram * prog, bool simplest) { } - void GLPrimitiveLine::draw(QOpenGLShaderProgram * prog, bool simplest) { glColor3f(material_.color_diffuse.redF(), material_.color_diffuse.greenF(), material_.color_diffuse.blueF()); glBegin(GL_LINES); @@ -38,24 +37,24 @@ void GLPrimitiveLine::draw(QOpenGLShaderProgram * prog, bool simplest) { } - GLPrimitiveCube::GLPrimitiveCube(float width, float length, float height, QVector3D pos): GLObjectBase() { geom_prim = Quads; - w = width; - l = length; - h = height; + w = width; + l = length; + h = height; moveTo(pos); - //init(); + // init(); } void GLPrimitiveCube::init() { float hw = w / 2.f, hl = l / 2.f, hh = h / 2.f; - //list = glGenLists(1); - //glNewList(list, GL_COMPILE); - //glColor4d(material_.color_diffuse.redF(), material_.color_diffuse.greenF(), material_.color_diffuse.blueF(), material_.color_diffuse.alphaF()); + // list = glGenLists(1); + // glNewList(list, GL_COMPILE); + // glColor4d(material_.color_diffuse.redF(), material_.color_diffuse.greenF(), material_.color_diffuse.blueF(), + // material_.color_diffuse.alphaF()); vbo.init(); - QVector & d_vertices(vbo.vertices()), & d_normals(vbo.normals()), & d_uvs(vbo.texcoords()); + QVector &d_vertices(vbo.vertices()), &d_normals(vbo.normals()), &d_uvs(vbo.texcoords()); d_vertices.clear(); d_normals.clear(); d_uvs.clear(); @@ -108,13 +107,13 @@ void GLPrimitiveCube::init() { GLPrimitiveEllipsoid::GLPrimitiveEllipsoid(float width, float length, float height, int seg_wl, int seg_h, QVector3D pos) { geom_prim = GLObjectBase::Triangles; - w = width; - l = length; - h = height; - swl = seg_wl; - sh = seg_h; + w = width; + l = length; + h = height; + swl = seg_wl; + sh = seg_h; moveTo(pos); - //init(); + // init(); } @@ -125,9 +124,12 @@ void GLPrimitiveEllipsoid::putTriangle(const QVector3D & v0, const QVector3D & v vbo.normals() << n.x() << n.y() << n.z(); return; QVector3D s(w, l, h); - n = (v0 * s).normalized(); vbo.normals() << n.x() << n.y() << n.z(); - n = (v1 * s).normalized(); vbo.normals() << n.x() << n.y() << n.z(); - n = (v2 * s).normalized(); vbo.normals() << n.x() << n.y() << n.z(); + n = (v0 * s).normalized(); + vbo.normals() << n.x() << n.y() << n.z(); + n = (v1 * s).normalized(); + vbo.normals() << n.x() << n.y() << n.z(); + n = (v2 * s).normalized(); + vbo.normals() << n.x() << n.y() << n.z(); } @@ -135,7 +137,7 @@ void GLPrimitiveEllipsoid::init() { QVector points; vbo.clear(); vbo.init(); - int ret = 0; + int ret = 0; int hseg = sh + 1, wlseg = swl + 1; float crw, crl, a, ch, twl; QVector3D cp(0., 0., -h / 2.f); @@ -161,7 +163,8 @@ void GLPrimitiveEllipsoid::init() { } } } - if (i == 1) putTriangle(points[0], points[ret - wlseg * 2 + 1], points[ret]); + if (i == 1) + putTriangle(points[0], points[ret - wlseg * 2 + 1], points[ret]); else { putTriangle(points[ret - wlseg * 2 + 1], points[ret], points[ret - wlseg * 2]); putTriangle(points[ret - wlseg * 2 + 1], points[ret - wlseg * 2], points[ret - wlseg * 4 + 1]); @@ -178,43 +181,43 @@ void GLPrimitiveEllipsoid::init() { void GLPrimitiveAxis::draw(QOpenGLShaderProgram * prog, bool simplest) { - float bs = 1.f; - float as = 0.1f; - float aw = 0.07f; + float bs = 1.f; + float as = 0.1f; + float aw = 0.07f; float cr_x = 0.8f, cg_y = 0.75f, cb_z = 0.8f; glBegin(GL_LINES); glColor3f(cr_x, 0, 0); glVertex3f(-bs, 0, 0); glVertex3f(bs, 0, 0); glVertex3f(bs, 0, 0); - glVertex3f(bs-as, aw, 0); + glVertex3f(bs - as, aw, 0); glVertex3f(bs, 0, 0); - glVertex3f(bs-as, -aw, 0); + glVertex3f(bs - as, -aw, 0); glVertex3f(bs, 0, 0); - glVertex3f(bs-as, 0, aw); + glVertex3f(bs - as, 0, aw); glVertex3f(bs, 0, 0); - glVertex3f(bs-as, 0, -aw); + glVertex3f(bs - as, 0, -aw); glColor3f(0, cg_y, 0); glVertex3f(0, -bs, 0); glVertex3f(0, bs, 0); glVertex3f(0, bs, 0); - glVertex3f(0, bs-as, aw); + glVertex3f(0, bs - as, aw); glVertex3f(0, bs, 0); - glVertex3f(0, bs-as, -aw); + glVertex3f(0, bs - as, -aw); glVertex3f(0, bs, 0); - glVertex3f(aw, bs-as, 0); + glVertex3f(aw, bs - as, 0); glVertex3f(0, bs, 0); - glVertex3f(-aw, bs-as, 0); + glVertex3f(-aw, bs - as, 0); glColor3f(0, 0, cb_z); glVertex3f(0, 0, -bs); glVertex3f(0, 0, bs); glVertex3f(0, 0, bs); - glVertex3f(aw, 0, bs-as); + glVertex3f(aw, 0, bs - as); glVertex3f(0, 0, bs); - glVertex3f(-aw, 0, bs-as); + glVertex3f(-aw, 0, bs - as); glVertex3f(0, 0, bs); - glVertex3f(0, aw, bs-as); + glVertex3f(0, aw, bs - as); glVertex3f(0, 0, bs); - glVertex3f(0, -aw, bs-as); + glVertex3f(0, -aw, bs - as); glEnd(); } diff --git a/libs/qglview/glprimitives.h b/libs/qglview/glprimitives.h index 7579b9b..b75869d 100644 --- a/libs/qglview/glprimitives.h +++ b/libs/qglview/glprimitives.h @@ -22,51 +22,53 @@ #include "globject.h" -class GLPrimitivePoint: public GLObjectBase -{ +class GLPrimitivePoint: public GLObjectBase { public: - GLPrimitivePoint(double size = 1., QVector3D pos = QVector3D()) {sz = 8.;} + GLPrimitivePoint(double size = 1., QVector3D pos = QVector3D()) { sz = 8.; } virtual void draw(QOpenGLShaderProgram * prog, bool simplest = false); + private: double sz; }; - - -class GLPrimitiveLine: public GLObjectBase -{ +class GLPrimitiveLine: public GLObjectBase { public: - GLPrimitiveLine(QVector3D p0_ = QVector3D(), QVector3D p1_ = QVector3D()) {p0 = p0_; p1 = p1_;} + GLPrimitiveLine(QVector3D p0_ = QVector3D(), QVector3D p1_ = QVector3D()) { + p0 = p0_; + p1 = p1_; + } virtual void draw(QOpenGLShaderProgram * prog, bool simplest = false); - QVector3D point0() const {return p0;} - QVector3D point1() const {return p1;} - void setPoint0(const QVector3D & p) {p0 = p;} - void setPoint1(const QVector3D & p) {p1 = p;} + QVector3D point0() const { return p0; } + QVector3D point1() const { return p1; } + void setPoint0(const QVector3D & p) { p0 = p; } + void setPoint1(const QVector3D & p) { p1 = p; } + private: QVector3D p0, p1; }; - - -class GLPrimitiveCube: public GLObjectBase -{ +class GLPrimitiveCube: public GLObjectBase { public: GLPrimitiveCube(float width = 1., float length = 1., float height = 1., QVector3D pos = QVector3D()); virtual void init(); + private: float w, l, h; }; - - -class GLPrimitiveEllipsoid: public GLObjectBase -{ +class GLPrimitiveEllipsoid: public GLObjectBase { public: - GLPrimitiveEllipsoid(float width = 1., float length = 1., float height = 1., int seg_wl = 10, int seg_h = 10, QVector3D pos = QVector3D()); + GLPrimitiveEllipsoid(float width = 1., + float length = 1., + float height = 1., + int seg_wl = 10, + int seg_h = 10, + QVector3D pos = QVector3D()); virtual void init(); + private: void putTriangle(const QVector3D & v0, const QVector3D & v1, const QVector3D & v2); float w, l, h; @@ -74,10 +76,9 @@ private: }; -class GLPrimitiveAxis: public GLObjectBase -{ +class GLPrimitiveAxis: public GLObjectBase { public: - GLPrimitiveAxis() {accept_fog = accept_light = cast_shadow = rec_shadow = select_ = false;} + GLPrimitiveAxis() { accept_fog = accept_light = cast_shadow = rec_shadow = select_ = false; } virtual void draw(QOpenGLShaderProgram * prog, bool simplest = false); }; diff --git a/libs/qglview/glrendererbase.cpp b/libs/qglview/glrendererbase.cpp index db5f31d..71e7544 100644 --- a/libs/qglview/glrendererbase.cpp +++ b/libs/qglview/glrendererbase.cpp @@ -17,6 +17,7 @@ */ #include "glrendererbase.h" + #include "globject.h" #include "qglview.h" @@ -25,7 +26,7 @@ GLRendererBase::GLRendererBase(QGLView * view_): view(*view_) { white_image = QImage(1, 1, QImage::Format_ARGB32); white_image.fill(0xFFFFFFFF); white_image_id = 0; - violent_image = QImage(1, 1, QImage::Format_ARGB32); + violent_image = QImage(1, 1, QImage::Format_ARGB32); violent_image.fill(QColor(127, 127, 255)); violent_image_id = 0; } @@ -36,18 +37,18 @@ void GLRendererBase::setupLight(const Light & l, int inpass_index, int gl_index) GLfloat pos[] = {0.f, 0.f, 0.f, 0.f}; GLfloat dir[] = {0.f, 0.f, 0.f}; GLfloat col[] = {0.f, 0.f, 0.f}; - pos[0] = l.light_type == Light::Directional ? -l.direction.x() : lp.x(); - pos[1] = l.light_type == Light::Directional ? -l.direction.y() : lp.y(); - pos[2] = l.light_type == Light::Directional ? -l.direction.z() : lp.z(); - pos[3] = l.light_type == Light::Directional ? 0. : 1.; - dir[0] = ld.x(); - dir[1] = ld.y(); - dir[2] = ld.z(); - col[0] = l.visible_ ? l.color().redF() * l.intensity : 0.f; - col[1] = l.visible_ ? l.color().greenF() * l.intensity : 0.f; - col[2] = l.visible_ ? l.color().blueF() * l.intensity : 0.f; + pos[0] = l.light_type == Light::Directional ? -l.direction.x() : lp.x(); + pos[1] = l.light_type == Light::Directional ? -l.direction.y() : lp.y(); + pos[2] = l.light_type == Light::Directional ? -l.direction.z() : lp.z(); + pos[3] = l.light_type == Light::Directional ? 0. : 1.; + dir[0] = ld.x(); + dir[1] = ld.y(); + dir[2] = ld.z(); + col[0] = l.visible_ ? l.color().redF() * l.intensity : 0.f; + col[1] = l.visible_ ? l.color().greenF() * l.intensity : 0.f; + col[2] = l.visible_ ? l.color().blueF() * l.intensity : 0.f; glEnable(gl_index); - //glLightfv(gl_index, GL_AMBIENT, ambient); + // glLightfv(gl_index, GL_AMBIENT, ambient); glLightfv(gl_index, GL_DIFFUSE, col); glLightfv(gl_index, GL_SPECULAR, col); glLightfv(gl_index, GL_POSITION, pos); @@ -57,11 +58,12 @@ void GLRendererBase::setupLight(const Light & l, int inpass_index, int gl_index) if (l.light_type == Light::Cone) { glLightfv(gl_index, GL_SPOT_DIRECTION, dir); glLightf(gl_index, GL_SPOT_CUTOFF, l.angle_end / 2.f); - glLightf(gl_index, GL_SPOT_EXPONENT, (1.f - piClamp((l.angle_end - l.angle_start) / (l.angle_end + 0.001f), 0., 1.f)) * 128.f); + glLightf(gl_index, + GL_SPOT_EXPONENT, + (1.f - piClamp((l.angle_end - l.angle_start) / (l.angle_end + 0.001f), 0., 1.f)) * 128.f); } else { glLightf(gl_index, GL_SPOT_CUTOFF, 180.); } - } @@ -78,18 +80,21 @@ void GLRendererBase::setupAmbientLight(const QColor & a, bool first_pass) { void GLRendererBase::setupShadersLights(int lights_count) { /*foreach (QOpenGLShaderProgram * i, view.shaders_ppl) { - i->bind(); - i->setUniformValue("lightsCount", lights_count); - i->setUniformValue("acc_light", lights_count > 0); - //i->setUniformValue("mat", mvm); + i->bind(); + i->setUniformValue("lightsCount", lights_count); + i->setUniformValue("acc_light", lights_count > 0); + //i->setUniformValue("mat", mvm); }*/ } -#define BIND_TEXTURE(ch, map) if (rp.prev_tex[ch] != mat.map.bitmap_id) { \ - rp.prev_tex[ch] = mat.map.bitmap_id; \ - glActiveTexture(GL_TEXTURE0 + ch); glBindTexture(GL_TEXTURE_2D, mat.map.bitmap_id); \ - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, view.feature(QGLView::qglAnisotropicLevel).toInt());} +#define BIND_TEXTURE(ch, map) \ + if (rp.prev_tex[ch] != mat.map.bitmap_id) { \ + rp.prev_tex[ch] = mat.map.bitmap_id; \ + glActiveTexture(GL_TEXTURE0 + ch); \ + glBindTexture(GL_TEXTURE_2D, mat.map.bitmap_id); \ + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, view.feature(QGLView::qglAnisotropicLevel).toInt()); \ + } void GLRendererBase::setupTextures(GLObjectBase & o, GLRendererBase::RenderingParameters & rp, bool first_object) { if (first_object) { @@ -99,12 +104,30 @@ void GLRendererBase::setupTextures(GLObjectBase & o, GLRendererBase::RenderingPa setupShadersTextures(o, rp); Material & mat(o.material_); if (rp.light) { - if (o.accept_light) {if (!rp.prev_light) {glSetLightEnabled(true); rp.prev_light = true;}} - else {if (rp.prev_light) {glSetLightEnabled(false); rp.prev_light = false;}} + if (o.accept_light) { + if (!rp.prev_light) { + glSetLightEnabled(true); + rp.prev_light = true; + } + } else { + if (rp.prev_light) { + glSetLightEnabled(false); + rp.prev_light = false; + } + } } if (rp.fog) { - if (o.accept_fog) {if (!rp.prev_fog) {glSetFogEnabled(true); rp.prev_fog = true;}} - else {if (rp.prev_fog) {glSetFogEnabled(false); rp.prev_fog = false;}} + if (o.accept_fog) { + if (!rp.prev_fog) { + glSetFogEnabled(true); + rp.prev_fog = true; + } + } else { + if (rp.prev_fog) { + glSetFogEnabled(false); + rp.prev_fog = false; + } + } } if (rp.textures) { BIND_TEXTURE(0, map_diffuse) @@ -123,7 +146,7 @@ void GLRendererBase::setupTextures(GLObjectBase & o, GLRendererBase::RenderingPa void GLRendererBase::setupLights(int pass, int lights_per_pass) { int light_start, light_end, lmax; light_start = pass * lights_per_pass; - light_end = qMin((pass + 1) * lights_per_pass, view.lights_.size()); + light_end = qMin((pass + 1) * lights_per_pass, view.lights_.size()); setupAmbientLight(view.ambientColor_, pass == 0); if (!view.lights_.isEmpty()) { setupShadersLights(light_end - light_start); @@ -154,19 +177,20 @@ void GLRendererBase::applyFilteringParameters() { void GLRendererBase::renderObjects(int pass, int light_pass, void * shaders, bool textures, bool light, bool fog) { RenderingParameters rpl; - rpl.pass = pass; + rpl.pass = pass; rpl.light_pass = light_pass; - rpl.shaders = shaders; - rpl.textures = textures; + rpl.shaders = shaders; + rpl.textures = textures; rpl.light = rpl.prev_light = light; rpl.fog = rpl.prev_fog = fog; - rpl.view_matrix = rp.view_matrix; - rpl.prev_view_matrix = rp.prev_view_matrix; - rpl.proj_matrix = rp.proj_matrix; - rpl.prev_proj_matrix = rp.prev_proj_matrix; - rpl.cam_offset_matrix = view.camera()->offsetMatrix(); - //qDebug() << "view:" << rp.view_matrix; - for (int i = 0; i < 32; ++i) rpl.prev_tex[i] = 0; + rpl.view_matrix = rp.view_matrix; + rpl.prev_view_matrix = rp.prev_view_matrix; + rpl.proj_matrix = rp.proj_matrix; + rpl.prev_proj_matrix = rp.prev_proj_matrix; + rpl.cam_offset_matrix = view.camera()->offsetMatrix(); + // qDebug() << "view:" << rp.view_matrix; + for (int i = 0; i < 32; ++i) + rpl.prev_tex[i] = 0; setupTextures(view.objects_, rpl, true); glSetLightEnabled(rpl.prev_light); glSetFogEnabled(rpl.prev_fog); @@ -181,16 +205,15 @@ void GLRendererBase::renderObjects(int pass, int light_pass, void * shaders, boo void GLRendererBase::renderSingleObject(GLObjectBase & o, RenderingParameters & rpl) { - if (!o.isInit()) - o.init(); - if (!o.isTexturesLoaded()) - o.loadTextures(); + if (!o.isInit()) o.init(); + if (!o.isTexturesLoaded()) o.loadTextures(); if (!o.visible_) return; if (rpl.pass == o.pass_) { Material & mat(o.material_); - QMatrix4x4 curview = rpl.view_matrix * rpl.cam_offset_matrix * o.itransform_, prevview = rpl.prev_view_matrix * rpl.cam_offset_matrix * o.itransform_; + QMatrix4x4 curview = rpl.view_matrix * rpl.cam_offset_matrix * o.itransform_, + prevview = rpl.prev_view_matrix * rpl.cam_offset_matrix * o.itransform_; setupTextures(o, rpl, false); - mat.apply((QOpenGLShaderProgram*)rpl.shaders); + mat.apply((QOpenGLShaderProgram *)rpl.shaders); glSetPolygonMode(o.render_mode != GLObjectBase::View ? o.render_mode : (view.rmode != GLObjectBase::View ? view.rmode : GL_FILL)); glLineWidth(o.line_width > 0.f ? o.line_width : view.lineWidth_); glPointSize(o.line_width > 0.f ? o.line_width : view.lineWidth_); @@ -199,9 +222,12 @@ void GLRendererBase::renderSingleObject(GLObjectBase & o, RenderingParameters & glActiveTexture(GL_TEXTURE0 + 3); if (mat.reflectivity > 0.f) { glEnable(GL_TEXTURE_CUBE_MAP); - if (!mat.map_reflection.isEmpty()) mat.map_reflection.bind(); - else glDisable(GL_TEXTURE_CUBE_MAP); - } else glDisable(GL_TEXTURE_CUBE_MAP); + if (!mat.map_reflection.isEmpty()) + mat.map_reflection.bind(); + else + glDisable(GL_TEXTURE_CUBE_MAP); + } else + glDisable(GL_TEXTURE_CUBE_MAP); if (rpl.light_pass > 0) glDisable(GL_TEXTURE_CUBE_MAP); GLfloat gm[16], bc[4] = {mat.reflectivity, mat.reflectivity, mat.reflectivity, mat.reflectivity}; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); @@ -211,21 +237,21 @@ void GLRendererBase::renderSingleObject(GLObjectBase & o, RenderingParameters & glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, bc); glGetFloatv(GL_MODELVIEW_MATRIX, gm); glMatrixMode(GL_TEXTURE); - ///glLoadTransposeMatrixf(gm); + /// glLoadTransposeMatrixf(gm); glScalef(-1., -1., -1.); glMatrixMode(GL_MODELVIEW); glActiveTexture(GL_TEXTURE0); } if (rpl.shaders) { - //qDebug() << o.name() << curview << curview.determinant(); - setUniformMatrices((QOpenGLShaderProgram*)rpl.shaders, rpl.proj_matrix, curview, rpl.prev_proj_matrix, prevview); + // qDebug() << o.name() << curview << curview.determinant(); + setUniformMatrices((QOpenGLShaderProgram *)rpl.shaders, rpl.proj_matrix, curview, rpl.prev_proj_matrix, prevview); } else { glMatrixMode(GL_MODELVIEW); setGLMatrix(curview); } - o.draw((QOpenGLShaderProgram*)rpl.shaders); + o.draw((QOpenGLShaderProgram *)rpl.shaders); } - foreach (GLObjectBase * i, o.children_) + foreach(GLObjectBase * i, o.children_) renderSingleObject(*i, rpl); } @@ -245,60 +271,58 @@ void GLRendererBase::renderShadow(Light * l, QOpenGLShaderProgram * prog, QMatri cam.rotateXY(-l->angle_end); cam.rotateZ(l->angle_end); l->dir1 = cam.direction() - rdir;*/ - //qDebug() << rdir << l->dir0 << l->dir1; + // qDebug() << rdir << l->dir0 << l->dir1; RenderingParameters rpl; - rpl.pass = GLObjectBase::Solid; - rpl.shaders = prog; + rpl.pass = GLObjectBase::Solid; + rpl.shaders = prog; rpl.textures = rpl.light = rpl.fog = false; - rpl.view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); - rpl.proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); - rpl.cam_offset_matrix = cam.offsetMatrix(); + rpl.view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); + rpl.proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); + rpl.cam_offset_matrix = cam.offsetMatrix(); QMatrix4x4 mbias; mbias.scale(0.5, 0.5, 0.5); mbias.translate(1., 1., 1.); - l->shadow_matrix = mbias*rpl.proj_matrix*rpl.view_matrix*rpl.cam_offset_matrix*mat;//;// * mbias; - //qDebug() << mbias; - //glPushMatrix(); + l->shadow_matrix = mbias * rpl.proj_matrix * rpl.view_matrix * rpl.cam_offset_matrix * mat; //;// * mbias; + // qDebug() << mbias; + // glPushMatrix(); renderSingleShadow(view.objects_, rpl); - //glPopMatrix(); + // glPopMatrix(); } void GLRendererBase::renderSingleShadow(GLObjectBase & o, RenderingParameters & rpl) { - if (!o.isInit()) - o.init(); + if (!o.isInit()) o.init(); if (!o.visible_) return; if (rpl.shaders) { - //qDebug() << o.name() << curview << curview.determinant(); - setUniformMatrices((QOpenGLShaderProgram*)rpl.shaders, rpl.proj_matrix, rpl.view_matrix * rpl.cam_offset_matrix * o.itransform_); + // qDebug() << o.name() << curview << curview.determinant(); + setUniformMatrices((QOpenGLShaderProgram *)rpl.shaders, rpl.proj_matrix, rpl.view_matrix * rpl.cam_offset_matrix * o.itransform_); } else { glMatrixMode(GL_MODELVIEW); setGLMatrix(rpl.view_matrix * rpl.cam_offset_matrix * o.itransform_); } - glPolygonMode(GL_FRONT_AND_BACK, o.render_mode != GLObjectBase::View ? o.render_mode : (view.rmode != GLObjectBase::View ? view.rmode : GL_FILL)); + glPolygonMode(GL_FRONT_AND_BACK, + o.render_mode != GLObjectBase::View ? o.render_mode : (view.rmode != GLObjectBase::View ? view.rmode : GL_FILL)); glLineWidth(o.line_width > 0.f ? o.line_width : view.lineWidth_); glPointSize(o.line_width > 0.f ? o.line_width : view.lineWidth_); - o.draw((QOpenGLShaderProgram*)rpl.shaders, true); - foreach (GLObjectBase * i, o.children_) + o.draw((QOpenGLShaderProgram *)rpl.shaders, true); + foreach(GLObjectBase * i, o.children_) renderSingleShadow(*i, rpl); } - - GLRendererBase::RenderingParameters::RenderingParameters() { - shaders = nullptr; + shaders = nullptr; cur_shader = nullptr; } void GLRendererBase::RenderingParameters::prepare() { - proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); - view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); - viewproj_matrix = proj_matrix * view_matrix; - normal_matrix = view_matrix.normalMatrix(); - proj_matrix_i = proj_matrix.inverted(); - view_matrix_i = view_matrix.inverted(); + proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); + view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); + viewproj_matrix = proj_matrix * view_matrix; + normal_matrix = view_matrix.normalMatrix(); + proj_matrix_i = proj_matrix.inverted(); + view_matrix_i = view_matrix.inverted(); viewproj_matrix_i = viewproj_matrix.inverted(); } diff --git a/libs/qglview/glrendererbase.h b/libs/qglview/glrendererbase.h index 7c56267..b5372e6 100644 --- a/libs/qglview/glrendererbase.h +++ b/libs/qglview/glrendererbase.h @@ -1,19 +1,19 @@ /* - QGLView - Ivan Pelipenko peri4ko@yandex.ru + QGLView + Ivan Pelipenko peri4ko@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef GLRENDERERBASE_H @@ -22,13 +22,15 @@ #include "glcamera.h" #include "glshaders.h" -class GLRendererBase: public QObject , protected QOpenGLExtraFunctions -{ +class GLRendererBase + : public QObject + , protected QOpenGLExtraFunctions { friend class QGLView; Q_OBJECT + public: GLRendererBase(QGLView * view_); - virtual void prepareScene() {;} + virtual void prepareScene() { ; } virtual void renderScene() = 0; struct RenderingParameters { @@ -74,7 +76,6 @@ protected: QGLView & view; QImage white_image, violent_image; GLuint white_image_id, violent_image_id; - }; #endif // GLRENDERERBASE_H diff --git a/libs/qglview/glshaders.cpp b/libs/qglview/glshaders.cpp index dd7217c..4b35e7c 100644 --- a/libs/qglview/glshaders.cpp +++ b/libs/qglview/glshaders.cpp @@ -32,77 +32,74 @@ const char qgl_vertex_head[] = "in vec3 qgl_Vertex;\n" "vec4 qgl_ftransform() {return qgl_ModelViewProjectionMatrix * vec4(qgl_Vertex, 1);}\n"; -const char qgl_fragment_head[] = - "in vec2 qgl_FragTexture;\n" - "in vec4 qgl_FragColor;\n" - "out vec4 qgl_FragData[gl_MaxDrawBuffers];\n"; +const char qgl_fragment_head[] = "in vec2 qgl_FragTexture;\n" + "in vec4 qgl_FragColor;\n" + "out vec4 qgl_FragData[gl_MaxDrawBuffers];\n"; -const char qgl_uniform[] = - "uniform mat4 qgl_ModelViewMatrix;\n" - "uniform mat4 qgl_ProjectionMatrix;\n" - "uniform mat4 qgl_ModelViewProjectionMatrix;\n" - "uniform mat3 qgl_NormalMatrix;\n" - "uniform mat4 qgl_ModelViewMatrixInverse;\n" - "uniform mat4 qgl_ProjectionMatrixInverse;\n" - "uniform mat4 qgl_ModelViewProjectionMatrixInverse;\n" - "uniform mat4 qgl_ModelViewMatrixTranspose;\n" - "uniform mat4 qgl_ProjectionMatrixTranspose;\n" - "uniform mat4 qgl_ModelViewProjectionMatrixTranspose;\n" - "uniform mat4 qgl_ModelViewMatrixInverseTranspose;\n" - "uniform mat4 qgl_ProjectionMatrixInverseTranspose;\n" - "uniform mat4 qgl_ModelViewProjectionMatrixInverseTranspose;\n"; +const char qgl_uniform[] = "uniform mat4 qgl_ModelViewMatrix;\n" + "uniform mat4 qgl_ProjectionMatrix;\n" + "uniform mat4 qgl_ModelViewProjectionMatrix;\n" + "uniform mat3 qgl_NormalMatrix;\n" + "uniform mat4 qgl_ModelViewMatrixInverse;\n" + "uniform mat4 qgl_ProjectionMatrixInverse;\n" + "uniform mat4 qgl_ModelViewProjectionMatrixInverse;\n" + "uniform mat4 qgl_ModelViewMatrixTranspose;\n" + "uniform mat4 qgl_ProjectionMatrixTranspose;\n" + "uniform mat4 qgl_ModelViewProjectionMatrixTranspose;\n" + "uniform mat4 qgl_ModelViewMatrixInverseTranspose;\n" + "uniform mat4 qgl_ProjectionMatrixInverseTranspose;\n" + "uniform mat4 qgl_ModelViewProjectionMatrixInverseTranspose;\n"; -const char qgl_structs[] = - "const int qgl_MaxLights = 8;\n" - "struct QGLLight {\n" - " vec4 color;\n" - " vec4 position;\n" - " vec4 direction;\n" - " float intensity;\n" - " float startAngle;\n" - " float startAngleCos;\n" - " float endAngle;\n" - " float endAngleCos;\n" - " float constantAttenuation;\n" - " float linearAttenuation;\n" - " float quadraticAttenuation;\n" - " sampler2DShadow shadow;\n" - //" sampler2D shadowColor\n" - " mat4 shadowMatrix;\n" - //" vec4 shadowDir0;\n" - //" vec4 shadowDir1;\n" - "};\n" - "struct QGLMap {\n" - " float offset;\n" - " float amount;\n" - " vec2 scale;\n" - " sampler2D map;\n" - "};\n" - "struct QGLMaterial {\n" - " float transparency;\n" - " float reflectivity;\n" - " float iof;\n" - " float dispersion;\n" - " vec4 color_diffuse;\n" - " vec4 color_specular;\n" - " vec4 color_self_illumination;\n" - " QGLMap map_diffuse;\n" - " QGLMap map_normal;\n" - " QGLMap map_relief;\n" - " QGLMap map_self_illumination;\n" - " QGLMap map_specularity;\n" - " QGLMap map_specular;\n" - "};\n" - "uniform QGLLight qgl_AmbientLight;\n" - "uniform QGLLight qgl_Light[qgl_MaxLights];\n" - "uniform QGLMaterial qgl_Material;\n"; +const char qgl_structs[] = "const int qgl_MaxLights = 8;\n" + "struct QGLLight {\n" + " vec4 color;\n" + " vec4 position;\n" + " vec4 direction;\n" + " float intensity;\n" + " float startAngle;\n" + " float startAngleCos;\n" + " float endAngle;\n" + " float endAngleCos;\n" + " float constantAttenuation;\n" + " float linearAttenuation;\n" + " float quadraticAttenuation;\n" + " sampler2DShadow shadow;\n" + //" sampler2D shadowColor\n" + " mat4 shadowMatrix;\n" + //" vec4 shadowDir0;\n" + //" vec4 shadowDir1;\n" + "};\n" + "struct QGLMap {\n" + " float offset;\n" + " float amount;\n" + " vec2 scale;\n" + " sampler2D map;\n" + "};\n" + "struct QGLMaterial {\n" + " float transparency;\n" + " float reflectivity;\n" + " float iof;\n" + " float dispersion;\n" + " vec4 color_diffuse;\n" + " vec4 color_specular;\n" + " vec4 color_self_illumination;\n" + " QGLMap map_diffuse;\n" + " QGLMap map_normal;\n" + " QGLMap map_relief;\n" + " QGLMap map_self_illumination;\n" + " QGLMap map_specularity;\n" + " QGLMap map_specular;\n" + "};\n" + "uniform QGLLight qgl_AmbientLight;\n" + "uniform QGLLight qgl_Light[qgl_MaxLights];\n" + "uniform QGLMaterial qgl_Material;\n"; QString loadShaderFile(QOpenGLShaderProgram * prog, QOpenGLShader::ShaderType type, const QString & file) { QFile f(file); if (!f.open(QIODevice::ReadOnly)) return ""; - QString all = QString::fromUtf8(f.readAll()); - int i = all.indexOf("#version"); + QString all = QString::fromUtf8(f.readAll()); + int i = all.indexOf("#version"); QString version = all.mid(i + 8, all.indexOf("\n", i) - i - 8).trimmed(); if (version.toInt() >= 150) { int ip = all.indexOf("\n", i); @@ -117,7 +114,7 @@ QString loadShaderFile(QOpenGLShaderProgram * prog, QOpenGLShader::ShaderType ty all.insert(ip + 1, qgl_uniform); } prog->addShaderFromSourceCode(type, all); - //qDebug() << "********" << all; + // qDebug() << "********" << all; return all; } @@ -126,20 +123,20 @@ bool loadShaders(QOpenGLShaderProgram * prog, const QString & name, const QStrin prog->removeAllShaders(); QDir d(dir); QFileInfoList sl; - //qDebug() << "[QGLView] Shader \"" + name + "\" load shaders from" << d.absolutePath(); + // qDebug() << "[QGLView] Shader \"" + name + "\" load shaders from" << d.absolutePath(); sl = d.entryInfoList(QStringList(name + ".geom"), QDir::Files | QDir::NoDotAndDotDot); - foreach (const QFileInfo & i, sl) { - //qDebug() << "[QGLView] Shader \"" + name + "\" add geometry shader:" << i.fileName(); + foreach(const QFileInfo & i, sl) { + // qDebug() << "[QGLView] Shader \"" + name + "\" add geometry shader:" << i.fileName(); loadShaderFile(prog, QOpenGLShader::Geometry, i.absoluteFilePath()); } sl = d.entryInfoList(QStringList(name + ".vert"), QDir::Files | QDir::NoDotAndDotDot); - foreach (const QFileInfo & i, sl) { - //qDebug() << "[QGLView] Shader \"" + name + "\" add vertex shader:" << i.fileName(); + foreach(const QFileInfo & i, sl) { + // qDebug() << "[QGLView] Shader \"" + name + "\" add vertex shader:" << i.fileName(); loadShaderFile(prog, QOpenGLShader::Vertex, i.absoluteFilePath()); } sl = d.entryInfoList(QStringList(name + ".frag"), QDir::Files | QDir::NoDotAndDotDot); - foreach (const QFileInfo & i, sl) { - //qDebug() << "[QGLView] Shader \"" + name + "\" add fragment shader:" << i.fileName(); + foreach(const QFileInfo & i, sl) { + // qDebug() << "[QGLView] Shader \"" + name + "\" add fragment shader:" << i.fileName(); loadShaderFile(prog, QOpenGLShader::Fragment, i.absoluteFilePath()); } if (!prog->link()) { @@ -153,17 +150,17 @@ bool loadShaders(QOpenGLShaderProgram * prog, const QString & name, const QStrin void setUniformMatrices(QOpenGLShaderProgram * prog, QMatrix4x4 proj, QMatrix4x4 view, QMatrix4x4 prevproj, QMatrix4x4 prevview) { if (!prog) return; if (!prog->isLinked()) return; - QMatrix4x4 mvpm = proj * view; + QMatrix4x4 mvpm = proj * view; QMatrix4x4 pmvpm = prevproj * prevview; - QMatrix3x3 nm = view.normalMatrix(); - //nm.in; + QMatrix3x3 nm = view.normalMatrix(); + // nm.in; prog->setUniformValue("qgl_ModelViewMatrix", view); prog->setUniformValue("qgl_ProjectionMatrix", proj); prog->setUniformValue("prev_ModelViewProjectioMatrix", pmvpm); prog->setUniformValue("prev_ModelViewMatrix", prevview); prog->setUniformValue("qgl_ModelViewProjectionMatrix", mvpm); prog->setUniformValue("qgl_NormalMatrix", nm); - //prog->setUniformValue("qgl_BumpMatrix", nm.); + // prog->setUniformValue("qgl_BumpMatrix", nm.); prog->setUniformValue("qgl_ModelViewMatrixTranspose", view.transposed()); prog->setUniformValue("qgl_ProjectionMatrixTranspose", proj.transposed()); prog->setUniformValue("qgl_ModelViewProjectionMatrixTranspose", mvpm.transposed()); @@ -183,12 +180,12 @@ void setUniformMap(QOpenGLShaderProgram * prog, QString map_name, const Map & ma void setUniformMaterial(QOpenGLShaderProgram * prog, const Material & mat) { if (!prog) return; if (!prog->isLinked()) return; - QOpenGLFunctions *glFuncs = QOpenGLContext::currentContext()->functions(); - GLfloat mat_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f}; - mat_diffuse[0] = mat.color_diffuse.redF(); - mat_diffuse[1] = mat.color_diffuse.greenF(); - mat_diffuse[2] = mat.color_diffuse.blueF(); - mat_diffuse[3] = mat.color_diffuse.alphaF() * (1.f - mat.transparency); + QOpenGLFunctions * glFuncs = QOpenGLContext::currentContext()->functions(); + GLfloat mat_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f}; + mat_diffuse[0] = mat.color_diffuse.redF(); + mat_diffuse[1] = mat.color_diffuse.greenF(); + mat_diffuse[2] = mat.color_diffuse.blueF(); + mat_diffuse[3] = mat.color_diffuse.alphaF() * (1.f - mat.transparency); glFuncs->glVertexAttrib4f(prog->attributeLocation("qgl_Color"), mat_diffuse[0], mat_diffuse[1], mat_diffuse[2], mat_diffuse[3]); prog->setUniformValue("qgl_Material.transparency", mat.transparency); prog->setUniformValue("qgl_Material.reflectivity", mat.reflectivity); @@ -203,11 +200,10 @@ void setUniformMaterial(QOpenGLShaderProgram * prog, const Material & mat) { setUniformMap(prog, "map_self_illumination", mat.map_self_illumination, 3, 6); setUniformMap(prog, "map_specularity", mat.map_specularity, 4, 6); setUniformMap(prog, "map_specular", mat.map_specular, 5, 6); - } -void setUniformLights(QOpenGLShaderProgram * prog, const QVector & lights, const QMatrix4x4 & mat, int shadow_start) { +void setUniformLights(QOpenGLShaderProgram * prog, const QVector & lights, const QMatrix4x4 & mat, int shadow_start) { for (int i = 0; i < lights.size(); ++i) setUniformLight(prog, lights[i], QString("qgl_Light[%1]").arg(i), mat, shadow_start + i); } @@ -228,13 +224,12 @@ void setUniformLight(QOpenGLShaderProgram * prog, Light * light, QString ulightn if (!prog) return; if (!prog->isLinked()) return; QMatrix4x4 m = mat * light->worldTransform(); - QVector4D pos(0, 0, 0, 1.), dir(light->direction, 1);//, dir0(light->dir0), dir1(light->dir1); - pos = m * pos; - dir = ((m * dir) - pos).normalized(); + QVector4D pos(0, 0, 0, 1.), dir(light->direction, 1); //, dir0(light->dir0), dir1(light->dir1); + pos = m * pos; + dir = ((m * dir) - pos).normalized(); float ang_start = light->angle_start / 2.f, ang_end = light->angle_end / 2.f; - if (light->light_type == Light::Omni) - ang_start = ang_end = 180.; - //qDebug() << "light" << light->name() << ulightn << pos; + if (light->light_type == Light::Omni) ang_start = ang_end = 180.; + // qDebug() << "light" << light->name() << ulightn << pos; prog->setUniformValue((ulightn + ".position").toLatin1().constData(), pos); prog->setUniformValue((ulightn + ".direction").toLatin1().constData(), dir); prog->setUniformValue((ulightn + ".intensity").toLatin1().constData(), GLfloat(light->intensity)); @@ -249,8 +244,8 @@ void setUniformLight(QOpenGLShaderProgram * prog, Light * light, QString ulightn prog->setUniformValue((ulightn + ".shadow").toLatin1().constData(), shadow); prog->setUniformValue((ulightn + ".shadowColor").toLatin1().constData(), shadow); prog->setUniformValue((ulightn + ".shadowMatrix").toLatin1().constData(), light->shadow_matrix); - //qDebug() << light->shadow_matrix; - //prog->setUniformValue((ulightn + ".shadowDir0").toLatin1().constData(), (mat * dir0)); - //prog->setUniformValue((ulightn + ".shadowDir1").toLatin1().constData(), (mat * dir1)); - //qDebug() << light->direction << light->dir0 << light->dir1; + // qDebug() << light->shadow_matrix; + // prog->setUniformValue((ulightn + ".shadowDir0").toLatin1().constData(), (mat * dir0)); + // prog->setUniformValue((ulightn + ".shadowDir1").toLatin1().constData(), (mat * dir1)); + // qDebug() << light->direction << light->dir0 << light->dir1; } diff --git a/libs/qglview/glshaders.h b/libs/qglview/glshaders.h index f28a76c..e03a5c9 100644 --- a/libs/qglview/glshaders.h +++ b/libs/qglview/glshaders.h @@ -27,9 +27,13 @@ class Light; QString loadShaderFile(QOpenGLShaderProgram * prog, QOpenGLShader::ShaderType type, const QString & file); bool loadShaders(QOpenGLShaderProgram * prog, const QString & name, const QString & dir = QString()); -void setUniformMatrices(QOpenGLShaderProgram * prog, QMatrix4x4 proj, QMatrix4x4 view, QMatrix4x4 prevproj = QMatrix4x4(), QMatrix4x4 prevview = QMatrix4x4()); +void setUniformMatrices(QOpenGLShaderProgram * prog, + QMatrix4x4 proj, + QMatrix4x4 view, + QMatrix4x4 prevproj = QMatrix4x4(), + QMatrix4x4 prevview = QMatrix4x4()); void setUniformMap(QOpenGLShaderProgram * prog, const Map & map, int channel, int def_channel); void setUniformMaterial(QOpenGLShaderProgram * prog, const Material & mat); -void setUniformLights(QOpenGLShaderProgram * prog, const QVector & lights, const QMatrix4x4 & mat, int shadow_start); +void setUniformLights(QOpenGLShaderProgram * prog, const QVector & lights, const QMatrix4x4 & mat, int shadow_start); void setUniformLight(QOpenGLShaderProgram * prog, Light * light, QString ulightn, const QMatrix4x4 & mat = QMatrix4x4(), int shadow = 0); #endif // GLSHADERS_H diff --git a/libs/qglview/gltexture_manager.cpp b/libs/qglview/gltexture_manager.cpp index 70d55aa..dfda9db 100644 --- a/libs/qglview/gltexture_manager.cpp +++ b/libs/qglview/gltexture_manager.cpp @@ -20,14 +20,14 @@ bool GLTextureManager::loadTextures() { - //glGenTextures(); + // glGenTextures(); QFileInfoList fil; Animation anim; for (int i = 0; i < anim_pathes.size(); ++i) { anim.path = anim_pathes[i].second; anim.bitmaps.clear(); fil = QDir(anim_pathes[i].first).entryInfoList(QDir::Files, QDir::Name); - foreach (const QFileInfo & fi, fil) { + foreach(const QFileInfo & fi, fil) { if (fi.baseName().indexOf(anim_pathes[i].second) < 0) continue; anim.bitmaps << loadTexture(fi.filePath(), false); } @@ -35,7 +35,7 @@ bool GLTextureManager::loadTextures() { anim_ids << QPair(anim_pathes[i].second, anim); } anim_pathes.clear(); - foreach (const QString & i, tex_pathes) + foreach(const QString & i, tex_pathes) loadTexture(i, true); tex_pathes.clear(); return true; diff --git a/libs/qglview/gltexture_manager.h b/libs/qglview/gltexture_manager.h index a07e9cb..6b68555 100644 --- a/libs/qglview/gltexture_manager.h +++ b/libs/qglview/gltexture_manager.h @@ -20,34 +20,40 @@ #define GLTEXTUREMANAGER_H #include "glmaterial.h" + #include #include -class GLTextureManager: public GLTextureManagerBase -{ +class GLTextureManager: public GLTextureManagerBase { public: - GLTextureManager() {;} - ~GLTextureManager() {deleteTextures();} + GLTextureManager() { ; } + ~GLTextureManager() { deleteTextures(); } struct Animation { QString path; QVector bitmaps; - GLuint bitmapID(const int frame) {if (frame < 0 || frame >= bitmaps.size()) return 0; return bitmaps[frame];} + GLuint bitmapID(const int frame) { + if (frame < 0 || frame >= bitmaps.size()) return 0; + return bitmaps[frame]; + } }; - void addTexture(const QString & path) {tex_pathes << path;} - void addAnimation(const QString & dir, const QString & name) {anim_pathes << QPair(dir, name);} + void addTexture(const QString & path) { tex_pathes << path; } + void addAnimation(const QString & dir, const QString & name) { anim_pathes << QPair(dir, name); } bool loadTextures(); void deleteTextures(); void deleteTexture(const QString & name); - Animation * findAnimation(const QString & name) {for (int i = 0; i < anim_ids.size(); ++i) if (anim_ids[i].first == name) return &(anim_ids[i].second); return 0;} + Animation * findAnimation(const QString & name) { + for (int i = 0; i < anim_ids.size(); ++i) + if (anim_ids[i].first == name) return &(anim_ids[i].second); + return 0; + } - QVector > anim_ids; + QVector> anim_ids; private: QStringList tex_pathes; - QList > anim_pathes; - + QList> anim_pathes; }; #endif // GLTEXTUREMANAGER_H diff --git a/libs/qglview/gltypes.cpp b/libs/qglview/gltypes.cpp index 971fa78..09bb008 100644 --- a/libs/qglview/gltypes.cpp +++ b/libs/qglview/gltypes.cpp @@ -22,7 +22,7 @@ #include //__GLWidget__ * currentQGLView; -//QMutex globMutex; +// QMutex globMutex; QString readCharsUntilNull(QDataStream & s) { @@ -39,15 +39,14 @@ QString readCharsUntilNull(QDataStream & s) { QString findFile(const QString & file, const QStringList & pathes) { QFileInfo fi(QString(file).replace("\\", "/")); - //qDebug() << "search" << file << "in" << pathes; + // qDebug() << "search" << file << "in" << pathes; if (fi.exists()) return fi.absoluteFilePath(); QString fn = fi.fileName(); if (fn.contains("/")) fn = fn.mid(fn.lastIndexOf("/")); - foreach (QString p, pathes) { + foreach(QString p, pathes) { QFileInfoList fil = QDir(p).entryInfoList(QStringList(fn), QDir::Files | QDir::NoDotAndDotDot); - //qDebug() << "findFile" << fn << "in" << p << "->" << fil.size(); - if (!fil.isEmpty()) - return fil[0].absoluteFilePath(); + // qDebug() << "findFile" << fn << "in" << p << "->" << fil.size(); + if (!fil.isEmpty()) return fil[0].absoluteFilePath(); } return QString(); } @@ -58,22 +57,28 @@ void glDrawQuad(QOpenGLShaderProgram * prog, QVector4D * corner_dirs, GLfloat x, glSetPolygonMode(GL_FILL); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); - int loc = prog ? prog->attributeLocation("qgl_Color") : -1, - locv = prog ? prog->attributeLocation("qgl_Vertex") : -1, - loct = prog ? prog->attributeLocation("qgl_Texture") : -1, - locc = prog ? prog->attributeLocation("view_corner") : -1; - //if (prog) {qDebug() << locv << loct << locc;} + int loc = prog ? prog->attributeLocation("qgl_Color") : -1, locv = prog ? prog->attributeLocation("qgl_Vertex") : -1, + loct = prog ? prog->attributeLocation("qgl_Texture") : -1, locc = prog ? prog->attributeLocation("view_corner") : -1; + // if (prog) {qDebug() << locv << loct << locc;} QOpenGLFunctions * glFuncs = QOpenGLContext::currentContext()->functions(); if (prog) { - static const GLfloat cols [] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}; - static const GLfloat verts[] = {x, y, x+w, y, x, y+h, x+w, y+h}; - static const GLfloat texs [] = {0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f}; - GLfloat vcs[] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + static const GLfloat cols[] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}; + static const GLfloat verts[] = {x, y, x + w, y, x, y + h, x + w, y + h}; + static const GLfloat texs[] = {0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f}; + GLfloat vcs[] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; if (corner_dirs) { - vcs[0] = corner_dirs[0].x(); vcs[1] = corner_dirs[0].y(); vcs[2] = corner_dirs[0].z(); - vcs[3] = corner_dirs[1].x(); vcs[4] = corner_dirs[1].y(); vcs[5] = corner_dirs[1].z(); - vcs[6] = corner_dirs[2].x(); vcs[7] = corner_dirs[2].y(); vcs[8] = corner_dirs[2].z(); - vcs[9] = corner_dirs[3].x(); vcs[10] = corner_dirs[3].y(); vcs[11] = corner_dirs[3].z(); + vcs[0] = corner_dirs[0].x(); + vcs[1] = corner_dirs[0].y(); + vcs[2] = corner_dirs[0].z(); + vcs[3] = corner_dirs[1].x(); + vcs[4] = corner_dirs[1].y(); + vcs[5] = corner_dirs[1].z(); + vcs[6] = corner_dirs[2].x(); + vcs[7] = corner_dirs[2].y(); + vcs[8] = corner_dirs[2].z(); + vcs[9] = corner_dirs[3].x(); + vcs[10] = corner_dirs[3].y(); + vcs[11] = corner_dirs[3].z(); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); @@ -96,10 +101,14 @@ void glDrawQuad(QOpenGLShaderProgram * prog, QVector4D * corner_dirs, GLfloat x, } else { glBegin(GL_TRIANGLE_STRIP); glColor4f(1.f, 1.f, 1.f, 1.f); - glTexCoord2f(0.f, 0.f); glVertex2f(x, y); - glTexCoord2f(1.f, 0.f); glVertex2f(x+w, y); - glTexCoord2f(0.f, 1.f); glVertex2f(x, y+h); - glTexCoord2f(1.f, 1.f); glVertex2f(x+w, y+h); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); glEnd(); } } @@ -141,21 +150,19 @@ void createGLTexture(GLuint & tex, int width, int height, const GLenum & format, glGenTextures(1, &tex); glBindTexture(target, tex); } - //glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + // glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (format == GL_DEPTH_COMPONENT || format == GL_DEPTH_COMPONENT16 || format == GL_DEPTH_COMPONENT24 || format == GL_DEPTH_COMPONENT32) glTexImage2D(target, 0, format, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, nullptr); else { int t = GL_UNSIGNED_BYTE; int f = GL_RGBA; - if (format == GL_RGB32F || format == GL_RGB16F || format == GL_RGBA32F || format == GL_RGBA16F) - t = GL_FLOAT; - if (format == GL_RGB32F || format == GL_RGB16F || format == GL_RGB8 || format == GL_RGB) - f = GL_RGB; + if (format == GL_RGB32F || format == GL_RGB16F || format == GL_RGBA32F || format == GL_RGBA16F) t = GL_FLOAT; + if (format == GL_RGB32F || format == GL_RGB16F || format == GL_RGB8 || format == GL_RGB) f = GL_RGB; glTexImage2D(target, 0, format, width, height, 0, f, t, nullptr); - //glGenerateMipmap(target); - //qDebug() << "glTexImage2D" << width << height << QString::number(t, 16); + // glGenerateMipmap(target); + // qDebug() << "glTexImage2D" << width << height << QString::number(t, 16); } - //qDebug() << QString::number(glGetError(), 16); + // qDebug() << QString::number(glGetError(), 16); } @@ -165,9 +172,9 @@ void createGLTexture(GLuint & tex, const QImage & image, const GLenum & format, } glBindTexture(target, tex); QImage im = image.mirrored(false, true).convertToFormat(QImage::Format_ARGB32, Qt::ColorOnly); - //const QImage & cim(im); - //glClearError(); - //glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + // const QImage & cim(im); + // glClearError(); + // glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (target == GL_TEXTURE_1D || target == GL_TEXTURE_2D || target == GL_TEXTURE_3D) { glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_REPEAT); @@ -177,7 +184,7 @@ void createGLTexture(GLuint & tex, const QImage & image, const GLenum & format, glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); } glTexImage2D(target, 0, format, im.width(), im.height(), 0, GL_BGRA, GL_UNSIGNED_BYTE, im.bits()); - //qDebug() << tex << im.width() << im.height() << im.bits() << glGetError(); + // qDebug() << tex << im.width() << im.height() << im.bits() << glGetError(); } @@ -186,8 +193,8 @@ QMatrix4x4 glMatrixPerspective(float angle, float aspect, float near_, float far float t = 1.f / (tanf(angle * deg2rad / 2.f)), e = 2.4e-7f; ret(0, 0) = t / aspect; ret(1, 1) = t; - ret(2, 2) = e - 1.f;//far_ / (far_ - near_) - 1.; - ret(2, 3) = (e - 2.f) * near_;//2. * far_ * near_ / (far_ - near_); + ret(2, 2) = e - 1.f; // far_ / (far_ - near_) - 1.; + ret(2, 3) = (e - 2.f) * near_; // 2. * far_ * near_ / (far_ - near_); ret(3, 2) = -1.f; ret(3, 3) = 0.f; return ret; @@ -214,14 +221,15 @@ QImage rotateQImageRight(const QImage & im) { } - - QColor colorFromString(const QString & str) { QString s = str.trimmed(); - int i = s.indexOf("\t"); + int i = s.indexOf("\t"); float r, g, b; - r = s.left(i).toFloat(); s = s.right(s.length() - i - 1); i = s.indexOf("\t"); - g = s.left(i).toFloat(); s = s.right(s.length() - i - 1); + r = s.left(i).toFloat(); + s = s.right(s.length() - i - 1); + i = s.indexOf("\t"); + g = s.left(i).toFloat(); + s = s.right(s.length() - i - 1); b = s.toFloat(); return QColor(r * 255.f, g * 255.f, b * 255.f); } @@ -230,9 +238,12 @@ QColor colorFromString(const QString & str) { QVector3D orthToVector(const QVector3D & v, const float & scale) { if (v.isNull()) return QVector3D(); QVector3D rv, fn, sn; - if (v.x() != 0.f) rv.setZ(1.); - else if (v.y() != 0.f) rv.setX(1.); - else rv.setY(1.); + if (v.x() != 0.f) + rv.setZ(1.); + else if (v.y() != 0.f) + rv.setX(1.); + else + rv.setY(1.); fn = QVector3D::crossProduct(v, rv).normalized(); sn = QVector3D::crossProduct(v, fn).normalized(); return fn * urand(scale) + sn * urand(scale); @@ -266,25 +277,31 @@ void lengthenVector(QVector3D & v, const float & l) { Vector3d::Vector3d(const QString & str) { QString s = str.trimmed(); - int i = s.indexOf("\t"); - x = s.left(i).toFloat(); s = s.right(s.length() - i - 1); i = s.indexOf("\t"); - y = s.left(i).toFloat(); s = s.right(s.length() - i - 1); - z = s.toFloat(); + int i = s.indexOf("\t"); + x = s.left(i).toFloat(); + s = s.right(s.length() - i - 1); + i = s.indexOf("\t"); + y = s.left(i).toFloat(); + s = s.right(s.length() - i - 1); + z = s.toFloat(); } Vector3i::Vector3i(const QString & str) { QString s = str.trimmed(); - int i = s.indexOf("\t"); - p0 = s.left(i).toInt(); s = s.right(s.length() - i - 1); i = s.indexOf("\t"); - p1 = s.left(i).toInt(); s = s.right(s.length() - i - 1); - p2 = s.toInt(); + int i = s.indexOf("\t"); + p0 = s.left(i).toInt(); + s = s.right(s.length() - i - 1); + i = s.indexOf("\t"); + p1 = s.left(i).toInt(); + s = s.right(s.length() - i - 1); + p2 = s.toInt(); } void glEnableDepth() { glEnable(GL_DEPTH_TEST); - //glDepthFunc(GL_GREATER); + // glDepthFunc(GL_GREATER); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); } @@ -298,7 +315,7 @@ void glDisableDepth() { void glClearFramebuffer(const QColor & color, bool depth) { glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); - //glClearDepth(0.); + // glClearDepth(0.); if (depth) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); else @@ -306,10 +323,8 @@ void glClearFramebuffer(const QColor & color, bool depth) { } - - QGLViewBase::QGLViewBase() { - camera_ = new Camera(); + camera_ = new Camera(); textures_manager = new GLTextureManager(); } @@ -347,13 +362,16 @@ Box3D::Box3D(const QVector & points) { iy = ay = points[0].y(); iz = az = points[0].z(); for (int i = 1; i < points.size(); ++i) { - ix = qMin(ix, points[i].x()); ax = qMax(ax, points[i].x()); - iy = qMin(iy, points[i].y()); ay = qMax(ay, points[i].y()); - iz = qMin(iz, points[i].z()); az = qMax(az, points[i].z()); + ix = qMin(ix, points[i].x()); + ax = qMax(ax, points[i].x()); + iy = qMin(iy, points[i].y()); + ay = qMax(ay, points[i].y()); + iz = qMin(iz, points[i].z()); + az = qMax(az, points[i].z()); } - x = ix; - y = iy; - z = iz; + x = ix; + y = iy; + z = iz; length = ax - ix; width = ay - iy; height = az - iz; @@ -363,20 +381,27 @@ Box3D::Box3D(const QVector & points) { QVector Box3D::corners() const { QVector ret; ret << QVector3D(x, y, z) << QVector3D(x, y + width, z) << QVector3D(x, y, z + height) << QVector3D(x, y + width, z + height) - << QVector3D(x + length, y, z) << QVector3D(x + length, y + width, z) - << QVector3D(x + length, y, z + height) << QVector3D(x + length, y + width, z + height); + << QVector3D(x + length, y, z) << QVector3D(x + length, y + width, z) << QVector3D(x + length, y, z + height) + << QVector3D(x + length, y + width, z + height); return ret; } -Box3D & Box3D::operator |=(const Box3D & o) { - if (isEmpty()) *this = o; +Box3D & Box3D::operator|=(const Box3D & o) { + if (isEmpty()) + *this = o; else { GLfloat mx = x + length, my = y + width, mz = z + height; GLfloat omx = o.x + o.length, omy = o.y + o.width, omz = o.z + o.height; - x = qMin(x, o.x); y = qMin(y, o.y); z = qMin(z, o.z); - mx = qMax(mx, omx); my = qMax(my, omy); mz = qMax(mz, omz); - length = mx - x; width = my - y; height = mz - z; + x = qMin(x, o.x); + y = qMin(y, o.y); + z = qMin(z, o.z); + mx = qMax(mx, omx); + my = qMax(my, omy); + mz = qMax(mz, omz); + length = mx - x; + width = my - y; + height = mz - z; } return *this; } diff --git a/libs/qglview/gltypes.h b/libs/qglview/gltypes.h index 00cf1b5..700cef1 100644 --- a/libs/qglview/gltypes.h +++ b/libs/qglview/gltypes.h @@ -30,9 +30,9 @@ #endif #ifndef WINDOWS # ifndef QNX -# ifndef MAC -# define LINUX -# endif +# ifndef MAC +# define LINUX +# endif # endif #endif #if __GNUC__ @@ -45,44 +45,44 @@ #include #ifndef WINDOWS # ifdef MAC -# include -# include -# include +# include +# include +# include # else -# include -# include -# include +# include +# include +# include # endif #endif +#include +#include +#include +#include +#include +#include +#include +#include #include -#include #include #include -#include -#include -#include -#include -#include -#include +#include #include #include -#include -#include -#include -#include +#include +#include #ifndef QNX -# include -# include +# include +# include #else -# include -# include +# include +# include #endif #include #ifdef WINDOWS # define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -# define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +# define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #endif #ifndef M_PI @@ -114,75 +114,166 @@ const float deg2rad = atanf(1.f) / 45.f; const float rad2deg = 45.f / atanf(1.f); # ifdef WINDOWS -inline int random() {return rand();} +inline int random() { + return rand(); +} # endif #else -#define random randomi +# define random randomi #endif #ifdef CC_VC -inline float round(const float & v) {return floor(v + 0.5);} +inline float round(const float & v) { + return floor(v + 0.5); +} #endif -inline float randomu() {return float(random()) / RAND_MAX;} +inline float randomu() { + return float(random()) / RAND_MAX; +} -inline const QSizeF operator *(const QSizeF & f, const QSizeF & s) {return QSizeF(f.width() * s.width(), f.height() * s.height());} +inline const QSizeF operator*(const QSizeF & f, const QSizeF & s) { + return QSizeF(f.width() * s.width(), f.height() * s.height()); +} #ifndef PIP_VERSION -template inline void piSwap(T & f, T & s) {T t(f); f = s; s = t;} -template inline Type piMin(const Type & f, const Type & s) {return (f > s) ? s : f;} -template inline Type piMin(const Type & f, const Type & s, const Type & t) {return (f < s && f < t) ? f : ((s < t) ? s : t);} -template inline Type piMax(const Type & f, const Type & s) {return (f < s) ? s : f;} -template inline Type piMax(const Type & f, const Type & s, const Type & t) {return (f > s && f > t) ? f : ((s > t) ? s : t);} -template inline Type piClamp(const Type & v, const Type & min, const Type & max) {return (v > max ? max : (v < min ? min : v));} -inline ushort letobe_s(ushort v) {return (v << 8) | (v >> 8);} +template +inline void piSwap(T & f, T & s) { + T t(f); + f = s; + s = t; +} +template +inline Type piMin(const Type & f, const Type & s) { + return (f > s) ? s : f; +} +template +inline Type piMin(const Type & f, const Type & s, const Type & t) { + return (f < s && f < t) ? f : ((s < t) ? s : t); +} +template +inline Type piMax(const Type & f, const Type & s) { + return (f < s) ? s : f; +} +template +inline Type piMax(const Type & f, const Type & s, const Type & t) { + return (f > s && f > t) ? f : ((s > t) ? s : t); +} +template +inline Type piClamp(const Type & v, const Type & min, const Type & max) { + return (v > max ? max : (v < min ? min : v)); +} +inline ushort letobe_s(ushort v) { + return (v << 8) | (v >> 8); +} #endif // return [-1, 1] -inline float urand(const float & scale = 1.) {return ((float)rand() / RAND_MAX - .5f) * (scale + scale);} +inline float urand(const float & scale = 1.) { + return ((float)rand() / RAND_MAX - .5f) * (scale + scale); +} // return [0, 1] -inline float uprand(const float & scale = 1.) {return ((float)rand() / RAND_MAX) * scale;} +inline float uprand(const float & scale = 1.) { + return ((float)rand() / RAND_MAX) * scale; +} QString readCharsUntilNull(QDataStream & s); QString findFile(const QString & file, const QStringList & pathes); -inline QColor operator *(const QColor & c, float v) {return QColor(piClamp(c.red() * v, 0, 255), piClamp(c.green() * v, 0, 255), piClamp(c.blue() * v, 0, 255), piClamp(c.alpha() * v, 0, 255));} -inline QColor operator /(const QColor & c, float v) {return QColor(piClamp(c.red() / v, 0, 255), piClamp(c.green() / v, 0, 255), piClamp(c.blue() / v, 0, 255), piClamp(c.alpha() / v, 0, 255));} +inline QColor operator*(const QColor & c, float v) { + return QColor(piClamp(c.red() * v, 0, 255), + piClamp(c.green() * v, 0, 255), + piClamp(c.blue() * v, 0, 255), + piClamp(c.alpha() * v, 0, 255)); +} +inline QColor operator/(const QColor & c, float v) { + return QColor(piClamp(c.red() / v, 0, 255), + piClamp(c.green() / v, 0, 255), + piClamp(c.blue() / v, 0, 255), + piClamp(c.alpha() / v, 0, 255)); +} -//extern __GLWidget__ * currentQGLView; +// extern __GLWidget__ * currentQGLView; -inline void qglColor(const QColor & c) {glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF());} +inline void qglColor(const QColor & c) { + glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF()); +} void qglMultMatrix(const QMatrix4x4 & m); void glEnableDepth(); void glDisableDepth(); -inline void glResetAllTransforms() {glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity();} -inline void glClearError() {int c = 100; while (glGetError() != GL_NO_ERROR && --c > 0) glGetError();} -inline void glClearAccumulation(const QColor & color = Qt::black) {glClearAccum(color.redF(), color.greenF(), color.blueF(), color.alphaF()); glClear(GL_ACCUM_BUFFER_BIT);} +inline void glResetAllTransforms() { + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); +} +inline void glClearError() { + int c = 100; + while (glGetError() != GL_NO_ERROR && --c > 0) + glGetError(); +} +inline void glClearAccumulation(const QColor & color = Qt::black) { + glClearAccum(color.redF(), color.greenF(), color.blueF(), color.alphaF()); + glClear(GL_ACCUM_BUFFER_BIT); +} void glClearFramebuffer(const QColor & color = Qt::black, bool depth = true); -inline void glSetCapEnabled(GLenum cap, bool on = true) {if (on) glEnable(cap); else glDisable(cap);} -inline void glSetLightEnabled(bool on) {if (on) glEnable(GL_LIGHTING); else glDisable(GL_LIGHTING);} -inline void glSetFogEnabled(bool on) {if (on) glEnable(GL_FOG); else glDisable(GL_FOG);} -inline void glSetPolygonMode(GLenum mode) {glPolygonMode(GL_FRONT_AND_BACK, mode);} -void glDrawQuad(QOpenGLShaderProgram * prog = 0, QVector4D * corner_dirs = 0, GLfloat x = -1.f, GLfloat y = -1.f, GLfloat w = 2.f, GLfloat h = 2.f); +inline void glSetCapEnabled(GLenum cap, bool on = true) { + if (on) + glEnable(cap); + else + glDisable(cap); +} +inline void glSetLightEnabled(bool on) { + if (on) + glEnable(GL_LIGHTING); + else + glDisable(GL_LIGHTING); +} +inline void glSetFogEnabled(bool on) { + if (on) + glEnable(GL_FOG); + else + glDisable(GL_FOG); +} +inline void glSetPolygonMode(GLenum mode) { + glPolygonMode(GL_FRONT_AND_BACK, mode); +} +void glDrawQuad(QOpenGLShaderProgram * prog = 0, + QVector4D * corner_dirs = 0, + GLfloat x = -1.f, + GLfloat y = -1.f, + GLfloat w = 2.f, + GLfloat h = 2.f); QMatrix4x4 getGLMatrix(GLenum matrix); void setGLMatrix(QMatrix4x4 matrix); -inline void deleteGLTexture(GLuint & tex) {if (tex != 0) glDeleteTextures(1, &tex); tex = 0;} -//# define QGLCI if (!QOpenGLContext::currentContext()) return; QOpenGLFunctions gf(QOpenGLContext::currentContext()); -//# define QGLC gf. -//inline void glActiveTextureChannel(int channel) {QGLCI gf.glActiveTexture(GL_TEXTURE0 + channel);} -//inline void glDisableTextures(int channels = 8) {QGLCI for (int i = channels - 1; i >= 0; --i) {glActiveTextureChannel(i); glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_CUBE_MAP);}} -//inline void glReleaseTextures(int channels = 8) {QGLCI for (int i = channels - 1; i >= 0; --i) {glActiveTextureChannel(i); glBindTexture(GL_TEXTURE_2D, 0); glBindTexture(GL_TEXTURE_CUBE_MAP, 0);}} -//inline void glReleaseFramebuffer() {QGLCI gf.glBindFramebuffer(GL_FRAMEBUFFER, 0);} -//inline void glReleaseShaders() {QGLCI gf.glUseProgram(0);} -//inline void deleteGLFramebuffer(GLuint & fbo) {QGLCI if (fbo != 0) gf.glDeleteFramebuffers(1, &fbo); fbo = 0;} -//inline void deleteGLRenderbuffer(GLuint & drbo) {QGLCI if (drbo != 0) gf.glDeleteRenderbuffers(1, &drbo); drbo = 0;} -//inline void deleteGLBuffer(GLuint & bo) {QGLCI if (bo != 0) gf.glDeleteBuffers(1, &bo); bo = 0;} -//inline void deleteGLVertexArray(GLuint & va) {QGLCI if (va != 0) gf.glDeleteVertexArrays(1, &va); va = 0;} +inline void deleteGLTexture(GLuint & tex) { + if (tex != 0) glDeleteTextures(1, &tex); + tex = 0; +} +// # define QGLCI if (!QOpenGLContext::currentContext()) return; QOpenGLFunctions gf(QOpenGLContext::currentContext()); +// # define QGLC gf. +// inline void glActiveTextureChannel(int channel) {QGLCI gf.glActiveTexture(GL_TEXTURE0 + channel);} +// inline void glDisableTextures(int channels = 8) {QGLCI for (int i = channels - 1; i >= 0; --i) {glActiveTextureChannel(i); +// glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_CUBE_MAP);}} inline void glReleaseTextures(int channels = 8) {QGLCI for (int i = channels +// - 1; i >= 0; --i) {glActiveTextureChannel(i); glBindTexture(GL_TEXTURE_2D, 0); glBindTexture(GL_TEXTURE_CUBE_MAP, 0);}} inline void +// glReleaseFramebuffer() {QGLCI gf.glBindFramebuffer(GL_FRAMEBUFFER, 0);} inline void glReleaseShaders() {QGLCI gf.glUseProgram(0);} inline +// void deleteGLFramebuffer(GLuint & fbo) {QGLCI if (fbo != 0) gf.glDeleteFramebuffers(1, &fbo); fbo = 0;} inline void +// deleteGLRenderbuffer(GLuint & drbo) {QGLCI if (drbo != 0) gf.glDeleteRenderbuffers(1, &drbo); drbo = 0;} inline void +// deleteGLBuffer(GLuint & bo) {QGLCI if (bo != 0) gf.glDeleteBuffers(1, &bo); bo = 0;} inline void deleteGLVertexArray(GLuint & va) {QGLCI +// if (va != 0) gf.glDeleteVertexArrays(1, &va); va = 0;} void createGLTexture(GLuint & tex, int width, int height, const GLenum & format = GL_RGBA8, const GLenum & target = GL_TEXTURE_2D); void createGLTexture(GLuint & tex, const QImage & image, const GLenum & format = GL_RGBA8, const GLenum & target = GL_TEXTURE_2D); -inline void qglTranslate(const QVector3D & v) {glTranslatef(v.x(), v.y(), v.z());} -inline void qglScale(const QVector3D & v) {glScalef(v.x(), v.y(), v.z());} +inline void qglTranslate(const QVector3D & v) { + glTranslatef(v.x(), v.y(), v.z()); +} +inline void qglScale(const QVector3D & v) { + glScalef(v.x(), v.y(), v.z()); +} QMatrix4x4 glMatrixPerspective(float angle, float aspect, float near_, float far_); QImage rotateQImageLeft(const QImage & im); QImage rotateQImageRight(const QImage & im); -inline QImage rotateQImage180(const QImage & im) {return im.mirrored(true, true);} -//const double deg2rad = atan(1.) / 45.; -//const double rad2deg = 45. / atan(1.); +inline QImage rotateQImage180(const QImage & im) { + return im.mirrored(true, true); +} +// const double deg2rad = atan(1.) / 45.; +// const double rad2deg = 45. / atan(1.); struct Box3D { GLfloat x; @@ -194,27 +285,72 @@ struct Box3D { GLfloat angle_z; GLfloat angle_xy; GLfloat angle_roll; - Box3D() {x = y = z = width = length = height = angle_z = angle_xy = angle_roll = 0.f;} - Box3D(const QVector3D & center, GLfloat hwid, GLfloat hlen, GLfloat hhei) {x = center.x() - hwid; y = center.y() - hlen; z = center.z() - hhei; width = 2 * hwid; length = 2 * hlen; height = 2 * hhei; angle_z = angle_xy = angle_roll = 0.f;} + Box3D() { x = y = z = width = length = height = angle_z = angle_xy = angle_roll = 0.f; } + Box3D(const QVector3D & center, GLfloat hwid, GLfloat hlen, GLfloat hhei) { + x = center.x() - hwid; + y = center.y() - hlen; + z = center.z() - hhei; + width = 2 * hwid; + length = 2 * hlen; + height = 2 * hhei; + angle_z = angle_xy = angle_roll = 0.f; + } Box3D(const QVector & points); - bool isEmpty() const {return (qAbs(width) < 1E-6f) || (qAbs(length) < 1E-6f) || (qAbs(height) < 1E-6f);} - QVector3D randomPoint() const {return QVector3D(uprand(length) + x, uprand(width) + y, uprand(height) + z);} - QVector3D pos() const {return QVector3D(x, y, z);} - QVector3D size() const {return QVector3D(length, width, height);} - QVector3D center() const {return QVector3D(length / 2.f + x, width / 2.f + y, height / 2.f + z);} - QVector3D angles() const {return QVector3D(angle_xy, angle_roll, angle_z);} + bool isEmpty() const { return (qAbs(width) < 1E-6f) || (qAbs(length) < 1E-6f) || (qAbs(height) < 1E-6f); } + QVector3D randomPoint() const { return QVector3D(uprand(length) + x, uprand(width) + y, uprand(height) + z); } + QVector3D pos() const { return QVector3D(x, y, z); } + QVector3D size() const { return QVector3D(length, width, height); } + QVector3D center() const { return QVector3D(length / 2.f + x, width / 2.f + y, height / 2.f + z); } + QVector3D angles() const { return QVector3D(angle_xy, angle_roll, angle_z); } QVector corners() const; - void setPos(const QVector3D & p) {x = p.x(); y = p.y(); z = p.z();} - void setAngles(const QVector3D & a) {angle_xy = a.x(); angle_roll = a.y(); angle_z = a.z();} - void setSize(const QVector3D & s) {length = s.x(); width = s.y(); height = s.z();} - Box3D & moveTo(const QVector3D & v) {x = v.x(); y = v.y(); z = v.z(); return *this;} - Box3D & move(const QVector3D & v) {x += v.x(); y += v.y(); z += v.z(); return *this;} - Box3D movedTo(const QVector3D & v) const {Box3D t(*this); t.x = v.x(); t.y = v.y(); t.z = v.z(); return t;} - Box3D moved(const QVector3D & v) const {Box3D t(*this); t.x += v.x(); t.y += v.y(); t.z += v.z(); return t;} - Box3D & operator |=(const Box3D & o); + void setPos(const QVector3D & p) { + x = p.x(); + y = p.y(); + z = p.z(); + } + void setAngles(const QVector3D & a) { + angle_xy = a.x(); + angle_roll = a.y(); + angle_z = a.z(); + } + void setSize(const QVector3D & s) { + length = s.x(); + width = s.y(); + height = s.z(); + } + Box3D & moveTo(const QVector3D & v) { + x = v.x(); + y = v.y(); + z = v.z(); + return *this; + } + Box3D & move(const QVector3D & v) { + x += v.x(); + y += v.y(); + z += v.z(); + return *this; + } + Box3D movedTo(const QVector3D & v) const { + Box3D t(*this); + t.x = v.x(); + t.y = v.y(); + t.z = v.z(); + return t; + } + Box3D moved(const QVector3D & v) const { + Box3D t(*this); + t.x += v.x(); + t.y += v.y(); + t.z += v.z(); + return t; + } + Box3D & operator|=(const Box3D & o); }; -inline QDebug operator <<(QDebug d, const Box3D & v) {d << "Box3D {start (" << v.x << "," << v.y << "," << v.z << "), size (" << v.length << "," << v.width << "," << v.height << ")}"; return d;} +inline QDebug operator<<(QDebug d, const Box3D & v) { + d << "Box3D {start (" << v.x << "," << v.y << "," << v.z << "), size (" << v.length << "," << v.width << "," << v.height << ")}"; + return d; +} struct Vector3d; @@ -224,89 +360,196 @@ struct Vector3d { GLfloat x; GLfloat y; GLfloat z; - Vector3d(GLfloat x_ = 0., GLfloat y_ = 0., GLfloat z_ = 0.) {x = x_; y = y_; z = z_;} - Vector3d(const QVector3D & v) {x = v.x(); y = v.y(); z = v.z();} + Vector3d(GLfloat x_ = 0., GLfloat y_ = 0., GLfloat z_ = 0.) { + x = x_; + y = y_; + z = z_; + } + Vector3d(const QVector3D & v) { + x = v.x(); + y = v.y(); + z = v.z(); + } Vector3d(const QString & str); - inline void clear() {x = y = z = 0.;} - inline GLfloat length() const {return sqrtf(x*x + y*y + z*z);} - inline GLfloat lengthSquared() const {return x*x + y*y + z*z;} + inline void clear() { x = y = z = 0.; } + inline GLfloat length() const { return sqrtf(x * x + y * y + z * z); } + inline GLfloat lengthSquared() const { return x * x + y * y + z * z; } Vector3d & normalize() { GLfloat l = length(); if (l == 0.f) return *this; - x /= l; y /= l; z /= l; + x /= l; + y /= l; + z /= l; return *this; } - Vector3d normalized() {return Vector3d(*this).normalize();} - Vector3d projectTo(Vector3d dir) {dir.normalize(); return dir * dot(dir, *this);} - Vector3d operator *(const GLfloat v) {return Vector3d(x*v, y*v, z*v);} - Vector3d operator /(const GLfloat v) {return Vector3d(x/v, y/v, z/v);} - Vector3d operator +(const GLfloat v) {return Vector3d(x+v, y+v, z+v);} - Vector3d operator -(const GLfloat v) {return Vector3d(x-v, y-v, z-v);} - Vector3d operator +(const Vector3d & v) {return Vector3d(x + v.x, y + v.y, z + v.z);} - Vector3d operator -(const Vector3d & v) {return Vector3d(x - v.x, y - v.y, z - v.z);} - Vector3d operator -() {return Vector3d(-x, -y, -z);} - Vector3d & operator *=(const GLfloat & v) {x *= v; y *= v; z *= v; return *this;} - Vector3d & operator /=(const GLfloat & v) {x /= v; y /= v; z /= v; return *this;} - Vector3d & operator +=(const GLfloat & v) {x += v; y += v; z += v; return *this;} - Vector3d & operator -=(const GLfloat & v) {x -= v; y -= v; z -= v; return *this;} - Vector3d & operator +=(const Vector3d & v) {x += v.x; y += v.y; z += v.z; return *this;} - Vector3d & operator -=(const Vector3d & v) {x -= v.x; y -= v.y; z -= v.z; return *this;} - bool operator ==(const Vector3d & v) {return x == v.x && y == v.y && z == v.z;} - QVector3D toQVector3D() const {return QVector3D(x, y, z);} + Vector3d normalized() { return Vector3d(*this).normalize(); } + Vector3d projectTo(Vector3d dir) { + dir.normalize(); + return dir * dot(dir, *this); + } + Vector3d operator*(const GLfloat v) { return Vector3d(x * v, y * v, z * v); } + Vector3d operator/(const GLfloat v) { return Vector3d(x / v, y / v, z / v); } + Vector3d operator+(const GLfloat v) { return Vector3d(x + v, y + v, z + v); } + Vector3d operator-(const GLfloat v) { return Vector3d(x - v, y - v, z - v); } + Vector3d operator+(const Vector3d & v) { return Vector3d(x + v.x, y + v.y, z + v.z); } + Vector3d operator-(const Vector3d & v) { return Vector3d(x - v.x, y - v.y, z - v.z); } + Vector3d operator-() { return Vector3d(-x, -y, -z); } + Vector3d & operator*=(const GLfloat & v) { + x *= v; + y *= v; + z *= v; + return *this; + } + Vector3d & operator/=(const GLfloat & v) { + x /= v; + y /= v; + z /= v; + return *this; + } + Vector3d & operator+=(const GLfloat & v) { + x += v; + y += v; + z += v; + return *this; + } + Vector3d & operator-=(const GLfloat & v) { + x -= v; + y -= v; + z -= v; + return *this; + } + Vector3d & operator+=(const Vector3d & v) { + x += v.x; + y += v.y; + z += v.z; + return *this; + } + Vector3d & operator-=(const Vector3d & v) { + x -= v.x; + y -= v.y; + z -= v.z; + return *this; + } + bool operator==(const Vector3d & v) { return x == v.x && y == v.y && z == v.z; } + QVector3D toQVector3D() const { return QVector3D(x, y, z); } }; -inline Vector3d operator *(const Vector3d & v0, const Vector3d & v1) { +inline Vector3d operator*(const Vector3d & v0, const Vector3d & v1) { return Vector3d(v0.y * v1.z - v1.y * v0.z, v1.x * v0.z - v0.x * v1.z, v0.x * v1.y - v1.x * v0.y); } -inline GLfloat dot(const Vector3d & v0, const Vector3d & v1) {return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z;} +inline GLfloat dot(const Vector3d & v0, const Vector3d & v1) { + return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z; +} struct Vector2d { GLfloat x; GLfloat y; - Vector2d(GLfloat x_ = 0., GLfloat y_ = 0.) {x = x_; y = y_;} - Vector2d(const Vector3d & v3) {x = v3.x; y = v3.y;} - Vector2d operator *(const GLfloat v) {return Vector2d(x*v, y*v);} - Vector2d operator /(const GLfloat v) {return Vector2d(x/v, y/v);} - Vector2d operator +(const GLfloat v) {return Vector2d(x+v, y+v);} - Vector2d operator -(const GLfloat v) {return Vector2d(x-v, y-v);} - Vector2d operator +(const Vector3d & v) {return Vector3d(x + v.x, y + v.y);} - Vector2d operator -(const Vector3d & v) {return Vector3d(x - v.x, y - v.y);} - Vector2d operator +(const Vector2d & v) {return Vector2d(x + v.x, y + v.y);} - Vector2d operator -(const Vector2d & v) {return Vector2d(x - v.x, y - v.y);} - Vector2d & operator *=(const GLfloat & v) {x *= v; y *= v; return *this;} - Vector2d & operator /=(const GLfloat & v) {x /= v; y /= v; return *this;} - Vector2d & operator +=(const GLfloat & v) {x += v; y += v; return *this;} - Vector2d & operator -=(const GLfloat & v) {x -= v; y -= v; return *this;} - Vector2d & operator +=(const Vector3d & v) {x += v.x; y += v.y;; return *this;} - Vector2d & operator -=(const Vector3d & v) {x -= v.x; y -= v.y;; return *this;} + Vector2d(GLfloat x_ = 0., GLfloat y_ = 0.) { + x = x_; + y = y_; + } + Vector2d(const Vector3d & v3) { + x = v3.x; + y = v3.y; + } + Vector2d operator*(const GLfloat v) { return Vector2d(x * v, y * v); } + Vector2d operator/(const GLfloat v) { return Vector2d(x / v, y / v); } + Vector2d operator+(const GLfloat v) { return Vector2d(x + v, y + v); } + Vector2d operator-(const GLfloat v) { return Vector2d(x - v, y - v); } + Vector2d operator+(const Vector3d & v) { return Vector3d(x + v.x, y + v.y); } + Vector2d operator-(const Vector3d & v) { return Vector3d(x - v.x, y - v.y); } + Vector2d operator+(const Vector2d & v) { return Vector2d(x + v.x, y + v.y); } + Vector2d operator-(const Vector2d & v) { return Vector2d(x - v.x, y - v.y); } + Vector2d & operator*=(const GLfloat & v) { + x *= v; + y *= v; + return *this; + } + Vector2d & operator/=(const GLfloat & v) { + x /= v; + y /= v; + return *this; + } + Vector2d & operator+=(const GLfloat & v) { + x += v; + y += v; + return *this; + } + Vector2d & operator-=(const GLfloat & v) { + x -= v; + y -= v; + return *this; + } + Vector2d & operator+=(const Vector3d & v) { + x += v.x; + y += v.y; + ; + return *this; + } + Vector2d & operator-=(const Vector3d & v) { + x -= v.x; + y -= v.y; + ; + return *this; + } }; struct Vector3i { - Vector3i(int p0_ = 0, int p1_ = 0, int p2_ = 0) {p0 = p0_; p1 = p1_; p2 = p2_;} + Vector3i(int p0_ = 0, int p1_ = 0, int p2_ = 0) { + p0 = p0_; + p1 = p1_; + p2 = p2_; + } Vector3i(const QString & str); - Vector3i movedX(const int & o) {return Vector3i(p0 + o, p1, p2);} - Vector3i movedY(const int & o) {return Vector3i(p0, p1 + o, p2);} - Vector3i movedZ(const int & o) {return Vector3i(p0, p1, p2 + o);} - Vector3i moved(const int & x, const int & y, const int & z) {return Vector3i(p0 + x, p1 + y, p2 + z);} + Vector3i movedX(const int & o) { return Vector3i(p0 + o, p1, p2); } + Vector3i movedY(const int & o) { return Vector3i(p0, p1 + o, p2); } + Vector3i movedZ(const int & o) { return Vector3i(p0, p1, p2 + o); } + Vector3i moved(const int & x, const int & y, const int & z) { return Vector3i(p0 + x, p1 + y, p2 + z); } int p0; int p1; int p2; - bool operator ==(const Vector3i & o) const {return p0 == o.p0 && p1 == o.p1 && p2 == o.p2;} - bool operator !=(const Vector3i & o) const {return p0 != o.p0 || p1 != o.p1 || p2 != o.p2;} - QVector3D toQVector3D() const {return QVector3D(p0, p1, p2);} + bool operator==(const Vector3i & o) const { return p0 == o.p0 && p1 == o.p1 && p2 == o.p2; } + bool operator!=(const Vector3i & o) const { return p0 != o.p0 || p1 != o.p1 || p2 != o.p2; } + QVector3D toQVector3D() const { return QVector3D(p0, p1, p2); } }; -inline Vector3i operator +(const Vector3i & f, const Vector3i & s) {return Vector3i(f.p0 + s.p0, f.p1 + s.p1, f.p2 + s.p2);} -inline Vector3i operator -(const Vector3i & f, const Vector3i & s) {return Vector3i(f.p0 - s.p0, f.p1 - s.p1, f.p2 - s.p2);} -inline Vector3i operator /(const Vector3i & f, const int & s) {return Vector3i(f.p0 / s, f.p1 / s, f.p2 / s);} -inline uint qHash(const Vector3i & v) {return v.p0 + v.p1 * 1024 + v.p2 * 1024 * 1024;} -inline QDebug operator <<(QDebug d, const Vector3d& v) {d.nospace() << "{" << v.x << ", " << v.y << ", " << v.z << "}"; return d.space();} -inline QDebug operator <<(QDebug d, const Vector3i & v) {d.nospace() << "{" << v.p0 << ", " << v.p1 << ", " << v.p2 << "}"; return d.space();} +inline Vector3i operator+(const Vector3i & f, const Vector3i & s) { + return Vector3i(f.p0 + s.p0, f.p1 + s.p1, f.p2 + s.p2); +} +inline Vector3i operator-(const Vector3i & f, const Vector3i & s) { + return Vector3i(f.p0 - s.p0, f.p1 - s.p1, f.p2 - s.p2); +} +inline Vector3i operator/(const Vector3i & f, const int & s) { + return Vector3i(f.p0 / s, f.p1 / s, f.p2 / s); +} +inline uint qHash(const Vector3i & v) { + return v.p0 + v.p1 * 1024 + v.p2 * 1024 * 1024; +} +inline QDebug operator<<(QDebug d, const Vector3d & v) { + d.nospace() << "{" << v.x << ", " << v.y << ", " << v.z << "}"; + return d.space(); +} +inline QDebug operator<<(QDebug d, const Vector3i & v) { + d.nospace() << "{" << v.p0 << ", " << v.p1 << ", " << v.p2 << "}"; + return d.space(); +} -inline QDataStream & operator <<(QDataStream & s, const Vector3d & v) {s << v.x << v.y << v.z; return s;} -inline QDataStream & operator >>(QDataStream & s, Vector3d & v) {s >> v.x >> v.y >> v.z; return s;} -inline QDataStream & operator <<(QDataStream & s, const Vector3i & v) {s << v.p0 << v.p1 << v.p2; return s;} -inline QDataStream & operator >>(QDataStream & s, Vector3i & v) {s >> v.p0 >> v.p1 >> v.p2; return s;} +inline QDataStream & operator<<(QDataStream & s, const Vector3d & v) { + s << v.x << v.y << v.z; + return s; +} +inline QDataStream & operator>>(QDataStream & s, Vector3d & v) { + s >> v.x >> v.y >> v.z; + return s; +} +inline QDataStream & operator<<(QDataStream & s, const Vector3i & v) { + s << v.p0 << v.p1 << v.p2; + return s; +} +inline QDataStream & operator>>(QDataStream & s, Vector3i & v) { + s >> v.p0 >> v.p1 >> v.p2; + return s; +} QColor colorFromString(const QString & str); inline float cosABV(const QVector3D & v0, const QVector3D & v1) { @@ -314,14 +557,23 @@ inline float cosABV(const QVector3D & v0, const QVector3D & v1) { if (l == 0.f) return 0.; return (QVector3D::dotProduct(v0, v1)) / l; } -inline QVector3D projection(const QVector3D & v, const QVector3D & to) {return to.normalized() * v.length() * cosABV(v, to);} +inline QVector3D projection(const QVector3D & v, const QVector3D & to) { + return to.normalized() * v.length() * cosABV(v, to); +} QVector3D orthToVector(const QVector3D & v, const float & scale = 1.); QVector3D rotateVector(const QVector3D & v, const QVector3D & a); void setVectorLength(QVector3D & v, const float & l); void lengthenVector(QVector3D & v, const float & l); -inline float squareLength(const QVector3D & from, const QVector3D & to) {return (to.x() - from.x())*(to.x() - from.x()) + (to.y() - from.y())*(to.y() - from.y()) + (to.z() - from.z())*(to.z() - from.z());} -inline QVector3D directionFromAngles(const QVector3D & a) {return rotateVector(QVector3D(1., 0., 0.), a);} -inline float frac(const float & x, const float & b) {return x - int(x / b) * b;} +inline float squareLength(const QVector3D & from, const QVector3D & to) { + return (to.x() - from.x()) * (to.x() - from.x()) + (to.y() - from.y()) * (to.y() - from.y()) + + (to.z() - from.z()) * (to.z() - from.z()); +} +inline QVector3D directionFromAngles(const QVector3D & a) { + return rotateVector(QVector3D(1., 0., 0.), a); +} +inline float frac(const float & x, const float & b) { + return x - int(x / b) * b; +} class GLObjectBase; class QGLView; @@ -329,9 +581,9 @@ class Light; class Camera; class GLTextureManagerBase; -class QGLViewBase -{ +class QGLViewBase { friend class GLObjectBase; + public: QGLViewBase(); virtual ~QGLViewBase(); @@ -339,6 +591,7 @@ public: const Camera * camera() const; void setCamera(Camera * camera); GLTextureManagerBase * textureManager(); + protected: virtual void collectLights() = 0; Camera * camera_; diff --git a/libs/qglview/glvbo.cpp b/libs/qglview/glvbo.cpp index 9c8e3d9..e6f4e30 100644 --- a/libs/qglview/glvbo.cpp +++ b/libs/qglview/glvbo.cpp @@ -21,21 +21,21 @@ GLVBO::GLVBO(GLenum usage_) { buffer_ = 0; - va_ = 0; - usage = usage_; + va_ = 0; + usage = usage_; changed = true; } GLVBO::~GLVBO() { - //destroy(); + // destroy(); } void GLVBO::init() { initializeOpenGLFunctions(); if (!isInit()) { - //glGenVertexArrays(1, &va_); + // glGenVertexArrays(1, &va_); glGenBuffers(1, &buffer_); } changed = true; @@ -45,8 +45,8 @@ void GLVBO::init() { void GLVBO::destroy() { if (buffer_ != 0) glDeleteFramebuffers(1, &buffer_); buffer_ = 0; -// if (va_ != 0) glDeleteVertexArrays(1, &va_); -// va_ = 0; + // if (va_ != 0) glDeleteVertexArrays(1, &va_); + // va_ = 0; } @@ -57,9 +57,9 @@ void GLVBO::calculateBinormals() { int vcnt = vertices_.size() / 3; if (texcoords_.size() != vcnt * 2) return; int tcnt = vcnt / 3; - //qDebug() << "calculateBinormals" << vcnt << tcnt << vertices_.size() << texcoords_.size() << "..."; + // qDebug() << "calculateBinormals" << vcnt << tcnt << vertices_.size() << texcoords_.size() << "..."; for (int t = 0; t < tcnt; ++t) { - int vi = t*9, ti = t*6; + int vi = t * 9, ti = t * 6; Vector3d v0(vertices_[vi + 0], vertices_[vi + 1], vertices_[vi + 2]); Vector3d v1(vertices_[vi + 3], vertices_[vi + 4], vertices_[vi + 5]); Vector3d v2(vertices_[vi + 6], vertices_[vi + 7], vertices_[vi + 8]); @@ -70,49 +70,53 @@ void GLVBO::calculateBinormals() { Vector2d dt1 = t1 - t0, dt2 = t2 - t0; Vector3d tan; Vector3d bitan; - tan = (dv1 * dt2.y - dv2 * dt1.y).normalize(); + tan = (dv1 * dt2.y - dv2 * dt1.y).normalize(); bitan = (dv2 * dt1.x - dv1 * dt2.x).normalize(); for (int i = 0; i < 3; ++i) { tangents_ << tan.x << tan.y << tan.z; bitangents_ << bitan.x << bitan.y << bitan.z; } - //qDebug() << " t" << t << vi << ti << dv1.toQVector3D() << "..."; + // qDebug() << " t" << t << vi << ti << dv1.toQVector3D() << "..."; } - //qDebug() << "calculateBinormals" << vcnt << tcnt << tangents_.size(); + // qDebug() << "calculateBinormals" << vcnt << tcnt << tangents_.size(); } bool GLVBO::rebuffer(bool clear_) { initializeOpenGLFunctions(); QVector data; - //data.clear(); + // data.clear(); calculateBinormals(); data << vertices_; if (!normals_.isEmpty()) { data << normals_; has_normals = true; - } else has_normals = false; + } else + has_normals = false; if (!texcoords_.isEmpty()) { data << texcoords_; has_texcoords = true; - } else has_texcoords = false; + } else + has_texcoords = false; if (!colors_.isEmpty()) { data << colors_; has_colors = true; - } else has_colors = false; + } else + has_colors = false; if (!tangents_.isEmpty()) { data << tangents_ << bitangents_; has_binormals = true; - } else has_binormals = false; - //glBindVertexArray(va_); - //qDebug() << "load buffer" << data.size() << buffer_; + } else + has_binormals = false; + // glBindVertexArray(va_); + // qDebug() << "load buffer" << data.size() << buffer_; glBindBuffer(GL_ARRAY_BUFFER, buffer_); glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.constData(), usage); glBindBuffer(GL_ARRAY_BUFFER, 0); - //glBindVertexArray(0); + // glBindVertexArray(0); vert_count = vertices_.size() / 3; - changed = false; - //qDebug() << "rebuff" << buffer_ << vert_count; + changed = false; + // qDebug() << "rebuff" << buffer_ << vert_count; if (clear_) clear(); return !isEmpty(); } @@ -121,26 +125,26 @@ bool GLVBO::rebuffer(bool clear_) { void GLVBO::draw(GLenum type, QOpenGLShaderProgram * prog, bool simplest) { if (buffer_ == 0 || vert_count == 0) return; if (changed) rebuffer(); - //qDebug() << "draw" << vert_count; - void * offset = (void*)(vert_count * 3 * sizeof(GLfloat)); - //glBindVertexArray(va_); + // qDebug() << "draw" << vert_count; + void * offset = (void *)(vert_count * 3 * sizeof(GLfloat)); + // glBindVertexArray(va_); void * offsets[5] = {0, 0, 0, 0, 0}; if (!simplest) { if (has_normals) { offsets[0] = offset; - offset = (void*)(llong(offset) + vert_count * 3 * sizeof(GLfloat)); + offset = (void *)(llong(offset) + vert_count * 3 * sizeof(GLfloat)); } if (has_texcoords) { offsets[1] = offset; - offset = (void*)(llong(offset) + vert_count * 2 * sizeof(GLfloat)); + offset = (void *)(llong(offset) + vert_count * 2 * sizeof(GLfloat)); } if (has_colors) { offsets[2] = offset; - offset = (void*)(llong(offset) + vert_count * 4 * sizeof(GLfloat)); + offset = (void *)(llong(offset) + vert_count * 4 * sizeof(GLfloat)); } if (has_binormals) { offsets[3] = offset; - offset = (void*)(llong(offset) + vert_count * 3 * sizeof(GLfloat)); + offset = (void *)(llong(offset) + vert_count * 3 * sizeof(GLfloat)); offsets[4] = offset; } } @@ -178,7 +182,7 @@ void GLVBO::draw(GLenum type, QOpenGLShaderProgram * prog, bool simplest) { locs << loc; } else glDisableVertexAttribArray(loc); - loc = prog->attributeLocation("qgl_Tangent"); + loc = prog->attributeLocation("qgl_Tangent"); int loc2 = prog->attributeLocation("qgl_Bitangent"); if (has_binormals) { glEnableVertexAttribArray(loc); @@ -198,22 +202,25 @@ void GLVBO::draw(GLenum type, QOpenGLShaderProgram * prog, bool simplest) { if (has_normals) { glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, offsets[0]); - } else glDisableClientState(GL_NORMAL_ARRAY); + } else + glDisableClientState(GL_NORMAL_ARRAY); if (has_texcoords) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, offsets[1]); - } else glDisableClientState(GL_TEXTURE_COORD_ARRAY); + } else + glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (has_colors) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, 0, offsets[2]); - } else glDisableClientState(GL_COLOR_ARRAY); + } else + glDisableClientState(GL_COLOR_ARRAY); } } - //qDebug() << "draw" << vert_count << buffer_ << offsets[0] << offsets[1] << offsets[3]; + // qDebug() << "draw" << vert_count << buffer_ << offsets[0] << offsets[1] << offsets[3]; glDrawArrays(type, 0, vert_count); - //qDebug() << "draw" << vert_count << buffer_ << "done"; + // qDebug() << "draw" << vert_count << buffer_ << "done"; glBindBuffer(GL_ARRAY_BUFFER, 0); - foreach (int l, locs) + foreach(int l, locs) glDisableVertexAttribArray(l); } @@ -290,7 +297,7 @@ bool GLVBO::loadFromFile(const QString & filename) { Box3D GLVBO::boundingBox() const { if (vertices_.size() < 3) return Box3D(); int vcnt = vertices_.size() / 3; - //qDebug() << "calculateBinormals" << vcnt << tcnt << vertices_.size() << texcoords_.size() << "..."; + // qDebug() << "calculateBinormals" << vcnt << tcnt << vertices_.size() << texcoords_.size() << "..."; GLfloat mix, miy, miz, max, may, maz; Vector3d v0(vertices_[0], vertices_[1], vertices_[2]); mix = max = v0.x; @@ -298,7 +305,7 @@ Box3D GLVBO::boundingBox() const { miz = maz = v0.z; Box3D bound; for (int t = 1; t < vcnt; ++t) { - int vi = t*3; + int vi = t * 3; Vector3d v(vertices_[vi + 0], vertices_[vi + 1], vertices_[vi + 2]); if (mix > v.x) mix = v.x; if (max < v.x) max = v.x; @@ -307,9 +314,9 @@ Box3D GLVBO::boundingBox() const { if (miz > v.z) miz = v.z; if (maz < v.z) maz = v.z; } - bound.x = mix; - bound.y = miy; - bound.z = miz; + bound.x = mix; + bound.y = miy; + bound.z = miz; bound.length = max - mix; bound.width = may - miy; bound.height = maz - miz; diff --git a/libs/qglview/glvbo.h b/libs/qglview/glvbo.h index d70f249..d2020c1 100644 --- a/libs/qglview/glvbo.h +++ b/libs/qglview/glvbo.h @@ -19,19 +19,19 @@ #ifndef GLVBO_H #define GLVBO_H -#include "gltypes.h" #include "chunkstream.h" +#include "gltypes.h" -class GLVBO : protected QOpenGLFunctions -{ +class GLVBO: protected QOpenGLFunctions { friend class GLObjectBase; - friend QDataStream & operator <<(QDataStream & s, const GLVBO & m); - friend QDataStream & operator >>(QDataStream & s, GLVBO & m); + friend QDataStream & operator<<(QDataStream & s, const GLVBO & m); + friend QDataStream & operator>>(QDataStream & s, GLVBO & m); + public: GLVBO(GLenum usage = GL_DYNAMIC_DRAW); ~GLVBO(); - //GLVBO & operator =(const GLVBO & o) {return *this;} + // GLVBO & operator =(const GLVBO & o) {return *this;} void init(); void destroy(); @@ -39,15 +39,27 @@ public: void draw(GLenum type, QOpenGLShaderProgram * prog, bool simplest = false); void clear(); - GLuint buffer() const {return buffer_;} - int verticesCount() const {return vertices_.size() / 3;} - bool isInit() const {return buffer_ != 0;} - bool isEmpty() const {return vertices_.size() < 3;} + GLuint buffer() const { return buffer_; } + int verticesCount() const { return vertices_.size() / 3; } + bool isInit() const { return buffer_ != 0; } + bool isEmpty() const { return vertices_.size() < 3; } - QVector & vertices() {changed = true; return vertices_;} - QVector & normals() {changed = true; return normals_;} - QVector & texcoords() {changed = true; return texcoords_;} - QVector & colors() {changed = true; return colors_;} + QVector & vertices() { + changed = true; + return vertices_; + } + QVector & normals() { + changed = true; + return normals_; + } + QVector & texcoords() { + changed = true; + return texcoords_; + } + QVector & colors() { + changed = true; + return colors_; + } void translatePoints(const QVector3D & dp); void scalePoints(const QVector3D & dp); @@ -66,29 +78,30 @@ private: GLuint buffer_, va_; int vert_count; bool changed, has_normals, has_texcoords, has_colors, has_binormals; - }; -inline QDataStream & operator <<(QDataStream & s, const GLVBO & m) { +inline QDataStream & operator<<(QDataStream & s, const GLVBO & m) { ChunkStream cs; - //qDebug() << "place VBO" << m.vertices_.size() << m.normals_.size() << m.texcoords_.size() << m.colors_.size() << "..."; - cs << cs.chunk(1, m.vertices_) << cs.chunk(2, m.normals_) << cs.chunk(3, m.texcoords_) << cs.chunk(4, m.colors_) << cs.chunk(5, m.usage); - //qDebug() << "place VBO done" << cs.data().size() << "..."; - s << qCompress(cs.data()); return s; + // qDebug() << "place VBO" << m.vertices_.size() << m.normals_.size() << m.texcoords_.size() << m.colors_.size() << "..."; + cs << cs.chunk(1, m.vertices_) << cs.chunk(2, m.normals_) << cs.chunk(3, m.texcoords_) << cs.chunk(4, m.colors_) + << cs.chunk(5, m.usage); + // qDebug() << "place VBO done" << cs.data().size() << "..."; + s << qCompress(cs.data()); + return s; } -inline QDataStream & operator >>(QDataStream & s, GLVBO & m) { +inline QDataStream & operator>>(QDataStream & s, GLVBO & m) { QByteArray ba; s >> ba; ba = qUncompress(ba); ChunkStream cs(ba); while (!cs.atEnd()) { switch (cs.read()) { - case 1: m.vertices_ = cs.getData >(); break; - case 2: m.normals_ = cs.getData >(); break; - case 3: m.texcoords_ = cs.getData >(); break; - case 4: m.colors_ = cs.getData >(); break; - case 5: m.usage = cs.getData(); break; + case 1: m.vertices_ = cs.getData>(); break; + case 2: m.normals_ = cs.getData>(); break; + case 3: m.texcoords_ = cs.getData>(); break; + case 4: m.colors_ = cs.getData>(); break; + case 5: m.usage = cs.getData(); break; } } m.changed = true; diff --git a/libs/qglview/glwidget.cpp b/libs/qglview/glwidget.cpp index 22c905a..b4553f6 100644 --- a/libs/qglview/glwidget.cpp +++ b/libs/qglview/glwidget.cpp @@ -1,14 +1,16 @@ #include "glwidget.h" -#include "renderer_simple.h" + #include "renderer_deferred_shading.h" +#include "renderer_simple.h" + #include -GLWidget::GLWidget(QWidget *parent) : QWidget(parent) { +GLWidget::GLWidget(QWidget * parent): QWidget(parent) { view_ = new QGLView(); view_->setFlags(windowFlags() | Qt::FramelessWindowHint); container = QWidget::createWindowContainer(view_, this); - lay = new QVBoxLayout(this); + lay = new QVBoxLayout(this); lay->addWidget(container); lay->setContentsMargins(0, 0, 0, 0); lay->setSpacing(0); @@ -68,8 +70,7 @@ bool GLWidget::isMouseSelectionEnabled() const { } -bool GLWidget::isCameraOrbit() const -{ +bool GLWidget::isCameraOrbit() const { return view_->isCameraOrbit(); } @@ -105,7 +106,7 @@ qreal GLWidget::selectionHaloFillAlpha() const { void GLWidget::addObject(GLObjectBase * o) { - view_->addObject(o); + view_->addObject(o); } @@ -114,7 +115,7 @@ QByteArray GLWidget::saveCamera() { } -void GLWidget::restoreCamera(const QByteArray &ba) { +void GLWidget::restoreCamera(const QByteArray & ba) { view_->restoreCamera(ba); } @@ -219,18 +220,18 @@ void GLWidget::setSelectionHaloFillAlpha(const qreal & arg) { void GLWidget::viewDoubleClicked() { -// qDebug() << "click widget!!"; + // qDebug() << "click widget!!"; if (view_->windowState() == Qt::WindowFullScreen) { -// view_->hide(); + // view_->hide(); container = QWidget::createWindowContainer(view_, this); lay->addWidget(container); container->show(); -// show(); + // show(); } else { -// hide(); + // hide(); view_->setParent(nullptr); view_->showFullScreen(); lay->removeWidget(container); } -// qDebug() << "click widge done!"; + // qDebug() << "click widge done!"; } diff --git a/libs/qglview/glwidget.h b/libs/qglview/glwidget.h index 1f8597e..4c2bda8 100644 --- a/libs/qglview/glwidget.h +++ b/libs/qglview/glwidget.h @@ -8,28 +8,28 @@ class QGLView; class GLRendererBase; class GLObjectBase; -class GLWidget : public QWidget -{ +class GLWidget: public QWidget { Q_OBJECT - Q_PROPERTY (QColor backColor READ backColor WRITE setBackColor) - Q_PROPERTY (qreal lineWidth READ lineWidth WRITE setLineWidth) - Q_PROPERTY (qreal FOV READ FOV WRITE setFOV) - Q_PROPERTY (qreal depthStart READ depthStart WRITE setDepthStart) - Q_PROPERTY (qreal depthEnd READ depthEnd WRITE setDepthEnd) - Q_PROPERTY (QColor ambientColor READ ambientColor WRITE setAmbientColor) - Q_PROPERTY (bool grabMouse READ isGrabMouseEnabled WRITE setGrabMouseEnabled) - Q_PROPERTY (bool mouseRotate READ isMouseRotateEnabled WRITE setMouseRotateEnabled) - Q_PROPERTY (bool mouseSelection READ isMouseSelectionEnabled WRITE setMouseSelectionEnabled) - Q_PROPERTY (bool cameraOrbit READ isCameraOrbit WRITE setCameraOrbit) - Q_PROPERTY (bool hoverHalo READ isHoverHaloEnabled WRITE setHoverHaloEnabled) - Q_PROPERTY (QColor hoverHaloColor READ hoverHaloColor WRITE setHoverHaloColor) - Q_PROPERTY (qreal hoverHaloFillAlpha READ hoverHaloFillAlpha WRITE setHoverHaloFillAlpha) - Q_PROPERTY (bool selectionHalo READ isSelectionHaloEnabled WRITE setSelectionHaloEnabled) - Q_PROPERTY (QColor selectionHaloColor READ selectionHaloColor WRITE setSelectionHaloColor) - Q_PROPERTY (qreal selectionHaloFillAlpha READ selectionHaloFillAlpha WRITE setSelectionHaloFillAlpha) + Q_PROPERTY(QColor backColor READ backColor WRITE setBackColor) + Q_PROPERTY(qreal lineWidth READ lineWidth WRITE setLineWidth) + Q_PROPERTY(qreal FOV READ FOV WRITE setFOV) + Q_PROPERTY(qreal depthStart READ depthStart WRITE setDepthStart) + Q_PROPERTY(qreal depthEnd READ depthEnd WRITE setDepthEnd) + Q_PROPERTY(QColor ambientColor READ ambientColor WRITE setAmbientColor) + Q_PROPERTY(bool grabMouse READ isGrabMouseEnabled WRITE setGrabMouseEnabled) + Q_PROPERTY(bool mouseRotate READ isMouseRotateEnabled WRITE setMouseRotateEnabled) + Q_PROPERTY(bool mouseSelection READ isMouseSelectionEnabled WRITE setMouseSelectionEnabled) + Q_PROPERTY(bool cameraOrbit READ isCameraOrbit WRITE setCameraOrbit) + Q_PROPERTY(bool hoverHalo READ isHoverHaloEnabled WRITE setHoverHaloEnabled) + Q_PROPERTY(QColor hoverHaloColor READ hoverHaloColor WRITE setHoverHaloColor) + Q_PROPERTY(qreal hoverHaloFillAlpha READ hoverHaloFillAlpha WRITE setHoverHaloFillAlpha) + Q_PROPERTY(bool selectionHalo READ isSelectionHaloEnabled WRITE setSelectionHaloEnabled) + Q_PROPERTY(QColor selectionHaloColor READ selectionHaloColor WRITE setSelectionHaloColor) + Q_PROPERTY(qreal selectionHaloFillAlpha READ selectionHaloFillAlpha WRITE setSelectionHaloFillAlpha) + public: - explicit GLWidget(QWidget *parent = nullptr); - QGLView * view() {return view_;} + explicit GLWidget(QWidget * parent = nullptr); + QGLView * view() { return view_; } QColor backColor() const; qreal lineWidth() const; @@ -50,8 +50,8 @@ public: qreal selectionHaloFillAlpha() const; void addObject(GLObjectBase * o); - QByteArray saveCamera(); - void restoreCamera(const QByteArray & ba); + QByteArray saveCamera(); + void restoreCamera(const QByteArray & ba); public slots: void stop(); diff --git a/libs/qglview/loader_3ds.cpp b/libs/qglview/loader_3ds.cpp index 9173da8..d1dc646 100644 --- a/libs/qglview/loader_3ds.cpp +++ b/libs/qglview/loader_3ds.cpp @@ -20,21 +20,21 @@ void Loader3DS::init3DSMesh(GLObjectBase * o, const QVector & smooth) { - QVector & vertices(o->VBO().vertices()), & normals(o->VBO().normals()), & uvs(o->VBO().texcoords()); - QVector & points(o->points), & puvws(o->puvws), fnormals; + QVector &vertices(o->VBO().vertices()), &normals(o->VBO().normals()), &uvs(o->VBO().texcoords()); + QVector &points(o->points), &puvws(o->puvws), fnormals; QVector & faces(o->faces); Vector3d pos = Vector3d(o->pos()); - bool has_uv = !puvws.isEmpty(); + bool has_uv = !puvws.isEmpty(); Vector3i cf; Vector3d v0, v1, v2, cn0, cn1, cn2; fnormals.resize(faces.size()); for (int i = 0; i < points.size(); ++i) points[i] -= pos; for (int i = 0; i < fnormals.size(); ++i) { - cf = faces[i]; - v0 = points[cf.p0]; - v1 = points[cf.p1]; - v2 = points[cf.p2]; + cf = faces[i]; + v0 = points[cf.p0]; + v1 = points[cf.p1]; + v2 = points[cf.p2]; fnormals[i] = ((v1 - v0) * (v2 - v0)).normalized(); } int fcnt = faces.size() * 3; @@ -43,56 +43,80 @@ void Loader3DS::init3DSMesh(GLObjectBase * o, const QVector & smooth) { if (has_uv) uvs.resize(fcnt * 2); int ind = 0, induv = 0, ncnt0, ncnt1, ncnt2; uint csg; - //qDebug() << faces.size(); + // qDebug() << faces.size(); if (smooth.isEmpty()) { for (int i = 0; i < faces.size(); ++i) { - cf = faces[i]; - cn0 = fnormals[i]; - v0 = points[cf.p0]; - v1 = points[cf.p1]; - v2 = points[cf.p2]; - vertices[ind] = v0.x; normals[ind] = cn0.x; ++ind; - vertices[ind] = v0.y; normals[ind] = cn0.y; ++ind; - vertices[ind] = v0.z; normals[ind] = cn0.z; ++ind; - vertices[ind] = v1.x; normals[ind] = cn0.x; ++ind; - vertices[ind] = v1.y; normals[ind] = cn0.y; ++ind; - vertices[ind] = v1.z; normals[ind] = cn0.z; ++ind; - vertices[ind] = v2.x; normals[ind] = cn0.x; ++ind; - vertices[ind] = v2.y; normals[ind] = cn0.y; ++ind; - vertices[ind] = v2.z; normals[ind] = cn0.z; ++ind; + cf = faces[i]; + cn0 = fnormals[i]; + v0 = points[cf.p0]; + v1 = points[cf.p1]; + v2 = points[cf.p2]; + vertices[ind] = v0.x; + normals[ind] = cn0.x; + ++ind; + vertices[ind] = v0.y; + normals[ind] = cn0.y; + ++ind; + vertices[ind] = v0.z; + normals[ind] = cn0.z; + ++ind; + vertices[ind] = v1.x; + normals[ind] = cn0.x; + ++ind; + vertices[ind] = v1.y; + normals[ind] = cn0.y; + ++ind; + vertices[ind] = v1.z; + normals[ind] = cn0.z; + ++ind; + vertices[ind] = v2.x; + normals[ind] = cn0.x; + ++ind; + vertices[ind] = v2.y; + normals[ind] = cn0.y; + ++ind; + vertices[ind] = v2.z; + normals[ind] = cn0.z; + ++ind; if (has_uv) { - uvs[induv] = puvws[cf.p0].x; ++induv; - uvs[induv] = puvws[cf.p0].y; ++induv; - uvs[induv] = puvws[cf.p1].x; ++induv; - uvs[induv] = puvws[cf.p1].y; ++induv; - uvs[induv] = puvws[cf.p2].x; ++induv; - uvs[induv] = puvws[cf.p2].y; ++induv; + uvs[induv] = puvws[cf.p0].x; + ++induv; + uvs[induv] = puvws[cf.p0].y; + ++induv; + uvs[induv] = puvws[cf.p1].x; + ++induv; + uvs[induv] = puvws[cf.p1].y; + ++induv; + uvs[induv] = puvws[cf.p2].x; + ++induv; + uvs[induv] = puvws[cf.p2].y; + ++induv; } } } else { for (int i = 0; i < faces.size(); ++i) { - cf = faces[i]; + cf = faces[i]; csg = smooth[i]; - v0 = points[cf.p0]; - v1 = points[cf.p1]; - v2 = points[cf.p2]; + v0 = points[cf.p0]; + v1 = points[cf.p1]; + v2 = points[cf.p2]; cn0 = cn1 = cn2 = fnormals[i]; ncnt0 = ncnt1 = ncnt2 = 1; for (int j = 0; j < faces.size(); ++j) { if (csg != smooth[j] || j == i) continue; - if (faces[j].p0 == cf.p0 || faces[j].p1 == cf.p0 || faces[j].p2 == cf.p0 || - points[faces[j].p0] == v0 || points[faces[j].p1] == v0 || points[faces[j].p2] == v0) { + if (faces[j].p0 == cf.p0 || faces[j].p1 == cf.p0 || faces[j].p2 == cf.p0 || points[faces[j].p0] == v0 || + points[faces[j].p1] == v0 || points[faces[j].p2] == v0) { cn0 += fnormals[j]; ++ncnt0; } - if (faces[j].p0 == cf.p1 || faces[j].p1 == cf.p1 || faces[j].p2 == cf.p1 || - points[faces[j].p0] == v1 || points[faces[j].p1] == v1 || points[faces[j].p2] == v1) { + if (faces[j].p0 == cf.p1 || faces[j].p1 == cf.p1 || faces[j].p2 == cf.p1 || points[faces[j].p0] == v1 || + points[faces[j].p1] == v1 || points[faces[j].p2] == v1) { cn1 += fnormals[j]; ++ncnt1; } - if (faces[j].p0 == cf.p2 || faces[j].p1 == cf.p2 || faces[j].p2 == cf.p2 || - points[faces[j].p0] == v2 || points[faces[j].p1] == v2 || points[faces[j].p2] == v2) { + if (faces[j].p0 == cf.p2 || faces[j].p1 == cf.p2 || faces[j].p2 == cf.p2 || points[faces[j].p0] == v2 || + points[faces[j].p1] == v2 || points[faces[j].p2] == v2) { cn2 += fnormals[j]; ++ncnt2; } @@ -100,22 +124,46 @@ void Loader3DS::init3DSMesh(GLObjectBase * o, const QVector & smooth) { cn0 /= ncnt0; cn1 /= ncnt1; cn2 /= ncnt2; - vertices[ind] = v0.x; normals[ind] = cn0.x; ++ind; - vertices[ind] = v0.y; normals[ind] = cn0.y; ++ind; - vertices[ind] = v0.z; normals[ind] = cn0.z; ++ind; - vertices[ind] = v1.x; normals[ind] = cn1.x; ++ind; - vertices[ind] = v1.y; normals[ind] = cn1.y; ++ind; - vertices[ind] = v1.z; normals[ind] = cn1.z; ++ind; - vertices[ind] = v2.x; normals[ind] = cn2.x; ++ind; - vertices[ind] = v2.y; normals[ind] = cn2.y; ++ind; - vertices[ind] = v2.z; normals[ind] = cn2.z; ++ind; + vertices[ind] = v0.x; + normals[ind] = cn0.x; + ++ind; + vertices[ind] = v0.y; + normals[ind] = cn0.y; + ++ind; + vertices[ind] = v0.z; + normals[ind] = cn0.z; + ++ind; + vertices[ind] = v1.x; + normals[ind] = cn1.x; + ++ind; + vertices[ind] = v1.y; + normals[ind] = cn1.y; + ++ind; + vertices[ind] = v1.z; + normals[ind] = cn1.z; + ++ind; + vertices[ind] = v2.x; + normals[ind] = cn2.x; + ++ind; + vertices[ind] = v2.y; + normals[ind] = cn2.y; + ++ind; + vertices[ind] = v2.z; + normals[ind] = cn2.z; + ++ind; if (has_uv) { - uvs[induv] = puvws[cf.p0].x; ++induv; - uvs[induv] = puvws[cf.p0].y; ++induv; - uvs[induv] = puvws[cf.p1].x; ++induv; - uvs[induv] = puvws[cf.p1].y; ++induv; - uvs[induv] = puvws[cf.p2].x; ++induv; - uvs[induv] = puvws[cf.p2].y; ++induv; + uvs[induv] = puvws[cf.p0].x; + ++induv; + uvs[induv] = puvws[cf.p0].y; + ++induv; + uvs[induv] = puvws[cf.p1].x; + ++induv; + uvs[induv] = puvws[cf.p1].y; + ++induv; + uvs[induv] = puvws[cf.p2].x; + ++induv; + uvs[induv] = puvws[cf.p2].y; + ++induv; } } } @@ -123,9 +171,8 @@ void Loader3DS::init3DSMesh(GLObjectBase * o, const QVector & smooth) { Material Loader3DS::materialByName(const QVector & materials, const QString & name) { - foreach (const Material & m, materials) - if (m.name == name) - return m; + foreach(const Material & m, materials) + if (m.name == name) return m; return Material(); } @@ -141,7 +188,7 @@ GLObjectBase * loadFrom3DSFile(const QString & filepath, float scale) { QVector materials; QVector smooth; QVector face_mats; - GLObjectBase * root = new GLObjectBase(), * co = nullptr; + GLObjectBase *root = new GLObjectBase(), *co = nullptr; Material mat; Loader3DS::Chunk cc; Loader3DS::Face face; @@ -155,188 +202,180 @@ GLObjectBase * loadFrom3DSFile(const QString & filepath, float scale) { uint col; root->setName(QFileInfo(f).baseName()); while (!stream.atEnd()) { - stream.readRawData((char * )&cc, sizeof(cc)); + stream.readRawData((char *)&cc, sizeof(cc)); switch (cc.id) { - case LOADER_3DS_CHUNK_MAIN: /*qDebug() << "main" << cc.size;*/ break; - case LOADER_3DS_CHUNK_OBJECTS: /*qDebug() << " objects" << cc.size;*/ break; - case LOADER_3DS_CHUNK_OBJECT: - if (co != nullptr) { - Loader3DS::init3DSMesh(co, smooth); - root->addChild(co); - } - co = new GLObjectBase(); - co->setName(readCharsUntilNull(stream)); - smooth.clear(); - //qDebug() << " object" << co->name(); - break; - case LOADER_3DS_CHUNK_MESH: /*qDebug() << " mesh" << cc.size;*/ break; - case LOADER_3DS_CHUNK_VERTLIST: - stream.readRawData((char * )&cnt, sizeof(ushort)); - co->points.resize(cnt); - //qDebug() << " vertices" << cnt; - for (int i = 0; i < cnt; ++i) { - stream.readRawData((char * )&co->points[i].x, sizeof(float)); - stream.readRawData((char * )&co->points[i].y, sizeof(float)); - stream.readRawData((char * )&co->points[i].z, sizeof(float)); - co->points[i] *= scale; - } - break; - case LOADER_3DS_CHUNK_FACELIST: - stream.readRawData((char * )&cnt, sizeof(ushort)); - co->faces.resize(cnt); - //qDebug() << " faces" << cnt; - for (int i = 0; i < cnt; ++i) { - stream.readRawData((char * )&face, sizeof(Loader3DS::Face)); - co->faces[i].p0 = face.v0; - co->faces[i].p1 = face.v1; - co->faces[i].p2 = face.v2; - } - break; - case LOADER_3DS_CHUNK_FACEMAT: - name = readCharsUntilNull(stream); - stream.readRawData((char * )&cnt, sizeof(ushort)); - face_mats.resize(cnt); - for (int i = 0; i < cnt; ++i) - stream.readRawData((char * )&(face_mats[i]), sizeof(ushort)); - //qDebug() << " facemat name" << name << cnt; - co->material().name = name; - break; - case LOADER_3DS_CHUNK_MAPLIST: - stream.readRawData((char * )&cnt, sizeof(ushort)); - co->puvws.resize(cnt); - //qDebug() << " texcoords" << cnt; - for (int i = 0; i < cnt; ++i) { - stream.readRawData((char * )&co->puvws[i].x, sizeof(float)); - stream.readRawData((char * )&co->puvws[i].y, sizeof(float)); - } - break; - case LOADER_3DS_CHUNK_SMOOTH: - cnt = co->faces.size(); - smooth.resize(cnt); - //qDebug() << " smooth" << cnt; - for (int i = 0; i < cnt; ++i) - stream.readRawData((char * )&smooth[i], sizeof(uint)); - break; - case LOADER_3DS_CHUNK_TRMATRIX: - //qDebug() << co->name(); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) - stream.readRawData((char * )&(matrix[i][j]), sizeof(float)); - //qDebug() << matrix[i][0] << matrix[i][1] << matrix[i][2]; - } - stream.readRawData((char * )&pos, sizeof(Vector3d)); - pos *= scale; - //qDebug() << "pos =" << pos; - co->setPos(pos.toQVector3D()); - break; - case LOADER_3DS_CHUNK_LIGHT: - //qDebug() << " light" << cc.size; - str = co->name(); - delete co; - co = new Light(); - co->setName(str); - stream.readRawData((char * )&pos, sizeof(Vector3d)); - pos *= scale; - co->setPos(pos.toQVector3D()); - break; - case LOADER_3DS_CHUNK_SPOTLIGHT: - stream.readRawData((char * )&pos, sizeof(Vector3d)); - pos *= scale; - globject_cast(co)->light_type = Light::Cone; - globject_cast(co)->direction = (pos.toQVector3D() - co->pos()).normalized(); - stream.readRawData((char * )&fl1, sizeof(float)); - stream.readRawData((char * )&fl, sizeof(float)); - globject_cast(co)->angle_start = fl1; - globject_cast(co)->angle_end = fl; - //qDebug() << "spotlight" << globject_cast(co)->direction << globject_cast(co)->angle_spread; - break; - case LOADER_3DS_CHUNK_LIGHT_OFF: - stream.skipRawData(cc.size - 6); - co->hide(); - break; - case LOADER_3DS_CHUNK_ATTENUATION_ON: - stream.skipRawData(cc.size - 6); - fl = globject_cast(co)->decay_end; - //fl1 = globject_cast(co)->decay_start; - globject_cast(co)->decay_quadratic = 4.f / fl; - //qDebug() << "decay" << globject_cast(co)->decay_quadratic; - break; - case LOADER_3DS_CHUNK_COLOR_F: - stream.readRawData((char * )&pos, sizeof(Vector3d)); - co->setColor(QColor::fromRgbF(pos.x, pos.y, pos.z)); - //qDebug() << " color_f" << co->color(); - break; - case LOADER_3DS_CHUNK_COLOR_B: - stream.readRawData((char * )&col, 3); - co->setColor(QColor::fromRgb(((uchar * )&col)[0], ((uchar * )&col)[1], ((uchar * )&col)[2])); - //qDebug() << " color_b" << co->color(); - break; - case LOADER_3DS_CHUNK_MULTIPLIER: - stream.readRawData((char * )&fl, sizeof(float)); - globject_cast(co)->intensity = fl; - //qDebug() << " multiplier" << fl; - break; - case LOADER_3DS_CHUNK_RANGE_START: - stream.readRawData((char * )&fl, sizeof(float)); - globject_cast(co)->decay_start = fl; - //qDebug() << " range start" << fl; - break; - case LOADER_3DS_CHUNK_RANGE_END: - stream.readRawData((char * )&fl, sizeof(float)); - globject_cast(co)->decay_end = fl; - //qDebug() << " range end" << fl; - break; - case LOADER_3DS_CHUNK_MATERIAL: - //stream.skipRawData(cc.size - 6); - if (!mat.name.isEmpty()) - materials << mat; - mat = Material(); - break; - case LOADER_3DS_CHUNK_MATERIAL_NAME: - mat.name = readCharsUntilNull(stream); - //qDebug() << "matname" << mat.name; - break; - case LOADER_3DS_CHUNK_AMBIENT_COLOR: - stream.skipRawData(cc.size - 9); - stream.readRawData((char * )&col, 3); - mat.color_self_illumination = QColor::fromRgb(((uchar * )&col)[0], ((uchar * )&col)[1], ((uchar * )&col)[2]); - //qDebug() << "mat diffuse" << mat.color_diffuse; - break; - case LOADER_3DS_CHUNK_DIFFUSE_COLOR: - stream.skipRawData(cc.size - 9); - stream.readRawData((char * )&col, 3); - mat.color_diffuse = QColor::fromRgb(((uchar * )&col)[0], ((uchar * )&col)[1], ((uchar * )&col)[2]); - //qDebug() << "mat diffuse" << mat.color_diffuse; - break; - case LOADER_3DS_CHUNK_SPECULAR_COLOR: - stream.skipRawData(cc.size - 9); - stream.readRawData((char * )&col, 3); - mat.color_specular = QColor::fromRgb(((uchar * )&col)[0], ((uchar * )&col)[1], ((uchar * )&col)[2]); - //qDebug() << "mat diffuse" << mat.color_diffuse; - break; - case LOADER_3DS_CHUNK_TEXTURE_MAP: - cur_map = LOADER_3DS_CHUNK_TEXTURE_MAP; - break; - case LOADER_3DS_CHUNK_BUMP_MAP: - cur_map = LOADER_3DS_CHUNK_BUMP_MAP; - break; - case LOADER_3DS_CHUNK_REFLECTION_MAP: - cur_map = LOADER_3DS_CHUNK_REFLECTION_MAP; - break; - case LOADER_3DS_CHUNK_MAP_FILENAME: - name = readCharsUntilNull(stream); - //qDebug() << " mat map" << QString::number(cur_map, 16) << name; - switch (cur_map) { - case LOADER_3DS_CHUNK_TEXTURE_MAP: mat.map_diffuse.bitmap_path = name; break; - case LOADER_3DS_CHUNK_BUMP_MAP: mat.map_normal.bitmap_path = name; break; - } - break; - default: /*qDebug() << "???" << QString::number(cc.id, 16).rightJustified(4, '0') << cc.size;*/ stream.skipRawData(cc.size - 6); + case LOADER_3DS_CHUNK_MAIN: /*qDebug() << "main" << cc.size;*/ break; + case LOADER_3DS_CHUNK_OBJECTS: /*qDebug() << " objects" << cc.size;*/ break; + case LOADER_3DS_CHUNK_OBJECT: + if (co != nullptr) { + Loader3DS::init3DSMesh(co, smooth); + root->addChild(co); + } + co = new GLObjectBase(); + co->setName(readCharsUntilNull(stream)); + smooth.clear(); + // qDebug() << " object" << co->name(); + break; + case LOADER_3DS_CHUNK_MESH: /*qDebug() << " mesh" << cc.size;*/ break; + case LOADER_3DS_CHUNK_VERTLIST: + stream.readRawData((char *)&cnt, sizeof(ushort)); + co->points.resize(cnt); + // qDebug() << " vertices" << cnt; + for (int i = 0; i < cnt; ++i) { + stream.readRawData((char *)&co->points[i].x, sizeof(float)); + stream.readRawData((char *)&co->points[i].y, sizeof(float)); + stream.readRawData((char *)&co->points[i].z, sizeof(float)); + co->points[i] *= scale; + } + break; + case LOADER_3DS_CHUNK_FACELIST: + stream.readRawData((char *)&cnt, sizeof(ushort)); + co->faces.resize(cnt); + // qDebug() << " faces" << cnt; + for (int i = 0; i < cnt; ++i) { + stream.readRawData((char *)&face, sizeof(Loader3DS::Face)); + co->faces[i].p0 = face.v0; + co->faces[i].p1 = face.v1; + co->faces[i].p2 = face.v2; + } + break; + case LOADER_3DS_CHUNK_FACEMAT: + name = readCharsUntilNull(stream); + stream.readRawData((char *)&cnt, sizeof(ushort)); + face_mats.resize(cnt); + for (int i = 0; i < cnt; ++i) + stream.readRawData((char *)&(face_mats[i]), sizeof(ushort)); + // qDebug() << " facemat name" << name << cnt; + co->material().name = name; + break; + case LOADER_3DS_CHUNK_MAPLIST: + stream.readRawData((char *)&cnt, sizeof(ushort)); + co->puvws.resize(cnt); + // qDebug() << " texcoords" << cnt; + for (int i = 0; i < cnt; ++i) { + stream.readRawData((char *)&co->puvws[i].x, sizeof(float)); + stream.readRawData((char *)&co->puvws[i].y, sizeof(float)); + } + break; + case LOADER_3DS_CHUNK_SMOOTH: + cnt = co->faces.size(); + smooth.resize(cnt); + // qDebug() << " smooth" << cnt; + for (int i = 0; i < cnt; ++i) + stream.readRawData((char *)&smooth[i], sizeof(uint)); + break; + case LOADER_3DS_CHUNK_TRMATRIX: + // qDebug() << co->name(); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) + stream.readRawData((char *)&(matrix[i][j]), sizeof(float)); + // qDebug() << matrix[i][0] << matrix[i][1] << matrix[i][2]; + } + stream.readRawData((char *)&pos, sizeof(Vector3d)); + pos *= scale; + // qDebug() << "pos =" << pos; + co->setPos(pos.toQVector3D()); + break; + case LOADER_3DS_CHUNK_LIGHT: + // qDebug() << " light" << cc.size; + str = co->name(); + delete co; + co = new Light(); + co->setName(str); + stream.readRawData((char *)&pos, sizeof(Vector3d)); + pos *= scale; + co->setPos(pos.toQVector3D()); + break; + case LOADER_3DS_CHUNK_SPOTLIGHT: + stream.readRawData((char *)&pos, sizeof(Vector3d)); + pos *= scale; + globject_cast(co)->light_type = Light::Cone; + globject_cast(co)->direction = (pos.toQVector3D() - co->pos()).normalized(); + stream.readRawData((char *)&fl1, sizeof(float)); + stream.readRawData((char *)&fl, sizeof(float)); + globject_cast(co)->angle_start = fl1; + globject_cast(co)->angle_end = fl; + // qDebug() << "spotlight" << globject_cast(co)->direction << globject_cast(co)->angle_spread; + break; + case LOADER_3DS_CHUNK_LIGHT_OFF: + stream.skipRawData(cc.size - 6); + co->hide(); + break; + case LOADER_3DS_CHUNK_ATTENUATION_ON: + stream.skipRawData(cc.size - 6); + fl = globject_cast(co)->decay_end; + // fl1 = globject_cast(co)->decay_start; + globject_cast(co)->decay_quadratic = 4.f / fl; + // qDebug() << "decay" << globject_cast(co)->decay_quadratic; + break; + case LOADER_3DS_CHUNK_COLOR_F: + stream.readRawData((char *)&pos, sizeof(Vector3d)); + co->setColor(QColor::fromRgbF(pos.x, pos.y, pos.z)); + // qDebug() << " color_f" << co->color(); + break; + case LOADER_3DS_CHUNK_COLOR_B: + stream.readRawData((char *)&col, 3); + co->setColor(QColor::fromRgb(((uchar *)&col)[0], ((uchar *)&col)[1], ((uchar *)&col)[2])); + // qDebug() << " color_b" << co->color(); + break; + case LOADER_3DS_CHUNK_MULTIPLIER: + stream.readRawData((char *)&fl, sizeof(float)); + globject_cast(co)->intensity = fl; + // qDebug() << " multiplier" << fl; + break; + case LOADER_3DS_CHUNK_RANGE_START: + stream.readRawData((char *)&fl, sizeof(float)); + globject_cast(co)->decay_start = fl; + // qDebug() << " range start" << fl; + break; + case LOADER_3DS_CHUNK_RANGE_END: + stream.readRawData((char *)&fl, sizeof(float)); + globject_cast(co)->decay_end = fl; + // qDebug() << " range end" << fl; + break; + case LOADER_3DS_CHUNK_MATERIAL: + // stream.skipRawData(cc.size - 6); + if (!mat.name.isEmpty()) materials << mat; + mat = Material(); + break; + case LOADER_3DS_CHUNK_MATERIAL_NAME: + mat.name = readCharsUntilNull(stream); + // qDebug() << "matname" << mat.name; + break; + case LOADER_3DS_CHUNK_AMBIENT_COLOR: + stream.skipRawData(cc.size - 9); + stream.readRawData((char *)&col, 3); + mat.color_self_illumination = QColor::fromRgb(((uchar *)&col)[0], ((uchar *)&col)[1], ((uchar *)&col)[2]); + // qDebug() << "mat diffuse" << mat.color_diffuse; + break; + case LOADER_3DS_CHUNK_DIFFUSE_COLOR: + stream.skipRawData(cc.size - 9); + stream.readRawData((char *)&col, 3); + mat.color_diffuse = QColor::fromRgb(((uchar *)&col)[0], ((uchar *)&col)[1], ((uchar *)&col)[2]); + // qDebug() << "mat diffuse" << mat.color_diffuse; + break; + case LOADER_3DS_CHUNK_SPECULAR_COLOR: + stream.skipRawData(cc.size - 9); + stream.readRawData((char *)&col, 3); + mat.color_specular = QColor::fromRgb(((uchar *)&col)[0], ((uchar *)&col)[1], ((uchar *)&col)[2]); + // qDebug() << "mat diffuse" << mat.color_diffuse; + break; + case LOADER_3DS_CHUNK_TEXTURE_MAP: cur_map = LOADER_3DS_CHUNK_TEXTURE_MAP; break; + case LOADER_3DS_CHUNK_BUMP_MAP: cur_map = LOADER_3DS_CHUNK_BUMP_MAP; break; + case LOADER_3DS_CHUNK_REFLECTION_MAP: cur_map = LOADER_3DS_CHUNK_REFLECTION_MAP; break; + case LOADER_3DS_CHUNK_MAP_FILENAME: + name = readCharsUntilNull(stream); + // qDebug() << " mat map" << QString::number(cur_map, 16) << name; + switch (cur_map) { + case LOADER_3DS_CHUNK_TEXTURE_MAP: mat.map_diffuse.bitmap_path = name; break; + case LOADER_3DS_CHUNK_BUMP_MAP: mat.map_normal.bitmap_path = name; break; + } + break; + default: /*qDebug() << "???" << QString::number(cc.id, 16).rightJustified(4, '0') << cc.size;*/ stream.skipRawData(cc.size - 6); } } - if (!mat.name.isEmpty()) - materials << mat; - foreach (const Material & m, materials) + if (!mat.name.isEmpty()) materials << mat; + foreach(const Material & m, materials) qDebug() << m.name; if (co != nullptr) { Loader3DS::init3DSMesh(co, smooth); diff --git a/libs/qglview/loader_3ds.h b/libs/qglview/loader_3ds.h index c744ecc..00cca15 100644 --- a/libs/qglview/loader_3ds.h +++ b/libs/qglview/loader_3ds.h @@ -19,58 +19,59 @@ #ifndef LOADER_3DS_H #define LOADER_3DS_H -#include "gltexture_manager.h" #include "globject.h" -#include -#include +#include "gltexture_manager.h" -#define LOADER_3DS_CHUNK_MAIN 0x4D4D // [-] сцена -#define LOADER_3DS_CHUNK_COLOR_F 0x0010 // [+] цвет во float -#define LOADER_3DS_CHUNK_COLOR_B 0x0011 // [+] цвет в byte -#define LOADER_3DS_CHUNK_OBJECTS 0x3D3D // [-] всяческие объекты -#define LOADER_3DS_CHUNK_OBJECT 0x4000 // [+] объект -#define LOADER_3DS_CHUNK_MESH 0x4100 // [-] mesh-объект -#define LOADER_3DS_CHUNK_VERTLIST 0x4110 // [+] список вершин -#define LOADER_3DS_CHUNK_FACELIST 0x4120 // [+] список граней -#define LOADER_3DS_CHUNK_FACEMAT 0x4130 // [+] материалы граней -#define LOADER_3DS_CHUNK_MAPLIST 0x4140 // [+] текстурные координаты -#define LOADER_3DS_CHUNK_SMOOTH 0x4150 // [+] группы сглаживания -#define LOADER_3DS_CHUNK_TRMATRIX 0x4160 // [+] матрица перевода -#define LOADER_3DS_CHUNK_LIGHT 0x4600 // [+] источник света -#define LOADER_3DS_CHUNK_SPOTLIGHT 0x4610 // [+] -#define LOADER_3DS_CHUNK_LIGHT_OFF 0x4620 // [+] -#define LOADER_3DS_CHUNK_ATTENUATION_ON 0x4625 // [+] -#define LOADER_3DS_CHUNK_RANGE_START 0x4659 // [+] -#define LOADER_3DS_CHUNK_RANGE_END 0x465A // [+] -#define LOADER_3DS_CHUNK_MULTIPLIER 0x465B // [+] -#define LOADER_3DS_CHUNK_CAMERA 0x4700 // [+] объект-камера -#define LOADER_3DS_CHUNK_MATERIAL 0xAFFF // [-] материал -#define LOADER_3DS_CHUNK_MATERIAL_NAME 0xA000 -#define LOADER_3DS_CHUNK_AMBIENT_COLOR 0xA010 -#define LOADER_3DS_CHUNK_DIFFUSE_COLOR 0xA020 -#define LOADER_3DS_CHUNK_SPECULAR_COLOR 0xA030 -#define LOADER_3DS_CHUNK_TEXTURE_MAP 0xA200 -#define LOADER_3DS_CHUNK_BUMP_MAP 0xA230 -#define LOADER_3DS_CHUNK_REFLECTION_MAP 0xA220 -#define LOADER_3DS_CHUNK_MAP_FILENAME 0xA300 -#define LOADER_3DS_CHUNK_MAP_PARAMETERS 0xA351 +#include +#include + +#define LOADER_3DS_CHUNK_MAIN 0x4D4D // [-] сцена +#define LOADER_3DS_CHUNK_COLOR_F 0x0010 // [+] цвет во float +#define LOADER_3DS_CHUNK_COLOR_B 0x0011 // [+] цвет в byte +#define LOADER_3DS_CHUNK_OBJECTS 0x3D3D // [-] всяческие объекты +#define LOADER_3DS_CHUNK_OBJECT 0x4000 // [+] объект +#define LOADER_3DS_CHUNK_MESH 0x4100 // [-] mesh-объект +#define LOADER_3DS_CHUNK_VERTLIST 0x4110 // [+] список вершин +#define LOADER_3DS_CHUNK_FACELIST 0x4120 // [+] список граней +#define LOADER_3DS_CHUNK_FACEMAT 0x4130 // [+] материалы граней +#define LOADER_3DS_CHUNK_MAPLIST 0x4140 // [+] текстурные координаты +#define LOADER_3DS_CHUNK_SMOOTH 0x4150 // [+] группы сглаживания +#define LOADER_3DS_CHUNK_TRMATRIX 0x4160 // [+] матрица перевода +#define LOADER_3DS_CHUNK_LIGHT 0x4600 // [+] источник света +#define LOADER_3DS_CHUNK_SPOTLIGHT 0x4610 // [+] +#define LOADER_3DS_CHUNK_LIGHT_OFF 0x4620 // [+] +#define LOADER_3DS_CHUNK_ATTENUATION_ON 0x4625 // [+] +#define LOADER_3DS_CHUNK_RANGE_START 0x4659 // [+] +#define LOADER_3DS_CHUNK_RANGE_END 0x465A // [+] +#define LOADER_3DS_CHUNK_MULTIPLIER 0x465B // [+] +#define LOADER_3DS_CHUNK_CAMERA 0x4700 // [+] объект-камера +#define LOADER_3DS_CHUNK_MATERIAL 0xAFFF // [-] материал +#define LOADER_3DS_CHUNK_MATERIAL_NAME 0xA000 +#define LOADER_3DS_CHUNK_AMBIENT_COLOR 0xA010 +#define LOADER_3DS_CHUNK_DIFFUSE_COLOR 0xA020 +#define LOADER_3DS_CHUNK_SPECULAR_COLOR 0xA030 +#define LOADER_3DS_CHUNK_TEXTURE_MAP 0xA200 +#define LOADER_3DS_CHUNK_BUMP_MAP 0xA230 +#define LOADER_3DS_CHUNK_REFLECTION_MAP 0xA220 +#define LOADER_3DS_CHUNK_MAP_FILENAME 0xA300 +#define LOADER_3DS_CHUNK_MAP_PARAMETERS 0xA351 namespace Loader3DS { #pragma pack(push, 1) - struct Chunk { - ushort id; - uint size; - }; - struct Face { - ushort v0; - ushort v1; - ushort v2; - ushort flags; - }; +struct Chunk { + ushort id; + uint size; +}; +struct Face { + ushort v0; + ushort v1; + ushort v2; + ushort flags; +}; #pragma pack(pop) - void init3DSMesh(GLObjectBase * o, const QVector & smooth); - Material materialByName(const QVector & materials, const QString & name); -} +void init3DSMesh(GLObjectBase * o, const QVector & smooth); +Material materialByName(const QVector & materials, const QString & name); +} // namespace Loader3DS GLObjectBase * loadFrom3DSFile(const QString & filepath, float scale = 1.0); diff --git a/libs/qglview/loader_ase.cpp b/libs/qglview/loader_ase.cpp index 53410f8..c7000a5 100644 --- a/libs/qglview/loader_ase.cpp +++ b/libs/qglview/loader_ase.cpp @@ -20,8 +20,8 @@ void LoaderASE::initASEMesh(GLObjectBase * o) { - QVector & vertices(o->VBO().vertices()), & normals(o->VBO().normals()), & uvs(o->VBO().texcoords()); - QVector & points(o->points), & puvws(o->puvws), & fnormals(o->normals); + QVector &vertices(o->VBO().vertices()), &normals(o->VBO().normals()), &uvs(o->VBO().texcoords()); + QVector &points(o->points), &puvws(o->puvws), &fnormals(o->normals); QVector & faces(o->faces); Vector3d pos = Vector3d(o->pos()); bool has_uv = !puvws.isEmpty(), has_norms = !fnormals.isEmpty(); @@ -33,14 +33,17 @@ void LoaderASE::initASEMesh(GLObjectBase * o) { if (!has_norms) { fnormals.resize(faces.size() * 3); for (int i = 0; i < faces.size(); ++i) { - cf = faces[i]; - v0 = points[cf.p0]; - v1 = points[cf.p1]; - v2 = points[cf.p2]; - cn0 = ((v1 - v0) * (v2 - v0)).normalized(); - fnormals[ni] = cn0; ++ni; - fnormals[ni] = cn0; ++ni; - fnormals[ni] = cn0; ++ni; + cf = faces[i]; + v0 = points[cf.p0]; + v1 = points[cf.p1]; + v2 = points[cf.p2]; + cn0 = ((v1 - v0) * (v2 - v0)).normalized(); + fnormals[ni] = cn0; + ++ni; + fnormals[ni] = cn0; + ++ni; + fnormals[ni] = cn0; + ++ni; } } int fcnt = faces.size() * 3; @@ -51,29 +54,56 @@ void LoaderASE::initASEMesh(GLObjectBase * o) { qDebug() << "init ase" << faces.size() << "faces"; ni = 0; for (int i = 0; i < faces.size(); ++i) { - cf = faces[i]; - v0 = points[cf.p0]; - v1 = points[cf.p1]; - v2 = points[cf.p2]; - cn0 = fnormals[ni]; ++ni; - cn1 = fnormals[ni]; ++ni; - cn2 = fnormals[ni]; ++ni; - vertices[ind] = v0.x; normals[ind] = cn0.x; ++ind; - vertices[ind] = v0.y; normals[ind] = cn0.y; ++ind; - vertices[ind] = v0.z; normals[ind] = cn0.z; ++ind; - vertices[ind] = v1.x; normals[ind] = cn1.x; ++ind; - vertices[ind] = v1.y; normals[ind] = cn1.y; ++ind; - vertices[ind] = v1.z; normals[ind] = cn1.z; ++ind; - vertices[ind] = v2.x; normals[ind] = cn2.x; ++ind; - vertices[ind] = v2.y; normals[ind] = cn2.y; ++ind; - vertices[ind] = v2.z; normals[ind] = cn2.z; ++ind; + cf = faces[i]; + v0 = points[cf.p0]; + v1 = points[cf.p1]; + v2 = points[cf.p2]; + cn0 = fnormals[ni]; + ++ni; + cn1 = fnormals[ni]; + ++ni; + cn2 = fnormals[ni]; + ++ni; + vertices[ind] = v0.x; + normals[ind] = cn0.x; + ++ind; + vertices[ind] = v0.y; + normals[ind] = cn0.y; + ++ind; + vertices[ind] = v0.z; + normals[ind] = cn0.z; + ++ind; + vertices[ind] = v1.x; + normals[ind] = cn1.x; + ++ind; + vertices[ind] = v1.y; + normals[ind] = cn1.y; + ++ind; + vertices[ind] = v1.z; + normals[ind] = cn1.z; + ++ind; + vertices[ind] = v2.x; + normals[ind] = cn2.x; + ++ind; + vertices[ind] = v2.y; + normals[ind] = cn2.y; + ++ind; + vertices[ind] = v2.z; + normals[ind] = cn2.z; + ++ind; if (has_uv) { - uvs[induv] = puvws[cf.p0].x; ++induv; - uvs[induv] = puvws[cf.p0].y; ++induv; - uvs[induv] = puvws[cf.p1].x; ++induv; - uvs[induv] = puvws[cf.p1].y; ++induv; - uvs[induv] = puvws[cf.p2].x; ++induv; - uvs[induv] = puvws[cf.p2].y; ++induv; + uvs[induv] = puvws[cf.p0].x; + ++induv; + uvs[induv] = puvws[cf.p0].y; + ++induv; + uvs[induv] = puvws[cf.p1].x; + ++induv; + uvs[induv] = puvws[cf.p1].y; + ++induv; + uvs[induv] = puvws[cf.p2].x; + ++induv; + uvs[induv] = puvws[cf.p2].y; + ++induv; } } } @@ -86,8 +116,8 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { return nullptr; } f.open(QIODevice::ReadOnly); - //QVector materials; - GLObjectBase * root = new GLObjectBase(), * co = nullptr; + // QVector materials; + GLObjectBase *root = new GLObjectBase(), *co = nullptr; root->setName(QFileInfo(f).baseName()); QTextStream stream(&f); QVector materials; @@ -95,7 +125,7 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { QVector faces, uvws; QVector normals; Vector3d cv; - int mst = -1;//, mat_ind; + int mst = -1; //, mat_ind; qint64 pst; QString line, cname; @@ -103,65 +133,85 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { /// Parse materials while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MATERIAL_LIST {"); + mst = line.indexOf("MATERIAL_LIST {"); } line = stream.readLine().trimmed(); - mst = line.indexOf("MATERIAL_COUNT"); + mst = line.indexOf("MATERIAL_COUNT"); materials.resize(line.right(line.length() - mst - 14).toInt()); - //qDebug() << materials.size() << "materials"; + // qDebug() << materials.size() << "materials"; for (int i = 0; i < materials.size(); ++i) { materials[i].map_diffuse.bitmap_id = 0; - mst = -1; + mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MATERIAL " + QString::number(i) + " {"); + mst = line.indexOf("MATERIAL " + QString::number(i) + " {"); } /// Parse material i while (line != "}" && !stream.atEnd()) { line = stream.readLine().trimmed(); - if (line.left(17) == "*MATERIAL_DIFFUSE") {materials[i].color_diffuse = colorFromString(line.right(line.length() - 18)); continue;} //qDebug() << "diffuse " << i << " = " << colorFromString(line.right(line.length() - 18)); - if (line.left(18) == "*MATERIAL_SPECULAR") {materials[i].color_specular = colorFromString(line.right(line.length() - 19)); continue;} //qDebug() << "specular " << i << " = " << colorFromString(line.right(line.length() - 19)); - if (line.left(23) == "*MATERIAL_SHINESTRENGTH") {materials[i].map_specular.color_amount = line.right(line.length() - 24).toFloat(); continue;} - if (line.left(15) == "*MATERIAL_SHINE") {materials[i].map_specularity.color_amount = 2.f / expf(line.right(line.length() - 16).toFloat()); continue;} - if (line.left(22) == "*MATERIAL_TRANSPARENCY") {materials[i].transparency = line.right(line.length() - 23).toFloat(); continue;} + if (line.left(17) == "*MATERIAL_DIFFUSE") { + materials[i].color_diffuse = colorFromString(line.right(line.length() - 18)); + continue; + } // qDebug() << "diffuse " << i << " = " << colorFromString(line.right(line.length() - 18)); + if (line.left(18) == "*MATERIAL_SPECULAR") { + materials[i].color_specular = colorFromString(line.right(line.length() - 19)); + continue; + } // qDebug() << "specular " << i << " = " << colorFromString(line.right(line.length() - 19)); + if (line.left(23) == "*MATERIAL_SHINESTRENGTH") { + materials[i].map_specular.color_amount = line.right(line.length() - 24).toFloat(); + continue; + } + if (line.left(15) == "*MATERIAL_SHINE") { + materials[i].map_specularity.color_amount = 2.f / expf(line.right(line.length() - 16).toFloat()); + continue; + } + if (line.left(22) == "*MATERIAL_TRANSPARENCY") { + materials[i].transparency = line.right(line.length() - 23).toFloat(); + continue; + } if (line.left(12) == "*MAP_DIFFUSE") { line = stream.readLine().trimmed(); - while (line.left(11) != "*MAP_AMOUNT" && !stream.atEnd()) line = stream.readLine().trimmed(); + while (line.left(11) != "*MAP_AMOUNT" && !stream.atEnd()) + line = stream.readLine().trimmed(); materials[i].map_normal.color_amount = line.right(line.length() - 12).toFloat(); - while (line.left(7) != "*BITMAP" && !stream.atEnd()) line = stream.readLine().trimmed(); + while (line.left(7) != "*BITMAP" && !stream.atEnd()) + line = stream.readLine().trimmed(); materials[i].map_diffuse.bitmap_path = line.mid(9, line.length() - 10); /*if (!materials[i].diffuse.bitmap_path.isEmpty()) { - materials[i].diffuse.bitmap_id = currentQGLView->bindTexture(QImage(materials[i].diffuse.bitmap_path)); - parent->textures << materials[i].diffuse.bitmap_id; + materials[i].diffuse.bitmap_id = currentQGLView->bindTexture(QImage(materials[i].diffuse.bitmap_path)); + parent->textures << materials[i].diffuse.bitmap_id; } qDebug() << materials[i].diffuse.bitmap_path << ", bind to" << materials[i].diffuse.bitmap_id;*/ - while (line != "}" && !stream.atEnd()) line = stream.readLine().trimmed(); + while (line != "}" && !stream.atEnd()) + line = stream.readLine().trimmed(); line = ""; continue; } if (line.left(9) == "*MAP_BUMP") { line = stream.readLine().trimmed(); - while (line.left(11) != "*MAP_AMOUNT" && !stream.atEnd()) line = stream.readLine().trimmed(); + while (line.left(11) != "*MAP_AMOUNT" && !stream.atEnd()) + line = stream.readLine().trimmed(); materials[i].map_normal.color_amount = line.right(line.length() - 12).toFloat(); - //qDebug() << "bump amount" << materials[i].bump.color_amount; - while (line.left(7) != "*BITMAP" && !stream.atEnd()) line = stream.readLine().trimmed(); + // qDebug() << "bump amount" << materials[i].bump.color_amount; + while (line.left(7) != "*BITMAP" && !stream.atEnd()) + line = stream.readLine().trimmed(); materials[i].map_normal.bitmap_path = line.mid(9, line.length() - 10); /*if (!materials[i].bump.bitmap_path.isEmpty()) { - materials[i].bump.bitmap_id = currentQGLView->bindTexture(QImage(materials[i].bump.bitmap_path)); - parent->textures << materials[i].bump.bitmap_id; + materials[i].bump.bitmap_id = currentQGLView->bindTexture(QImage(materials[i].bump.bitmap_path)); + parent->textures << materials[i].bump.bitmap_id; } qDebug() << materials[i].bump.bitmap_path << ", bind to" << materials[i].bump.bitmap_id;*/ - while (line != "}" && !stream.atEnd()) line = stream.readLine().trimmed(); + while (line != "}" && !stream.atEnd()) + line = stream.readLine().trimmed(); line = ""; continue; } } - } - //bs << materials; + // bs << materials; /// Geometry objects int cotype = 0; - mst = -1; + mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); if (line.indexOf("GEOMOBJECT {") >= 0 || line.indexOf("LIGHTOBJECT {") >= 0) { @@ -169,17 +219,17 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { if (line.indexOf("LIGHTOBJECT {") >= 0) cotype = 1; mst = -1; if (co != nullptr) { - co->points = points; - co->faces = faces; + co->points = points; + co->faces = faces; co->normals = normals; - co->uvws = uvws; + co->uvws = uvws; LoaderASE::initASEMesh(co); root->addChild(co); } co = new GLObjectBase(); while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("NODE_NAME"); + mst = line.indexOf("NODE_NAME"); } cname = line.right(line.length() - mst - 10); co->setName(cname.mid(1, cname.length() - 2)); @@ -188,94 +238,101 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { mst = -1; switch (cotype) { case 0: - //qDebug() << "object"; + // qDebug() << "object"; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH {"); + mst = line.indexOf("MESH {"); } mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NUMVERTEX "); + mst = line.indexOf("MESH_NUMVERTEX "); } points.resize(line.right(line.length() - mst - 15).toInt()); - //qDebug() << points.size() << "vertices"; + // qDebug() << points.size() << "vertices"; mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NUMFACES "); + mst = line.indexOf("MESH_NUMFACES "); } faces.resize(line.right(line.length() - mst - 14).toInt()); normals.resize(faces.size() * 3); - //qDebug() << faces.size() << "faces"; - //uvws.resize(faces.size()); + // qDebug() << faces.size() << "faces"; + // uvws.resize(faces.size()); /// Points mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_VERTEX_LIST {"); + mst = line.indexOf("MESH_VERTEX_LIST {"); } for (int i = 0; i < points.size(); ++i) { - line = stream.readLine().trimmed(); - mst = line.indexOf("MESH_VERTEX"); + line = stream.readLine().trimmed(); + mst = line.indexOf("MESH_VERTEX"); points[i] = Vector3d(line.right(line.length() - mst - 17)) * scale; - //qDebug() << points[i]; + // qDebug() << points[i]; } /// Faces mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_FACE_LIST {"); + mst = line.indexOf("MESH_FACE_LIST {"); } for (int i = 0; i < faces.size(); ++i) { - line = stream.readLine().trimmed(); - mst = line.indexOf("MESH_FACE"); - line = line.right(line.length() - mst - 15); - mst = line.indexOf("A:"); line = line.right(line.length() - mst - 2); - mst = line.indexOf("B:"); - faces[i].p0 = line.left(mst).toInt(); line = line.right(line.length() - mst - 2); - mst = line.indexOf("C:"); - faces[i].p1 = line.left(mst).toInt(); line = line.right(line.length() - mst - 2); - mst = line.indexOf("AB"); + line = stream.readLine().trimmed(); + mst = line.indexOf("MESH_FACE"); + line = line.right(line.length() - mst - 15); + mst = line.indexOf("A:"); + line = line.right(line.length() - mst - 2); + mst = line.indexOf("B:"); + faces[i].p0 = line.left(mst).toInt(); + line = line.right(line.length() - mst - 2); + mst = line.indexOf("C:"); + faces[i].p1 = line.left(mst).toInt(); + line = line.right(line.length() - mst - 2); + mst = line.indexOf("AB"); faces[i].p2 = line.left(mst).toInt(); - //qDebug() << faces[i]; + // qDebug() << faces[i]; } /// Texture coordinates mst = -1; pst = stream.pos(); while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NUMTVERTEX "); + mst = line.indexOf("MESH_NUMTVERTEX "); } if (mst >= 0) { puvws.resize(line.right(line.length() - mst - 16).toInt()); - //qDebug() << puvws.size() << "tvertices"; + // qDebug() << puvws.size() << "tvertices"; mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_TVERTLIST {"); + mst = line.indexOf("MESH_TVERTLIST {"); } for (int i = 0; i < puvws.size(); ++i) { - line = stream.readLine().trimmed(); - mst = line.indexOf("MESH_TVERT"); line = line.right(line.length() - mst - 10); - mst = line.indexOf("\t"); line = line.right(line.length() - mst - 1); + line = stream.readLine().trimmed(); + mst = line.indexOf("MESH_TVERT"); + line = line.right(line.length() - mst - 10); + mst = line.indexOf("\t"); + line = line.right(line.length() - mst - 1); puvws[i] = Vector3d(line); } mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NUMTVFACES "); + mst = line.indexOf("MESH_NUMTVFACES "); } uvws.resize(line.right(line.length() - mst - 16).toInt()); mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_TFACELIST {"); + mst = line.indexOf("MESH_TFACELIST {"); } for (int i = 0; i < uvws.size(); ++i) { - line = stream.readLine().trimmed(); - mst = line.indexOf("MESH_TFACE"); line = line.right(line.length() - mst - 10); - mst = line.indexOf("\t"); line = line.right(line.length() - mst - 1); + line = stream.readLine().trimmed(); + mst = line.indexOf("MESH_TFACE"); + line = line.right(line.length() - mst - 10); + mst = line.indexOf("\t"); + line = line.right(line.length() - mst - 1); uvws[i] = Vector3i(line); } } else { @@ -288,26 +345,32 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NORMALS {"); + mst = line.indexOf("MESH_NORMALS {"); } for (int i = 0; i < faces.size(); ++i) { - line = stream.readLine(); - line = stream.readLine().trimmed(); mst = line.indexOf(" "); - line = line.right(line.length() - mst - 1); normals[i * 3] = Vector3d(line); - line = stream.readLine().trimmed(); mst = line.indexOf(" "); - line = line.right(line.length() - mst - 1); normals[i * 3 + 1] = Vector3d(line); - line = stream.readLine().trimmed(); mst = line.indexOf(" "); - line = line.right(line.length() - mst - 1); normals[i * 3 + 2] = Vector3d(line); - //qDebug() << normals[i][0] << normals[i][1] << normals[i][2]; + line = stream.readLine(); + line = stream.readLine().trimmed(); + mst = line.indexOf(" "); + line = line.right(line.length() - mst - 1); + normals[i * 3] = Vector3d(line); + line = stream.readLine().trimmed(); + mst = line.indexOf(" "); + line = line.right(line.length() - mst - 1); + normals[i * 3 + 1] = Vector3d(line); + line = stream.readLine().trimmed(); + mst = line.indexOf(" "); + line = line.right(line.length() - mst - 1); + normals[i * 3 + 2] = Vector3d(line); + // qDebug() << normals[i][0] << normals[i][1] << normals[i][2]; } /// Material index mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MATERIAL_REF "); + mst = line.indexOf("MATERIAL_REF "); } - //mat_ind = line.right(line.length() - mst - 13).toInt(); - //qDebug() << mat_ind.back(); + // mat_ind = line.right(line.length() - mst - 13).toInt(); + // qDebug() << mat_ind.back(); if (points.size() == 0 || faces.size() == 0) { mst = -1; continue; @@ -316,51 +379,51 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { /// Compiling into GLList /*glNewList(model, GL_COMPILE); if (mat_ind < 0 || mat_ind >= materials.size()) { - mat_diffuse[0] = cfr; - mat_diffuse[1] = cfg; - mat_diffuse[2] = cfb; - glColor3f(cfr, cfg, cfb); - glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); - glMaterialfv(GL_FRONT, GL_SPECULAR, mat_none); - glMaterialf(GL_FRONT, GL_SHININESS, 0.); + mat_diffuse[0] = cfr; + mat_diffuse[1] = cfg; + mat_diffuse[2] = cfb; + glColor3f(cfr, cfg, cfb); + glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); + glMaterialfv(GL_FRONT, GL_SPECULAR, mat_none); + glMaterialf(GL_FRONT, GL_SHININESS, 0.); } else { - materials[mat_ind].apply(); - //parent->material_ = materials[mat_ind]; + materials[mat_ind].apply(); + //parent->material_ = materials[mat_ind]; } glBegin(GL_TRIANGLES); if (normals_) { - for (int i = 0; i < faces.size(); ++i) { - glNormal3d(normals[i][0].x, normals[i][0].y, normals[i][0].z); - glTexCoord3d(puvws[uvws[i].p0].x, puvws[uvws[i].p0].y, puvws[uvws[i].p0].z); - cv = points[faces[i].p0] * scale; glVertex3d(cv.x, cv.y, cv.z); - glNormal3d(normals[i][1].x, normals[i][1].y, normals[i][1].z); - glTexCoord3d(puvws[uvws[i].p1].x, puvws[uvws[i].p1].y, puvws[uvws[i].p1].z); - cv = points[faces[i].p1] * scale; glVertex3d(cv.x, cv.y, cv.z); - glNormal3d(normals[i][2].x, normals[i][2].y, normals[i][2].z); - glTexCoord3d(puvws[uvws[i].p2].x, puvws[uvws[i].p2].y, puvws[uvws[i].p2].z); - cv = points[faces[i].p2] * scale; glVertex3d(cv.x, cv.y, cv.z); - } + for (int i = 0; i < faces.size(); ++i) { + glNormal3d(normals[i][0].x, normals[i][0].y, normals[i][0].z); + glTexCoord3d(puvws[uvws[i].p0].x, puvws[uvws[i].p0].y, puvws[uvws[i].p0].z); + cv = points[faces[i].p0] * scale; glVertex3d(cv.x, cv.y, cv.z); + glNormal3d(normals[i][1].x, normals[i][1].y, normals[i][1].z); + glTexCoord3d(puvws[uvws[i].p1].x, puvws[uvws[i].p1].y, puvws[uvws[i].p1].z); + cv = points[faces[i].p1] * scale; glVertex3d(cv.x, cv.y, cv.z); + glNormal3d(normals[i][2].x, normals[i][2].y, normals[i][2].z); + glTexCoord3d(puvws[uvws[i].p2].x, puvws[uvws[i].p2].y, puvws[uvws[i].p2].z); + cv = points[faces[i].p2] * scale; glVertex3d(cv.x, cv.y, cv.z); + } } else { - for (int i = 0; i < faces.size(); ++i) { - glTexCoord3d(puvws[uvws[i].p0].x, puvws[uvws[i].p0].y, puvws[uvws[i].p0].z); - cv = points[faces[i].p0] * scale; glVertex3d(cv.x, cv.y, cv.z); - glTexCoord3d(puvws[uvws[i].p1].x, puvws[uvws[i].p1].y, puvws[uvws[i].p1].z); - cv = points[faces[i].p1] * scale; glVertex3d(cv.x, cv.y, cv.z); - glTexCoord3d(puvws[uvws[i].p2].x, puvws[uvws[i].p2].y, puvws[uvws[i].p2].z); - cv = points[faces[i].p2] * scale; glVertex3d(cv.x, cv.y, cv.z); - } + for (int i = 0; i < faces.size(); ++i) { + glTexCoord3d(puvws[uvws[i].p0].x, puvws[uvws[i].p0].y, puvws[uvws[i].p0].z); + cv = points[faces[i].p0] * scale; glVertex3d(cv.x, cv.y, cv.z); + glTexCoord3d(puvws[uvws[i].p1].x, puvws[uvws[i].p1].y, puvws[uvws[i].p1].z); + cv = points[faces[i].p1] * scale; glVertex3d(cv.x, cv.y, cv.z); + glTexCoord3d(puvws[uvws[i].p2].x, puvws[uvws[i].p2].y, puvws[uvws[i].p2].z); + cv = points[faces[i].p2] * scale; glVertex3d(cv.x, cv.y, cv.z); + } } glEnd();*/ ///// Save binary - //bs << mat_ind << points << faces << puvws << uvws << normals; + // bs << mat_ind << points << faces << puvws << uvws << normals; break; case 1: qDebug() << "light"; mst = -1; while (mst < 0 && !stream.atEnd()) { line = stream.readLine(); - mst = line.indexOf("MESH_NORMALS {"); + mst = line.indexOf("MESH_NORMALS {"); } break; } @@ -369,10 +432,10 @@ GLObjectBase * loadFromASEFile(const QString & filepath, float scale) { } f.close(); if (co != nullptr) { - co->points = points; - co->faces = faces; + co->points = points; + co->faces = faces; co->normals = normals; - co->uvws = uvws; + co->uvws = uvws; LoaderASE::initASEMesh(co); root->addChild(co); } diff --git a/libs/qglview/loader_ase.h b/libs/qglview/loader_ase.h index b5af039..34cf2bd 100644 --- a/libs/qglview/loader_ase.h +++ b/libs/qglview/loader_ase.h @@ -20,11 +20,12 @@ #define LOADER_ASE_H #include "globject.h" -#include + #include +#include namespace LoaderASE { - void initASEMesh(GLObjectBase * o); +void initASEMesh(GLObjectBase * o); } GLObjectBase * loadFromASEFile(const QString & filepath, float scale = 1.0); diff --git a/libs/qglview/loader_dae.cpp b/libs/qglview/loader_dae.cpp index 08f193e..dbfd6b8 100644 --- a/libs/qglview/loader_dae.cpp +++ b/libs/qglview/loader_dae.cpp @@ -17,15 +17,15 @@ */ #include "loader_dae.h" + #include #include Material LoaderDAE::materialByName(const QVector & materials, const QString & name) { - foreach (const Material & m, materials) { - //qDebug() << m.name << " ??? " << name; - if (m.name == name) - return m; + foreach(const Material & m, materials) { + // qDebug() << m.name << " ??? " << name; + if (m.name == name) return m; } return Material(); } @@ -79,21 +79,21 @@ QString readXMLTexture(QDomElement n, QDomElement prof, QDomElement li) { tag = tex; } else { bool found = false; - int cnt = 0; + int cnt = 0; while (!tex.isEmpty() && !found && cnt < 10) { found = false; cnt++; for (int i = 0; i < elist.count(); ++i) { QDomNode dn = elist.at(i); if (dn.attributes().namedItem("sid").nodeValue() == tex) { - //qDebug() << "found!"; + // qDebug() << "found!"; if (dn.firstChild().nodeName() == "sampler2D") { tex = dn.firstChildElement("sampler2D").firstChildElement("source").firstChild().nodeValue(); break; } if (dn.firstChild().nodeName() == "surface") { tag = dn.firstChildElement("surface").firstChildElement("init_from").firstChild().nodeValue(); - //qDebug() << tex << "->" << tag; + // qDebug() << tex << "->" << tag; tex.clear(); found = true; break; @@ -103,7 +103,7 @@ QString readXMLTexture(QDomElement n, QDomElement prof, QDomElement li) { } if (cnt == 10) return QString(); } - //qDebug() << tag; + // qDebug() << tag; if (tag.isEmpty()) return QString(); elist = li.elementsByTagName("image"); for (int i = 0; i < elist.count(); ++i) { @@ -112,7 +112,7 @@ QString readXMLTexture(QDomElement n, QDomElement prof, QDomElement li) { tex = dn.firstChildElement("init_from").firstChild().nodeValue(); tex.replace("\\", "/"); if (tex.startsWith("file:") && tex.mid(5, 3) != "///") tex.insert(6, "/"); - //qDebug() << "found" << tex << QUrl(tex).toLocalFile(); + // qDebug() << "found" << tex << QUrl(tex).toLocalFile(); tex = QUrl(tex).toLocalFile(); if (tex == "/") tex.clear(); return tex; @@ -128,12 +128,12 @@ QVector LoaderDAE::readMaterials(QDomElement le, QDomElement li, bool for (int i = 0; i < elist.count(); ++i) { QDomNode dn = elist.at(i); Material mat; - mat.name = dn.attributes().namedItem("id").nodeValue(); + mat.name = dn.attributes().namedItem("id").nodeValue(); QDomElement prof = dn.firstChildElement("profile_COMMON"); - QDomNode pn = prof.firstChildElement("technique").firstChild(); + QDomNode pn = prof.firstChildElement("technique").firstChild(); QColor col; QString text; - + col = readXMLColor(pn.firstChildElement("emission")); if (col.isValid()) mat.color_self_illumination = col; col = readXMLColor(pn.firstChildElement("diffuse")); @@ -141,17 +141,17 @@ QVector LoaderDAE::readMaterials(QDomElement le, QDomElement li, bool col = readXMLColor(pn.firstChildElement("specular")); if (col.isValid()) mat.color_specular = col; mat.map_specularity.color_amount = 2.f / expf(readXMLFloat(pn.firstChildElement("shininess"))); - mat.transparency = readXMLFloat(pn.firstChildElement("transparency")); + mat.transparency = readXMLFloat(pn.firstChildElement("transparency")); if (!fbx) mat.transparency = 1.f - mat.transparency; text = readXMLTexture(pn.firstChildElement("diffuse"), prof, li); if (!text.isEmpty()) mat.map_diffuse.bitmap_path = text; text = readXMLTexture(pn.firstChildElement("diffuse"), prof, li); if (!text.isEmpty()) mat.map_diffuse.bitmap_path = text; - - pn = prof.firstChildElement("technique").firstChildElement("extra").firstChild(); + + pn = prof.firstChildElement("technique").firstChildElement("extra").firstChild(); text = readXMLTexture(pn.firstChildElement("bump"), prof, li); if (!text.isEmpty()) mat.map_normal.bitmap_path = text; - + ret << mat; qDebug() << "** Material" << mat.name; qDebug() << " emission" << mat.color_self_illumination; @@ -173,13 +173,13 @@ QMatrix4x4 readXMLTransformations(QDomElement n) { } -void readScene(QDomElement n, QMatrix4x4 cm, QVector, QMatrix4x4> > & ret, QString last_name = QString()) { +void readScene(QDomElement n, QMatrix4x4 cm, QVector, QMatrix4x4>> & ret, QString last_name = QString()) { QDomNodeList evsl = n.childNodes(); if (n.hasAttribute("name")) last_name = n.attribute("name"); for (int i = 0; i < evsl.count(); ++i) { QDomElement dt = evsl.at(i).toElement(); QVector4D v; -//qDebug() << dt.nodeName(); + // qDebug() << dt.nodeName(); if (dt.nodeName() == "translate") { v = readXMLVector(dt); cm.translate(v.toVector3D()); @@ -207,11 +207,11 @@ void readScene(QDomElement n, QMatrix4x4 cm, QVector, QMatrix4x4>(QPair(gid, last_name), cm); continue; } - //qDebug() << name << m; + // qDebug() << name << m; } ret << QPair, QMatrix4x4>(QPair("", last_name), cm); } @@ -228,21 +228,26 @@ GLObjectBase * loadFromDAEFile(const QString & filepath, float scale) { qDebug() << "[Loader DAE] Error: can`t parse \"" + filepath + "\""; return nullptr; } - //qDebug() << "parse" << tm.elapsed(); + // qDebug() << "parse" << tm.elapsed(); QDomElement maine = dom.firstChildElement("COLLADA"); - bool fbx = maine.firstChildElement("asset").firstChildElement("contributor").firstChildElement("authoring_tool").firstChild().nodeValue().startsWith("FBX"); - QVector materials = LoaderDAE::readMaterials(maine.firstChildElement("library_effects"), - maine.firstChildElement("library_images"), fbx); - GLObjectBase * root = new GLObjectBase(), * co = nullptr; - QMap > objects; - + bool fbx = maine.firstChildElement("asset") + .firstChildElement("contributor") + .firstChildElement("authoring_tool") + .firstChild() + .nodeValue() + .startsWith("FBX"); + QVector materials = + LoaderDAE::readMaterials(maine.firstChildElement("library_effects"), maine.firstChildElement("library_images"), fbx); + GLObjectBase *root = new GLObjectBase(), *co = nullptr; + QMap> objects; + QMap mat_names; - QDomElement mvse = maine.firstChildElement("library_visual_scenes").firstChildElement("visual_scene"); + QDomElement mvse = maine.firstChildElement("library_visual_scenes").firstChildElement("visual_scene"); QDomNodeList evsl = mvse.elementsByTagName("instance_material"); QDomNodeList matl = maine.firstChildElement("library_materials").elementsByTagName("material"); for (int i = 0; i < evsl.count(); ++i) { QDomElement dn = evsl.at(i).toElement(); - QString tn = dn.attribute("target"); + QString tn = dn.attribute("target"); if (tn.startsWith("#")) tn.remove(0, 1); for (int j = 0; j < matl.count(); ++j) { QDomElement dm = matl.at(j).toElement(); @@ -250,34 +255,33 @@ GLObjectBase * loadFromDAEFile(const QString & filepath, float scale) { QString en = dm.firstChildElement("instance_effect").attribute("url"); if (en.startsWith("#")) en.remove(0, 1); mat_names[dn.attribute("symbol")] = en; - //qDebug() << dn.attribute("symbol") << "->" << en; + // qDebug() << dn.attribute("symbol") << "->" << en; } } } - + QDomNodeList elist = maine.firstChildElement("library_geometries").elementsByTagName("geometry"); for (int i = 0; i < elist.count(); ++i) { - QDomNode dn = elist.at(i); + QDomNode dn = elist.at(i); QString name = dn.attributes().namedItem("name").nodeValue(); - QString gid = dn.attributes().namedItem("id").nodeValue(); + QString gid = dn.attributes().namedItem("id").nodeValue(); if (name.isEmpty()) continue; dn = dn.firstChildElement("mesh"); QMap source_names; - QMap > source_data; + QMap> source_data; QDomNodeList esrc = dn.toElement().elementsByTagName("source"); for (int j = 0; j < esrc.count(); ++j) { - QDomNode ds = esrc.at(j); - QString id = ds.attributes().namedItem("id").nodeValue(); + QDomNode ds = esrc.at(j); + QString id = ds.attributes().namedItem("id").nodeValue(); QDomNodeList evert = dn.toElement().elementsByTagName("vertices"); for (int k = 0; k < evert.count(); ++k) { QDomNode dv = evert.at(k); QString vid = dv.attributes().namedItem("id").nodeValue(); - if (dv.firstChildElement("input").attribute("source") == ("#" + id)) - source_names[vid] = id; -//qDebug() << " found source sin" << vid; + if (dv.firstChildElement("input").attribute("source") == ("#" + id)) source_names[vid] = id; + // qDebug() << " found source sin" << vid; } QVector & sd(source_data[id]); - int stride = ds.firstChildElement("technique_common").firstChildElement("accessor").attribute("stride").toInt(); + int stride = ds.firstChildElement("technique_common").firstChildElement("accessor").attribute("stride").toInt(); QString astr = ds.firstChildElement("float_array").firstChild().nodeValue().trimmed(); astr.replace("\n", " "); astr.remove("\r"); @@ -291,37 +295,46 @@ GLObjectBase * loadFromDAEFile(const QString & filepath, float scale) { if (stride >= 3) v.z = sl[c + 2].toFloat(); sd << v; } -//qDebug() << " found source" << id << "stride =" << stride << ":" << sd; -//qDebug() << " readed" << sd.size(); + // qDebug() << " found source" << id << "stride =" << stride << ":" << sd; + // qDebug() << " readed" << sd.size(); } QDomNodeList etr = dn.toElement().elementsByTagName("triangles"); - //QMatrix4x4 m = matrices.value(gid); -//qDebug() << "found geom" << name; - QVector ol; + // QMatrix4x4 m = matrices.value(gid); + // qDebug() << "found geom" << name; + QVector ol; for (int j = 0; j < etr.count(); ++j) { - QDomElement ds = etr.at(j).toElement(); + QDomElement ds = etr.at(j).toElement(); QString matname = mat_names[ds.attribute("material")]; QVector p; QStringList psl = ds.firstChildElement("p").firstChild().nodeValue().trimmed().split(" "); - foreach (const QString & s, psl) + foreach(const QString & s, psl) p << s.toInt(); QDomNodeList einp = ds.elementsByTagName("input"); - int pbv = einp.count();//, tc = qMin(ds.attribute("count").toInt(), p.size() / pbv); - co = new GLObjectBase(); + int pbv = einp.count(); //, tc = qMin(ds.attribute("count").toInt(), p.size() / pbv); + co = new GLObjectBase(); co->setName(name + "_" + QString::number(j)); - //co->setTransform(m); + // co->setTransform(m); co->material() = LoaderDAE::materialByName(materials, matname); qDebug() << " tri" << co->material().name << matname; - QVector & vertices(co->VBO().vertices()), & normals(co->VBO().normals()), & uvs(co->VBO().texcoords()); + QVector &vertices(co->VBO().vertices()), &normals(co->VBO().normals()), &uvs(co->VBO().texcoords()); for (int k = 0; k < einp.count(); ++k) { QDomElement di = einp.at(k).toElement(); QString src = di.attribute("source"), sem = di.attribute("semantic").toLower(); - int offset = di.attribute("offset").toInt(); + int offset = di.attribute("offset").toInt(); QVector * curv = nullptr; - int pccnt = 0; - if (sem == "vertex") {curv = &vertices; pccnt = 3;} - if (sem == "normal") {curv = &normals; pccnt = 3;} - if (sem == "texcoord") {curv = &uvs; pccnt = 2;} + int pccnt = 0; + if (sem == "vertex") { + curv = &vertices; + pccnt = 3; + } + if (sem == "normal") { + curv = &normals; + pccnt = 3; + } + if (sem == "texcoord") { + curv = &uvs; + pccnt = 2; + } if (curv == nullptr) continue; if (src.startsWith("#")) src.remove(0, 1); QVector & data(source_data[source_names.value(src, src)]); @@ -332,24 +345,26 @@ GLObjectBase * loadFromDAEFile(const QString & filepath, float scale) { if (pccnt == 3) (*curv) << v.z; } } - //qDebug() << " input" << sem << "from" << data.size() << "->" << (*curv) << pbv; + // qDebug() << " input" << sem << "from" << data.size() << "->" << (*curv) << pbv; } - //qDebug() << "geom" << gid << co; + // qDebug() << "geom" << gid << co; ol << co; } objects[gid] = ol; } - + elist = maine.firstChildElement("library_lights").elementsByTagName("light"); for (int i = 0; i < elist.count(); ++i) { QDomElement dn = elist.at(i).toElement(); - QString name = dn.attributes().namedItem("name").nodeValue(); - QString gid = dn.attributes().namedItem("id").nodeValue(); + QString name = dn.attributes().namedItem("name").nodeValue(); + QString gid = dn.attributes().namedItem("id").nodeValue(); if (name.isEmpty() || name == "EnvironmentAmbientLight") continue; QDomElement dl = dn.firstChildElement("technique_common").firstChild().toElement(); - Light * lo = new Light(); - if (dl.nodeName() == "point") lo->light_type = Light::Omni; - else if (dl.nodeName() == "spot") lo->light_type = Light::Cone; + Light * lo = new Light(); + if (dl.nodeName() == "point") + lo->light_type = Light::Omni; + else if (dl.nodeName() == "spot") + lo->light_type = Light::Cone; else { delete lo; continue; @@ -361,62 +376,67 @@ GLObjectBase * loadFromDAEFile(const QString & filepath, float scale) { if (!ml.isEmpty()) lo->intensity = ml.at(0).firstChild().nodeValue().toFloat(); lo->setColor(lo->color() / lo->intensity); QString sv; - sv = dl.firstChildElement("constant_attenuation").firstChild().nodeValue(); if (!sv.isEmpty()) lo->decay_const = sv.toFloat(); - sv = dl.firstChildElement("linear_attenuation").firstChild().nodeValue(); if (!sv.isEmpty()) lo->decay_linear = sv.toFloat(); - sv = dl.firstChildElement("quadratic_attenuation").firstChild().nodeValue(); if (!sv.isEmpty()) lo->decay_quadratic = sv.toFloat(); - ///lo->setTransform(matrices.value(name)); + sv = dl.firstChildElement("constant_attenuation").firstChild().nodeValue(); + if (!sv.isEmpty()) lo->decay_const = sv.toFloat(); + sv = dl.firstChildElement("linear_attenuation").firstChild().nodeValue(); + if (!sv.isEmpty()) lo->decay_linear = sv.toFloat(); + sv = dl.firstChildElement("quadratic_attenuation").firstChild().nodeValue(); + if (!sv.isEmpty()) lo->decay_quadratic = sv.toFloat(); + /// lo->setTransform(matrices.value(name)); if (lo->light_type == Light::Cone) { - ml = dn.elementsByTagName("decay_falloff"); if (!ml.isEmpty()) lo->angle_end = ml.at(0).firstChild().nodeValue().toFloat(); - ml = dn.elementsByTagName("hotspot_beam"); if (!ml.isEmpty()) lo->angle_start = ml.at(0).firstChild().nodeValue().toFloat(); + ml = dn.elementsByTagName("decay_falloff"); + if (!ml.isEmpty()) lo->angle_end = ml.at(0).firstChild().nodeValue().toFloat(); + ml = dn.elementsByTagName("hotspot_beam"); + if (!ml.isEmpty()) lo->angle_start = ml.at(0).firstChild().nodeValue().toFloat(); } - QVector ol; + QVector ol; ol << lo; objects[gid] = ol; - //qDebug() << "light" << name; + // qDebug() << "light" << name; } - //qDebug() << "readed" << objects.size(); - - QVector, QMatrix4x4> > scene; + // qDebug() << "readed" << objects.size(); + + QVector, QMatrix4x4>> scene; readScene(mvse, QMatrix4x4(), scene); for (int i = 0; i < scene.size(); ++i) { QPair, QMatrix4x4> so = scene[i]; if (so.first.first.isEmpty()) continue; - QVector ol = objects.value(so.first.first); - foreach (GLObjectBase * o, ol) { + QVector ol = objects.value(so.first.first); + foreach(GLObjectBase * o, ol) { o = o->clone(); o->setName(so.first.second); o->setTransform(so.second); root->addChild(o); - //qDebug() << " add" << so.first.second << o->name(); + // qDebug() << " add" << so.first.second << o->name(); } - //qDebug() << "add" << so.first << ol.size(); + // qDebug() << "add" << so.first << ol.size(); } - + for (int i = 0; i < root->childCount(); ++i) { GLObjectBase * o = root->child(i); if (o->type() == GLObjectBase::glLight) { - Light * l = (Light*)o; + Light * l = (Light *)o; if (l->light_type == Light::Directional || l->light_type == Light::Cone) { QString tn = l->name() + ".Target"; - //qDebug() << "search target" << tn; + // qDebug() << "search target" << tn; for (int s = 0; s < scene.size(); ++s) { QPair, QMatrix4x4> so = scene[s]; if (so.first.second == tn) { - //qDebug() << "found target" << tn; + // qDebug() << "found target" << tn; QVector3D tp = so.second.column(3).toVector3D(); l->direction = (tp - l->pos()).normalized(); - //qDebug() << "dir" << l->direction; + // qDebug() << "dir" << l->direction; } } } } } - - QList > dol = objects.values(); + + QList> dol = objects.values(); for (int i = 0; i < dol.size(); ++i) for (int j = 0; j < dol[i].size(); ++j) delete dol[i][j]; - + root->setScale(0.001f); qDebug() << "[Loader DAE] Loaded" << root->childCount() << "objects from" << filepath; return root; diff --git a/libs/qglview/loader_dae.h b/libs/qglview/loader_dae.h index 16da9cb..e8ebc5d 100644 --- a/libs/qglview/loader_dae.h +++ b/libs/qglview/loader_dae.h @@ -19,16 +19,17 @@ #ifndef LOADER_DAE_H #define LOADER_DAE_H -#include "gltexture_manager.h" #include "globject.h" -#include +#include "gltexture_manager.h" + #include #include +#include namespace LoaderDAE { - Material materialByName(const QVector & materials, const QString & name); - QVector readMaterials(QDomElement le, QDomElement li, bool fbx); -} +Material materialByName(const QVector & materials, const QString & name); +QVector readMaterials(QDomElement le, QDomElement li, bool fbx); +} // namespace LoaderDAE GLObjectBase * loadFromDAEFile(const QString & filepath, float scale = 1.0); diff --git a/libs/qglview/loader_obj.cpp b/libs/qglview/loader_obj.cpp index 631f567..1d8302d 100644 --- a/libs/qglview/loader_obj.cpp +++ b/libs/qglview/loader_obj.cpp @@ -19,51 +19,78 @@ #include "loader_obj.h" -void LoaderOBJ::initOBJMesh(GLObjectBase * o, const QVector & src_vertices, const QVector & src_normals, const QVector & src_texcoords) { - QVector & vertices(o->VBO().vertices()), & normals(o->VBO().normals()), & uvs(o->VBO().texcoords()); - QVector & faces(o->faces), & uvws(o->uvws), & norms(o->norms); - //Vector3d pos = Vector3d(o->pos()); +void LoaderOBJ::initOBJMesh(GLObjectBase * o, + const QVector & src_vertices, + const QVector & src_normals, + const QVector & src_texcoords) { + QVector &vertices(o->VBO().vertices()), &normals(o->VBO().normals()), &uvs(o->VBO().texcoords()); + QVector &faces(o->faces), &uvws(o->uvws), &norms(o->norms); + // Vector3d pos = Vector3d(o->pos()); bool has_uv = !uvws.isEmpty(); Vector3i cf, ct, cn; Vector3d v[3], t[3], n[3]; - //for (int i = 0; i < points.size(); ++i) + // for (int i = 0; i < points.size(); ++i) // points[i] -= pos; int fcnt = faces.size() * 3; vertices.resize(fcnt * 3); normals.resize(vertices.size()); if (has_uv) uvs.resize(fcnt * 2); int ind = 0, induv = 0; - //qDebug() << "initOBJMesh" << faces.size(); + // qDebug() << "initOBJMesh" << faces.size(); for (int i = 0; i < faces.size(); ++i) { - cf = faces[i]; - ct = uvws[i]; - cn = norms[i]; - v[0] = src_vertices[cf.p0]; - v[1] = src_vertices[cf.p1]; - v[2] = src_vertices[cf.p2]; - n[0] = src_normals[cn.p0]; - n[1] = src_normals[cn.p1]; - n[2] = src_normals[cn.p2]; - vertices[ind] = v[0].x; normals[ind] = n[0].x; ++ind; - vertices[ind] = v[0].y; normals[ind] = n[0].y; ++ind; - vertices[ind] = v[0].z; normals[ind] = n[0].z; ++ind; - vertices[ind] = v[1].x; normals[ind] = n[1].x; ++ind; - vertices[ind] = v[1].y; normals[ind] = n[1].y; ++ind; - vertices[ind] = v[1].z; normals[ind] = n[1].z; ++ind; - vertices[ind] = v[2].x; normals[ind] = n[2].x; ++ind; - vertices[ind] = v[2].y; normals[ind] = n[2].y; ++ind; - vertices[ind] = v[2].z; normals[ind] = n[2].z; ++ind; + cf = faces[i]; + ct = uvws[i]; + cn = norms[i]; + v[0] = src_vertices[cf.p0]; + v[1] = src_vertices[cf.p1]; + v[2] = src_vertices[cf.p2]; + n[0] = src_normals[cn.p0]; + n[1] = src_normals[cn.p1]; + n[2] = src_normals[cn.p2]; + vertices[ind] = v[0].x; + normals[ind] = n[0].x; + ++ind; + vertices[ind] = v[0].y; + normals[ind] = n[0].y; + ++ind; + vertices[ind] = v[0].z; + normals[ind] = n[0].z; + ++ind; + vertices[ind] = v[1].x; + normals[ind] = n[1].x; + ++ind; + vertices[ind] = v[1].y; + normals[ind] = n[1].y; + ++ind; + vertices[ind] = v[1].z; + normals[ind] = n[1].z; + ++ind; + vertices[ind] = v[2].x; + normals[ind] = n[2].x; + ++ind; + vertices[ind] = v[2].y; + normals[ind] = n[2].y; + ++ind; + vertices[ind] = v[2].z; + normals[ind] = n[2].z; + ++ind; if (has_uv) { if ((ct.p0 >= 0) && (ct.p1 >= 0) && (ct.p2 >= 0)) { - t[0] = src_texcoords[ct.p0]; - t[1] = src_texcoords[ct.p1]; - t[2] = src_texcoords[ct.p2]; - uvs[induv] = t[0].x; ++induv; - uvs[induv] = t[0].y; ++induv; - uvs[induv] = t[1].x; ++induv; - uvs[induv] = t[1].y; ++induv; - uvs[induv] = t[2].x; ++induv; - uvs[induv] = t[2].y; ++induv; + t[0] = src_texcoords[ct.p0]; + t[1] = src_texcoords[ct.p1]; + t[2] = src_texcoords[ct.p2]; + uvs[induv] = t[0].x; + ++induv; + uvs[induv] = t[0].y; + ++induv; + uvs[induv] = t[1].x; + ++induv; + uvs[induv] = t[1].y; + ++induv; + uvs[induv] = t[2].x; + ++induv; + uvs[induv] = t[2].y; + ++induv; } } } @@ -73,7 +100,8 @@ void LoaderOBJ::initOBJMesh(GLObjectBase * o, const QVector & src_vert Vector3d readVector3d(QString s) { Vector3d ret; QStringList sl(s.trimmed().split(" ")); - sl.removeAll(""); sl.removeAll(" "); + sl.removeAll(""); + sl.removeAll(" "); if (sl.size() > 0) ret.x = sl[0].toFloat(); if (sl.size() > 1) ret.y = sl[1].toFloat(); if (sl.size() > 2) ret.z = sl[2].toFloat(); @@ -84,7 +112,8 @@ Vector3d readVector3d(QString s) { Vector2d readVector2d(QString s) { Vector2d ret; QStringList sl(s.trimmed().split(" ")); - sl.removeAll(""); sl.removeAll(" "); + sl.removeAll(""); + sl.removeAll(" "); if (sl.size() > 0) ret.x = sl[0].toFloat(); if (sl.size() > 1) ret.y = sl[1].toFloat(); return ret; @@ -99,7 +128,8 @@ QColor readColor(QString s) { void readFaces(QString s, GLObjectBase * co) { QStringList sl(s.trimmed().split(" ")); - sl.removeAll(""); sl.removeAll(" "); + sl.removeAll(""); + sl.removeAll(" "); static Vector3i inds[4]; for (int i = 0; i < sl.size(); ++i) { inds[i].p0 = inds[i].p1 = inds[i].p2 = 0; @@ -111,15 +141,15 @@ void readFaces(QString s, GLObjectBase * co) { } if (sl.size() == 3) { co->faces << Vector3i(inds[0].p0 - 1, inds[1].p0 - 1, inds[2].p0 - 1); - co->uvws << Vector3i(inds[0].p1 - 1, inds[1].p1 - 1, inds[2].p1 - 1); + co->uvws << Vector3i(inds[0].p1 - 1, inds[1].p1 - 1, inds[2].p1 - 1); co->norms << Vector3i(inds[0].p2 - 1, inds[1].p2 - 1, inds[2].p2 - 1); } if (sl.size() == 4) { co->faces << Vector3i(inds[0].p0 - 1, inds[1].p0 - 1, inds[2].p0 - 1); - co->uvws << Vector3i(inds[0].p1 - 1, inds[1].p1 - 1, inds[2].p1 - 1); + co->uvws << Vector3i(inds[0].p1 - 1, inds[1].p1 - 1, inds[2].p1 - 1); co->norms << Vector3i(inds[0].p2 - 1, inds[1].p2 - 1, inds[2].p2 - 1); co->faces << Vector3i(inds[0].p0 - 1, inds[2].p0 - 1, inds[3].p0 - 1); - co->uvws << Vector3i(inds[0].p1 - 1, inds[2].p1 - 1, inds[3].p1 - 1); + co->uvws << Vector3i(inds[0].p1 - 1, inds[2].p1 - 1, inds[3].p1 - 1); co->norms << Vector3i(inds[0].p2 - 1, inds[2].p2 - 1, inds[3].p2 - 1); } } @@ -140,9 +170,8 @@ QVector readMTL(QString obj_path, QString path) { while (!stream.atEnd()) { QString line = stream.readLine().trimmed(); if (line.startsWith("newmtl")) { - if (!mat.name.isEmpty()) - ret << mat; - mat = Material(); + if (!mat.name.isEmpty()) ret << mat; + mat = Material(); mat.name = line.mid(6).trimmed(); continue; } @@ -155,12 +184,12 @@ QVector readMTL(QString obj_path, QString path) { continue; } if (line.startsWith("Ks")) { - Vector3d v = readVector3d(line.mid(2).trimmed()); + Vector3d v = readVector3d(line.mid(2).trimmed()); mat.map_specular.color_amount = v.length(); - float mc = qMax(v.x, qMax(v.y, v.z)); + float mc = qMax(v.x, qMax(v.y, v.z)); if (mc > 0.f) v /= mc; mat.color_specular = QColor::fromRgbF(v.x, v.y, v.z); - //qDebug() << mat.shine_strength << mat.color_specular; + // qDebug() << mat.shine_strength << mat.color_specular; continue; } if (line.startsWith("Ns")) { @@ -178,27 +207,25 @@ QVector readMTL(QString obj_path, QString path) { if (line.startsWith("map_bump")) { line = line.mid(8).trimmed(); if (line.startsWith("-bm")) { - line = line.mid(3).trimmed(); - QString sv = line.left(line.indexOf(" ")); - line = line.mid(sv.size()).trimmed(); + line = line.mid(3).trimmed(); + QString sv = line.left(line.indexOf(" ")); + line = line.mid(sv.size()).trimmed(); mat.map_normal.color_amount = sv.toFloat(); } mat.map_normal.bitmap_path = findFile(line, sp); - //qDebug() << "BUMP" << mat.name << mat.bump_scale << mat.bump.bitmap_path; + // qDebug() << "BUMP" << mat.name << mat.bump_scale << mat.bump.bitmap_path; continue; } } - if (!mat.name.isEmpty()) - ret << mat; + if (!mat.name.isEmpty()) ret << mat; qDebug() << "load from MTL" << f.fileName() << ret.size() << "materials"; return ret; } Material LoaderOBJ::materialByName(const QVector & materials, const QString & name) { - foreach (const Material & m, materials) - if (m.name == name) - return m; + foreach(const Material & m, materials) + if (m.name == name) return m; return Material(); } @@ -213,13 +240,13 @@ GLObjectBase * loadFromOBJFile(const QString & filepath, float scale) { QTextStream stream(&f); QVector vertices, normals, texcoords; QVector materials; - GLObjectBase * root = new GLObjectBase(), * co = nullptr; + GLObjectBase *root = new GLObjectBase(), *co = nullptr; QString name, line, pline; root->setName(QFileInfo(f).baseName()); int cnt = 0; while (!stream.atEnd()) { pline = line; - line = stream.readLine().trimmed(); + line = stream.readLine().trimmed(); if (line.startsWith("mtllib")) { materials = readMTL(filepath, line.mid(6).trimmed()); continue; @@ -245,7 +272,7 @@ GLObjectBase * loadFromOBJFile(const QString & filepath, float scale) { } co = new GLObjectBase(); co->setName(name); - //qDebug() << "new object" << co->name(); + // qDebug() << "new object" << co->name(); continue; } if (line.startsWith("f ")) { diff --git a/libs/qglview/loader_obj.h b/libs/qglview/loader_obj.h index aa248b9..118e39e 100644 --- a/libs/qglview/loader_obj.h +++ b/libs/qglview/loader_obj.h @@ -19,23 +19,27 @@ #ifndef LOADER_OBJ_H #define LOADER_OBJ_H -#include "gltexture_manager.h" #include "globject.h" -#include +#include "gltexture_manager.h" + #include +#include namespace LoaderOBJ { #pragma pack(push, 1) - struct Face { - ushort v0; - ushort v1; - ushort v2; - ushort flags; - }; +struct Face { + ushort v0; + ushort v1; + ushort v2; + ushort flags; +}; #pragma pack(pop) - void initOBJMesh(GLObjectBase * o, const QVector & vertices, const QVector & normals, const QVector & texcoords); - Material materialByName(const QVector & materials, const QString & name); -} +void initOBJMesh(GLObjectBase * o, + const QVector & vertices, + const QVector & normals, + const QVector & texcoords); +Material materialByName(const QVector & materials, const QString & name); +} // namespace LoaderOBJ GLObjectBase * loadFromOBJFile(const QString & filepath, float scale = 1.0); diff --git a/libs/qglview/loader_qgl.cpp b/libs/qglview/loader_qgl.cpp index 95af19b..9a3c601 100644 --- a/libs/qglview/loader_qgl.cpp +++ b/libs/qglview/loader_qgl.cpp @@ -17,6 +17,7 @@ */ #include "loader_qgl.h" + #include "chunkstream.h" @@ -36,8 +37,8 @@ GLObjectBase * loadFromQGLFile(const QString & filepath) { return 0; } GLObjectBase * root = 0; - ushort version = 0xFFFF; - f.peek((char*)&version, 2); + ushort version = 0xFFFF; + f.peek((char *)&version, 2); if (version == 1) { s.skipRawData(2); s >> root; @@ -46,8 +47,7 @@ GLObjectBase * loadFromQGLFile(const QString & filepath) { return 0; } root->buildTransform(); - if (root->name().isEmpty()) - root->setName(QFileInfo(f).baseName()); + if (root->name().isEmpty()) root->setName(QFileInfo(f).baseName()); qDebug() << "[Loader QGL] Loaded" << root->childCount() << "objects from" << filepath; return root; } @@ -55,15 +55,14 @@ GLObjectBase * loadFromQGLFile(const QString & filepath) { bool saveToQGLFile(const QString & filepath, const GLObjectBase * o) { QFile f(filepath); - if (!f.open(QIODevice::ReadWrite)) - return false; + if (!f.open(QIODevice::ReadWrite)) return false; f.resize(0); QDataStream s(&f); s.setVersion(QDataStream::Qt_4_8); - char sign[4] = {'Q', 'G', 'L', 'F'}; + char sign[4] = {'Q', 'G', 'L', 'F'}; ushort version = 1; s.writeRawData(sign, 4); - s.writeRawData((char*)&version, 2); + s.writeRawData((char *)&version, 2); s << o; return true; } diff --git a/libs/qglview/loader_qgl.h b/libs/qglview/loader_qgl.h index 5f252d8..d515b2f 100644 --- a/libs/qglview/loader_qgl.h +++ b/libs/qglview/loader_qgl.h @@ -20,10 +20,10 @@ #define LOADER_QGL_H #include "globject.h" + #include -namespace LoaderQGL { -} +namespace LoaderQGL {} GLObjectBase * loadFromQGLFile(const QString & filepath); bool saveToQGLFile(const QString & filepath, const GLObjectBase * o); diff --git a/libs/qglview/material_editor.cpp b/libs/qglview/material_editor.cpp index 502a84e..3f24db6 100644 --- a/libs/qglview/material_editor.cpp +++ b/libs/qglview/material_editor.cpp @@ -17,6 +17,7 @@ */ #include "material_editor.h" + #include "ui_material_editor.h" @@ -31,11 +32,8 @@ MaterialEditor::MaterialEditor(QWidget * parent): QWidget(parent) { void MaterialEditor::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } @@ -56,32 +54,38 @@ void MaterialEditor::setMaterial(const Material & m) { ui->mapSpecularity->setMap(m.map_specularity); ui->mapBump->setMap(m.map_normal); ui->mapRelief->setMap(m.map_relief); - ui->lineReflFront->setProperty("GLpath", m.map_reflection.path(0)); ui->lineReflFront->setText(QFileInfo(m.map_reflection.path(0)).fileName()); - ui->lineReflBack->setProperty("GLpath", m.map_reflection.path(1)); ui->lineReflBack->setText(QFileInfo(m.map_reflection.path(1)).fileName()); - ui->lineReflLeft->setProperty("GLpath", m.map_reflection.path(2)); ui->lineReflLeft->setText(QFileInfo(m.map_reflection.path(2)).fileName()); - ui->lineReflRight->setProperty("GLpath", m.map_reflection.path(3)); ui->lineReflRight->setText(QFileInfo(m.map_reflection.path(3)).fileName()); - ui->lineReflTop->setProperty("GLpath", m.map_reflection.path(4)); ui->lineReflTop->setText(QFileInfo(m.map_reflection.path(4)).fileName()); - ui->lineReflBottom->setProperty("GLpath", m.map_reflection.path(5)); ui->lineReflBottom->setText(QFileInfo(m.map_reflection.path(5)).fileName()); + ui->lineReflFront->setProperty("GLpath", m.map_reflection.path(0)); + ui->lineReflFront->setText(QFileInfo(m.map_reflection.path(0)).fileName()); + ui->lineReflBack->setProperty("GLpath", m.map_reflection.path(1)); + ui->lineReflBack->setText(QFileInfo(m.map_reflection.path(1)).fileName()); + ui->lineReflLeft->setProperty("GLpath", m.map_reflection.path(2)); + ui->lineReflLeft->setText(QFileInfo(m.map_reflection.path(2)).fileName()); + ui->lineReflRight->setProperty("GLpath", m.map_reflection.path(3)); + ui->lineReflRight->setText(QFileInfo(m.map_reflection.path(3)).fileName()); + ui->lineReflTop->setProperty("GLpath", m.map_reflection.path(4)); + ui->lineReflTop->setText(QFileInfo(m.map_reflection.path(4)).fileName()); + ui->lineReflBottom->setProperty("GLpath", m.map_reflection.path(5)); + ui->lineReflBottom->setText(QFileInfo(m.map_reflection.path(5)).fileName()); active = true; } Material MaterialEditor::material() { Material m; - m.color_diffuse = ui->colorDiffuse->color(); - m.color_specular = ui->colorSpecular->color(); + m.color_diffuse = ui->colorDiffuse->color(); + m.color_specular = ui->colorSpecular->color(); m.color_self_illumination = ui->colorSelfIllum->color(); - m.glass = ui->checkGlass->isChecked(); - m.transparency = ui->spinTransparent->value(); - m.reflectivity = ui->spinReflect->value(); - m.iof = ui->spinIOF->value(); - m.dispersion = ui->spinDispersion->value(); - m.map_diffuse = ui->mapDiffuse->map(); - m.map_specular = ui->mapSpecular->map(); - m.map_self_illumination = ui->mapSelfIllum->map(); - m.map_specularity = ui->mapSpecularity->map(); - m.map_normal = ui->mapBump->map(); - m.map_relief = ui->mapRelief->map(); + m.glass = ui->checkGlass->isChecked(); + m.transparency = ui->spinTransparent->value(); + m.reflectivity = ui->spinReflect->value(); + m.iof = ui->spinIOF->value(); + m.dispersion = ui->spinDispersion->value(); + m.map_diffuse = ui->mapDiffuse->map(); + m.map_specular = ui->mapSpecular->map(); + m.map_self_illumination = ui->mapSelfIllum->map(); + m.map_specularity = ui->mapSpecularity->map(); + m.map_normal = ui->mapBump->map(); + m.map_relief = ui->mapRelief->map(); m.map_reflection.setPath(0, ui->lineReflFront->property("GLpath").toString()); m.map_reflection.setPath(1, ui->lineReflBack->property("GLpath").toString()); m.map_reflection.setPath(2, ui->lineReflLeft->property("GLpath").toString()); @@ -93,7 +97,10 @@ Material MaterialEditor::material() { void MaterialEditor::on_buttonReflFrontSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflFront->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflFront->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflFront->setProperty("GLpath", str); ui->lineReflFront->setText(QFileInfo(str).fileName()); @@ -102,7 +109,10 @@ void MaterialEditor::on_buttonReflFrontSelect_clicked() { void MaterialEditor::on_buttonReflBackSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflBack->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflBack->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflBack->setProperty("GLpath", str); ui->lineReflBack->setText(QFileInfo(str).fileName()); @@ -111,7 +121,10 @@ void MaterialEditor::on_buttonReflBackSelect_clicked() { void MaterialEditor::on_buttonReflLeftSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflLeft->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflLeft->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflLeft->setProperty("GLpath", str); ui->lineReflLeft->setText(QFileInfo(str).fileName()); @@ -120,7 +133,10 @@ void MaterialEditor::on_buttonReflLeftSelect_clicked() { void MaterialEditor::on_buttonReflRightSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflRight->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflRight->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflRight->setProperty("GLpath", str); ui->lineReflRight->setText(QFileInfo(str).fileName()); @@ -129,7 +145,10 @@ void MaterialEditor::on_buttonReflRightSelect_clicked() { void MaterialEditor::on_buttonReflTopSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflTop->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflTop->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflTop->setProperty("GLpath", str); ui->lineReflTop->setText(QFileInfo(str).fileName()); @@ -138,7 +157,10 @@ void MaterialEditor::on_buttonReflTopSelect_clicked() { void MaterialEditor::on_buttonReflBottomSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->lineReflBottom->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->lineReflBottom->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->lineReflBottom->setProperty("GLpath", str); ui->lineReflBottom->setText(QFileInfo(str).fileName()); @@ -194,12 +216,18 @@ void MaterialEditor::on_buttonLoadCubeDir_clicked() { GLCubeTexture cb(0); cb.loadPathesFromDirectory(dir); active = false; - ui->lineReflFront->setProperty("GLpath", cb.path(0)); ui->lineReflFront->setText(QFileInfo(cb.path(0)).fileName()); - ui->lineReflBack->setProperty("GLpath", cb.path(1)); ui->lineReflBack->setText(QFileInfo(cb.path(1)).fileName()); - ui->lineReflLeft->setProperty("GLpath", cb.path(2)); ui->lineReflLeft->setText(QFileInfo(cb.path(2)).fileName()); - ui->lineReflRight->setProperty("GLpath", cb.path(3)); ui->lineReflRight->setText(QFileInfo(cb.path(3)).fileName()); - ui->lineReflTop->setProperty("GLpath", cb.path(4)); ui->lineReflTop->setText(QFileInfo(cb.path(4)).fileName()); - ui->lineReflBottom->setProperty("GLpath", cb.path(5)); ui->lineReflBottom->setText(QFileInfo(cb.path(5)).fileName()); + ui->lineReflFront->setProperty("GLpath", cb.path(0)); + ui->lineReflFront->setText(QFileInfo(cb.path(0)).fileName()); + ui->lineReflBack->setProperty("GLpath", cb.path(1)); + ui->lineReflBack->setText(QFileInfo(cb.path(1)).fileName()); + ui->lineReflLeft->setProperty("GLpath", cb.path(2)); + ui->lineReflLeft->setText(QFileInfo(cb.path(2)).fileName()); + ui->lineReflRight->setProperty("GLpath", cb.path(3)); + ui->lineReflRight->setText(QFileInfo(cb.path(3)).fileName()); + ui->lineReflTop->setProperty("GLpath", cb.path(4)); + ui->lineReflTop->setText(QFileInfo(cb.path(4)).fileName()); + ui->lineReflBottom->setProperty("GLpath", cb.path(5)); + ui->lineReflBottom->setText(QFileInfo(cb.path(5)).fileName()); active = true; materialChanged(); } diff --git a/libs/qglview/material_editor.h b/libs/qglview/material_editor.h index a5ca4ee..51b8503 100644 --- a/libs/qglview/material_editor.h +++ b/libs/qglview/material_editor.h @@ -19,16 +19,17 @@ #ifndef MATERIAL_EDITOR_H #define MATERIAL_EDITOR_H -#include #include "glmaterial.h" +#include + namespace Ui { - class MaterialEditor; +class MaterialEditor; }; -class MaterialEditor: public QWidget -{ +class MaterialEditor: public QWidget { Q_OBJECT + public: explicit MaterialEditor(QWidget * parent = 0); @@ -42,7 +43,9 @@ protected: Ui::MaterialEditor * ui; private slots: - void materialChanged() {if (active) emit changed();} + void materialChanged() { + if (active) emit changed(); + } void on_buttonReflFrontSelect_clicked(); void on_buttonReflFrontClear_clicked(); void on_buttonReflBackSelect_clicked(); @@ -59,7 +62,6 @@ private slots: signals: void changed(); - }; #endif // MATERIAL_EDITOR_H diff --git a/libs/qglview/material_map_editor.cpp b/libs/qglview/material_map_editor.cpp index d3e8672..8fbe681 100644 --- a/libs/qglview/material_map_editor.cpp +++ b/libs/qglview/material_map_editor.cpp @@ -17,6 +17,7 @@ */ #include "material_map_editor.h" + #include "ui_material_map_editor.h" @@ -30,11 +31,8 @@ MaterialMapEditor::MaterialMapEditor(QWidget * parent): QWidget(parent) { void MaterialMapEditor::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } @@ -56,7 +54,8 @@ void MaterialMapEditor::setMap(const Map & m) { ui->sliderOffset->setValue(m.color_offset); ui->spinScaleX->setValue(m.bitmap_scale.x()); ui->spinScaleY->setValue(m.bitmap_scale.y()); - ui->linePath->setProperty("GLpath", m.bitmap_path); ui->linePath->setText(QFileInfo(m.bitmap_path).fileName()); + ui->linePath->setProperty("GLpath", m.bitmap_path); + ui->linePath->setText(QFileInfo(m.bitmap_path).fileName()); updateIcon(); active = true; } @@ -74,7 +73,10 @@ Map MaterialMapEditor::map() { void MaterialMapEditor::on_buttonSelect_clicked() { - QString str = QFileDialog::getOpenFileName(this, "Select image", ui->linePath->property("GLpath").toString(), "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); + QString str = QFileDialog::getOpenFileName(this, + "Select image", + ui->linePath->property("GLpath").toString(), + "Images(*.bmp *.jpg *.jpeg *.png *.tif *.tiff *.tga);;All files(*)"); if (str.isEmpty()) return; ui->linePath->setProperty("GLpath", str); ui->linePath->setText(QFileInfo(str).fileName()); diff --git a/libs/qglview/material_map_editor.h b/libs/qglview/material_map_editor.h index a664561..824b121 100644 --- a/libs/qglview/material_map_editor.h +++ b/libs/qglview/material_map_editor.h @@ -19,16 +19,17 @@ #ifndef MATERIAL_MAP_EDITOR_H #define MATERIAL_MAP_EDITOR_H -#include #include "glmaterial.h" +#include + namespace Ui { - class MaterialMapEditor; +class MaterialMapEditor; }; -class MaterialMapEditor: public QWidget -{ +class MaterialMapEditor: public QWidget { Q_OBJECT + public: explicit MaterialMapEditor(QWidget * parent = 0); @@ -44,13 +45,14 @@ protected: Ui::MaterialMapEditor * ui; private slots: - void mapChanged() {if (active) emit changed();} + void mapChanged() { + if (active) emit changed(); + } void on_buttonSelect_clicked(); void on_buttonClear_clicked(); signals: void changed(); - }; #endif // MATERIAL_MAP_EDITOR_H diff --git a/libs/qglview/openglwindow.cpp b/libs/qglview/openglwindow.cpp index cb3bc2a..6bdc38f 100644 --- a/libs/qglview/openglwindow.cpp +++ b/libs/qglview/openglwindow.cpp @@ -1,4 +1,5 @@ #include "openglwindow.h" + #include #include #include @@ -6,11 +7,7 @@ #include -OpenGLWindow::OpenGLWindow(QWindow *parent) - : QWindow(parent) - , m_context(nullptr) - , m_device(nullptr) -{ +OpenGLWindow::OpenGLWindow(QWindow * parent): QWindow(parent), m_context(nullptr), m_device(nullptr) { setFlags(flags() | Qt::FramelessWindowHint); setSurfaceType(QWindow::OpenGLSurface); QSurfaceFormat format = QSurfaceFormat::defaultFormat(); @@ -25,7 +22,7 @@ OpenGLWindow::OpenGLWindow(QWindow *parent) #endif format.setDepthBufferSize(24); format.setSamples(8); -// format.setStencilBufferSize(8); + // format.setStencilBufferSize(8); setFormat(format); QSurfaceFormat::setDefaultFormat(format); } @@ -36,21 +33,19 @@ OpenGLWindow::~OpenGLWindow() { } -void OpenGLWindow::render(QPainter *painter) { -} +void OpenGLWindow::render(QPainter * painter) {} -void OpenGLWindow::initialize() { -} +void OpenGLWindow::initialize() {} void OpenGLWindow::render() { -// if (!m_device) m_device = new QOpenGLPaintDevice; -// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); -// m_device->setSize(size() * devicePixelRatio()); -// m_device->setDevicePixelRatio(devicePixelRatio()); -// QPainter painter(m_device); -// render(&painter); + // if (!m_device) m_device = new QOpenGLPaintDevice; + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + // m_device->setSize(size() * devicePixelRatio()); + // m_device->setDevicePixelRatio(devicePixelRatio()); + // QPainter painter(m_device); + // render(&painter); } @@ -59,25 +54,21 @@ void OpenGLWindow::renderLater() { } -bool OpenGLWindow::event(QEvent *event) { +bool OpenGLWindow::event(QEvent * event) { switch (event->type()) { - case QEvent::UpdateRequest: - renderNow(); - return true; - default: - return QWindow::event(event); + case QEvent::UpdateRequest: renderNow(); return true; + default: return QWindow::event(event); } } -void OpenGLWindow::exposeEvent(QExposeEvent *event) { +void OpenGLWindow::exposeEvent(QExposeEvent * event) { if (isExposed()) renderNow(); } void OpenGLWindow::renderNow() { - if (!isExposed()) - return; + if (!isExposed()) return; bool needsInitialize = false; if (!m_context) { m_context = new QOpenGLContext(this); @@ -93,4 +84,3 @@ void OpenGLWindow::renderNow() { render(); m_context->swapBuffers(this); } - diff --git a/libs/qglview/openglwindow.h b/libs/qglview/openglwindow.h index 504028c..71f4504 100644 --- a/libs/qglview/openglwindow.h +++ b/libs/qglview/openglwindow.h @@ -1,36 +1,37 @@ -#include #include +#include class QPainter; class QOpenGLContext; class QOpenGLPaintDevice; -class OpenGLWindow : public QWindow, protected QOpenGLFunctions -{ +class OpenGLWindow + : public QWindow + , protected QOpenGLFunctions { Q_OBJECT + public: - explicit OpenGLWindow(QWindow *parent = nullptr); + explicit OpenGLWindow(QWindow * parent = nullptr); ~OpenGLWindow(); - virtual void render(QPainter *painter); + virtual void render(QPainter * painter); virtual void render(); virtual void initialize(); - QOpenGLContext * context() {return m_context;} + QOpenGLContext * context() { return m_context; } public slots: void renderLater(); void renderNow(); protected: - bool event(QEvent *event) override; + bool event(QEvent * event) override; - void exposeEvent(QExposeEvent *event) override; + void exposeEvent(QExposeEvent * event) override; private: - QOpenGLContext *m_context; - QOpenGLPaintDevice *m_device; + QOpenGLContext * m_context; + QOpenGLPaintDevice * m_device; }; - diff --git a/libs/qglview/plugin/qglview_designerplugin.cpp b/libs/qglview/plugin/qglview_designerplugin.cpp index 708776b..04c4ed2 100644 --- a/libs/qglview/plugin/qglview_designerplugin.cpp +++ b/libs/qglview/plugin/qglview_designerplugin.cpp @@ -1,14 +1,13 @@ #include "qglview_designerplugin.h" + #include "qglviewplugin.h" -QGLViewDesignerPlugin::QGLViewDesignerPlugin(QObject * parent): QObject(parent) -{ +QGLViewDesignerPlugin::QGLViewDesignerPlugin(QObject * parent): QObject(parent) { m_widgets.append(new QGLViewPlugin(this)); } -QList QGLViewDesignerPlugin::customWidgets() const { +QList QGLViewDesignerPlugin::customWidgets() const { return m_widgets; } - diff --git a/libs/qglview/plugin/qglview_designerplugin.h b/libs/qglview/plugin/qglview_designerplugin.h index db6fc67..ba7610c 100644 --- a/libs/qglview/plugin/qglview_designerplugin.h +++ b/libs/qglview/plugin/qglview_designerplugin.h @@ -1,22 +1,23 @@ #ifndef QGLVIEW_DESIGNERPLUGIN_H #define QGLVIEW_DESIGNERPLUGIN_H -#include #include +#include -class QGLViewDesignerPlugin: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QGLViewDesignerPlugin + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "qad.qglview") Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) + public: QGLViewDesignerPlugin(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QGLVIEW_DESIGNERPLUGIN_H diff --git a/libs/qglview/plugin/qglviewplugin.cpp b/libs/qglview/plugin/qglviewplugin.cpp index d20f2f2..1ae35fd 100644 --- a/libs/qglview/plugin/qglviewplugin.cpp +++ b/libs/qglview/plugin/qglviewplugin.cpp @@ -1,9 +1,11 @@ -#include "glwidget.h" #include "qglviewplugin.h" -#include + #include "glprimitives.h" +#include "glwidget.h" #include "qglview.h" +#include + QGLViewPlugin::QGLViewPlugin(QObject * parent): QObject(parent) { m_initialized = false; @@ -11,8 +13,7 @@ QGLViewPlugin::QGLViewPlugin(QObject * parent): QObject(parent) { void QGLViewPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -30,21 +31,24 @@ QWidget * QGLViewPlugin::createWidget(QWidget * parent) { if (m_initialized) { auto axis = new GLObjectBase(); GLObjectBase * obj; - float al = 1.; - obj = new GLPrimitiveLine(QVector3D(0, 0, -al), QVector3D(0, 0, al)); - obj->material().color_diffuse = Qt::darkBlue; obj->setAcceptLight(false); + float al = 1.; + obj = new GLPrimitiveLine(QVector3D(0, 0, -al), QVector3D(0, 0, al)); + obj->material().color_diffuse = Qt::darkBlue; + obj->setAcceptLight(false); obj->setSelectable(false); axis->addChild(obj); - obj = new GLPrimitiveLine(QVector3D(-al, 0, 0), QVector3D(al, 0, 0)); - obj->material().color_diffuse = Qt::darkRed; obj->setAcceptLight(false); + obj = new GLPrimitiveLine(QVector3D(-al, 0, 0), QVector3D(al, 0, 0)); + obj->material().color_diffuse = Qt::darkRed; + obj->setAcceptLight(false); obj->setSelectable(false); axis->addChild(obj); - obj = new GLPrimitiveLine(QVector3D(0, -al, 0), QVector3D(0, al, 0)); - obj->material().color_diffuse = Qt::darkGreen; obj->setAcceptLight(false); + obj = new GLPrimitiveLine(QVector3D(0, -al, 0), QVector3D(0, al, 0)); + obj->material().color_diffuse = Qt::darkGreen; + obj->setAcceptLight(false); obj->setSelectable(false); axis->addChild(obj); w->view()->addObject(axis); - auto cam_light = new Light(); + auto cam_light = new Light(); cam_light->intensity = 0.5; cam_light->setName("Camera_Light"); w->view()->camera()->addChild(cam_light); @@ -92,4 +96,3 @@ QString QGLViewPlugin::domXml() const { QString QGLViewPlugin::includeFile() const { return QLatin1String("glwidget.h"); } - diff --git a/libs/qglview/plugin/qglviewplugin.h b/libs/qglview/plugin/qglviewplugin.h index 6516afb..444a03a 100644 --- a/libs/qglview/plugin/qglviewplugin.h +++ b/libs/qglview/plugin/qglviewplugin.h @@ -5,8 +5,9 @@ #include -class QGLViewPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QGLViewPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -27,7 +28,6 @@ public: private: bool m_initialized; - }; -#endif //QGLVIEWPLUGIN_H +#endif // QGLVIEWPLUGIN_H diff --git a/libs/qglview/propertyeditor.cpp b/libs/qglview/propertyeditor.cpp index 6b602a7..3671aa5 100644 --- a/libs/qglview/propertyeditor.cpp +++ b/libs/qglview/propertyeditor.cpp @@ -1,54 +1,127 @@ #include "propertyeditor.h" + +#include "clineedit.h" #include "colorbutton.h" #include "qpointedit.h" #include "qrectedit.h" -#include "clineedit.h" -#include -#include -#include + #include +#include +#include +#include QWidget * Delegate::widgetForProperty(QWidget * parent, const QModelIndex & index) const { - QWidget * w = 0; - int type = 0; + QWidget * w = 0; + int type = 0; QVariant value = index.data(Qt::UserRole); if (index.data(Qt::UserRole + 2).toString() == "__flags") return 0; if (index.data(Qt::UserRole + 1).toString() == "__flag") { qulonglong key = index.data(Qt::UserRole).toULongLong(); - value = index.parent().data(Qt::UserRole); - w = new QCheckBox(parent); type = 14; ((QCheckBox*)w)->setChecked(((value.toULongLong() & key) == key && key != 0) || (value.toULongLong() == 0 && key == 0)); - ((QCheckBox*)w)->setText("0x" + QString::number(key, 16).toUpper()); - connect((QCheckBox*)w, SIGNAL(clicked(bool)), this, SLOT(changedFlag())); - //qDebug() << prop.enumerator().name(); + value = index.parent().data(Qt::UserRole); + w = new QCheckBox(parent); + type = 14; + ((QCheckBox *)w)->setChecked(((value.toULongLong() & key) == key && key != 0) || (value.toULongLong() == 0 && key == 0)); + ((QCheckBox *)w)->setText("0x" + QString::number(key, 16).toUpper()); + connect((QCheckBox *)w, SIGNAL(clicked(bool)), this, SLOT(changedFlag())); + // qDebug() << prop.enumerator().name(); } else { if (value.canConvert()) { PropertyValuePair prop = value.value(); if (prop.first.isEnumType()) { - w = new QComboBox(parent); type = 13; ((QComboBox*)w)->setCurrentIndex(value.toInt()); + w = new QComboBox(parent); + type = 13; + ((QComboBox *)w)->setCurrentIndex(value.toInt()); w->setProperty("__prop", QVariant::fromValue(prop.first)); QMetaEnum menum = prop.first.enumerator(); for (int i = 0; i < menum.keyCount(); ++i) { - ((QComboBox*)w)->addItem(QString(menum.key(i)) + " (0x" + QString::number(menum.value(i), 16).toUpper() + ")", menum.value(i)); - if (menum.value(i) == prop.second.toInt()) - ((QComboBox*)w)->setCurrentIndex(i); + ((QComboBox *)w) + ->addItem(QString(menum.key(i)) + " (0x" + QString::number(menum.value(i), 16).toUpper() + ")", menum.value(i)); + if (menum.value(i) == prop.second.toInt()) ((QComboBox *)w)->setCurrentIndex(i); } - connect((QComboBox*)w, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect((QComboBox *)w, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); } } else { switch (value.type()) { - case QVariant::Int: w = new QSpinBox(parent); type = 2; ((QSpinBox*)w)->setRange(-0x7FFFFFFF, 0x7FFFFFFF); connect((QSpinBox*)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); break; - case QVariant::UInt: w = new QSpinBox(parent); type = 3; ((QSpinBox*)w)->setRange(0, 0xFFFFFFFF); connect((QSpinBox*)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); break; - case QVariant::LongLong: w = new QSpinBox(parent); type = 4; ((QSpinBox*)w)->setRange(-0x7FFFFFFF, 0x7FFFFFFF); connect((QSpinBox*)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); break; - case QVariant::ULongLong: w = new QSpinBox(parent); type = 5; ((QSpinBox*)w)->setRange(0, 0xFFFFFFFF); connect((QSpinBox*)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); break; - case QVariant::Double: w = new QDoubleSpinBox(parent); type = 6; ((QDoubleSpinBox*)w)->setRange(-999999999, 999999999); ((QDoubleSpinBox*)w)->setDecimals(3); connect((QDoubleSpinBox*)w, SIGNAL(valueChanged(double)), this, SLOT(changed())); break; - case QVariant::Bool: w = new QCheckBox(parent); type = 7; ((QCheckBox*)w)->setChecked(value.toBool()); connect((QCheckBox*)w, SIGNAL(toggled(bool)), this, SLOT(changed())); break; - case QVariant::Color: w = new ColorButton(parent); type = 8; ((ColorButton*)w)->setUseAlphaChannel(true); ((ColorButton*)w)->setColor(value.value()); connect((ColorButton*)w, SIGNAL(colorChanged(QColor)), this, SLOT(changed())); break; - case QVariant::Point: w = new QPointEdit(parent); type = 9; ((QPointEdit*)w)->setDecimals(0); ((QPointEdit*)w)->setValue(QPointF(value.toPoint())); connect((QPointEdit*)w, SIGNAL(valueChanged(QPointF)), this, SLOT(changed())); break; - case QVariant::PointF: w = new QPointEdit(parent); type = 10; ((QPointEdit*)w)->setDecimals(3); ((QPointEdit*)w)->setValue(value.toPointF()); connect((QPointEdit*)w, SIGNAL(valueChanged(QPointF)), this, SLOT(changed())); break; - case QVariant::Rect: w = new QRectEdit(parent); type = 11; ((QRectEdit*)w)->setDecimals(0); ((QRectEdit*)w)->setValue(QRectF(value.toRect())); connect((QRectEdit*)w, SIGNAL(valueChanged(QRectF)), this, SLOT(changed())); break; - case QVariant::RectF: w = new QRectEdit(parent); type = 12; ((QRectEdit*)w)->setDecimals(3); ((QRectEdit*)w)->setValue(value.toRectF()); connect((QRectEdit*)w, SIGNAL(valueChanged(QRectF)), this, SLOT(changed())); break; - case QVariant::String: default: w = new CLineEdit(parent); type = 1; ((CLineEdit*)w)->setDefaultText(value.toString()); connect((CLineEdit*)w, SIGNAL(textChanged(QString)), this, SLOT(changed())); break; + case QVariant::Int: + w = new QSpinBox(parent); + type = 2; + ((QSpinBox *)w)->setRange(-0x7FFFFFFF, 0x7FFFFFFF); + connect((QSpinBox *)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); + break; + case QVariant::UInt: + w = new QSpinBox(parent); + type = 3; + ((QSpinBox *)w)->setRange(0, 0xFFFFFFFF); + connect((QSpinBox *)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); + break; + case QVariant::LongLong: + w = new QSpinBox(parent); + type = 4; + ((QSpinBox *)w)->setRange(-0x7FFFFFFF, 0x7FFFFFFF); + connect((QSpinBox *)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); + break; + case QVariant::ULongLong: + w = new QSpinBox(parent); + type = 5; + ((QSpinBox *)w)->setRange(0, 0xFFFFFFFF); + connect((QSpinBox *)w, SIGNAL(valueChanged(int)), this, SLOT(changed())); + break; + case QVariant::Double: + w = new QDoubleSpinBox(parent); + type = 6; + ((QDoubleSpinBox *)w)->setRange(-999999999, 999999999); + ((QDoubleSpinBox *)w)->setDecimals(3); + connect((QDoubleSpinBox *)w, SIGNAL(valueChanged(double)), this, SLOT(changed())); + break; + case QVariant::Bool: + w = new QCheckBox(parent); + type = 7; + ((QCheckBox *)w)->setChecked(value.toBool()); + connect((QCheckBox *)w, SIGNAL(toggled(bool)), this, SLOT(changed())); + break; + case QVariant::Color: + w = new ColorButton(parent); + type = 8; + ((ColorButton *)w)->setUseAlphaChannel(true); + ((ColorButton *)w)->setColor(value.value()); + connect((ColorButton *)w, SIGNAL(colorChanged(QColor)), this, SLOT(changed())); + break; + case QVariant::Point: + w = new QPointEdit(parent); + type = 9; + ((QPointEdit *)w)->setDecimals(0); + ((QPointEdit *)w)->setValue(QPointF(value.toPoint())); + connect((QPointEdit *)w, SIGNAL(valueChanged(QPointF)), this, SLOT(changed())); + break; + case QVariant::PointF: + w = new QPointEdit(parent); + type = 10; + ((QPointEdit *)w)->setDecimals(3); + ((QPointEdit *)w)->setValue(value.toPointF()); + connect((QPointEdit *)w, SIGNAL(valueChanged(QPointF)), this, SLOT(changed())); + break; + case QVariant::Rect: + w = new QRectEdit(parent); + type = 11; + ((QRectEdit *)w)->setDecimals(0); + ((QRectEdit *)w)->setValue(QRectF(value.toRect())); + connect((QRectEdit *)w, SIGNAL(valueChanged(QRectF)), this, SLOT(changed())); + break; + case QVariant::RectF: + w = new QRectEdit(parent); + type = 12; + ((QRectEdit *)w)->setDecimals(3); + ((QRectEdit *)w)->setValue(value.toRectF()); + connect((QRectEdit *)w, SIGNAL(valueChanged(QRectF)), this, SLOT(changed())); + break; + case QVariant::String: + default: + w = new CLineEdit(parent); + type = 1; + ((CLineEdit *)w)->setDefaultText(value.toString()); + connect((CLineEdit *)w, SIGNAL(textChanged(QString)), this, SLOT(changed())); + break; } } } @@ -65,15 +138,18 @@ QWidget * Delegate::widgetForProperty(QWidget * parent, const QModelIndex & inde void Delegate::setWidgetProperty(QWidget * w, const QVariant & value) const { if (w == 0) return; switch (w->property("__type").toInt()) { - case 1: ((CLineEdit*)w)->setText(value.toString()); break; - case 2: case 3: case 4: case 5: ((QSpinBox*)w)->setValue(value.toInt()); break; - case 6: ((QDoubleSpinBox*)w)->setValue(value.toDouble()); break; - case 7: ((QCheckBox*)w)->setChecked(value.toBool()); break; - case 8: ((ColorButton*)w)->setColor(value.value()); break; - case 9: ((QPointEdit*)w)->setValue(value.value()); break; - case 10: ((QPointEdit*)w)->setValue(value.value()); break; - case 11: ((QRectEdit*)w)->setValue(value.value()); break; - case 12: ((QRectEdit*)w)->setValue(value.value()); break; + case 1: ((CLineEdit *)w)->setText(value.toString()); break; + case 2: + case 3: + case 4: + case 5: ((QSpinBox *)w)->setValue(value.toInt()); break; + case 6: ((QDoubleSpinBox *)w)->setValue(value.toDouble()); break; + case 7: ((QCheckBox *)w)->setChecked(value.toBool()); break; + case 8: ((ColorButton *)w)->setColor(value.value()); break; + case 9: ((QPointEdit *)w)->setValue(value.value()); break; + case 10: ((QPointEdit *)w)->setValue(value.value()); break; + case 11: ((QRectEdit *)w)->setValue(value.value()); break; + case 12: ((QRectEdit *)w)->setValue(value.value()); break; } } @@ -81,19 +157,22 @@ void Delegate::setWidgetProperty(QWidget * w, const QVariant & value) const { const QVariant Delegate::widgetProperty(QWidget * w) const { if (w == 0) return QVariant(); switch (w->property("__type").toInt()) { - case 1: return QVariant::fromValue(((CLineEdit*)w)->text()); break; - case 2: return QVariant::fromValue(((QSpinBox*)w)->value()); break; - case 3: return QVariant::fromValue(((QSpinBox*)w)->value()); break; - case 4: return QVariant::fromValue(((QSpinBox*)w)->value()); break; - case 5: return QVariant::fromValue(((QSpinBox*)w)->value()); break; - case 6: return QVariant::fromValue(((QDoubleSpinBox*)w)->value()); break; - case 7: return QVariant::fromValue(((QCheckBox*)w)->isChecked()); break; - case 8: return QVariant::fromValue(((ColorButton*)w)->color()); break; - case 9: return QVariant::fromValue(((QPointEdit*)w)->value().toPoint()); break; - case 10: return QVariant::fromValue(((QPointEdit*)w)->value()); break; - case 11: return QVariant::fromValue(((QRectEdit*)w)->value().toRect()); break; - case 12: return QVariant::fromValue(((QRectEdit*)w)->value()); break; - case 13: return QVariant::fromValue(PropertyValuePair(w->property("__prop").value(), ((QComboBox*)w)->itemData(((QComboBox*)w)->currentIndex()))); break; + case 1: return QVariant::fromValue(((CLineEdit *)w)->text()); break; + case 2: return QVariant::fromValue(((QSpinBox *)w)->value()); break; + case 3: return QVariant::fromValue(((QSpinBox *)w)->value()); break; + case 4: return QVariant::fromValue(((QSpinBox *)w)->value()); break; + case 5: return QVariant::fromValue(((QSpinBox *)w)->value()); break; + case 6: return QVariant::fromValue(((QDoubleSpinBox *)w)->value()); break; + case 7: return QVariant::fromValue(((QCheckBox *)w)->isChecked()); break; + case 8: return QVariant::fromValue(((ColorButton *)w)->color()); break; + case 9: return QVariant::fromValue(((QPointEdit *)w)->value().toPoint()); break; + case 10: return QVariant::fromValue(((QPointEdit *)w)->value()); break; + case 11: return QVariant::fromValue(((QRectEdit *)w)->value().toRect()); break; + case 12: return QVariant::fromValue(((QRectEdit *)w)->value()); break; + case 13: + return QVariant::fromValue( + PropertyValuePair(w->property("__prop").value(), ((QComboBox *)w)->itemData(((QComboBox *)w)->currentIndex()))); + break; default: return QVariant(); break; } return QVariant(); @@ -101,35 +180,44 @@ const QVariant Delegate::widgetProperty(QWidget * w) const { void Delegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const { - if (index.data(Qt::UserRole + 1).toString() != "__flag") - model->setData(index, widgetProperty(editor), Qt::UserRole); + if (index.data(Qt::UserRole + 1).toString() != "__flag") model->setData(index, widgetProperty(editor), Qt::UserRole); } void Delegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QStyledItemDelegate::paint(painter, option, index); - QVariant value = index.data(Qt::UserRole); - QStyle * style = QApplication::style(); - QStyleOption * so = 0; + QVariant value = index.data(Qt::UserRole); + QStyle * style = QApplication::style(); + QStyleOption * so = 0; QStyleOptionComplex * soc = 0; QString text; QRect rect; - QPalette::ColorRole role = (option.state.testFlag(QStyle::State_Selected) && option.state.testFlag(QStyle::State_Active) ? QPalette::HighlightedText : QPalette::WindowText); + QPalette::ColorRole role = + (option.state.testFlag(QStyle::State_Selected) && option.state.testFlag(QStyle::State_Active) ? QPalette::HighlightedText + : QPalette::WindowText); if (index.data(Qt::UserRole + 2).toString() == "__flags") { text = "0x" + QString::number(value.toInt(), 16).toUpper(); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); return; } if (index.data(Qt::UserRole + 1) == "__flag") { - qulonglong key = index.data(Qt::UserRole).toULongLong(); - value = index.parent().data(Qt::UserRole); - so = new QStyleOptionButton(); - so->rect = option.rect; - so->palette = option.palette; + qulonglong key = index.data(Qt::UserRole).toULongLong(); + value = index.parent().data(Qt::UserRole); + so = new QStyleOptionButton(); + so->rect = option.rect; + so->palette = option.palette; so->fontMetrics = option.fontMetrics; - ((QStyleOptionButton*)so)->state = (((value.toULongLong() & key) == key && key != 0) || (value.toULongLong() == 0 && key == 0) ? QStyle::State_On : QStyle::State_Off) | option.state; - ((QStyleOptionButton*)so)->text = "0x" + QString::number(key, 16).toUpper(); + ((QStyleOptionButton *)so)->state = + (((value.toULongLong() & key) == key && key != 0) || (value.toULongLong() == 0 && key == 0) ? QStyle::State_On + : QStyle::State_Off) | + option.state; + ((QStyleOptionButton *)so)->text = "0x" + QString::number(key, 16).toUpper(); if (option.state.testFlag(QStyle::State_Selected)) so->palette.setColor(QPalette::WindowText, so->palette.color(QPalette::HighlightedText)); style->drawControl(QStyle::CE_CheckBox, so, painter); @@ -144,126 +232,180 @@ void Delegate::paint(QPainter * painter, const QStyleOptionViewItem & option, co break; } } - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); } } else { - switch (value.type()) { + switch (value.type()) { case QVariant::Int: text.setNum(value.toInt()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::UInt: text.setNum(value.toUInt()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::LongLong: text.setNum(value.toLongLong()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::ULongLong: text.setNum(value.toULongLong()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::Double: text.setNum(value.toDouble(), 'f', 3); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::Bool: - so = new QStyleOptionButton(); - so->rect = option.rect; - so->state = option.state; - so->palette = option.palette; - so->fontMetrics = option.fontMetrics; - ((QStyleOptionButton*)so)->state = (value.toBool() ? QStyle::State_On : QStyle::State_Off) | option.state; + so = new QStyleOptionButton(); + so->rect = option.rect; + so->state = option.state; + so->palette = option.palette; + so->fontMetrics = option.fontMetrics; + ((QStyleOptionButton *)so)->state = (value.toBool() ? QStyle::State_On : QStyle::State_Off) | option.state; style->drawControl(QStyle::CE_CheckBox, so, painter); break; case QVariant::Color: - rect = option.rect;//style->subElementRect(QStyle::QStyle::SE_FrameContents, so); + rect = option.rect; // style->subElementRect(QStyle::QStyle::SE_FrameContents, so); rect.setRect(rect.x() + 3, rect.y() + 3, rect.width() - 6, rect.height() - 6); painter->fillRect(rect, ab); painter->fillRect(rect, value.value()); break; case QVariant::Point: text = pointString(value.toPoint()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::PointF: text = pointString(value.toPointF()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::Rect: text = rectString(value.toRect()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; case QVariant::RectF: text = rectString(value.toRectF()); - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text, role); + style->drawItemText(painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, text), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + text, + role); break; - case QVariant::String: default: - style->drawItemText(painter, style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, value.toString()), - Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, value.toString(), role); + case QVariant::String: + default: + style->drawItemText( + painter, + style->itemTextRect(option.fontMetrics, option.rect, Qt::AlignLeft | Qt::AlignVCenter, true, value.toString()), + Qt::AlignLeft | Qt::AlignVCenter, + option.palette, + true, + value.toString(), + role); break; } } } - /*so = new QStyleOptionFrame(); - so->rect = option.rect; - so->state = option.state; - so->palette = option.palette; - so->fontMetrics = option.fontMetrics; - ((QStyleOptionFrame*)so)->state = (value.toBool() ? QStyle::State_On : QStyle::State_Off); - style->drawPrimitive(QStyle::PE_PanelLineEdit, so, painter); - style->drawPrimitive(QStyle::PE_FrameLineEdit, so, painter); - break;*/ + /*so = new QStyleOptionFrame(); + so->rect = option.rect; + so->state = option.state; + so->palette = option.palette; + so->fontMetrics = option.fontMetrics; + ((QStyleOptionFrame*)so)->state = (value.toBool() ? QStyle::State_On : QStyle::State_Off); + style->drawPrimitive(QStyle::PE_PanelLineEdit, so, painter); + style->drawPrimitive(QStyle::PE_FrameLineEdit, so, painter); + break;*/ if (so != 0) delete so; if (soc != 0) delete soc; - } void Delegate::changedFlag() { - QAbstractItemModel * model = const_cast(cmi.model()); - model->setData(cmi, qobject_cast(sender())->isChecked(), Qt::UserRole + 3); - QModelIndex p = cmi.parent(), mi; - int row = 0; + QAbstractItemModel * model = const_cast(cmi.model()); + model->setData(cmi, qobject_cast(sender())->isChecked(), Qt::UserRole + 3); + QModelIndex p = cmi.parent(), mi; + int row = 0; qulonglong val = 0; QList chldr; mi = model->index(row, 1, p); while (mi.isValid()) { chldr << mi; model->setData(mi, !mi.data(Qt::UserRole + 4).toBool(), Qt::UserRole + 4); - mi =model->index(++row, 1, p); + mi = model->index(++row, 1, p); } - bool cc = cmi.data(Qt::UserRole + 3).toBool(); + bool cc = cmi.data(Qt::UserRole + 3).toBool(); qulonglong cv = cmi.data(Qt::UserRole).toULongLong(); - //qDebug() << "*****"; + // qDebug() << "*****"; if (cc && cv == 0) { val = 0; - //qDebug() << "null" << cv; + // qDebug() << "null" << cv; } else { if (!cc && cv != 0) { - //qDebug() << "uncheck" << cv; + // qDebug() << "uncheck" << cv; for (int i = 0; i < chldr.size(); ++i) { if (chldr[i] == cmi) continue; - //qDebug() << (chldr[i].data(Qt::UserRole).toULongLong() & cv); - if (chldr[i].data(Qt::UserRole).toULongLong() & cv) - model->setData(chldr[i], false, Qt::UserRole + 3); + // qDebug() << (chldr[i].data(Qt::UserRole).toULongLong() & cv); + if (chldr[i].data(Qt::UserRole).toULongLong() & cv) model->setData(chldr[i], false, Qt::UserRole + 3); } } for (int i = 0; i < chldr.size(); ++i) { - //qDebug() << chldr[i].data(Qt::UserRole + 3).toBool(); - if (chldr[i].data(Qt::UserRole + 3).toBool()) - val |= chldr[i].data(Qt::UserRole).toULongLong(); + // qDebug() << chldr[i].data(Qt::UserRole + 3).toBool(); + if (chldr[i].data(Qt::UserRole + 3).toBool()) val |= chldr[i].data(Qt::UserRole).toULongLong(); } } for (int i = 0; i < chldr.size(); ++i) { @@ -271,25 +413,22 @@ void Delegate::changedFlag() { cv = chldr[i].data(Qt::UserRole).toULongLong(); model->setData(chldr[i], ((val & cv) == cv && cv != 0) || (val == 0 && cv == 0), Qt::UserRole + 3); } - //qDebug() << val; + // qDebug() << val; model->setData(p, val, Qt::UserRole); model->setData(p.sibling(p.row(), 1), val, Qt::UserRole); } - PropertyEditor::PropertyEditor(QWidget * parent): QTreeWidget(parent) { - object = 0; + object = 0; active_ = false; configTree(); - connect(this, SIGNAL(itemClicked(QTreeWidgetItem * , int)), this, SLOT(itemClicked(QTreeWidgetItem * , int))); - connect(this, SIGNAL(itemChanged(QTreeWidgetItem * , int)), this, SLOT(itemChanged(QTreeWidgetItem * , int))); + connect(this, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(itemClicked(QTreeWidgetItem *, int))); + connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(itemChanged(QTreeWidgetItem *, int))); } -PropertyEditor::~PropertyEditor() { - -} +PropertyEditor::~PropertyEditor() {} void PropertyEditor::changeEvent(QEvent * e) { @@ -312,7 +451,6 @@ void PropertyEditor::configTree() { setHeaderLabels(lbls); setAlternatingRowColors(true); setItemDelegateForColumn(1, new Delegate()); - } @@ -341,25 +479,25 @@ void PropertyEditor::rebuild() { clear(); configTree(); if (object == 0) return; - active_ = false; + active_ = false; const QMetaObject * mo = object->metaObject(); - QList mol; + QList mol; while (mo != 0) { mol.push_front(mo); mo = mo->superClass(); } int ps, pe; - QTreeWidgetItem * ti, * tli, * tfi; + QTreeWidgetItem *ti, *tli, *tfi; QVariant value; -// QWidget * pw = 0; + // QWidget * pw = 0; int chue = 0; QColor bc; font_b = font(); font_b.setBold(true); - foreach (const QMetaObject * o, mol) { - ps = o->propertyOffset(); - pe = o->propertyCount();// - ps; - //qDebug() << i->className() << ps << pe; + foreach(const QMetaObject * o, mol) { + ps = o->propertyOffset(); + pe = o->propertyCount(); // - ps; + // qDebug() << i->className() << ps << pe; tli = new QTreeWidgetItem(); tli->setText(0, o->className()); tli->setFont(0, font_b); @@ -371,7 +509,7 @@ void PropertyEditor::rebuild() { for (int i = ps; i < pe; ++i) { props << o->property(i); value = o->property(i).read(object); - ti = new QTreeWidgetItem(); + ti = new QTreeWidgetItem(); ti->setSizeHint(1, QSize(20, 20)); bc.setHsv(chue, 60, 245 + (i % 2) * 20 - 10); setItemBackColor(ti, bc); @@ -394,14 +532,13 @@ void PropertyEditor::rebuild() { ti->setData(1, Qt::UserRole, value); ti->setData(1, Qt::UserRole + 2, "__flags"); ti->setData(0, Qt::UserRole + 1, QVariant::fromValue(props.back())); - } - else if (props.back().isEnumType()) + } else if (props.back().isEnumType()) value.setValue(PropertyValuePair(props.back(), value)); - //ti->setText(1, value.toString()); + // ti->setText(1, value.toString()); ti->setData(1, Qt::UserRole, value); tli->addChild(ti); - //const_cast(indexFromItem(ti, 1)).; - //if (pw != 0) setItemWidget(ti, 1, pw); + // const_cast(indexFromItem(ti, 1)).; + // if (pw != 0) setItemWidget(ti, 1, pw); } chue += 60; chue %= 360; @@ -410,6 +547,4 @@ void PropertyEditor::rebuild() { } -void PropertyEditor::refresh() { - -} +void PropertyEditor::refresh() {} diff --git a/libs/qglview/propertyeditor.h b/libs/qglview/propertyeditor.h index 6bbc480..0a420be 100644 --- a/libs/qglview/propertyeditor.h +++ b/libs/qglview/propertyeditor.h @@ -1,68 +1,87 @@ #ifndef PROPERTYEDITOR_H #define PROPERTYEDITOR_H -#include +#include +#include #include #include -#include -#include #include +#include #include class Delegate: public QStyledItemDelegate { Q_OBJECT + public: - Delegate(QObject * parent = 0): QStyledItemDelegate() {ab = QBrush(QImage(":/icons/alpha.png"));} - - QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const {cmi = const_cast(index); return widgetForProperty(parent, index);} - void setEditorData(QWidget * editor, const QModelIndex & index) const {setWidgetProperty(editor, index.data(Qt::UserRole));} + Delegate(QObject * parent = 0): QStyledItemDelegate() { ab = QBrush(QImage(":/icons/alpha.png")); } + + QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const { + cmi = const_cast(index); + return widgetForProperty(parent, index); + } + void setEditorData(QWidget * editor, const QModelIndex & index) const { setWidgetProperty(editor, index.data(Qt::UserRole)); } void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; - void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const {editor->setGeometry(option.rect);} + void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const { + editor->setGeometry(option.rect); + } void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const; - + private: QWidget * widgetForProperty(QWidget * parent, const QModelIndex & index) const; void setWidgetProperty(QWidget * w, const QVariant & value) const; const QVariant widgetProperty(QWidget * w) const; - QString pointString(const QPoint & p) const {return QString::number(p.x()) + " x " + QString::number(p.y());} - QString pointString(const QPointF & p) const {return QString::number(p.x()) + " x " + QString::number(p.y());} - QString rectString(const QRect & r) const {return QString::number(r.x()) + " x " + QString::number(r.y()) + " : " + - QString::number(r.width()) + " x " + QString::number(r.height());} - QString rectString(const QRectF & r) const {return QString::number(r.x()) + " x " + QString::number(r.y()) + " : " + - QString::number(r.width()) + " x " + QString::number(r.height());} - + QString pointString(const QPoint & p) const { return QString::number(p.x()) + " x " + QString::number(p.y()); } + QString pointString(const QPointF & p) const { return QString::number(p.x()) + " x " + QString::number(p.y()); } + QString rectString(const QRect & r) const { + return QString::number(r.x()) + " x " + QString::number(r.y()) + " : " + QString::number(r.width()) + " x " + + QString::number(r.height()); + } + QString rectString(const QRectF & r) const { + return QString::number(r.x()) + " x " + QString::number(r.y()) + " : " + QString::number(r.width()) + " x " + + QString::number(r.height()); + } + QBrush ab; mutable QModelIndex cmi; - + private slots: - void changed() {setModelData((QWidget * )sender(), const_cast(cmi.model()), cmi);} + void changed() { setModelData((QWidget *)sender(), const_cast(cmi.model()), cmi); } void changedFlag(); - }; typedef QPair PropertyValuePair; -Q_DECLARE_METATYPE (PropertyValuePair) +Q_DECLARE_METATYPE(PropertyValuePair) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - Q_DECLARE_METATYPE (QMetaProperty) +Q_DECLARE_METATYPE(QMetaProperty) #endif class PropertyEditor: public QTreeWidget { Q_OBJECT + public: explicit PropertyEditor(QWidget * parent = 0); virtual ~PropertyEditor(); - void assignObject(QObject * o) {object = o; rebuild();} + void assignObject(QObject * o) { + object = o; + rebuild(); + } protected: void changeEvent(QEvent * e); private: void configTree(); - void setItemBackColor(QTreeWidgetItem * i, const QColor & c) {i->setBackground(0, c); i->setBackground(1, c);} - void setItemForeColor(QTreeWidgetItem * i, const QColor & c) {i->setForeground(0, c); i->setForeground(1, c);} + void setItemBackColor(QTreeWidgetItem * i, const QColor & c) { + i->setBackground(0, c); + i->setBackground(1, c); + } + void setItemForeColor(QTreeWidgetItem * i, const QColor & c) { + i->setForeground(0, c); + i->setForeground(1, c); + } void rebuild(); void refresh(); @@ -74,7 +93,6 @@ private: private slots: void itemClicked(QTreeWidgetItem * item, int column); void itemChanged(QTreeWidgetItem * item, int column); - }; #endif // PROPERTYEDITOR_H diff --git a/libs/qglview/qglview.cpp b/libs/qglview/qglview.cpp index d710577..4e9d902 100644 --- a/libs/qglview/qglview.cpp +++ b/libs/qglview/qglview.cpp @@ -1,64 +1,64 @@ /* - QGLView - Ivan Pelipenko peri4ko@yandex.ru + QGLView + Ivan Pelipenko peri4ko@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #include "qglview.h" -#include #include #include +#include QGLView::QGLView(): OpenGLWindow(), fbo_selection(3) { -// setFrameShape(QFrame::NoFrame); -// setViewportUpdateMode(FullViewportUpdate); -// setCacheMode(CacheNone); -// setMouseTracking(true); -// setFocusPolicy(Qt::WheelFocus); -// setScene(new QGraphicsScene()); -// setInteractive(true); + // setFrameShape(QFrame::NoFrame); + // setViewportUpdateMode(FullViewportUpdate); + // setCacheMode(CacheNone); + // setMouseTracking(true); + // setFocusPolicy(Qt::WheelFocus); + // setScene(new QGraphicsScene()); + // setInteractive(true); setIcon(QIcon("://icons/qglview.png")); - deleting_ = false; - timer = 0; + deleting_ = false; + timer = 0; need_init_ = is_first_draw = true; - objects_.is_root = true; - objects_.view_ = this; - backColor_ = Qt::darkGray; - hoverHaloColor_ = QColor(195, 140, 255, 96); - selectionHaloColor_ = QColor(175, 255, 140); - ambientColor_ = QColor(10, 10, 10); - lastPos = QPoint(-1, -1); - lineWidth_ = 1.; - max_anisotropic = 1; - max_texture_chanels = 8; + objects_.is_root = true; + objects_.view_ = this; + backColor_ = Qt::darkGray; + hoverHaloColor_ = QColor(195, 140, 255, 96); + selectionHaloColor_ = QColor(175, 255, 140); + ambientColor_ = QColor(10, 10, 10); + lastPos = QPoint(-1, -1); + lineWidth_ = 1.; + max_anisotropic = 1; + max_texture_chanels = 8; cameraOrbit_ = lightEnabled_ = true; shaders_supported = selecting_ = customMouseMove_ = false; - sel_button = Qt::LeftButton; - sel_mod = Qt::NoModifier; - renderer_ = nullptr; - fps_cnt = 0; + sel_button = Qt::LeftButton; + sel_mod = Qt::NoModifier; + renderer_ = nullptr; + fps_cnt = 0; fps_tm = fps_ = 0.; sel_obj = hov_obj = nullptr; fogDensity_ = fogEnd_ = 1.; - fogStart_ = 0.; - fogMode_ = Exp; - hoverHaloFill_ = 0.333f; - selectionHaloFill_ = 0.5f; - //lmode = Simple; + fogStart_ = 0.; + fogMode_ = Exp; + hoverHaloFill_ = 0.333f; + selectionHaloFill_ = 0.5f; + // lmode = Simple; shader_select = shader_halo = nullptr; setFeature(qglMSAA, false); setFeature(qglFXAA, false); @@ -88,18 +88,18 @@ QGLView::QGLView(): OpenGLWindow(), fbo_selection(3) { setFeature(qglDepthOfFieldFocus, 1.); setFeature(qglDepthOfFieldDiaphragm, 8.); mouse_first = mouseSelect_ = hoverHalo_ = selectionHalo_ = true; - mouseRotate_ = true; + mouseRotate_ = true; fogEnabled_ = is_init = grabMouse_ = shaders_bind = changed_ = false; - rmode = GLObjectBase::Fill; - sel_mode = QGLView::SingleSelection; -// sel_pen = QPen(Qt::black, 1, Qt::DashLine); -// sel_brush = QBrush(QColor(170, 100, 255, 120)); + rmode = GLObjectBase::Fill; + sel_mode = QGLView::SingleSelection; + // sel_pen = QPen(Qt::black, 1, Qt::DashLine); + // sel_brush = QBrush(QColor(170, 100, 255, 120)); camera()->setAim(QVector3D()); camera()->setPos(QVector3D(2, 2, 2)); camera()->setName("Camera"); addObject(camera()); emit cameraPosChanged(camera()->pos()); - //camera().aim_ = camera().pos_; + // camera().aim_ = camera().pos_; ktm_.restart(); } @@ -139,9 +139,9 @@ void QGLView::addObject(GLObjectBase * o) { objects_.addChild(o); o->setView(this); collectLights(); - QList cl = o->children(true); + QList cl = o->children(true); cl << o; - foreach (GLObjectBase * i, cl) { + foreach(GLObjectBase * i, cl) { emit objectAdded(i); } if (is_init) { @@ -199,7 +199,7 @@ void QGLView::removeLight(int index) { void QGLView::removeLight(Light * l) { - foreach (Light * i, lights_) + foreach(Light * i, lights_) if (i == l) removeObject(i); lights_.removeAll(l); } @@ -207,7 +207,8 @@ void QGLView::removeLight(Light * l) { void QGLView::clearLights(bool deleteAll) { if (deleteAll) - foreach (Light * i, lights_) delete i; + foreach(Light * i, lights_) + delete i; lights_.clear(); } @@ -228,7 +229,7 @@ Light * QGLView::light(int index) { Light * QGLView::light(const QString & name) { - foreach (Light * i, lights_) + foreach(Light * i, lights_) if (i->name_ == name) return i; return nullptr; } @@ -237,7 +238,7 @@ Light * QGLView::light(const QString & name) { void QGLView::selectObject(GLObjectBase * o) { if (o == sel_obj) return; GLObjectBase * pso = sel_obj; - sel_obj = o; + sel_obj = o; emit selectionChanged(sel_obj, pso); } @@ -250,7 +251,7 @@ void QGLView::timerEvent(QTimerEvent *) { renderNow(); if (ktm_.elapsed() < QApplication::keyboardInputInterval()) return; Qt::KeyboardModifiers km = QApplication::keyboardModifiers(); - foreach (int i, keys_) + foreach(int i, keys_) emit keyEvent((Qt::Key)i, km); } @@ -260,19 +261,19 @@ void QGLView::render() { resizeGL(width(), height()); QRect g_rect(QPoint(), size()); emit glBeforePaint(); - //qDebug() << "paintGL"; - //QMutexLocker ml_v(&v_mutex); + // qDebug() << "paintGL"; + // QMutexLocker ml_v(&v_mutex); glEnable(GL_CULL_FACE); - //glDisable(GL_CULL_FACE); + // glDisable(GL_CULL_FACE); camera()->apply(aspect); - //objects_.preparePos(camera()); + // objects_.preparePos(camera()); start_rp.cam_offset_matrix = camera()->offsetMatrix(); - start_rp.proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); - start_rp.view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); - //objects_.buildTransform(); + start_rp.proj_matrix = getGLMatrix(GL_PROJECTION_MATRIX); + start_rp.view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); + // objects_.buildTransform(); /// Selection detect - //glClearFramebuffer(QColor(100, 0, 0, 0)); + // glClearFramebuffer(QColor(100, 0, 0, 0)); if (mouseSelect_) { glReleaseTextures(); glEnableDepth(); @@ -294,8 +295,8 @@ void QGLView::render() { if (shaders_supported && shader_select->isLinked()) shader_select->bind(); renderSelection(); if (shaders_supported && shader_select->isLinked()) shader_select->release(); - uchar cgid[4] = {0, 0, 0, 0}; - uint iid = 0; + uchar cgid[4] = {0, 0, 0, 0}; + uint iid = 0; GLObjectBase * so = nullptr; if (!g_rect.contains(lastPos)) { if (hov_obj != nullptr) { @@ -305,13 +306,13 @@ void QGLView::render() { } else { glReadPixels(lastPos.x(), height() - lastPos.y(), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, cgid); iid = uint(cgid[0] << 24) | uint(cgid[1] << 16) | uint(cgid[2] << 8) | cgid[3]; - so = ids.value(iid, nullptr); - //qDebug() <name() << cgid[3]; + // if (so != 0) qDebug() << sel_obj->name() << cgid[3]; } if (selectionHalo_ && sel_obj) { fbo_selection.setWriteBuffer(2); @@ -329,9 +330,9 @@ void QGLView::render() { } camera()->apply(aspect); - start_rp.cam_offset_matrix = camera()->offsetMatrix(); - cur_mvpm = start_rp.proj_matrix * start_rp.view_matrix * start_rp.cam_offset_matrix; - //objects_.preparePos(camera()); + start_rp.cam_offset_matrix = camera()->offsetMatrix(); + cur_mvpm = start_rp.proj_matrix * start_rp.view_matrix * start_rp.cam_offset_matrix; + // objects_.preparePos(camera()); static GLRendererBase * prev_rend = nullptr; glShadeModel(GL_SMOOTH); @@ -355,7 +356,7 @@ void QGLView::render() { glReleaseTextures(); glBindFramebuffer(GL_FRAMEBUFFER, 0); - //glClearFramebuffer(Qt::black, false); + // glClearFramebuffer(Qt::black, false); glActiveTexture(GL_TEXTURE0); glEnable(GL_BLEND); @@ -365,13 +366,13 @@ void QGLView::render() { glBlendFunc(GL_SRC_ALPHA, GL_ONE); if (selectionHalo_ && sel_obj) { glBindTexture(GL_TEXTURE_2D, fbo_selection.colorTexture(2)); - //qDebug() << "draw sel"; + // qDebug() << "draw sel"; glDrawQuad(); } if (hoverHalo_ && hov_obj) { glBindTexture(GL_TEXTURE_2D, fbo_selection.colorTexture(1)); - //qDebug() << "draw hover"; - //glBindTexture(GL_TEXTURE_2D, textures_manager->loadTexture("batt_pn.jpg")); + // qDebug() << "draw hover"; + // glBindTexture(GL_TEXTURE_2D, textures_manager->loadTexture("batt_pn.jpg")); glDrawQuad(); } } @@ -380,11 +381,11 @@ void QGLView::render() { glBindFramebuffer(GL_FRAMEBUFFER, 0); glUseProgram(0); - //glDisable(GL_BLEND); - //glDisable(GL_LIGHTING); - //glActiveTexture(GL_TEXTURE0); - //glBindTexture(GL_TEXTURE_2D, textures_manager->loadTexture("batt_pn.jpg")); - //glDrawQuad(); + // glDisable(GL_BLEND); + // glDisable(GL_LIGHTING); + // glActiveTexture(GL_TEXTURE0); + // glBindTexture(GL_TEXTURE_2D, textures_manager->loadTexture("batt_pn.jpg")); + // glDrawQuad(); emit glEndPaint(); @@ -424,14 +425,14 @@ void QGLView::render() { time.restart(); fps_cnt++; if (fps_tm < 1000.) return; - fps_ = fps_cnt / fps_tm * 1000.; - fps_tm = 0.; + fps_ = fps_cnt / fps_tm * 1000.; + fps_tm = 0.; fps_cnt = 0; } void QGLView::initialize() { - //initializeOpenGLFunctions(); + // initializeOpenGLFunctions(); glEnable(GL_TEXTURE_MAX_ANISOTROPY_EXT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glEnableDepth(); @@ -458,10 +459,10 @@ void QGLView::initialize() { checkCaps(); shader_select = new QOpenGLShaderProgram(context()); - shader_halo = new QOpenGLShaderProgram(context()); + shader_halo = new QOpenGLShaderProgram(context()); reloadThisShaders(); - is_init = true; - //resizeGL(width(), height()); + is_init = true; + // resizeGL(width(), height()); need_init_ = false; emit glInitializeDone(); } @@ -478,18 +479,19 @@ void QGLView::renderHalo(const GLObjectBase * obj, const uint iid, const QColor shader_halo->setUniformValue("qgl_ModelViewProjectionMatrix", QMatrix4x4()); shader_halo->setUniformValue("t0", 0); shader_halo->setUniformValue("dt", QVector2D(1.f / width(), 1.f / height())); - shader_halo->setUniformValue("selected", QVector4D(float((iid >> 24) & 0xFF) / 255.f, - float((iid >> 16) & 0xFF) / 255.f, - float((iid >> 8) & 0xFF) / 255.f, - float( iid & 0xFF) / 255.f)); + shader_halo->setUniformValue("selected", + QVector4D(float((iid >> 24) & 0xFF) / 255.f, + float((iid >> 16) & 0xFF) / 255.f, + float((iid >> 8) & 0xFF) / 255.f, + float(iid & 0xFF) / 255.f)); shader_halo->setUniformValue("color", color); shader_halo->setUniformValue("fill", GLfloat(fill)); - //qDebug() << "render halo" << iid << shader_halo->log() << shader_halo->programId(); + // qDebug() << "render halo" << iid << shader_halo->log() << shader_halo->programId(); glDisableDepth(); - //glClearFramebuffer(color); + // glClearFramebuffer(color); glDrawQuad(shader_halo); glDepthMask(GL_TRUE); - //glFlush(); + // glFlush(); shader_halo->release(); } else { glClearFramebuffer(Qt::black, false); @@ -498,7 +500,7 @@ void QGLView::renderHalo(const GLObjectBase * obj, const uint iid, const QColor void QGLView::renderSelection() { -// cid = 1; + // cid = 1; ids.clear(); if (shaders_supported) { if (shader_select) { @@ -509,7 +511,7 @@ void QGLView::renderSelection() { } } } - //qDebug() << sh_id_loc; + // qDebug() << sh_id_loc; start_rp.view_matrix = getGLMatrix(GL_MODELVIEW_MATRIX); glPushMatrix(); renderSingleSelection(objects_); @@ -524,32 +526,34 @@ void QGLView::renderSingleSelection(GLObjectBase & o) { } if (!o.visible_ || !o.select_) return; QMatrix4x4 curview = start_rp.view_matrix * start_rp.cam_offset_matrix * o.itransform_; - uint id = qHash((quint64)&o); + uint id = qHash((quint64)&o); ids.insert(id, &o); glLineWidth(o.line_width > 0.f ? o.line_width : lineWidth_); glPointSize(o.line_width > 0.f ? o.line_width : lineWidth_); - if (shaders_supported){ + if (shaders_supported) { if (shader_select) { if (shader_select->isLinked()) { setUniformMatrices(shader_select, start_rp.proj_matrix, curview); - shader_select->setUniformValue(sh_id_loc, QVector4D(float((id >> 24) & 0xFF) / 255.f, - float((id >> 16) & 0xFF) / 255.f, - float((id >> 8) & 0xFF) / 255.f, - float(id & 0xFF) / 255.f)); + shader_select->setUniformValue(sh_id_loc, + QVector4D(float((id >> 24) & 0xFF) / 255.f, + float((id >> 16) & 0xFF) / 255.f, + float((id >> 8) & 0xFF) / 255.f, + float(id & 0xFF) / 255.f)); } } } else { setGLMatrix(curview); glColor4f(float((id >> 24) & 0xFF) / 255.f, - float((id >> 16) & 0xFF) / 255.f, - float((id >> 8) & 0xFF) / 255.f, - float(id & 0xFF) / 255.f); + float((id >> 16) & 0xFF) / 255.f, + float((id >> 8) & 0xFF) / 255.f, + float(id & 0xFF) / 255.f); } - //qDebug() << o.name() << "assign to" << sh_id_loc << cid; - //glColor4f(float((cid >> 24) & 0xFF) / 255.f, float((cid >> 16) & 0xFF) / 255.f, float((cid >> 8) & 0xFF) / 255.f, float(cid & 0xFF) / 255.f); -// ++cid; + // qDebug() << o.name() << "assign to" << sh_id_loc << cid; + // glColor4f(float((cid >> 24) & 0xFF) / 255.f, float((cid >> 16) & 0xFF) / 255.f, float((cid >> 8) & 0xFF) / 255.f, float(cid & 0xFF) / + // 255.f); + // ++cid; o.draw(nullptr, true); - foreach (GLObjectBase * i, o.children_) + foreach(GLObjectBase * i, o.children_) renderSingleSelection(*i); } @@ -562,7 +566,7 @@ void QGLView::collectLights() { void QGLView::objectDeleted(GLObjectBase * o) { if (deleting_) return; - //qDebug() << "del" << o; + // qDebug() << "del" << o; if (sel_obj == o) selectObject(nullptr); if (hov_obj == o) hov_obj = nullptr; collectLights(); @@ -571,23 +575,23 @@ void QGLView::objectDeleted(GLObjectBase * o) { void QGLView::collectObjectLights(GLObjectBase * o) { if (o->type_ == GLObjectBase::glLight) { - lights_ << globject_cast(o); + lights_ << globject_cast(o); o->view_ = this; } - foreach (GLObjectBase * i, o->children()) + foreach(GLObjectBase * i, o->children()) collectObjectLights(i); } void QGLView::objectsCountInternal(int * cnt, GLObjectBase * where) { ++(*cnt); - foreach (GLObjectBase * i, where->children_) + foreach(GLObjectBase * i, where->children_) objectsCountInternal(cnt, i); } void QGLView::removeObjectInternal(GLObjectBase * o, GLObjectBase * where) { - foreach (GLObjectBase * i, where->children_) { + foreach(GLObjectBase * i, where->children_) { if (o == i) where->removeChild(i); else @@ -599,9 +603,9 @@ void QGLView::removeObjectInternal(GLObjectBase * o, GLObjectBase * where) { void QGLView::checkCaps() { glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropic); - //glGetIntegerv(GL_MAX_TEXTURE_UNITS, &max_texture_chanels); - //qDebug() << max_texture_chanels; - //qDebug() << max_texture_chanels; + // glGetIntegerv(GL_MAX_TEXTURE_UNITS, &max_texture_chanels); + // qDebug() << max_texture_chanels; + // qDebug() << max_texture_chanels; shaders_supported = QOpenGLShaderProgram::hasOpenGLShaderPrograms(); } @@ -610,7 +614,7 @@ void QGLView::reloadThisShaders() { if (!shaders_supported) return; loadShaders(shader_select, "selection", "://shaders"); loadShaders(shader_halo, "selection_halo", "://shaders"); - //loadShaders(shader_rope, "rope", "://shaders"); + // loadShaders(shader_rope, "rope", "://shaders"); } void QGLView::glReleaseTextures(int channels) { @@ -634,7 +638,8 @@ void QGLView::applyFog() { fog_col[1] = fogColor_.greenF(); fog_col[2] = fogColor_.blueF(); glFogfv(GL_FOG_COLOR, fog_col); - } else glDisable(GL_FOG); + } else + glDisable(GL_FOG); } @@ -643,10 +648,10 @@ void QGLView::resizeGL(int width, int height) { if (width <= 0 || height <= 0) return; if (prev_size == QSize(width, height)) return; prev_size = QSize(width, height); - aspect = float(width) / float(height); + aspect = float(width) / float(height); if (renderer_) renderer_->resize(width, height); mouse_first = true; - //qDebug() << "resize" << width << height; + // qDebug() << "resize" << width << height; fbo_selection.resize(width, height); iaspect = (aspect == 0.f) ? 0. : 1 / aspect; glViewport(0, 0, width, height); @@ -655,14 +660,13 @@ void QGLView::resizeGL(int width, int height) { void QGLView::mouseReleaseEvent(QMouseEvent * e) { -// qDebug() << "mouseReleaseEvent" << e << isActive(); -// QGraphicsView::mouseReleaseEvent(e); - //setCursor(QCursor(Qt::ArrowCursor)); + // qDebug() << "mouseReleaseEvent" << e << isActive(); + // QGraphicsView::mouseReleaseEvent(e); + // setCursor(QCursor(Qt::ArrowCursor)); selecting_ = false; if (mouseSelect_ && e->button() == Qt::LeftButton) { if ((lastPos - downPos).manhattanLength() < 8) { - if (sel_obj != hov_obj) - selectObject(hov_obj); + if (sel_obj != hov_obj) selectObject(hov_obj); } } emit glMouseReleaseEvent(e); @@ -670,38 +674,38 @@ void QGLView::mouseReleaseEvent(QMouseEvent * e) { void QGLView::mousePressEvent(QMouseEvent * e) { -// qDebug() << "mousePressEvent" << e << isActive(); -// QGraphicsView::mousePressEvent(e); -// mouseThis_ = (scene()->itemAt(mapToScene(e->pos()) , QTransform() ) == 0); + // qDebug() << "mousePressEvent" << e << isActive(); + // QGraphicsView::mousePressEvent(e); + // mouseThis_ = (scene()->itemAt(mapToScene(e->pos()) , QTransform() ) == 0); selecting_ = false; if (!QRect(QPoint(), size()).contains(e->pos())) return; /// TODO select by rect - //if (e->button() == sel_button && e->modifiers() == sel_mod) + // if (e->button() == sel_button && e->modifiers() == sel_mod) // selecting_ = true; lastPos = e->pos(); downPos = lastPos; - //qDebug() << mouseThis_; + // qDebug() << mouseThis_; emit glMousePressEvent(e); } void QGLView::mouseMoveEvent(QMouseEvent * e) { -// qDebug() << "mouseMoveEvent" << e << isActive(); -// QGraphicsView::mouseMoveEvent(e); - //lastPos = e->pos(); + // qDebug() << "mouseMoveEvent" << e << isActive(); + // QGraphicsView::mouseMoveEvent(e); + // lastPos = e->pos(); if (selecting_) { return; } -// if (!QRect(QPoint(), size()).contains(e->pos())) return; - //if (scene()->itemAt(mapToScene(e->pos())) != 0) return; - ///qDebug() << e->x() << e->y(); + // if (!QRect(QPoint(), size()).contains(e->pos())) return; + // if (scene()->itemAt(mapToScene(e->pos())) != 0) return; + /// qDebug() << e->x() << e->y(); QRect g_rect(QPoint(), size()); if (mouseRotate_) { float dx = e->x() - lastPos.x(); float dy = e->y() - lastPos.y(); if (e->buttons() & Qt::LeftButton) { - //camera().angle_z += dx / 4.; - //camera().angle_xy += dy / 4.; + // camera().angle_z += dx / 4.; + // camera().angle_xy += dy / 4.; if (cameraOrbit_) { camera()->orbitZ(dx / 4.f); camera()->orbitXY(dy / 4.f); @@ -714,16 +718,16 @@ void QGLView::mouseMoveEvent(QMouseEvent * e) { float ad = camera()->distance(); camera()->moveLeft(dx / 1000.f * ad); camera()->moveUp(dy / 1000.f * ad); - //camera().pos.setX(camera().pos.x() + camera().pos.z() * dx / 500.); - //camera().pos.setY(camera().pos.y() - camera().pos.z() * dy / 500.); + // camera().pos.setX(camera().pos.x() + camera().pos.z() * dx / 500.); + // camera().pos.setY(camera().pos.y() - camera().pos.z() * dy / 500.); emit cameraPosChanged(camera()->pos()); } - //lights[0]->pos_ = camera().pos(); + // lights[0]->pos_ = camera().pos(); } if (customMouseMove_) emit customMouseMoveEvent(e->pos(), lastPos, e->buttons()); lastPos = e->pos(); if (grabMouse_) { - //if (!isrunning) return; + // if (!isrunning) return; QCursor::setPos(mapToGlobal(QRect(QPoint(), size()).center())); static bool mouse_sec = false; if (mouse_sec) { @@ -732,13 +736,13 @@ void QGLView::mouseMoveEvent(QMouseEvent * e) { } if (mouse_first) { mouse_first = false; - mouse_sec = true; - //qDebug() << "first" << e->pos(); + mouse_sec = true; + // qDebug() << "first" << e->pos(); return; } lastPos = g_rect.center(); - int dx = e->x() - lastPos.x(); - int dy = e->y() - lastPos.y(); + int dx = e->x() - lastPos.x(); + int dy = e->y() - lastPos.y(); emit glMouseMoveEvent(new QMouseEvent(QEvent::MouseMove, QPoint(dx, dy), e->button(), e->buttons(), e->modifiers())); return; } @@ -750,21 +754,21 @@ void QGLView::wheelEvent(QWheelEvent * e) { if (mouseRotate_) { double ang = #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - e->delta(); + e->delta(); #else - e->angleDelta().y(); + e->angleDelta().y(); #endif - if (ang > 0) camera()->flyCloser(0.1f); //camera().pos.setZ(camera().pos.z() - 0.1 * camera().pos.z()); - if (ang < 0) camera()->flyFarer(0.1f); //camera().pos.setZ(camera().pos.z() + 0.1 * camera().pos.z()); + if (ang > 0) camera()->flyCloser(0.1f); // camera().pos.setZ(camera().pos.z() - 0.1 * camera().pos.z()); + if (ang < 0) camera()->flyFarer(0.1f); // camera().pos.setZ(camera().pos.z() + 0.1 * camera().pos.z()); emit cameraPosChanged(camera()->pos()); } emit glWheelEvent(e); } -void QGLView::leaveEvent(QEvent * ) { +void QGLView::leaveEvent(QEvent *) { lastPos = QPoint(-1, -1); - //qDebug() << lastPos; + // qDebug() << lastPos; } @@ -789,8 +793,7 @@ void QGLView::focusOutEvent(QFocusEvent *) { void QGLView::mouseDoubleClickEvent(QMouseEvent * e) { - if (e->buttons().testFlag(QT_MID_BUTTON)) - emit doubleClick(); + if (e->buttons().testFlag(QT_MID_BUTTON)) emit doubleClick(); } @@ -811,7 +814,7 @@ QByteArray QGLView::saveCamera() { } -void QGLView::restoreCamera(const QByteArray &ba) { +void QGLView::restoreCamera(const QByteArray & ba) { if (ba.isEmpty()) return; ChunkStream cs(ba); QVector3D pos, aim, ang; @@ -850,4 +853,3 @@ void QGLView::restoreFeatures(const QByteArray & ba) { ds >> f; features_ = f; } - diff --git a/libs/qglview/qglview.h b/libs/qglview/qglview.h index e218b4b..1cf60fa 100644 --- a/libs/qglview/qglview.h +++ b/libs/qglview/qglview.h @@ -1,71 +1,81 @@ /* - QGLView - Ivan Pelipenko peri4ko@yandex.ru + QGLView + Ivan Pelipenko peri4ko@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QGLVIEW_H #define QGLVIEW_H -#include "openglwindow.h" #include "glframebuffer.h" -#include "glprimitives.h" #include "glparticles_system.h" +#include "glprimitives.h" #include "glrendererbase.h" +#include "openglwindow.h" + #include #include -class QGLView: public OpenGLWindow, public QGLViewBase -{ +class QGLView + : public OpenGLWindow + , public QGLViewBase { friend class GLRendererBase; friend class GLObjectBase; Q_OBJECT - Q_PROPERTY (QColor backColor READ backColor WRITE setBackColor) - Q_PROPERTY (float lineWidth READ lineWidth WRITE setLineWidth) - Q_PROPERTY (float FOV READ FOV WRITE setFOV) - Q_PROPERTY (float depthStart READ depthStart WRITE setDepthStart) - Q_PROPERTY (float depthEnd READ depthEnd WRITE setDepthEnd) - Q_PROPERTY (QColor ambientColor READ ambientColor WRITE setAmbientColor) - Q_PROPERTY (QColor fogColor READ fogColor WRITE setFogColor) - Q_PROPERTY (float fogDensity READ fogDensity WRITE setFogDensity) - Q_PROPERTY (float fogStart READ fogStart WRITE setFogStart) - Q_PROPERTY (float fogEnd READ fogEnd WRITE setFogEnd) - Q_PROPERTY (FogMode fogMode READ fogMode WRITE setFogMode) - Q_PROPERTY (bool fogEnabled READ isFogEnabled WRITE setFogEnabled) - Q_PROPERTY (int renderMode READ renderMode WRITE setRenderMode) - Q_PROPERTY (bool grabMouse READ isGrabMouseEnabled WRITE setGrabMouseEnabled) - Q_PROPERTY (bool mouseRotate READ isMouseRotateEnabled WRITE setMouseRotateEnabled) - Q_PROPERTY (bool mouseSelection READ isMouseSelectionEnabled WRITE setMouseSelectionEnabled) - Q_PROPERTY (bool cameraOrbit READ isCameraOrbit WRITE setCameraOrbit) - Q_PROPERTY (bool hoverHalo READ isHoverHaloEnabled WRITE setHoverHaloEnabled) - Q_PROPERTY (QColor hoverHaloColor READ hoverHaloColor WRITE setHoverHaloColor) - Q_PROPERTY (float hoverHaloFillAlpha READ hoverHaloFillAlpha WRITE setHoverHaloFillAlpha) - Q_PROPERTY (bool selectionHalo READ isSelectionHaloEnabled WRITE setSelectionHaloEnabled) - Q_PROPERTY (QColor selectionHaloColor READ selectionHaloColor WRITE setSelectionHaloColor) - Q_PROPERTY (float selectionHaloFillAlpha READ selectionHaloFillAlpha WRITE setSelectionHaloFillAlpha) - Q_PROPERTY (Qt::MouseButton selectionButton READ selectionButton WRITE setSelectionButton) - Q_PROPERTY (Qt::KeyboardModifier selectionModifier READ selectionModifier WRITE setSelectionModifier) - Q_PROPERTY (SelectionMode selectionMode READ selectionMode WRITE setSelectionMode) + Q_PROPERTY(QColor backColor READ backColor WRITE setBackColor) + Q_PROPERTY(float lineWidth READ lineWidth WRITE setLineWidth) + Q_PROPERTY(float FOV READ FOV WRITE setFOV) + Q_PROPERTY(float depthStart READ depthStart WRITE setDepthStart) + Q_PROPERTY(float depthEnd READ depthEnd WRITE setDepthEnd) + Q_PROPERTY(QColor ambientColor READ ambientColor WRITE setAmbientColor) + Q_PROPERTY(QColor fogColor READ fogColor WRITE setFogColor) + Q_PROPERTY(float fogDensity READ fogDensity WRITE setFogDensity) + Q_PROPERTY(float fogStart READ fogStart WRITE setFogStart) + Q_PROPERTY(float fogEnd READ fogEnd WRITE setFogEnd) + Q_PROPERTY(FogMode fogMode READ fogMode WRITE setFogMode) + Q_PROPERTY(bool fogEnabled READ isFogEnabled WRITE setFogEnabled) + Q_PROPERTY(int renderMode READ renderMode WRITE setRenderMode) + Q_PROPERTY(bool grabMouse READ isGrabMouseEnabled WRITE setGrabMouseEnabled) + Q_PROPERTY(bool mouseRotate READ isMouseRotateEnabled WRITE setMouseRotateEnabled) + Q_PROPERTY(bool mouseSelection READ isMouseSelectionEnabled WRITE setMouseSelectionEnabled) + Q_PROPERTY(bool cameraOrbit READ isCameraOrbit WRITE setCameraOrbit) + Q_PROPERTY(bool hoverHalo READ isHoverHaloEnabled WRITE setHoverHaloEnabled) + Q_PROPERTY(QColor hoverHaloColor READ hoverHaloColor WRITE setHoverHaloColor) + Q_PROPERTY(float hoverHaloFillAlpha READ hoverHaloFillAlpha WRITE setHoverHaloFillAlpha) + Q_PROPERTY(bool selectionHalo READ isSelectionHaloEnabled WRITE setSelectionHaloEnabled) + Q_PROPERTY(QColor selectionHaloColor READ selectionHaloColor WRITE setSelectionHaloColor) + Q_PROPERTY(float selectionHaloFillAlpha READ selectionHaloFillAlpha WRITE setSelectionHaloFillAlpha) + Q_PROPERTY(Qt::MouseButton selectionButton READ selectionButton WRITE setSelectionButton) + Q_PROPERTY(Qt::KeyboardModifier selectionModifier READ selectionModifier WRITE setSelectionModifier) + Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode) public: QGLView(); virtual ~QGLView(); - enum FogMode {Linear = GL_LINEAR, Exp = GL_EXP, Exp2 = GL_EXP2}; - enum SelectionMode {NoSelection, SingleSelection, MultiSelection}; + enum FogMode { + Linear = GL_LINEAR, + Exp = GL_EXP, + Exp2 = GL_EXP2 + }; + enum SelectionMode { + NoSelection, + SingleSelection, + MultiSelection + }; enum Feature { qglMSAA, qglFXAA, @@ -96,8 +106,8 @@ public: qglDepthOfFieldDiaphragm }; - Q_ENUMS (FogMode) - Q_ENUMS (SelectionMode) + Q_ENUMS(FogMode) + Q_ENUMS(SelectionMode) void stop(); void start(float freq = 60.); @@ -105,72 +115,76 @@ public: GLRendererBase * renderer(); void setRenderer(GLRendererBase * r, GLRendererBase ** prev = nullptr); - QColor backColor() const {return backColor_;} - float lineWidth() const {return lineWidth_;} - float FOV() const {return camera()->fov_;} - float depthStart() const {return camera()->depth_start;} - float depthEnd() const {return camera()->depth_end;} - float currentFPS() const {return fps_;} - int maxAnisotropicLevel() const {return max_anisotropic;} + QColor backColor() const { return backColor_; } + float lineWidth() const { return lineWidth_; } + float FOV() const { return camera()->fov_; } + float depthStart() const { return camera()->depth_start; } + float depthEnd() const { return camera()->depth_end; } + float currentFPS() const { return fps_; } + int maxAnisotropicLevel() const { return max_anisotropic; } - QColor ambientColor() const {return ambientColor_;} - QColor fogColor() const {return fogColor_;} - float fogDensity() const {return fogDensity_;} - float fogStart() const {return fogStart_;} - float fogEnd() const {return fogEnd_;} - FogMode fogMode() const {return fogMode_;} - bool isFogEnabled() const {return fogEnabled_;} - bool isLightEnabled() const {return lightEnabled_;} - bool isGrabMouseEnabled() const {return grabMouse_;} - bool isMouseRotateEnabled() const {return mouseRotate_;} - bool isMouseSelectionEnabled() const {return mouseSelect_;} - bool isCameraOrbit() const {return cameraOrbit_;} - bool isHoverHaloEnabled() const {return hoverHalo_;} - QColor hoverHaloColor() const {return hoverHaloColor_;} - float hoverHaloFillAlpha() const {return hoverHaloFill_;} - bool isSelectionHaloEnabled() const {return selectionHalo_;} - QColor selectionHaloColor() const {return selectionHaloColor_;} - float selectionHaloFillAlpha() const {return selectionHaloFill_;} + QColor ambientColor() const { return ambientColor_; } + QColor fogColor() const { return fogColor_; } + float fogDensity() const { return fogDensity_; } + float fogStart() const { return fogStart_; } + float fogEnd() const { return fogEnd_; } + FogMode fogMode() const { return fogMode_; } + bool isFogEnabled() const { return fogEnabled_; } + bool isLightEnabled() const { return lightEnabled_; } + bool isGrabMouseEnabled() const { return grabMouse_; } + bool isMouseRotateEnabled() const { return mouseRotate_; } + bool isMouseSelectionEnabled() const { return mouseSelect_; } + bool isCameraOrbit() const { return cameraOrbit_; } + bool isHoverHaloEnabled() const { return hoverHalo_; } + QColor hoverHaloColor() const { return hoverHaloColor_; } + float hoverHaloFillAlpha() const { return hoverHaloFill_; } + bool isSelectionHaloEnabled() const { return selectionHalo_; } + QColor selectionHaloColor() const { return selectionHaloColor_; } + float selectionHaloFillAlpha() const { return selectionHaloFill_; } - QVariant feature(Feature f) const {return features_.value(int(f));} - QVariant setFeature(Feature f, const QVariant & value) {QVariant ret = features_.value(int(f)); features_[int(f)] = value; return ret;} - bool isFeatureEnabled(Feature f) const {return features_[int(f)].toBool();} + QVariant feature(Feature f) const { return features_.value(int(f)); } + QVariant setFeature(Feature f, const QVariant & value) { + QVariant ret = features_.value(int(f)); + features_[int(f)] = value; + return ret; + } + bool isFeatureEnabled(Feature f) const { return features_[int(f)].toBool(); } - int renderMode() const {return (int)rmode;} - void setRenderMode(int mode) {rmode = (GLObjectBase::RenderMode)mode;} + int renderMode() const { return (int)rmode; } + void setRenderMode(int mode) { rmode = (GLObjectBase::RenderMode)mode; } void addObject(GLObjectBase * o); -// void addObject(GLObjectBase & o) {addObject(&o);} + // void addObject(GLObjectBase & o) {addObject(&o);} int objectsCount(bool all = false); void removeObject(GLObjectBase * o, bool inChildren = true); void removeObject(GLObjectBase & o, bool inChildren = true); void clearObjects(bool deleteAll = false); - QList objects(bool all = false); + QList objects(bool all = false); int lightsCount() const; void removeLight(int index); void removeLight(Light * l); void clearLights(bool deleteAll = false); - QList lights() {return lights_;} + QList lights() { return lights_; } void addTexture(const QString & path); void addAnimation(const QString & dir, const QString & name); - const GLObjectBase & rootObject() {return objects_;} - GLObjectBase * object(int index) {return objects_.child(index);} - GLObjectBase * object(const QString & name) {return objects_.child(name);} + const GLObjectBase & rootObject() { return objects_; } + GLObjectBase * object(int index) { return objects_.child(index); } + GLObjectBase * object(const QString & name) { return objects_.child(name); } Light * light(int index); Light * light(const QString & name); - SelectionMode selectionMode() const {return sel_mode;} - Qt::MouseButton selectionButton() const {return sel_button;} - Qt::KeyboardModifier selectionModifier() const {return sel_mod;} + SelectionMode selectionMode() const { return sel_mode; } + Qt::MouseButton selectionButton() const { return sel_button; } + Qt::KeyboardModifier selectionModifier() const { return sel_mod; } - void setSelectionMode(SelectionMode v) {sel_mode = v;} - void setSelectionButton(Qt::MouseButton v) {sel_button = v;} - void setSelectionModifier(Qt::KeyboardModifier v) {sel_mod = v;} + void setSelectionMode(SelectionMode v) { sel_mode = v; } + void setSelectionButton(Qt::MouseButton v) { sel_button = v; } + void setSelectionModifier(Qt::KeyboardModifier v) { sel_mod = v; } void selectObject(GLObjectBase * o); - GLObjectBase * selectedObject() const {return sel_obj;} + GLObjectBase * selectedObject() const { return sel_obj; } void glReleaseTextures(int channels = 8); QByteArray saveCamera(); @@ -186,14 +200,14 @@ protected: void render(); void resizeEvent(QResizeEvent * e); - void timerEvent(QTimerEvent * ); + void timerEvent(QTimerEvent *); void initialize(); void resizeGL(int width, int height); void mousePressEvent(QMouseEvent * e); void mouseMoveEvent(QMouseEvent * e); void mouseReleaseEvent(QMouseEvent * e); void wheelEvent(QWheelEvent * e); - void leaveEvent(QEvent * ); + void leaveEvent(QEvent *); void mouseDoubleClickEvent(QMouseEvent * e); void keyPressEvent(QKeyEvent * e); @@ -212,7 +226,7 @@ private: void objectsCountInternal(int * cnt, GLObjectBase * where); void removeObjectInternal(GLObjectBase * o, GLObjectBase * where); void renderSingleSelection(GLObjectBase & o); - //void renderSingleShadow(GLObjectBase & o); + // void renderSingleShadow(GLObjectBase & o); void renderHalo(const GLObjectBase * obj, const uint iid, const QColor & color, const float & fill); void reloadThisShaders(); void processKeys(); @@ -220,18 +234,18 @@ private: QPoint lastPos, downPos; GLObjectBase objects_; - QList lights_; -// uint cid; - QHash ids; + QList lights_; + // uint cid; + QHash ids; QSet keys_; FogMode fogMode_; QColor backColor_, fogColor_, ambientColor_, hoverHaloColor_, selectionHaloColor_; QElapsedTimer time, ktm_; GLint max_anisotropic, max_texture_chanels; GLObjectBase::RenderMode rmode; - GLObjectBase * sel_obj, * hov_obj; + GLObjectBase *sel_obj, *hov_obj; GLFramebuffer fbo_selection; - QOpenGLShaderProgram * shader_select, * shader_halo; + QOpenGLShaderProgram *shader_select, *shader_halo; GLRendererBase * renderer_; SelectionMode sel_mode; Qt::MouseButton sel_button; @@ -247,33 +261,39 @@ private: bool hoverHalo_, selectionHalo_, shaders_bind, selecting_; public slots: - void setBackColor(const QColor & arg) {backColor_ = arg;} - void setLineWidth(const float & arg) {lineWidth_ = arg;} - void setFOV(const float & arg) {camera()->fov_ = arg;} - void setDepthStart(const float & arg) {camera()->depth_start = arg;} - void setDepthEnd(const float & arg) {camera()->depth_end = arg;} - void setAmbientColor(const QColor & arg) {ambientColor_ = arg;} - void setFogColor(const QColor & arg) {fogColor_ = arg;} - void setFogDensity(const float & arg) {fogDensity_ = arg;} - void setFogStart(const float & arg) {fogStart_ = arg;} - void setFogEnd(const float & arg) {fogEnd_ = arg;} - void setFogMode(const FogMode & arg) {fogMode_ = arg;} - void setFogEnabled(const bool & arg) {fogEnabled_ = arg;} - void setLightEnabled(const bool & arg) {lightEnabled_ = arg;} - void setGrabMouseEnabled(const bool & arg) {grabMouse_ = arg; mouse_first = true;} - void setMouseRotateEnabled(const bool & arg) {mouseRotate_ = arg;} - void setMouseSelectionEnabled(const bool & arg) {mouseSelect_ = arg;} - void setCustomMouseMove(const bool & arg) {customMouseMove_ = arg;} - void setCameraOrbit(const bool & arg) {cameraOrbit_ = arg;} - void setHoverHaloEnabled(const bool & arg) {hoverHalo_ = arg;} - void setHoverHaloColor(const QColor & arg) {hoverHaloColor_ = arg;} - void setHoverHaloFillAlpha(const float & arg) {hoverHaloFill_ = arg;} - void setSelectionHaloEnabled(const bool & arg) {selectionHalo_ = arg;} - void setSelectionHaloColor(const QColor & arg) {selectionHaloColor_ = arg;} - void setSelectionHaloFillAlpha(const float & arg) {selectionHaloFill_ = arg;} + void setBackColor(const QColor & arg) { backColor_ = arg; } + void setLineWidth(const float & arg) { lineWidth_ = arg; } + void setFOV(const float & arg) { camera()->fov_ = arg; } + void setDepthStart(const float & arg) { camera()->depth_start = arg; } + void setDepthEnd(const float & arg) { camera()->depth_end = arg; } + void setAmbientColor(const QColor & arg) { ambientColor_ = arg; } + void setFogColor(const QColor & arg) { fogColor_ = arg; } + void setFogDensity(const float & arg) { fogDensity_ = arg; } + void setFogStart(const float & arg) { fogStart_ = arg; } + void setFogEnd(const float & arg) { fogEnd_ = arg; } + void setFogMode(const FogMode & arg) { fogMode_ = arg; } + void setFogEnabled(const bool & arg) { fogEnabled_ = arg; } + void setLightEnabled(const bool & arg) { lightEnabled_ = arg; } + void setGrabMouseEnabled(const bool & arg) { + grabMouse_ = arg; + mouse_first = true; + } + void setMouseRotateEnabled(const bool & arg) { mouseRotate_ = arg; } + void setMouseSelectionEnabled(const bool & arg) { mouseSelect_ = arg; } + void setCustomMouseMove(const bool & arg) { customMouseMove_ = arg; } + void setCameraOrbit(const bool & arg) { cameraOrbit_ = arg; } + void setHoverHaloEnabled(const bool & arg) { hoverHalo_ = arg; } + void setHoverHaloColor(const QColor & arg) { hoverHaloColor_ = arg; } + void setHoverHaloFillAlpha(const float & arg) { hoverHaloFill_ = arg; } + void setSelectionHaloEnabled(const bool & arg) { selectionHalo_ = arg; } + void setSelectionHaloColor(const QColor & arg) { selectionHaloColor_ = arg; } + void setSelectionHaloFillAlpha(const float & arg) { selectionHaloFill_ = arg; } - void reloadShaders() {if (renderer_ != nullptr) renderer_->reloadShaders(); reloadThisShaders();} - void deselect() {sel_obj = nullptr;} + void reloadShaders() { + if (renderer_ != nullptr) renderer_->reloadShaders(); + reloadThisShaders(); + } + void deselect() { sel_obj = nullptr; } signals: void glBeforePaint(); @@ -294,9 +314,8 @@ signals: void hoverChanged(GLObjectBase * cur, GLObjectBase * prev); void selectionChanged(GLObjectBase * cur, GLObjectBase * prev); - void objectAdded(GLObjectBase * ); + void objectAdded(GLObjectBase *); void doubleClick(); - }; #endif // QGLVIEW_H diff --git a/libs/qglview/qglview_test/main.cpp b/libs/qglview/qglview_test/main.cpp index f6ef851..d2f1dc0 100644 --- a/libs/qglview/qglview_test/main.cpp +++ b/libs/qglview/qglview_test/main.cpp @@ -16,10 +16,11 @@ along with this program. If not, see . */ +#include "qglview_window.h" + #include #include #include -#include "qglview_window.h" int main(int argc, char ** argv) { @@ -29,7 +30,7 @@ int main(int argc, char ** argv) { w.show(); QStringList al(a.arguments()); al.pop_front(); - foreach (QString s, al) + foreach(QString s, al) w.loadFile(s); return a.exec(); } diff --git a/libs/qglview/qglview_test/qglview_window.cpp b/libs/qglview/qglview_test/qglview_window.cpp index f91a8e1..a2bf452 100644 --- a/libs/qglview/qglview_test/qglview_window.cpp +++ b/libs/qglview/qglview_test/qglview_window.cpp @@ -17,12 +17,14 @@ */ #include "qglview_window.h" -#include "loader_qgl.h" -#include "loader_ase.h" + #include "loader_3ds.h" -#include "loader_obj.h" +#include "loader_ase.h" #include "loader_dae.h" +#include "loader_obj.h" +#include "loader_qgl.h" #include "qad_types.h" + #include #include #include @@ -32,18 +34,18 @@ QGLViewWindow::QGLViewWindow(QWidget * parent): QMainWindow(parent), Ui::QGLView setupUi(this); session.setFile("session_qglview_test.conf"); session.addEntry(this); - icon_geo = QIcon(":/icons/type-geo.png"); + icon_geo = QIcon(":/icons/type-geo.png"); icon_camera = QIcon(":/icons/type-camera.png"); - icon_light = QIcon(":/icons/type-light.png"); + icon_light = QIcon(":/icons/type-light.png"); QAction * a = new QAction(QIcon(":/icons/edit-delete.png"), "Remove"); connect(a, SIGNAL(triggered()), this, SLOT(removeObjects())); treeObjects->addAction(a); - spinViewLineWidth->setValue(lineThickness()*2); - + spinViewLineWidth->setValue(lineThickness() * 2); + sel_obj = nullptr; view->view()->camera()->setAim(QVector3D()); view->view()->camera()->setPos(QVector3D(2, 2, 2)); -// view->setFrameShape(QFrame::NoFrame); + // view->setFrameShape(QFrame::NoFrame); view->view()->setRenderer(new RendererSimple(view->view())); view->view()->setMouseRotateEnabled(true); view->view()->setMouseSelectionEnabled(true); @@ -95,30 +97,36 @@ QGLViewWindow::QGLViewWindow(QWidget * parent): QMainWindow(parent), Ui::QGLView axis = new GLObjectBase(); GLObjectBase * obj; - float al = 1.; - obj = new GLPrimitiveLine(QVector3D(0, 0, -al), QVector3D(0, 0, al)); - obj->material().color_diffuse = Qt::darkBlue; obj->setAcceptLight(false); + float al = 1.; + obj = new GLPrimitiveLine(QVector3D(0, 0, -al), QVector3D(0, 0, al)); + obj->material().color_diffuse = Qt::darkBlue; + obj->setAcceptLight(false); axis->addChild(obj); - obj = new GLPrimitiveLine(QVector3D(-al, 0, 0), QVector3D(al, 0, 0)); - obj->material().color_diffuse = Qt::darkRed; obj->setAcceptLight(false); + obj = new GLPrimitiveLine(QVector3D(-al, 0, 0), QVector3D(al, 0, 0)); + obj->material().color_diffuse = Qt::darkRed; + obj->setAcceptLight(false); axis->addChild(obj); - obj = new GLPrimitiveLine(QVector3D(0, -al, 0), QVector3D(0, al, 0)); - obj->material().color_diffuse = Qt::darkGreen; obj->setAcceptLight(false); + obj = new GLPrimitiveLine(QVector3D(0, -al, 0), QVector3D(0, al, 0)); + obj->material().color_diffuse = Qt::darkGreen; + obj->setAcceptLight(false); axis->addChild(obj); view->view()->addObject(axis); - cam_light = new Light(); + cam_light = new Light(); cam_light->intensity = 0.5; cam_light->setName("Camera_Light"); view->view()->camera()->addChild(cam_light); view->view()->start(-1); - startTimer(1000/60); + startTimer(1000 / 60); - connect(view->view(), SIGNAL(selectionChanged(GLObjectBase*,GLObjectBase*)), this, SLOT(selectionChanged(GLObjectBase*,GLObjectBase*))); + connect(view->view(), + SIGNAL(selectionChanged(GLObjectBase *, GLObjectBase *)), + this, + SLOT(selectionChanged(GLObjectBase *, GLObjectBase *))); connect(view->view(), SIGNAL(keyEvent(Qt::Key, Qt::KeyboardModifiers)), this, SLOT(view_keyEvent(Qt::Key, Qt::KeyboardModifiers))); connect(matEditor, SIGNAL(changed()), this, SLOT(materialChanged())); - //view->view()->addObject(&partsys); + // view->view()->addObject(&partsys); partsys.material().color_diffuse = Qt::red; treeProps->assignObject(&partsys); session.load(); @@ -127,7 +135,7 @@ QGLViewWindow::QGLViewWindow(QWidget * parent): QMainWindow(parent), Ui::QGLView QGLViewWindow::~QGLViewWindow() { session.save(); - //delete ps; + // delete ps; } @@ -140,9 +148,9 @@ void QGLViewWindow::changeEvent(QEvent * e) { } -void QGLViewWindow::timerEvent(QTimerEvent * ) { - //static double t = 0.; - //cam_light->intensity = checkCameraLight->isChecked() ? 0.5 : 0.; +void QGLViewWindow::timerEvent(QTimerEvent *) { + // static double t = 0.; + // cam_light->intensity = checkCameraLight->isChecked() ? 0.5 : 0.; cam_light->setVisible(checkCameraLight->isChecked()); //((RendererSimple*)(view->view()->renderer()))->mpos = view->view()->mapFromGlobal(QCursor::pos()); statusBar()->showMessage(QString("FPS: %1").arg(QString::number(view->view()->currentFPS(), 'f', 2))); @@ -179,7 +187,7 @@ void QGLViewWindow::makeObjetTree(const GLObjectBase * o, QTreeWidgetItem * ti) if (o == axis) return; for (int i = 0; i < o->childCount(); ++i) { const GLObjectBase * co = o->child(i); - QTreeWidgetItem * ci = new QTreeWidgetItem(ti); + QTreeWidgetItem * ci = new QTreeWidgetItem(ti); ci->setText(0, co->name()); ci->setData(0, Qt::UserRole, quintptr(co)); switch (co->type()) { @@ -195,22 +203,22 @@ void QGLViewWindow::makeObjetTree(const GLObjectBase * o, QTreeWidgetItem * ti) void QGLViewWindow::selectionChanged(GLObjectBase * cur, GLObjectBase *) { sel_obj = cur; - //qDebug() << "selected" << (cur != 0 ? cur->name() : "0"); + // qDebug() << "selected" << (cur != 0 ? cur->name() : "0"); labelName->setText(cur != nullptr ? cur->name() : ""); /**if (cur == 0) box->hide(); else { - box->setScale(cur->boundingBox().size()); - box->setPos(cur->boundingBox().pos()); - Box3D b = cur->boundingBox().movedTo(-cur->boundingBox().center()); - b.z = -b.z - b.height; - ps->setEmitterRect(b); - cur->addChild(box); - box->show(); + box->setScale(cur->boundingBox().size()); + box->setPos(cur->boundingBox().pos()); + Box3D b = cur->boundingBox().movedTo(-cur->boundingBox().center()); + b.z = -b.z - b.height; + ps->setEmitterRect(b); + cur->addChild(box); + box->show(); }*/ objectEditor->setObject(sel_obj); if (sel_obj == nullptr) return; matEditor->setMaterial(sel_obj->material()); - //qDebug() << sel_obj->boundingBox(); + // qDebug() << sel_obj->boundingBox(); } @@ -224,8 +232,10 @@ void QGLViewWindow::on_comboRenderer_currentIndexChanged(int val) { GLRendererBase * pr = nullptr; switch (val) { case 0: view->view()->setRenderer(new RendererSimple(view->view()), &pr); break; - case 1: view->view()->setRenderer(new RendererDeferredShading(view->view()), &pr); break; - //case 2: view->view()->setRenderer(new RendererRT(view), &pr); break; + case 1: + view->view()->setRenderer(new RendererDeferredShading(view->view()), &pr); + break; + // case 2: view->view()->setRenderer(new RendererRT(view), &pr); break; } if (pr != nullptr) delete pr; } @@ -240,15 +250,18 @@ void QGLViewWindow::on_actionReset_triggered() { void QGLViewWindow::on_actionImport_triggered() { - QStringList fl = QFileDialog::getOpenFileNames(this, "Select files", prev_path, "Supported types(*.qgl *.ase *.3ds *.obj *.dae);;" - "QGLView(*.qgl);;" - "Ascii Scene Export(*.ase);;" - "3D Studio(*.3ds);;" - "Wavefront OBJ(*.obj);;" - "Collada(*.dae)"); + QStringList fl = QFileDialog::getOpenFileNames(this, + "Select files", + prev_path, + "Supported types(*.qgl *.ase *.3ds *.obj *.dae);;" + "QGLView(*.qgl);;" + "Ascii Scene Export(*.ase);;" + "3D Studio(*.3ds);;" + "Wavefront OBJ(*.obj);;" + "Collada(*.dae)"); if (fl.isEmpty()) return; prev_path = fl.back(); - foreach (QString f, fl) + foreach(QString f, fl) importFile(f); } @@ -256,8 +269,7 @@ void QGLViewWindow::on_actionImport_triggered() { void QGLViewWindow::on_actionSave_triggered() { QString f = QFileDialog::getSaveFileName(this, "Select file", prev_path, "QGLView(*.qgl)"); if (f.isEmpty()) return; - if (f.right(4).toLower() != ".qgl") - f += ".qgl"; + if (f.right(4).toLower() != ".qgl") f += ".qgl"; prev_path = f; view->view()->removeObject(axis); QApplication::setOverrideCursor(Qt::WaitCursor); @@ -271,8 +283,7 @@ void QGLViewWindow::on_actionSaveSelected_triggered() { if (!sel_obj) return; QString f = QFileDialog::getSaveFileName(this, "Select file", prev_path, "QGLView(*.qgl)"); if (f.isEmpty()) return; - if (f.right(4).toLower() != ".qgl") - f += ".qgl"; + if (f.right(4).toLower() != ".qgl") f += ".qgl"; prev_path = f; QApplication::setOverrideCursor(Qt::WaitCursor); saveToQGLFile(f, sel_obj); @@ -281,12 +292,15 @@ void QGLViewWindow::on_actionSaveSelected_triggered() { void QGLViewWindow::on_actionOpen_triggered() { - QString f = QFileDialog::getOpenFileName(this, "Select file", prev_path, "Supported types(*.qgl *.ase *.3ds *.obj *.dae);;" - "QGLView(*.qgl);;" - "Ascii Scene Export(*.ase);;" - "3D Studio(*.3ds);;" - "Wavefront OBJ(*.obj);;" - "Collada(*.dae)"); + QString f = QFileDialog::getOpenFileName(this, + "Select file", + prev_path, + "Supported types(*.qgl *.ase *.3ds *.obj *.dae);;" + "QGLView(*.qgl);;" + "Ascii Scene Export(*.ase);;" + "3D Studio(*.3ds);;" + "Wavefront OBJ(*.obj);;" + "Collada(*.dae)"); if (f.isEmpty()) return; prev_path = f; importFile(f); @@ -294,10 +308,9 @@ void QGLViewWindow::on_actionOpen_triggered() { void QGLViewWindow::view_keyEvent(Qt::Key k, Qt::KeyboardModifiers m) { - //qDebug() << k; + // qDebug() << k; double spd = 0.2; - if (m.testFlag(Qt::ShiftModifier)) - spd = 0.5; + if (m.testFlag(Qt::ShiftModifier)) spd = 0.5; switch (k) { case Qt::Key_W: view->view()->camera()->moveForward(spd); break; case Qt::Key_S: view->view()->camera()->moveBackward(spd); break; @@ -309,17 +322,16 @@ void QGLViewWindow::view_keyEvent(Qt::Key k, Qt::KeyboardModifiers m) { void QGLViewWindow::on_treeObjects_itemClicked(QTreeWidgetItem * ti, int) { - ((GLObjectBase*)(ti->data(0, Qt::UserRole).toULongLong()))->select(); - //qDebug() << ((GLObjectBase*)(ti->data(0, Qt::UserRole).toULongLong()))->type(); - if (sel_obj->type() == GLObjectBase::glCamera) - view->view()->setCamera((Camera*)sel_obj); + ((GLObjectBase *)(ti->data(0, Qt::UserRole).toULongLong()))->select(); + // qDebug() << ((GLObjectBase*)(ti->data(0, Qt::UserRole).toULongLong()))->type(); + if (sel_obj->type() == GLObjectBase::glCamera) view->view()->setCamera((Camera *)sel_obj); } void QGLViewWindow::removeObjects() { - QList sil = treeObjects->selectedItems(); - foreach (QTreeWidgetItem * i, sil) { - GLObjectBase * o = (GLObjectBase*)(i->data(0, Qt::UserRole).toULongLong()); + QList sil = treeObjects->selectedItems(); + foreach(QTreeWidgetItem * i, sil) { + GLObjectBase * o = (GLObjectBase *)(i->data(0, Qt::UserRole).toULongLong()); delete o; } qDeleteAll(sil); @@ -334,20 +346,19 @@ void QGLViewWindow::objectsTreeChanged() { void QGLViewWindow::on_pushButton_clicked() { - //view->view()->removeLight(view->view()->lightsCount() - 1); - //setWindowTitle(QString::number(view->view()->lightsCount())); + // view->view()->removeLight(view->view()->lightsCount() - 1); + // setWindowTitle(QString::number(view->view()->lightsCount())); QVector3D wp = view->view()->light(0)->worldPos(); view->view()->camera()->setPos(wp); - view->view()->camera()->setAim(wp + (view->view()->light(0)->worldTransform() * QVector4D(view->view()->light(0)->direction)).toVector3D()*100); + view->view()->camera()->setAim( + wp + (view->view()->light(0)->worldTransform() * QVector4D(view->view()->light(0)->direction)).toVector3D() * 100); } void QGLViewWindow::on_pushButton_3_clicked() { - QList ol = view->view()->objects(true); + QList ol = view->view()->objects(true); qDebug() << ol.size(); - foreach (GLObjectBase * i, ol) { + foreach(GLObjectBase * i, ol) { i->VBO().rebuffer(); } } - - diff --git a/libs/qglview/qglview_test/qglview_window.h b/libs/qglview/qglview_test/qglview_window.h index 97062d5..1252614 100644 --- a/libs/qglview/qglview_test/qglview_window.h +++ b/libs/qglview/qglview_test/qglview_window.h @@ -19,32 +19,35 @@ #ifndef QGLVIEWWINDOW_H #define QGLVIEWWINDOW_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ui_qglview_window.h" #include "loader_3ds.h" #include "loader_ase.h" -#include "renderer_simple.h" #include "renderer_deferred_shading.h" +#include "renderer_simple.h" #include "session_manager.h" -//#include "renderer_rt.h" +#include "ui_qglview_window.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include "renderer_rt.h" #include "glparticles_system.h" #include "qglview.h" #include "ui_qglview_window.h" -class QGLViewWindow: public QMainWindow, public Ui::QGLViewWindow -{ +class QGLViewWindow + : public QMainWindow + , public Ui::QGLViewWindow { Q_OBJECT + public: QGLViewWindow(QWidget * parent = 0); ~QGLViewWindow(); @@ -54,7 +57,7 @@ public: private: // Qt`s overloaded void changeEvent(QEvent * e); - void timerEvent(QTimerEvent * ); + void timerEvent(QTimerEvent *); void importFile(const QString & path); void makeObjetTree(const GLObjectBase * o, QTreeWidgetItem * ti); @@ -62,7 +65,7 @@ private: QTranslator translator; QIcon icon_geo, icon_camera, icon_light; QString prev_path; - GLObjectBase * sel_obj, * axis; + GLObjectBase *sel_obj, *axis; Light * cam_light; GLPrimitiveCube * box; Material m; @@ -72,48 +75,51 @@ private: GLParticlesSystem partsys; private slots: - void on_spinFOV_valueChanged(double val) {view->view()->setFOV(val);} - void on_spinDepthStart_valueChanged(double val) {view->view()->setDepthStart(val);} - void on_spinDepthEnd_valueChanged(double val) {view->view()->setDepthEnd(val);} + void on_spinFOV_valueChanged(double val) { view->view()->setFOV(val); } + void on_spinDepthStart_valueChanged(double val) { view->view()->setDepthStart(val); } + void on_spinDepthEnd_valueChanged(double val) { view->view()->setDepthEnd(val); } void on_comboRenderer_currentIndexChanged(int val); - void on_comboViewRenderMode_currentIndexChanged(int val) {static int modes[] = {GL_POINT, GL_LINE, GL_FILL}; view->view()->setRenderMode((GLObjectBase::RenderMode)modes[val]);} - void on_groupHoverHalo_clicked(bool val) {view->view()->setHoverHaloEnabled(val);} - void on_groupSelectionHalo_clicked(bool val) {view->view()->setSelectionHaloEnabled(val);} - void on_spinHoverHaloFill_valueChanged(double val) {view->view()->setHoverHaloFillAlpha(val);} - void on_spinSelectionHaloFill_valueChanged(double val) {view->view()->setSelectionHaloFillAlpha(val);} - void on_colorHoverHalo_colorChanged(QColor color) {view->view()->setHoverHaloColor(color);} - void on_colorSelectionHalo_colorChanged(QColor color) {view->view()->setSelectionHaloColor(color);} - void on_checkFXAA_clicked(bool val) {view->view()->setFeature(QGLView::qglFXAA, val);} - void on_checkMSAA_clicked(bool val) {view->view()->setFeature(QGLView::qglMSAA, val);} - void on_colorBack_colorChanged(QColor color) {view->view()->setBackColor(color);} - void on_colorAmbient_colorChanged(QColor color) {view->view()->setAmbientColor(color);} - void on_checkCameraOrbit_clicked(bool val) {view->view()->setCameraOrbit(val);} - void on_spinViewLineWidth_valueChanged(double val) {view->view()->setLineWidth(val);} + void on_comboViewRenderMode_currentIndexChanged(int val) { + static int modes[] = {GL_POINT, GL_LINE, GL_FILL}; + view->view()->setRenderMode((GLObjectBase::RenderMode)modes[val]); + } + void on_groupHoverHalo_clicked(bool val) { view->view()->setHoverHaloEnabled(val); } + void on_groupSelectionHalo_clicked(bool val) { view->view()->setSelectionHaloEnabled(val); } + void on_spinHoverHaloFill_valueChanged(double val) { view->view()->setHoverHaloFillAlpha(val); } + void on_spinSelectionHaloFill_valueChanged(double val) { view->view()->setSelectionHaloFillAlpha(val); } + void on_colorHoverHalo_colorChanged(QColor color) { view->view()->setHoverHaloColor(color); } + void on_colorSelectionHalo_colorChanged(QColor color) { view->view()->setSelectionHaloColor(color); } + void on_checkFXAA_clicked(bool val) { view->view()->setFeature(QGLView::qglFXAA, val); } + void on_checkMSAA_clicked(bool val) { view->view()->setFeature(QGLView::qglMSAA, val); } + void on_colorBack_colorChanged(QColor color) { view->view()->setBackColor(color); } + void on_colorAmbient_colorChanged(QColor color) { view->view()->setAmbientColor(color); } + void on_checkCameraOrbit_clicked(bool val) { view->view()->setCameraOrbit(val); } + void on_spinViewLineWidth_valueChanged(double val) { view->view()->setLineWidth(val); } - void on_groupShadows_clicked(bool val) {view->view()->setFeature(QGLView::qglShadowsEnabled, val);} - void on_groupEyeAccomodation_clicked(bool val) {view->view()->setFeature(QGLView::qglEyeAccomodationEnabled, val);} - void on_groupBloom_clicked(bool val) {view->view()->setFeature(QGLView::qglBloomEnabled, val);} - void on_groupMotionBlur_clicked(bool val) {view->view()->setFeature(QGLView::qglMotionBlurEnabled, val);} - void on_groupReflections_clicked(bool val) {view->view()->setFeature(QGLView::qglReflectionsEnabled, val);} - void on_checkSoftShadows_clicked(bool val) {view->view()->setFeature(QGLView::qglShadowsSoftEnabled, val);} - void on_groupSSAO_clicked(bool val) {view->view()->setFeature(QGLView::qglSSAOEnabled, val);} - void on_groupDOF_clicked(bool val) {view->view()->setFeature(QGLView::qglDepthOfFieldEnabled, val);} - void on_checkDOFAutoFocus_clicked(bool val) {view->view()->setFeature(QGLView::qglDepthOfFieldAutoFocusEnabled, val);} - void on_spinDOFFocus_valueChanged(double val) {view->view()->setFeature(QGLView::qglDepthOfFieldFocus, val);} - void on_spinDOFDiaphragm_valueChanged(double val) {view->view()->setFeature(QGLView::qglDepthOfFieldDiaphragm, val);} - void on_spinDOFSpeed_valueChanged(double val) {view->view()->setFeature(QGLView::qglDepthOfFieldAutoFocusSpeed, val);} - void on_spinAccom_valueChanged(double val) {view->view()->setFeature(QGLView::qglEyeAccomodationTime, val);} - void on_spinAccomMS_valueChanged(double val) {view->view()->setFeature(QGLView::qglEyeAccomodationMaxSpeed, val);} - void on_checkReflectionsBlur_clicked(bool val) {view->view()->setFeature(QGLView::qglReflectionsBlur, val);} - void on_spinShadowmapSize_valueChanged(double val) {view->view()->setFeature(QGLView::qglShadowsMapSize, val);} - void on_spinMotionBlurFactor_valueChanged(double val) {view->view()->setFeature(QGLView::qglMotionBlurFactor, val);} - void on_spinMotionBlurSteps_valueChanged(int val) {view->view()->setFeature(QGLView::qglMotionBlurSteps, val);} - void on_spinBloomFactor_valueChanged(double val) {view->view()->setFeature(QGLView::qglBloomFactor, val);} - void on_spinBloomRadius_valueChanged(int val) {view->view()->setFeature(QGLView::qglBloomRadius, val);} - void on_spinBloomThreshold_valueChanged(double val) {view->view()->setFeature(QGLView::qglBloomThreshold, val);} - void on_spinSSAORadius_valueChanged(int val) {view->view()->setFeature(QGLView::qglSSAORadius, val);} + void on_groupShadows_clicked(bool val) { view->view()->setFeature(QGLView::qglShadowsEnabled, val); } + void on_groupEyeAccomodation_clicked(bool val) { view->view()->setFeature(QGLView::qglEyeAccomodationEnabled, val); } + void on_groupBloom_clicked(bool val) { view->view()->setFeature(QGLView::qglBloomEnabled, val); } + void on_groupMotionBlur_clicked(bool val) { view->view()->setFeature(QGLView::qglMotionBlurEnabled, val); } + void on_groupReflections_clicked(bool val) { view->view()->setFeature(QGLView::qglReflectionsEnabled, val); } + void on_checkSoftShadows_clicked(bool val) { view->view()->setFeature(QGLView::qglShadowsSoftEnabled, val); } + void on_groupSSAO_clicked(bool val) { view->view()->setFeature(QGLView::qglSSAOEnabled, val); } + void on_groupDOF_clicked(bool val) { view->view()->setFeature(QGLView::qglDepthOfFieldEnabled, val); } + void on_checkDOFAutoFocus_clicked(bool val) { view->view()->setFeature(QGLView::qglDepthOfFieldAutoFocusEnabled, val); } + void on_spinDOFFocus_valueChanged(double val) { view->view()->setFeature(QGLView::qglDepthOfFieldFocus, val); } + void on_spinDOFDiaphragm_valueChanged(double val) { view->view()->setFeature(QGLView::qglDepthOfFieldDiaphragm, val); } + void on_spinDOFSpeed_valueChanged(double val) { view->view()->setFeature(QGLView::qglDepthOfFieldAutoFocusSpeed, val); } + void on_spinAccom_valueChanged(double val) { view->view()->setFeature(QGLView::qglEyeAccomodationTime, val); } + void on_spinAccomMS_valueChanged(double val) { view->view()->setFeature(QGLView::qglEyeAccomodationMaxSpeed, val); } + void on_checkReflectionsBlur_clicked(bool val) { view->view()->setFeature(QGLView::qglReflectionsBlur, val); } + void on_spinShadowmapSize_valueChanged(double val) { view->view()->setFeature(QGLView::qglShadowsMapSize, val); } + void on_spinMotionBlurFactor_valueChanged(double val) { view->view()->setFeature(QGLView::qglMotionBlurFactor, val); } + void on_spinMotionBlurSteps_valueChanged(int val) { view->view()->setFeature(QGLView::qglMotionBlurSteps, val); } + void on_spinBloomFactor_valueChanged(double val) { view->view()->setFeature(QGLView::qglBloomFactor, val); } + void on_spinBloomRadius_valueChanged(int val) { view->view()->setFeature(QGLView::qglBloomRadius, val); } + void on_spinBloomThreshold_valueChanged(double val) { view->view()->setFeature(QGLView::qglBloomThreshold, val); } + void on_spinSSAORadius_valueChanged(int val) { view->view()->setFeature(QGLView::qglSSAORadius, val); } - void on_actionExit_triggered() {close();} + void on_actionExit_triggered() { close(); } void on_actionReset_triggered(); void on_actionImport_triggered(); void on_actionSave_triggered(); @@ -130,7 +136,7 @@ private slots: void selectionChanged(GLObjectBase * cur, GLObjectBase *); void on_pushButton_clicked(); - void on_pushButton_2_clicked() {view->view()->reloadShaders();} + void on_pushButton_2_clicked() { view->view()->reloadShaders(); } void on_pushButton_3_clicked(); public slots: @@ -139,7 +145,6 @@ signals: private: QMatrix4x4 cam_mat; - }; #endif // QGLVIEWWINDOW_H diff --git a/libs/qglview/renderer_deferred_shading.cpp b/libs/qglview/renderer_deferred_shading.cpp index 9a371b5..e9e6c37 100644 --- a/libs/qglview/renderer_deferred_shading.cpp +++ b/libs/qglview/renderer_deferred_shading.cpp @@ -17,35 +17,29 @@ */ #include "renderer_deferred_shading.h" + #include -RendererDeferredShading::RendererDeferredShading(QGLView * view_): GLRendererBase(view_), -fbo_g(5, true, GL_RGBA16F), fbo_out(3, false, GL_RGBA16F), fbo_hsmall(1, false, GL_RGB16F) { - shaders << ShaderPair("FXAA", &shader_fxaa) - << ShaderPair("dsl_pass_0", &shader_ds_0) - << ShaderPair("dsl_pass_1", &shader_ds_1) - << ShaderPair("hdr", &shader_hdr) - << ShaderPair("downscale", &shader_small) - << ShaderPair("bloom_pass_0", &shader_bloom_0) - << ShaderPair("bloom_pass_1", &shader_bloom_1) - << ShaderPair("fbo_add", &shader_fbo_add) - << ShaderPair("motion_blur", &shader_motion_blur) - << ShaderPair("shadow", &shader_shadow) - << ShaderPair("ssr", &shader_ssr) - << ShaderPair("ssr_blur", &shader_ssr_blur) - << ShaderPair("ssr_merge", &shader_ssr_merge) - << ShaderPair("ssao_blur", &shader_ssao_blur) - << ShaderPair("ssao_merge", &shader_ssao_merge) - << ShaderPair("dof", &shader_dof); +RendererDeferredShading::RendererDeferredShading(QGLView * view_) + : GLRendererBase(view_) + , fbo_g(5, true, GL_RGBA16F) + , fbo_out(3, false, GL_RGBA16F) + , fbo_hsmall(1, false, GL_RGB16F) { + shaders << ShaderPair("FXAA", &shader_fxaa) << ShaderPair("dsl_pass_0", &shader_ds_0) << ShaderPair("dsl_pass_1", &shader_ds_1) + << ShaderPair("hdr", &shader_hdr) << ShaderPair("downscale", &shader_small) << ShaderPair("bloom_pass_0", &shader_bloom_0) + << ShaderPair("bloom_pass_1", &shader_bloom_1) << ShaderPair("fbo_add", &shader_fbo_add) + << ShaderPair("motion_blur", &shader_motion_blur) << ShaderPair("shadow", &shader_shadow) << ShaderPair("ssr", &shader_ssr) + << ShaderPair("ssr_blur", &shader_ssr_blur) << ShaderPair("ssr_merge", &shader_ssr_merge) + << ShaderPair("ssao_blur", &shader_ssao_blur) << ShaderPair("ssao_merge", &shader_ssao_merge) << ShaderPair("dof", &shader_dof); for (int i = 0; i < shaders.size(); ++i) *(shaders[i].second) = nullptr; lights_per_pass = 8; - tnoise = 0; - exposure_ = 1.; - df = new QWidget(); + tnoise = 0; + exposure_ = 1.; + df = new QWidget(); df->setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); - label_exp = new QLabel(); + label_exp = new QLabel(); label_exp_step = new QLabel(); df->layout()->addWidget(label_exp); df->layout()->addWidget(label_exp_step); @@ -53,7 +47,7 @@ fbo_g(5, true, GL_RGBA16F), fbo_out(3, false, GL_RGBA16F), fbo_hsmall(1, false, pal.setBrush(QPalette::Window, QColor(255, 255, 255, 192)); df->setPalette(pal); if (view_) - ;//view_->addObject(df); + ; // view_->addObject(df); } @@ -67,24 +61,24 @@ RendererDeferredShading::~RendererDeferredShading() { void RendererDeferredShading::renderScene() { - //qDebug() << lights_per_pass; - QMatrix4x4 mproj = rp.proj_matrix; - QMatrix4x4 mproji = rp.proj_matrix_i; - QMatrix4x4 mview = rp.view_matrix; - QMatrix4x4 mviewi = rp.view_matrix_i; + // qDebug() << lights_per_pass; + QMatrix4x4 mproj = rp.proj_matrix; + QMatrix4x4 mproji = rp.proj_matrix_i; + QMatrix4x4 mview = rp.view_matrix; + QMatrix4x4 mviewi = rp.view_matrix_i; QMatrix4x4 mviewproji = (mproj * mview).inverted(); - QMatrix4x4 moffset = view.camera()->offsetMatrix(); - QMatrix4x4 moffseti = moffset.inverted(); - rp.prev_proj_matrix = prev_proj; - rp.prev_view_matrix = prev_view; + QMatrix4x4 moffset = view.camera()->offsetMatrix(); + QMatrix4x4 moffseti = moffset.inverted(); + rp.prev_proj_matrix = prev_proj; + rp.prev_view_matrix = prev_view; QMatrix4x4 vc_proji; vc_proji.perspective(90., 1., view.camera()->depthStart(), view.camera()->depthEnd()); - vc_proji = vc_proji.inverted(); + vc_proji = vc_proji.inverted(); corner_dirs[0] = (mproji * QVector4D(-1, -1, 0, 1)); - corner_dirs[1] = (mproji * QVector4D( 1, -1, 0, 1)); - corner_dirs[2] = (mproji * QVector4D(-1, 1, 0, 1)); - corner_dirs[3] = (mproji * QVector4D( 1, 1, 0, 1)); - //qDebug() << corner_dirs[0] << corner_dirs[1] << corner_dirs[2] << corner_dirs[3]; + corner_dirs[1] = (mproji * QVector4D(1, -1, 0, 1)); + corner_dirs[2] = (mproji * QVector4D(-1, 1, 0, 1)); + corner_dirs[3] = (mproji * QVector4D(1, 1, 0, 1)); + // qDebug() << corner_dirs[0] << corner_dirs[1] << corner_dirs[2] << corner_dirs[3]; fbo_g.bind(); int buffs[] = {0, 1, 2, 3, 4}; fbo_g.setWriteBuffers(buffs, 5); @@ -113,10 +107,10 @@ void RendererDeferredShading::renderScene() { shader_ds_0->setUniformValue("t3", 3); shader_ds_0->setUniformValue("t4", 4); shader_ds_0->setUniformValue("dt", QVector2D(1.f / view.width(), 1.f / view.height())); - //qDebug() << rp.view_matrix << prev_view; - //shader_ds_0->setUniformValue("qgl_ModelViewMatrix", rp.view_matrix); + // qDebug() << rp.view_matrix << prev_view; + // shader_ds_0->setUniformValue("qgl_ModelViewMatrix", rp.view_matrix); renderObjects(GLObjectBase::Solid, 0, shader_ds_0, true, false, false); - //glReleaseShaders(); + // glReleaseShaders(); fbo_g.release(); if (view.isFeatureEnabled(QGLView::qglShadowsEnabled)) { @@ -133,7 +127,7 @@ void RendererDeferredShading::renderScene() { glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); - //qDebug() << "render shadows"; + // qDebug() << "render shadows"; for (int i = 0; i < view.lightsCount(); ++i) { Light * l = view.light(i); if (l->light_type == Light::Omni) continue; @@ -141,26 +135,26 @@ void RendererDeferredShading::renderScene() { l->shadow_map.bind(); l->shadow_map.setWriteBuffer(0); glClearFramebuffer(); - //glClear(GL_DEPTH_BUFFER_BIT); - renderShadow(l, shader_shadow, moffseti*mviewi); + // glClear(GL_DEPTH_BUFFER_BIT); + renderShadow(l, shader_shadow, moffseti * mviewi); l->shadow_map.release(); } } -// glUseProgram(0); -//// fbo_g.bindColorTextures(); -// glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(0)); -// glActiveTexture(GL_TEXTURE0); -// glDrawQuad(); -// return; + // glUseProgram(0); + //// fbo_g.bindColorTextures(); + // glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(0)); + // glActiveTexture(GL_TEXTURE0); + // glDrawQuad(); + // return; glResetAllTransforms(); glSetLightEnabled(false); glEnable(GL_TEXTURE_2D); glDisable(GL_BLEND); - //glBlendFunc(GL_ONE, GL_ONE); + // glBlendFunc(GL_ONE, GL_ONE); glDisableDepth(); rp.prepare(); - //qDebug() << rp.view_matrix; + // qDebug() << rp.view_matrix; shader_ds_1->bind(); shader_ds_1->setUniformValue("z_far", view.depthEnd()); shader_ds_1->setUniformValue("z_near", view.depthStart()); @@ -183,25 +177,25 @@ void RendererDeferredShading::renderScene() { fbo_out.bind(); fbo_out.setWriteBuffer(0); glClearFramebuffer(Qt::black, false); - //QVector lpos; - //qDebug() << view_matrix; + // QVector lpos; + // qDebug() << view_matrix; shader_ds_1->setUniformValue("t_pp", 6); int passes = (view.lightsCount() - 1) / lights_per_pass + 1; if (passes < 1) passes = 1; - //qDebug() << "render in" << passes << "passes (" << lights_per_pass << ")"; + // qDebug() << "render in" << passes << "passes (" << lights_per_pass << ")"; int wi, ri; for (int l = 0; l < passes; ++l) { wi = 1 - l % 2; ri = l % 2; - //qDebug() << " pass" << l << "read from" << ri << "write to" << wi; + // qDebug() << " pass" << l << "read from" << ri << "write to" << wi; glActiveTexture(GL_TEXTURE0 + 6); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); fbo_out.setWriteBuffer(wi); setupDSLights(l, mview * moffset); glDrawQuad(shader_ds_1, corner_dirs); - //break; + // break; } - //fbo_out.release(); + // fbo_out.release(); wi = 1 - passes % 2; ri = passes % 2; glActiveTexture(GL_TEXTURE0); @@ -210,16 +204,25 @@ void RendererDeferredShading::renderScene() { if (view.isFeatureEnabled(QGLView::qglSSAOEnabled)) { fbo_out.setWriteBuffer(2); fbo_out.setReadBuffer(ri); - glBlitFramebuffer(0, 0, fbo_out.width(), fbo_out.height(), 0, 0, fbo_out.width(), fbo_out.height(), GL_COLOR_BUFFER_BIT, GL_NEAREST); + glBlitFramebuffer(0, + 0, + fbo_out.width(), + fbo_out.height(), + 0, + 0, + fbo_out.width(), + fbo_out.height(), + GL_COLOR_BUFFER_BIT, + GL_NEAREST); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(2)); glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(1)); glActiveTexture(GL_TEXTURE0); - //glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); - //glActiveTextureChannel(1); - //glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(0)); - int lri = ri, lwi = wi;//, lms = ri; + // glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); + // glActiveTextureChannel(1); + // glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(0)); + int lri = ri, lwi = wi; //, lms = ri; shader_ssao_blur->bind(); shader_ssao_blur->setUniformValue("qgl_ModelViewProjectionMatrix", QMatrix4x4()); shader_ssao_blur->setUniformValue("dt", QVector2D(1.f / fbo_out.width(), 1.f / fbo_out.height())); @@ -227,7 +230,7 @@ void RendererDeferredShading::renderScene() { shader_ssao_blur->setUniformValue("ts", 1); shader_ssao_blur->setUniformValue("tg1", 2); int passes = view.feature(QGLView::qglSSAORadius).toInt(); - int crad = 1; + int crad = 1; for (int p = 0; p < passes; ++p) { glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(lri)); fbo_out.setWriteBuffer(lwi); @@ -236,7 +239,7 @@ void RendererDeferredShading::renderScene() { piSwap(lwi, lri); crad *= 2; } - //qDebug() << wi << ri << lms; + // qDebug() << wi << ri << lms; /*wi = lri; ri = 1 - lms;*/ glEnable(GL_TEXTURE_1D); @@ -244,9 +247,9 @@ void RendererDeferredShading::renderScene() { glGenTextures(1, &tnoise); glBindTexture(GL_TEXTURE_1D, tnoise); QByteArray ba; - for (int i = 0; i < 32*3; ++i) + for (int i = 0; i < 32 * 3; ++i) ba.push_back(char(random() % 256)); - //qDebug() << ba; + // qDebug() << ba; glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB8, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, ba.constData()); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -277,11 +280,11 @@ void RendererDeferredShading::renderScene() { glDisable(GL_TEXTURE_1D); wi = lri; ri = lwi; - //piSwap(wi, ri); + // piSwap(wi, ri); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); - //piSwap(wi, ri); + // piSwap(wi, ri); } if (view.isFeatureEnabled(QGLView::qglReflectionsEnabled)) { @@ -289,8 +292,8 @@ void RendererDeferredShading::renderScene() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//_MIPMAP_LINEAR); - //glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //_MIPMAP_LINEAR); + // glGenerateMipmap(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, fbo_g.colorTexture(0)); glActiveTexture(GL_TEXTURE0 + 2); @@ -315,11 +318,11 @@ void RendererDeferredShading::renderScene() { shader_ssr_blur->setUniformValue("dt", QVector2D(1.f / fbo_out.width(), 1.f / fbo_out.height())); shader_ssr_blur->setUniformValue("t0", 0); int passes = 5; - int crad = 1; + int crad = 1; for (int p = 0; p < passes; ++p) { glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(lri)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //_MIPMAP_LINEAR); fbo_out.setWriteBuffer(lwi); shader_ssr_blur->setUniformValue("radius", GLfloat(crad)); glDrawQuad(shader_ssr_blur); @@ -327,7 +330,7 @@ void RendererDeferredShading::renderScene() { crad *= 2; } } - //qDebug() << wi << ri << lms; + // qDebug() << wi << ri << lms; wi = lri; ri = 1 - lms; @@ -345,7 +348,7 @@ void RendererDeferredShading::renderScene() { glDrawQuad(shader_ssr_merge); wi = ri; ri = 1 - ri; - //piSwap(wi, ri); + // piSwap(wi, ri); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(wi)); @@ -355,16 +358,16 @@ void RendererDeferredShading::renderScene() { if (view.isFeatureEnabled(QGLView::qglDepthOfFieldEnabled)) { if (view.isFeatureEnabled(QGLView::qglDepthOfFieldAutoFocusEnabled)) { GLfloat cw; - //glReadBuffer(); + // glReadBuffer(); fbo_g.bind(); glReadPixels(fbo_out.width() / 2, fbo_out.height() / 2, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &cw); fbo_out.bind(); const float _pe = 2.4e-7f; - float cz = cw + cw - 1; - cz = ((_pe - 2.f) * view.depthStart()) / (cz + _pe - 1.f); // infinite depth - float z = view.feature(QGLView::qglDepthOfFieldFocus).toFloat(), - s = view.feature(QGLView::qglDepthOfFieldAutoFocusSpeed).toFloat(); - z = z * (1.f - s) + cz * s; + float cz = cw + cw - 1; + cz = ((_pe - 2.f) * view.depthStart()) / (cz + _pe - 1.f); // infinite depth + float z = view.feature(QGLView::qglDepthOfFieldFocus).toFloat(), + s = view.feature(QGLView::qglDepthOfFieldAutoFocusSpeed).toFloat(); + z = z * (1.f - s) + cz * s; view.setFeature(QGLView::qglDepthOfFieldFocus, z); } shader_dof->bind(); @@ -408,33 +411,34 @@ void RendererDeferredShading::renderScene() { glDrawQuad(shader_small); hcontent.resize(fbo_hsmall.width() * fbo_hsmall.height()); glReadPixels(0, 0, fbo_hsmall.width(), fbo_hsmall.height(), GL_RGB, GL_FLOAT, hcontent.data()); - GLfloat max[3] = {0.,0.,0.};//min[3] = {10000.,10000.,10000.},; + GLfloat max[3] = {0., 0., 0.}; // min[3] = {10000.,10000.,10000.},; for (int i = 0; i < hcontent.size(); ++i) { - //if (min[0] > hcontent[i].x) min[0] = hcontent[i].x; + // if (min[0] > hcontent[i].x) min[0] = hcontent[i].x; if (max[0] < hcontent[i].x) max[0] = hcontent[i].x; - //if (min[1] > hcontent[i].y) min[1] = hcontent[i].y; + // if (min[1] > hcontent[i].y) min[1] = hcontent[i].y; if (max[1] < hcontent[i].y) max[1] = hcontent[i].y; - //if (min[2] > hcontent[i].z) min[2] = hcontent[i].z; + // if (min[2] > hcontent[i].z) min[2] = hcontent[i].z; if (max[2] < hcontent[i].z) max[2] = hcontent[i].z; } GLfloat mluma = (0.299f * max[0]) + (0.587f * max[1]) + (0.114f * max[2]); - float nexp = mluma / 16.f, dexp = nexp - exposure_, mestep = exposure_ * view.feature(QGLView::qglEyeAccomodationMaxSpeed).toFloat(); + float nexp = mluma / 16.f, dexp = nexp - exposure_, + mestep = exposure_ * view.feature(QGLView::qglEyeAccomodationMaxSpeed).toFloat(); dexp /= view.feature(QGLView::qglEyeAccomodationTime).toFloat(); - if (dexp > 0.f && dexp > mestep/4) dexp = mestep/4; + if (dexp > 0.f && dexp > mestep / 4) dexp = mestep / 4; if (dexp < 0.f && dexp < -mestep) dexp = -mestep; exposure_ += dexp; label_exp->setText(QString("exposure: %1").arg(exposure_)); label_exp_step->setText(QString("d_exposure: %1").arg(dexp)); - //qDebug() << min[0] << max[0] << min[1] << max[1] << min[2] << max[2]; + // qDebug() << min[0] << max[0] << min[1] << max[1] << min[2] << max[2]; fbo_hsmall.release(); - //glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); + // glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); fbo_out.bind(); fbo_out.setWriteBuffer(wi); shader_hdr->bind(); shader_hdr->setUniformValue("qgl_ModelViewProjectionMatrix", QMatrix4x4()); shader_hdr->setUniformValue("t0", 0); - shader_hdr->setUniformValue("exposure", GLfloat(1.f/exposure_)); + shader_hdr->setUniformValue("exposure", GLfloat(1.f / exposure_)); glDrawQuad(shader_hdr); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(wi)); piSwap(wi, ri); @@ -460,9 +464,18 @@ void RendererDeferredShading::renderScene() { if (view.isFeatureEnabled(QGLView::qglBloomEnabled)) { fbo_out.setWriteBuffer(2); fbo_out.setReadBuffer(ri); - glBlitFramebuffer(0, 0, fbo_out.width(), fbo_out.height(), 0, 0, fbo_out.width(), fbo_out.height(), GL_COLOR_BUFFER_BIT, GL_NEAREST); - //QTime tm; - //tm.restart(); + glBlitFramebuffer(0, + 0, + fbo_out.width(), + fbo_out.height(), + 0, + 0, + fbo_out.width(), + fbo_out.height(), + GL_COLOR_BUFFER_BIT, + GL_NEAREST); + // QTime tm; + // tm.restart(); fbo_out.setWriteBuffer(wi); shader_bloom_0->bind(); shader_bloom_0->setUniformValue("qgl_ModelViewProjectionMatrix", QMatrix4x4()); @@ -479,20 +492,19 @@ void RendererDeferredShading::renderScene() { shader_bloom_1->setUniformValue("t0", 0); int radius = view.feature(QGLView::qglBloomRadius).toInt(); int passes = qMax(int(ceil(log2(radius))), 1); - int crad = 1; + int crad = 1; for (int p = 0; p < passes; ++p) { glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); fbo_out.setWriteBuffer(wi); - if (p == passes - 1) - crad = piMax(1, radius - crad); + if (p == passes - 1) crad = piMax(1, radius - crad); shader_bloom_1->setUniformValue("radius", crad); glDrawQuad(shader_bloom_1); piSwap(wi, ri); crad *= 2; } - //qDebug() << tm.elapsed(); + // qDebug() << tm.elapsed(); fbo_out.setWriteBuffer(wi); -// glActiveTextureChannel(0); + // glActiveTextureChannel(0); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(ri)); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, fbo_out.colorTexture(2)); @@ -519,8 +531,7 @@ void RendererDeferredShading::renderScene() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } glDrawQuad(); - if (view.isFeatureEnabled(QGLView::qglFXAA)) - shader_fxaa->release(); + if (view.isFeatureEnabled(QGLView::qglFXAA)) shader_fxaa->release(); prev_proj = mproj; prev_view = mview; } @@ -536,8 +547,8 @@ void RendererDeferredShading::resize(int width, int height) { fbo_g.resize(width, height); fbo_out.resize(width, height); fbo_hsmall.resize(width / 16, height / 16); -// view.setSceneRect(QRect(0, 0, width, height)); - //df->move(-width / 2, -height / 2); + // view.setSceneRect(QRect(0, 0, width, height)); + // df->move(-width / 2, -height / 2); } @@ -561,15 +572,15 @@ void RendererDeferredShading::setupShadersTextures(GLObjectBase & object, GLRend void RendererDeferredShading::setupDSLights(int pass, const QMatrix4x4 & view_matrix) { int light_start, light_end, lmax, shadow_start = 7; - light_start = pass * lights_per_pass; - light_end = qMin((pass + 1) * lights_per_pass, view.lights().size()); - lmax = light_start + lights_per_pass; + light_start = pass * lights_per_pass; + light_end = qMin((pass + 1) * lights_per_pass, view.lights().size()); + lmax = light_start + lights_per_pass; amb_light.intensity = (pass == 0 ? 1. : 0.); amb_light.setColor(pass == 0 ? view.ambientColor() : Qt::black); amb_light.setName("ambient"); setUniformLight(shader_ds_1, &amb_light, "qgl_AmbientLight"); amb_light.intensity = 0.; - QVector lv; + QVector lv; for (int i = light_start; i < light_end; ++i) { lv << view.lights()[i]; glActiveTexture(GL_TEXTURE0 + shadow_start + i - light_start); @@ -586,12 +597,10 @@ void RendererDeferredShading::setupDSLights(int pass, const QMatrix4x4 & view_ma amb_light.setName("null"); for (int i = light_end; i < lmax; ++i) lv << &amb_light; - //QStringList lnl; foreach (Light * l, lv) lnl << l->name(); - //qDebug() << " lights" << light_start << "->" << light_end << ", inactive" << (lmax - light_end) << lnl; + // QStringList lnl; foreach (Light * l, lv) lnl << l->name(); + // qDebug() << " lights" << light_start << "->" << light_end << ", inactive" << (lmax - light_end) << lnl; setUniformLights(shader_ds_1, lv, view_matrix, shadow_start); } -void RendererDeferredShading::setupAmbientLight(const QColor & a, bool first_pass) { - -} +void RendererDeferredShading::setupAmbientLight(const QColor & a, bool first_pass) {} diff --git a/libs/qglview/renderer_deferred_shading.h b/libs/qglview/renderer_deferred_shading.h index abddc2d..adfea4a 100644 --- a/libs/qglview/renderer_deferred_shading.h +++ b/libs/qglview/renderer_deferred_shading.h @@ -20,11 +20,11 @@ #define RENDERER_DEFERRED_SHADING_H #include "qglview.h" + #include -class RendererDeferredShading: public GLRendererBase -{ +class RendererDeferredShading: public GLRendererBase { public: RendererDeferredShading(QGLView * view); virtual ~RendererDeferredShading(); @@ -36,7 +36,7 @@ public: protected: void setupShadersTextures(GLObjectBase & object, RenderingParameters & rp); - void setupShadersLights(int lights_count) {cplc = lights_count;} + void setupShadersLights(int lights_count) { cplc = lights_count; } void setupDSLights(int pass, const QMatrix4x4 & view_matrix); void setupAmbientLight(const QColor & a, bool first_pass); @@ -46,10 +46,10 @@ private: int cplc, lights_per_pass; float exposure_; GLFramebuffer fbo_g, fbo_out, fbo_hsmall; - QOpenGLShaderProgram * shader_fxaa, * shader_ds_0, * shader_ds_1, * shader_hdr, * shader_small; - QOpenGLShaderProgram * shader_bloom_0, * shader_bloom_1, * shader_motion_blur, * shader_fbo_add; - QOpenGLShaderProgram * shader_shadow, * shader_ssr, * shader_ssr_blur, * shader_ssr_merge; - QOpenGLShaderProgram * shader_ssao_blur, * shader_ssao_merge, * shader_dof; + QOpenGLShaderProgram *shader_fxaa, *shader_ds_0, *shader_ds_1, *shader_hdr, *shader_small; + QOpenGLShaderProgram *shader_bloom_0, *shader_bloom_1, *shader_motion_blur, *shader_fbo_add; + QOpenGLShaderProgram *shader_shadow, *shader_ssr, *shader_ssr_blur, *shader_ssr_merge; + QOpenGLShaderProgram *shader_ssao_blur, *shader_ssao_merge, *shader_dof; GLuint tnoise; QVector shaders; @@ -60,8 +60,7 @@ private: Light amb_light; QWidget * df; - QLabel * label_exp, * label_exp_step; - + QLabel *label_exp, *label_exp_step; }; #endif // RENDERER_DEFERRED_SHADING_H diff --git a/libs/qglview/renderer_simple.cpp b/libs/qglview/renderer_simple.cpp index 45444b6..a45d519 100644 --- a/libs/qglview/renderer_simple.cpp +++ b/libs/qglview/renderer_simple.cpp @@ -19,11 +19,13 @@ #include "renderer_simple.h" -RendererSimple::RendererSimple(QGLView * view_): GLRendererBase(view_), fbo(2) -, fbo_c(1, true, GL_RGBA32F) /// WARNING +RendererSimple::RendererSimple(QGLView * view_) + : GLRendererBase(view_) + , fbo(2) + , fbo_c(1, true, GL_RGBA32F) /// WARNING { shader_fxaa = 0; - shader = 0; /// WARNING + shader = 0; /// WARNING } @@ -33,8 +35,8 @@ void RendererSimple::reloadShaders() { loadShaders(shader_fxaa, "FXAA", "://shaders"); } /*if (shader == 0) { - shader = new QOpenGLShaderProgram(view.context()); /// WARNING - loadShaders(shader, "test", "shaders"); /// WARNING + shader = new QOpenGLShaderProgram(view.context()); /// WARNING + loadShaders(shader, "test", "shaders"); /// WARNING }*/ } @@ -48,12 +50,12 @@ void RendererSimple::resizeFBO(int w, int h) { void RendererSimple::renderScene() { int passes = (view.lightsCount() - 1) / 8 + 1; - //QMatrix4x4 pm = getGLMatrix(GL_PROJECTION_MATRIX), mvm = getGLMatrix(GL_MODELVIEW_MATRIX), pmvm = pm * mvm, lpm, lmvm, lpmvm; - //glSetCapEnabled(GL_MULTISAMPLE, view.isFeatureEnabled(QGLView::qglMSAA)); + // QMatrix4x4 pm = getGLMatrix(GL_PROJECTION_MATRIX), mvm = getGLMatrix(GL_MODELVIEW_MATRIX), pmvm = pm * mvm, lpm, lmvm, lpmvm; + // glSetCapEnabled(GL_MULTISAMPLE, view.isFeatureEnabled(QGLView::qglMSAA)); if (passes < 1) passes = 1; - //glEnable(GL_FOG); - //if (view.isFeatureEnabled(QGLView::qglFXAA)) fbo.bind(); - //glEnable(GL_TEXTURE_2D); + // glEnable(GL_FOG); + // if (view.isFeatureEnabled(QGLView::qglFXAA)) fbo.bind(); + // glEnable(GL_TEXTURE_2D); if (passes > 1 || view.isFeatureEnabled(QGLView::qglFXAA)) { fbo.bind(); fbo.setWriteBuffer(0); @@ -73,8 +75,8 @@ void RendererSimple::renderScene() { glClearFramebuffer(Qt::black, false); view.camera()->apply(view.aspect); } - //rp.cam_offset_matrix = view.camera()->offsetMatrix(); - //rp.prepare(); + // rp.cam_offset_matrix = view.camera()->offsetMatrix(); + // rp.prepare(); setupLights(l, 8); renderObjects(GLObjectBase::Solid, l, nullptr, true, view.isLightEnabled(), view.isFogEnabled()); renderObjects(GLObjectBase::Transparent, l, nullptr, true, true, view.isFogEnabled()); diff --git a/libs/qglview/renderer_simple.h b/libs/qglview/renderer_simple.h index 4eb8e93..b4d3869 100644 --- a/libs/qglview/renderer_simple.h +++ b/libs/qglview/renderer_simple.h @@ -21,16 +21,17 @@ #include "qglview.h" -class RendererSimple: public GLRendererBase -{ +class RendererSimple: public GLRendererBase { public: RendererSimple(QGLView * view); - virtual ~RendererSimple() {if (shader_fxaa != 0) delete shader_fxaa;} + virtual ~RendererSimple() { + if (shader_fxaa != 0) delete shader_fxaa; + } virtual void renderScene(); virtual void reloadShaders(); - virtual void init(int width, int height) {resizeFBO(width, height);} - virtual void resize(int width, int height) {resizeFBO(width, height);} + virtual void init(int width, int height) { resizeFBO(width, height); } + virtual void resize(int width, int height) { resizeFBO(width, height); } QPoint mpos; @@ -38,10 +39,9 @@ protected: private: void resizeFBO(int w, int h); - - GLFramebuffer fbo, fbo_c; - QOpenGLShaderProgram * shader_fxaa, * shader; + GLFramebuffer fbo, fbo_c; + QOpenGLShaderProgram *shader_fxaa, *shader; }; #endif // RENDERER_SIMPLE_H diff --git a/libs/qglview/shaders/fxaa_v3.h b/libs/qglview/shaders/fxaa_v3.h index 633482e..14e1497 100644 --- a/libs/qglview/shaders/fxaa_v3.h +++ b/libs/qglview/shaders/fxaa_v3.h @@ -34,11 +34,11 @@ Example, Or, #define FXAA_360 1 - + Or, #define FXAA_PS3 1 - + Etc. (2.) @@ -49,7 +49,7 @@ Then include this file, (3.) Then call the FXAA pixel shader from within your desired shader. Look at the FXAA Quality FxaaPixelShader() for docs on inputs. -As for FXAA 3.11 all inputs for all shaders are the same +As for FXAA 3.11 all inputs for all shaders are the same to enable easy porting between platforms. return FxaaPixelShader(...); @@ -80,7 +80,7 @@ Look at the FXAA Quality FxaaPixelShader() for docs on inputs. (6.) Have FXAA vertex shader run as a full screen triangle, -and output "pos" and "fxaaConsolePosPos" +and output "pos" and "fxaaConsolePosPos" such that inputs in the pixel shader provide, // {xy} = center of pixel @@ -97,7 +97,7 @@ Insure the texture sampler(s) used by FXAA are set to bilinear filtering. ------------------------------------------------------------------------------ INTEGRATION - RGBL AND COLORSPACE ------------------------------------------------------------------------------ -FXAA3 requires RGBL as input unless the following is set, +FXAA3 requires RGBL as input unless the following is set, #define FXAA_GREEN_AS_LUMA 1 @@ -150,7 +150,7 @@ Getting luma correct is required for the algorithm to work correctly. ------------------------------------------------------------------------------ Applying FXAA to a framebuffer with linear RGB color will look worse. This is very counter intuitive, but happends to be true in this case. -The reason is because dithering artifacts will be more visiable +The reason is because dithering artifacts will be more visiable in a linear colorspace. @@ -184,191 +184,191 @@ A. Or use FXAA_GREEN_AS_LUMA. // /*--------------------------------------------------------------------------*/ #ifndef FXAA_PS3 - #define FXAA_PS3 0 +# define FXAA_PS3 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_360 - #define FXAA_360 0 +# define FXAA_360 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_360_OPT - #define FXAA_360_OPT 0 +# define FXAA_360_OPT 0 #endif /*==========================================================================*/ #ifndef FXAA_PC - // - // FXAA Quality - // The high quality PC algorithm. - // - #define FXAA_PC 0 +// +// FXAA Quality +// The high quality PC algorithm. +// +# define FXAA_PC 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_PC_CONSOLE - // - // The console algorithm for PC is included - // for developers targeting really low spec machines. - // Likely better to just run FXAA_PC, and use a really low preset. - // - #define FXAA_PC_CONSOLE 0 +// +// The console algorithm for PC is included +// for developers targeting really low spec machines. +// Likely better to just run FXAA_PC, and use a really low preset. +// +# define FXAA_PC_CONSOLE 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GLSL_120 - #define FXAA_GLSL_120 0 +# define FXAA_GLSL_120 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GLSL_130 - #define FXAA_GLSL_130 0 +# define FXAA_GLSL_130 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_3 - #define FXAA_HLSL_3 0 +# define FXAA_HLSL_3 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_4 - #define FXAA_HLSL_4 0 +# define FXAA_HLSL_4 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_5 - #define FXAA_HLSL_5 0 +# define FXAA_HLSL_5 0 #endif /*==========================================================================*/ #ifndef FXAA_GREEN_AS_LUMA - // - // For those using non-linear color, - // and either not able to get luma in alpha, or not wanting to, - // this enables FXAA to run using green as a proxy for luma. - // So with this enabled, no need to pack luma in alpha. - // - // This will turn off AA on anything which lacks some amount of green. - // Pure red and blue or combination of only R and B, will get no AA. - // - // Might want to lower the settings for both, - // fxaaConsoleEdgeThresholdMin - // fxaaQualityEdgeThresholdMin - // In order to insure AA does not get turned off on colors - // which contain a minor amount of green. - // - // 1 = On. - // 0 = Off. - // - #define FXAA_GREEN_AS_LUMA 0 +// +// For those using non-linear color, +// and either not able to get luma in alpha, or not wanting to, +// this enables FXAA to run using green as a proxy for luma. +// So with this enabled, no need to pack luma in alpha. +// +// This will turn off AA on anything which lacks some amount of green. +// Pure red and blue or combination of only R and B, will get no AA. +// +// Might want to lower the settings for both, +// fxaaConsoleEdgeThresholdMin +// fxaaQualityEdgeThresholdMin +// In order to insure AA does not get turned off on colors +// which contain a minor amount of green. +// +// 1 = On. +// 0 = Off. +// +# define FXAA_GREEN_AS_LUMA 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_EARLY_EXIT - // - // Controls algorithm's early exit path. - // On PS3 turning this ON adds 2 cycles to the shader. - // On 360 turning this OFF adds 10ths of a millisecond to the shader. - // Turning this off on console will result in a more blurry image. - // So this defaults to on. - // - // 1 = On. - // 0 = Off. - // - #define FXAA_EARLY_EXIT 1 +// +// Controls algorithm's early exit path. +// On PS3 turning this ON adds 2 cycles to the shader. +// On 360 turning this OFF adds 10ths of a millisecond to the shader. +// Turning this off on console will result in a more blurry image. +// So this defaults to on. +// +// 1 = On. +// 0 = Off. +// +# define FXAA_EARLY_EXIT 1 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_DISCARD - // - // Only valid for PC OpenGL currently. - // Probably will not work when FXAA_GREEN_AS_LUMA = 1. - // - // 1 = Use discard on pixels which don't need AA. - // For APIs which enable concurrent TEX+ROP from same surface. - // 0 = Return unchanged color on pixels which don't need AA. - // - #define FXAA_DISCARD 0 +// +// Only valid for PC OpenGL currently. +// Probably will not work when FXAA_GREEN_AS_LUMA = 1. +// +// 1 = Use discard on pixels which don't need AA. +// For APIs which enable concurrent TEX+ROP from same surface. +// 0 = Return unchanged color on pixels which don't need AA. +// +# define FXAA_DISCARD 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_FAST_PIXEL_OFFSET - // - // Used for GLSL 120 only. - // - // 1 = GL API supports fast pixel offsets - // 0 = do not use fast pixel offsets - // - #ifdef GL_EXT_gpu_shader4 - #define FXAA_FAST_PIXEL_OFFSET 1 - #endif - #ifdef GL_NV_gpu_shader5 - #define FXAA_FAST_PIXEL_OFFSET 1 - #endif - #ifdef GL_ARB_gpu_shader5 - #define FXAA_FAST_PIXEL_OFFSET 1 - #endif - #ifndef FXAA_FAST_PIXEL_OFFSET - #define FXAA_FAST_PIXEL_OFFSET 0 - #endif +// +// Used for GLSL 120 only. +// +// 1 = GL API supports fast pixel offsets +// 0 = do not use fast pixel offsets +// +# ifdef GL_EXT_gpu_shader4 +# define FXAA_FAST_PIXEL_OFFSET 1 +# endif +# ifdef GL_NV_gpu_shader5 +# define FXAA_FAST_PIXEL_OFFSET 1 +# endif +# ifdef GL_ARB_gpu_shader5 +# define FXAA_FAST_PIXEL_OFFSET 1 +# endif +# ifndef FXAA_FAST_PIXEL_OFFSET +# define FXAA_FAST_PIXEL_OFFSET 0 +# endif #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GATHER4_ALPHA - // - // 1 = API supports gather4 on alpha channel. - // 0 = API does not support gather4 on alpha channel. - // - #if (FXAA_HLSL_5 == 1) - #define FXAA_GATHER4_ALPHA 1 - #endif - #ifdef GL_ARB_gpu_shader5 - #define FXAA_GATHER4_ALPHA 1 - #endif - #ifdef GL_NV_gpu_shader5 - #define FXAA_GATHER4_ALPHA 1 - #endif - #ifndef FXAA_GATHER4_ALPHA - #define FXAA_GATHER4_ALPHA 0 - #endif +// +// 1 = API supports gather4 on alpha channel. +// 0 = API does not support gather4 on alpha channel. +// +# if (FXAA_HLSL_5 == 1) +# define FXAA_GATHER4_ALPHA 1 +# endif +# ifdef GL_ARB_gpu_shader5 +# define FXAA_GATHER4_ALPHA 1 +# endif +# ifdef GL_NV_gpu_shader5 +# define FXAA_GATHER4_ALPHA 1 +# endif +# ifndef FXAA_GATHER4_ALPHA +# define FXAA_GATHER4_ALPHA 0 +# endif #endif /*============================================================================ FXAA CONSOLE PS3 - TUNING KNOBS ============================================================================*/ #ifndef FXAA_CONSOLE__PS3_EDGE_SHARPNESS - // - // Consoles the sharpness of edges on PS3 only. - // Non-PS3 tuning is done with shader input. - // - // Due to the PS3 being ALU bound, - // there are only two safe values here: 4 and 8. - // These options use the shaders ability to a free *|/ by 2|4|8. - // - // 8.0 is sharper - // 4.0 is softer - // 2.0 is really soft (good for vector graphics inputs) - // - #if 1 - #define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 8.0 - #endif - #if 0 - #define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 4.0 - #endif - #if 0 - #define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 2.0 - #endif +// +// Consoles the sharpness of edges on PS3 only. +// Non-PS3 tuning is done with shader input. +// +// Due to the PS3 being ALU bound, +// there are only two safe values here: 4 and 8. +// These options use the shaders ability to a free *|/ by 2|4|8. +// +// 8.0 is sharper +// 4.0 is softer +// 2.0 is really soft (good for vector graphics inputs) +// +# if 1 +# define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 8.0 +# endif +# if 0 +# define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 4.0 +# endif +# if 0 +# define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 2.0 +# endif #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_CONSOLE__PS3_EDGE_THRESHOLD - // - // Only effects PS3. - // Non-PS3 tuning is done with shader input. - // - // The minimum amount of local contrast required to apply algorithm. - // The console setting has a different mapping than the quality setting. - // - // This only applies when FXAA_EARLY_EXIT is 1. - // - // Due to the PS3 being ALU bound, - // there are only two safe values here: 0.25 and 0.125. - // These options use the shaders ability to a free *|/ by 2|4|8. - // - // 0.125 leaves less aliasing, but is softer - // 0.25 leaves more aliasing, and is sharper - // - #if 1 - #define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.125 - #else - #define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.25 - #endif +// +// Only effects PS3. +// Non-PS3 tuning is done with shader input. +// +// The minimum amount of local contrast required to apply algorithm. +// The console setting has a different mapping than the quality setting. +// +// This only applies when FXAA_EARLY_EXIT is 1. +// +// Due to the PS3 being ALU bound, +// there are only two safe values here: 0.25 and 0.125. +// These options use the shaders ability to a free *|/ by 2|4|8. +// +// 0.125 leaves less aliasing, but is softer +// 0.25 leaves more aliasing, and is sharper +// +# if 1 +# define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.125 +# else +# define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.25 +# endif #endif /*============================================================================ @@ -377,27 +377,27 @@ A. Or use FXAA_GREEN_AS_LUMA. NOTE the other tuning knobs are now in the shader function inputs! ============================================================================*/ #ifndef FXAA_QUALITY__PRESET - // - // Choose the quality preset. - // This needs to be compiled into the shader as it effects code. - // Best option to include multiple presets is to - // in each shader define the preset, then include this file. - // - // OPTIONS - // ----------------------------------------------------------------------- - // 10 to 15 - default medium dither (10=fastest, 15=highest quality) - // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality) - // 39 - no dither, very expensive - // - // NOTES - // ----------------------------------------------------------------------- - // 12 = slightly faster then FXAA 3.9 and higher edge quality (default) - // 13 = about same speed as FXAA 3.9 and better than 12 - // 23 = closest to FXAA 3.9 visually and performance wise - // _ = the lowest digit is directly related to performance - // _ = the highest digit is directly related to style - // - #define FXAA_QUALITY__PRESET 12 +// +// Choose the quality preset. +// This needs to be compiled into the shader as it effects code. +// Best option to include multiple presets is to +// in each shader define the preset, then include this file. +// +// OPTIONS +// ----------------------------------------------------------------------- +// 10 to 15 - default medium dither (10=fastest, 15=highest quality) +// 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality) +// 39 - no dither, very expensive +// +// NOTES +// ----------------------------------------------------------------------- +// 12 = slightly faster then FXAA 3.9 and higher edge quality (default) +// 13 = about same speed as FXAA 3.9 and better than 12 +// 23 = closest to FXAA 3.9 visually and performance wise +// _ = the lowest digit is directly related to performance +// _ = the highest digit is directly related to style +// +# define FXAA_QUALITY__PRESET 12 #endif @@ -411,291 +411,296 @@ NOTE the other tuning knobs are now in the shader function inputs! FXAA QUALITY - MEDIUM DITHER PRESETS ============================================================================*/ #if (FXAA_QUALITY__PRESET == 10) - #define FXAA_QUALITY__PS 3 - #define FXAA_QUALITY__P0 1.5 - #define FXAA_QUALITY__P1 3.0 - #define FXAA_QUALITY__P2 12.0 +# define FXAA_QUALITY__PS 3 +# define FXAA_QUALITY__P0 1.5 +# define FXAA_QUALITY__P1 3.0 +# define FXAA_QUALITY__P2 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 11) - #define FXAA_QUALITY__PS 4 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 3.0 - #define FXAA_QUALITY__P3 12.0 +# define FXAA_QUALITY__PS 4 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 3.0 +# define FXAA_QUALITY__P3 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 12) - #define FXAA_QUALITY__PS 5 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 4.0 - #define FXAA_QUALITY__P4 12.0 +# define FXAA_QUALITY__PS 5 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 4.0 +# define FXAA_QUALITY__P4 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 13) - #define FXAA_QUALITY__PS 6 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 4.0 - #define FXAA_QUALITY__P5 12.0 +# define FXAA_QUALITY__PS 6 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 4.0 +# define FXAA_QUALITY__P5 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 14) - #define FXAA_QUALITY__PS 7 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 4.0 - #define FXAA_QUALITY__P6 12.0 +# define FXAA_QUALITY__PS 7 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 4.0 +# define FXAA_QUALITY__P6 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 15) - #define FXAA_QUALITY__PS 8 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 4.0 - #define FXAA_QUALITY__P7 12.0 +# define FXAA_QUALITY__PS 8 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 4.0 +# define FXAA_QUALITY__P7 12.0 #endif /*============================================================================ FXAA QUALITY - LOW DITHER PRESETS ============================================================================*/ #if (FXAA_QUALITY__PRESET == 20) - #define FXAA_QUALITY__PS 3 - #define FXAA_QUALITY__P0 1.5 - #define FXAA_QUALITY__P1 2.0 - #define FXAA_QUALITY__P2 8.0 +# define FXAA_QUALITY__PS 3 +# define FXAA_QUALITY__P0 1.5 +# define FXAA_QUALITY__P1 2.0 +# define FXAA_QUALITY__P2 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 21) - #define FXAA_QUALITY__PS 4 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 8.0 +# define FXAA_QUALITY__PS 4 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 22) - #define FXAA_QUALITY__PS 5 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 8.0 +# define FXAA_QUALITY__PS 5 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 23) - #define FXAA_QUALITY__PS 6 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 8.0 +# define FXAA_QUALITY__PS 6 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 24) - #define FXAA_QUALITY__PS 7 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 3.0 - #define FXAA_QUALITY__P6 8.0 +# define FXAA_QUALITY__PS 7 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 3.0 +# define FXAA_QUALITY__P6 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 25) - #define FXAA_QUALITY__PS 8 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 4.0 - #define FXAA_QUALITY__P7 8.0 +# define FXAA_QUALITY__PS 8 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 4.0 +# define FXAA_QUALITY__P7 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 26) - #define FXAA_QUALITY__PS 9 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 2.0 - #define FXAA_QUALITY__P7 4.0 - #define FXAA_QUALITY__P8 8.0 +# define FXAA_QUALITY__PS 9 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 4.0 +# define FXAA_QUALITY__P8 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 27) - #define FXAA_QUALITY__PS 10 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 2.0 - #define FXAA_QUALITY__P7 2.0 - #define FXAA_QUALITY__P8 4.0 - #define FXAA_QUALITY__P9 8.0 +# define FXAA_QUALITY__PS 10 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 4.0 +# define FXAA_QUALITY__P9 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 28) - #define FXAA_QUALITY__PS 11 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 2.0 - #define FXAA_QUALITY__P7 2.0 - #define FXAA_QUALITY__P8 2.0 - #define FXAA_QUALITY__P9 4.0 - #define FXAA_QUALITY__P10 8.0 +# define FXAA_QUALITY__PS 11 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 4.0 +# define FXAA_QUALITY__P10 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY__PRESET == 29) - #define FXAA_QUALITY__PS 12 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.5 - #define FXAA_QUALITY__P2 2.0 - #define FXAA_QUALITY__P3 2.0 - #define FXAA_QUALITY__P4 2.0 - #define FXAA_QUALITY__P5 2.0 - #define FXAA_QUALITY__P6 2.0 - #define FXAA_QUALITY__P7 2.0 - #define FXAA_QUALITY__P8 2.0 - #define FXAA_QUALITY__P9 2.0 - #define FXAA_QUALITY__P10 4.0 - #define FXAA_QUALITY__P11 8.0 +# define FXAA_QUALITY__PS 12 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 2.0 +# define FXAA_QUALITY__P10 4.0 +# define FXAA_QUALITY__P11 8.0 #endif /*============================================================================ FXAA QUALITY - EXTREME QUALITY ============================================================================*/ #if (FXAA_QUALITY__PRESET == 39) - #define FXAA_QUALITY__PS 12 - #define FXAA_QUALITY__P0 1.0 - #define FXAA_QUALITY__P1 1.0 - #define FXAA_QUALITY__P2 1.0 - #define FXAA_QUALITY__P3 1.0 - #define FXAA_QUALITY__P4 1.0 - #define FXAA_QUALITY__P5 1.5 - #define FXAA_QUALITY__P6 2.0 - #define FXAA_QUALITY__P7 2.0 - #define FXAA_QUALITY__P8 2.0 - #define FXAA_QUALITY__P9 2.0 - #define FXAA_QUALITY__P10 4.0 - #define FXAA_QUALITY__P11 8.0 +# define FXAA_QUALITY__PS 12 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.0 +# define FXAA_QUALITY__P2 1.0 +# define FXAA_QUALITY__P3 1.0 +# define FXAA_QUALITY__P4 1.0 +# define FXAA_QUALITY__P5 1.5 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 2.0 +# define FXAA_QUALITY__P10 4.0 +# define FXAA_QUALITY__P11 8.0 #endif - /*============================================================================ API PORTING ============================================================================*/ #if (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1) - #define FxaaBool bool - #define FxaaDiscard discard - #define FxaaFloat float - #define FxaaFloat2 vec2 - #define FxaaFloat3 vec3 - #define FxaaFloat4 vec4 - #define FxaaHalf float - #define FxaaHalf2 vec2 - #define FxaaHalf3 vec3 - #define FxaaHalf4 vec4 - #define FxaaInt2 ivec2 - #define FxaaSat(x) clamp(x, 0.0, 1.0) - #define FxaaTex sampler2D +# define FxaaBool bool +# define FxaaDiscard discard +# define FxaaFloat float +# define FxaaFloat2 vec2 +# define FxaaFloat3 vec3 +# define FxaaFloat4 vec4 +# define FxaaHalf float +# define FxaaHalf2 vec2 +# define FxaaHalf3 vec3 +# define FxaaHalf4 vec4 +# define FxaaInt2 ivec2 +# define FxaaSat(x) clamp(x, 0.0, 1.0) +# define FxaaTex sampler2D #else - #define FxaaBool bool - #define FxaaDiscard clip(-1) - #define FxaaFloat float - #define FxaaFloat2 float2 - #define FxaaFloat3 float3 - #define FxaaFloat4 float4 - #define FxaaHalf half - #define FxaaHalf2 half2 - #define FxaaHalf3 half3 - #define FxaaHalf4 half4 - #define FxaaSat(x) saturate(x) +# define FxaaBool bool +# define FxaaDiscard clip(-1) +# define FxaaFloat float +# define FxaaFloat2 float2 +# define FxaaFloat3 float3 +# define FxaaFloat4 float4 +# define FxaaHalf half +# define FxaaHalf2 half2 +# define FxaaHalf3 half3 +# define FxaaHalf4 half4 +# define FxaaSat(x) saturate(x) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GLSL_120 == 1) - // Requires, - // #version 120 - // And at least, - // #extension GL_EXT_gpu_shader4 : enable - // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9) - #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0) - #if (FXAA_FAST_PIXEL_OFFSET == 1) - #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o) - #else - #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0) - #endif - #if (FXAA_GATHER4_ALPHA == 1) - // use #extension GL_ARB_gpu_shader5 : enable - #define FxaaTexAlpha4(t, p) textureGather(t, p, 3) - #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) - #define FxaaTexGreen4(t, p) textureGather(t, p, 1) - #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) - #endif +// Requires, +// #version 120 +// And at least, +// #extension GL_EXT_gpu_shader4 : enable +// (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9) +# define FxaaTexTop(t, p) texture2DLod(t, p, 0.0) +# if (FXAA_FAST_PIXEL_OFFSET == 1) +# define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o) +# else +# define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0) +# endif +# if (FXAA_GATHER4_ALPHA == 1) +// use #extension GL_ARB_gpu_shader5 : enable +# define FxaaTexAlpha4(t, p) textureGather(t, p, 3) +# define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) +# define FxaaTexGreen4(t, p) textureGather(t, p, 1) +# define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) +# endif #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GLSL_130 == 1) - // Requires "#version 130" or better - #define FxaaTexTop(t, p) textureLod(t, p, 0.0) - #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o) - #if (FXAA_GATHER4_ALPHA == 1) - // use #extension GL_ARB_gpu_shader5 : enable - #define FxaaTexAlpha4(t, p) textureGather(t, p, 3) - #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) - #define FxaaTexGreen4(t, p) textureGather(t, p, 1) - #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) - #endif +// Requires "#version 130" or better +# define FxaaTexTop(t, p) textureLod(t, p, 0.0) +# define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o) +# if (FXAA_GATHER4_ALPHA == 1) +// use #extension GL_ARB_gpu_shader5 : enable +# define FxaaTexAlpha4(t, p) textureGather(t, p, 3) +# define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) +# define FxaaTexGreen4(t, p) textureGather(t, p, 1) +# define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) +# endif #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_3 == 1) || (FXAA_360 == 1) || (FXAA_PS3 == 1) - #define FxaaInt2 float2 - #define FxaaTex sampler2D - #define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0)) - #define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0)) +# define FxaaInt2 float2 +# define FxaaTex sampler2D +# define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0)) +# define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0)) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_4 == 1) - #define FxaaInt2 int2 - struct FxaaTex { SamplerState smpl; Texture2D tex; }; - #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) - #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) +# define FxaaInt2 int2 +struct FxaaTex { + SamplerState smpl; + Texture2D tex; +}; +# define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) +# define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_5 == 1) - #define FxaaInt2 int2 - struct FxaaTex { SamplerState smpl; Texture2D tex; }; - #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) - #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) - #define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p) - #define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o) - #define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p) - #define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o) +# define FxaaInt2 int2 +struct FxaaTex { + SamplerState smpl; + Texture2D tex; +}; +# define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) +# define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) +# define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p) +# define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o) +# define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p) +# define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o) #endif @@ -703,13 +708,15 @@ NOTE the other tuning knobs are now in the shader function inputs! GREEN AS LUMA OPTION SUPPORT FUNCTION ============================================================================*/ #if (FXAA_GREEN_AS_LUMA == 0) - //FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; } - FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return dot(rgba.rgb, FxaaFloat3(0.299, 0.587, 0.114)); } +// FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; } +FxaaFloat FxaaLuma(FxaaFloat4 rgba) { + return dot(rgba.rgb, FxaaFloat3(0.299, 0.587, 0.114)); +} #else - FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; } -#endif - - +FxaaFloat FxaaLuma(FxaaFloat4 rgba) { + return rgba.y; +} +#endif /*============================================================================ @@ -720,71 +727,71 @@ NOTE the other tuning knobs are now in the shader function inputs! #if (FXAA_PC == 1) /*--------------------------------------------------------------------------*/ FxaaFloat4 FxaaPixelShader( - // + // // Use noperspective interpolation here (turn off perspective interpolation). // {xy} = center of pixel - FxaaFloat2 pos, - // + FxaaFloat2 pos, + // // Used only for FXAA Console, and not used on the 360 version. // Use noperspective interpolation here (turn off perspective interpolation). // {xy__} = upper left of pixel // {__zw} = lower right of pixel - FxaaFloat4 fxaaConsolePosPos, - // + FxaaFloat4 fxaaConsolePosPos, + // // Input color texture. // {rgb_} = color in linear or perceptual color space // if (FXAA_GREEN_AS_LUMA == 0) // {___a} = luma in perceptual color space (not linear) - FxaaTex tex, - // + FxaaTex tex, + // // Only used on the optimized 360 version of FXAA Console. // For everything but 360, just use the same input here as for "tex". // For 360, same texture, just alias with a 2nd sampler. // This sampler needs to have an exponent bias of -1. - FxaaTex fxaaConsole360TexExpBiasNegOne, - // + FxaaTex fxaaConsole360TexExpBiasNegOne, + // // Only used on the optimized 360 version of FXAA Console. // For everything but 360, just use the same input here as for "tex". // For 360, same texture, just alias with a 3nd sampler. // This sampler needs to have an exponent bias of -2. - FxaaTex fxaaConsole360TexExpBiasNegTwo, - // + FxaaTex fxaaConsole360TexExpBiasNegTwo, + // // Only used on FXAA Quality. // This must be from a constant/uniform. // {x_} = 1.0/screenWidthInPixels // {_y} = 1.0/screenHeightInPixels - FxaaFloat2 fxaaQualityRcpFrame, - // + FxaaFloat2 fxaaQualityRcpFrame, + // // Only used on FXAA Console. // This must be from a constant/uniform. // This effects sub-pixel AA quality and inversely sharpness. // Where N ranges between, // N = 0.50 (default) // N = 0.33 (sharper) - // {x___} = -N/screenWidthInPixels + // {x___} = -N/screenWidthInPixels // {_y__} = -N/screenHeightInPixels - // {__z_} = N/screenWidthInPixels - // {___w} = N/screenHeightInPixels - FxaaFloat4 fxaaConsoleRcpFrameOpt, - // + // {__z_} = N/screenWidthInPixels + // {___w} = N/screenHeightInPixels + FxaaFloat4 fxaaConsoleRcpFrameOpt, + // // Only used on FXAA Console. // Not used on 360, but used on PS3 and PC. // This must be from a constant/uniform. - // {x___} = -2.0/screenWidthInPixels + // {x___} = -2.0/screenWidthInPixels // {_y__} = -2.0/screenHeightInPixels - // {__z_} = 2.0/screenWidthInPixels - // {___w} = 2.0/screenHeightInPixels - FxaaFloat4 fxaaConsoleRcpFrameOpt2, - // + // {__z_} = 2.0/screenWidthInPixels + // {___w} = 2.0/screenHeightInPixels + FxaaFloat4 fxaaConsoleRcpFrameOpt2, + // // Only used on FXAA Console. // Only used on 360 in place of fxaaConsoleRcpFrameOpt2. // This must be from a constant/uniform. - // {x___} = 8.0/screenWidthInPixels + // {x___} = 8.0/screenWidthInPixels // {_y__} = 8.0/screenHeightInPixels - // {__z_} = -4.0/screenWidthInPixels - // {___w} = -4.0/screenHeightInPixels - FxaaFloat4 fxaaConsole360RcpFrameOpt2, - // + // {__z_} = -4.0/screenWidthInPixels + // {___w} = -4.0/screenHeightInPixels + FxaaFloat4 fxaaConsole360RcpFrameOpt2, + // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY__SUBPIX define. // It is here now to allow easier tuning. @@ -795,8 +802,8 @@ FxaaFloat4 FxaaPixelShader( // 0.50 - lower limit (sharper, less sub-pixel aliasing removal) // 0.25 - almost off // 0.00 - completely off - FxaaFloat fxaaQualitySubpix, - // + FxaaFloat fxaaQualitySubpix, + // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY__EDGE_THRESHOLD define. // It is here now to allow easier tuning. @@ -804,10 +811,10 @@ FxaaFloat4 FxaaPixelShader( // 0.333 - too little (faster) // 0.250 - low quality // 0.166 - default - // 0.125 - high quality + // 0.125 - high quality // 0.063 - overkill (slower) - FxaaFloat fxaaQualityEdgeThreshold, - // + FxaaFloat fxaaQualityEdgeThreshold, + // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY__EDGE_THRESHOLD_MIN define. // It is here now to allow easier tuning. @@ -821,8 +828,8 @@ FxaaFloat4 FxaaPixelShader( // will appear very dark in the green channel! // Tune by looking at mostly non-green content, // then start at zero and increase until aliasing is a problem. - FxaaFloat fxaaQualityEdgeThresholdMin, - // + FxaaFloat fxaaQualityEdgeThresholdMin, + // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE__EDGE_SHARPNESS define. // It is here now to allow easier tuning. @@ -835,8 +842,8 @@ FxaaFloat4 FxaaPixelShader( // 8.0 is sharper (default!!!) // 4.0 is softer // 2.0 is really soft (good only for vector graphics inputs) - FxaaFloat fxaaConsoleEdgeSharpness, - // + FxaaFloat fxaaConsoleEdgeSharpness, + // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE__EDGE_THRESHOLD define. // It is here now to allow easier tuning. @@ -849,15 +856,15 @@ FxaaFloat4 FxaaPixelShader( // Other platforms can use other values. // 0.125 leaves less aliasing, but is softer (default!!!) // 0.25 leaves more aliasing, and is sharper - FxaaFloat fxaaConsoleEdgeThreshold, - // + FxaaFloat fxaaConsoleEdgeThreshold, + // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE__EDGE_THRESHOLD_MIN define. // It is here now to allow easier tuning. // Trims the algorithm from processing darks. // The console setting has a different mapping than the quality setting. // This only applies when FXAA_EARLY_EXIT is 1. - // This does not apply to PS3, + // This does not apply to PS3, // PS3 was simplified to avoid more shader instructions. // 0.06 - faster but more aliasing in darks // 0.05 - default @@ -868,478 +875,474 @@ FxaaFloat4 FxaaPixelShader( // will appear very dark in the green channel! // Tune by looking at mostly non-green content, // then start at zero and increase until aliasing is a problem. - FxaaFloat fxaaConsoleEdgeThresholdMin, - // + FxaaFloat fxaaConsoleEdgeThresholdMin, + // // Extra constants for 360 FXAA Console only. // Use zeros or anything else for other platforms. // These must be in physical constant registers and NOT immedates. // Immedates will result in compiler un-optimizing. // {xyzw} = float4(1.0, -1.0, 0.25, -0.25) - FxaaFloat4 fxaaConsole360ConstDir -) { -/*--------------------------------------------------------------------------*/ - FxaaFloat2 posM; - posM.x = pos.x; - posM.y = pos.y; - #if (FXAA_GATHER4_ALPHA == 1) - #if (FXAA_DISCARD == 0) - FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); - #if (FXAA_GREEN_AS_LUMA == 0) - #define lumaM rgbyM.w - #else - #define lumaM rgbyM.y - #endif - #endif - #if (FXAA_GREEN_AS_LUMA == 0) - FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM); - FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1)); - #else - FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM); - FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1)); - #endif - #if (FXAA_DISCARD == 1) - #define lumaM luma4A.w - #endif - #define lumaE luma4A.z - #define lumaS luma4A.x - #define lumaSE luma4A.y - #define lumaNW luma4B.w - #define lumaN luma4B.z - #define lumaW luma4B.x - #else - FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); - #if (FXAA_GREEN_AS_LUMA == 0) - #define lumaM rgbyM.w - #else - #define lumaM rgbyM.y - #endif - FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy)); - #endif -/*--------------------------------------------------------------------------*/ - FxaaFloat maxSM = max(lumaS, lumaM); - FxaaFloat minSM = min(lumaS, lumaM); - FxaaFloat maxESM = max(lumaE, maxSM); - FxaaFloat minESM = min(lumaE, minSM); - FxaaFloat maxWN = max(lumaN, lumaW); - FxaaFloat minWN = min(lumaN, lumaW); - FxaaFloat rangeMax = max(maxWN, maxESM); - FxaaFloat rangeMin = min(minWN, minESM); - FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; - FxaaFloat range = rangeMax - rangeMin; - FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); - FxaaBool earlyExit = range < rangeMaxClamped; -/*--------------------------------------------------------------------------*/ - if(earlyExit) - #if (FXAA_DISCARD == 1) - FxaaDiscard; - #else - return rgbyM; - #endif -/*--------------------------------------------------------------------------*/ - #if (FXAA_GATHER4_ALPHA == 0) - FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); - #else - FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy)); - FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); - #endif -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaNS = lumaN + lumaS; - FxaaFloat lumaWE = lumaW + lumaE; - FxaaFloat subpixRcpRange = 1.0/range; - FxaaFloat subpixNSWE = lumaNS + lumaWE; - FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS; - FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE; -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaNESE = lumaNE + lumaSE; - FxaaFloat lumaNWNE = lumaNW + lumaNE; - FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE; - FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE; -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaNWSW = lumaNW + lumaSW; - FxaaFloat lumaSWSE = lumaSW + lumaSE; - FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); - FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); - FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; - FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE; - FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4; - FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4; -/*--------------------------------------------------------------------------*/ - FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE; - FxaaFloat lengthSign = fxaaQualityRcpFrame.x; - FxaaBool horzSpan = edgeHorz >= edgeVert; - FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; -/*--------------------------------------------------------------------------*/ - if(!horzSpan) lumaN = lumaW; - if(!horzSpan) lumaS = lumaE; - if(horzSpan) lengthSign = fxaaQualityRcpFrame.y; - FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM; -/*--------------------------------------------------------------------------*/ - FxaaFloat gradientN = lumaN - lumaM; - FxaaFloat gradientS = lumaS - lumaM; - FxaaFloat lumaNN = lumaN + lumaM; - FxaaFloat lumaSS = lumaS + lumaM; - FxaaBool pairN = abs(gradientN) >= abs(gradientS); - FxaaFloat gradient = max(abs(gradientN), abs(gradientS)); - if(pairN) lengthSign = -lengthSign; - FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); -/*--------------------------------------------------------------------------*/ - FxaaFloat2 posB; - posB.x = posM.x; - posB.y = posM.y; - FxaaFloat2 offNP; - offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; - offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; - if(!horzSpan) posB.x += lengthSign * 0.5; - if( horzSpan) posB.y += lengthSign * 0.5; -/*--------------------------------------------------------------------------*/ - FxaaFloat2 posN; - posN.x = posB.x - offNP.x * FXAA_QUALITY__P0; - posN.y = posB.y - offNP.y * FXAA_QUALITY__P0; - FxaaFloat2 posP; - posP.x = posB.x + offNP.x * FXAA_QUALITY__P0; - posP.y = posB.y + offNP.y * FXAA_QUALITY__P0; - FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0; - FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN)); - FxaaFloat subpixE = subpixC * subpixC; - FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP)); -/*--------------------------------------------------------------------------*/ - if(!pairN) lumaNN = lumaSS; - FxaaFloat gradientScaled = gradient * 1.0/4.0; - FxaaFloat lumaMM = lumaM - lumaNN * 0.5; - FxaaFloat subpixF = subpixD * subpixE; - FxaaBool lumaMLTZero = lumaMM < 0.0; -/*--------------------------------------------------------------------------*/ - lumaEndN -= lumaNN * 0.5; - lumaEndP -= lumaNN * 0.5; - FxaaBool doneN = abs(lumaEndN) >= gradientScaled; - FxaaBool doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P1; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P1; - FxaaBool doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P1; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P1; -/*--------------------------------------------------------------------------*/ - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P2; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P2; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P2; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P2; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 3) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P3; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P3; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P3; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P3; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 4) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P4; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P4; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P4; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P4; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 5) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P5; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P5; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P5; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P5; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 6) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P6; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P6; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P6; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P6; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 7) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P7; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P7; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P7; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P7; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 8) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P8; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P8; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P8; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P8; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 9) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P9; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P9; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P9; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P9; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 10) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P10; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P10; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P10; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P10; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 11) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P11; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P11; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P11; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P11; -/*--------------------------------------------------------------------------*/ - #if (FXAA_QUALITY__PS > 12) - if(doneNP) { - if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); - if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); - if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; - if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; - doneN = abs(lumaEndN) >= gradientScaled; - doneP = abs(lumaEndP) >= gradientScaled; - if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P12; - if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P12; - doneNP = (!doneN) || (!doneP); - if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P12; - if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P12; -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } - #endif -/*--------------------------------------------------------------------------*/ - } -/*--------------------------------------------------------------------------*/ - FxaaFloat dstN = posM.x - posN.x; - FxaaFloat dstP = posP.x - posM.x; - if(!horzSpan) dstN = posM.y - posN.y; - if(!horzSpan) dstP = posP.y - posM.y; -/*--------------------------------------------------------------------------*/ - FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; - FxaaFloat spanLength = (dstP + dstN); - FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; - FxaaFloat spanLengthRcp = 1.0/spanLength; -/*--------------------------------------------------------------------------*/ - FxaaBool directionN = dstN < dstP; - FxaaFloat dst = min(dstN, dstP); - FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP; - FxaaFloat subpixG = subpixF * subpixF; - FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5; - FxaaFloat subpixH = subpixG * fxaaQualitySubpix; -/*--------------------------------------------------------------------------*/ - FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0; - FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH); - if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign; - if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign; - #if (FXAA_DISCARD == 1) - return FxaaTexTop(tex, posM); - #else - return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM); - #endif + FxaaFloat4 fxaaConsole360ConstDir) { + /*--------------------------------------------------------------------------*/ + FxaaFloat2 posM; + posM.x = pos.x; + posM.y = pos.y; +# if (FXAA_GATHER4_ALPHA == 1) +# if (FXAA_DISCARD == 0) + FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); +# if (FXAA_GREEN_AS_LUMA == 0) +# define lumaM rgbyM.w +# else +# define lumaM rgbyM.y +# endif +# endif +# if (FXAA_GREEN_AS_LUMA == 0) + FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM); + FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1)); +# else + FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM); + FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1)); +# endif +# if (FXAA_DISCARD == 1) +# define lumaM luma4A.w +# endif +# define lumaE luma4A.z +# define lumaS luma4A.x +# define lumaSE luma4A.y +# define lumaNW luma4B.w +# define lumaN luma4B.z +# define lumaW luma4B.x +# else + FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); +# if (FXAA_GREEN_AS_LUMA == 0) +# define lumaM rgbyM.w +# else +# define lumaM rgbyM.y +# endif + FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(0, 1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, 0), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(0, -1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy)); +# endif + /*--------------------------------------------------------------------------*/ + FxaaFloat maxSM = max(lumaS, lumaM); + FxaaFloat minSM = min(lumaS, lumaM); + FxaaFloat maxESM = max(lumaE, maxSM); + FxaaFloat minESM = min(lumaE, minSM); + FxaaFloat maxWN = max(lumaN, lumaW); + FxaaFloat minWN = min(lumaN, lumaW); + FxaaFloat rangeMax = max(maxWN, maxESM); + FxaaFloat rangeMin = min(minWN, minESM); + FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; + FxaaFloat range = rangeMax - rangeMin; + FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); + FxaaBool earlyExit = range < rangeMaxClamped; + /*--------------------------------------------------------------------------*/ + if (earlyExit) +# if (FXAA_DISCARD == 1) + FxaaDiscard; +# else + return rgbyM; +# endif + /*--------------------------------------------------------------------------*/ +# if (FXAA_GATHER4_ALPHA == 0) + FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, -1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, 1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); +# else + FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); +# endif + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaNS = lumaN + lumaS; + FxaaFloat lumaWE = lumaW + lumaE; + FxaaFloat subpixRcpRange = 1.0 / range; + FxaaFloat subpixNSWE = lumaNS + lumaWE; + FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS; + FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE; + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaNESE = lumaNE + lumaSE; + FxaaFloat lumaNWNE = lumaNW + lumaNE; + FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE; + FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE; + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaNWSW = lumaNW + lumaSW; + FxaaFloat lumaSWSE = lumaSW + lumaSE; + FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); + FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); + FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; + FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE; + FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4; + FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4; + /*--------------------------------------------------------------------------*/ + FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE; + FxaaFloat lengthSign = fxaaQualityRcpFrame.x; + FxaaBool horzSpan = edgeHorz >= edgeVert; + FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; + /*--------------------------------------------------------------------------*/ + if (!horzSpan) lumaN = lumaW; + if (!horzSpan) lumaS = lumaE; + if (horzSpan) lengthSign = fxaaQualityRcpFrame.y; + FxaaFloat subpixB = (subpixA * (1.0 / 12.0)) - lumaM; + /*--------------------------------------------------------------------------*/ + FxaaFloat gradientN = lumaN - lumaM; + FxaaFloat gradientS = lumaS - lumaM; + FxaaFloat lumaNN = lumaN + lumaM; + FxaaFloat lumaSS = lumaS + lumaM; + FxaaBool pairN = abs(gradientN) >= abs(gradientS); + FxaaFloat gradient = max(abs(gradientN), abs(gradientS)); + if (pairN) lengthSign = -lengthSign; + FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); + /*--------------------------------------------------------------------------*/ + FxaaFloat2 posB; + posB.x = posM.x; + posB.y = posM.y; + FxaaFloat2 offNP; + offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; + offNP.y = (horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; + if (!horzSpan) posB.x += lengthSign * 0.5; + if (horzSpan) posB.y += lengthSign * 0.5; + /*--------------------------------------------------------------------------*/ + FxaaFloat2 posN; + posN.x = posB.x - offNP.x * FXAA_QUALITY__P0; + posN.y = posB.y - offNP.y * FXAA_QUALITY__P0; + FxaaFloat2 posP; + posP.x = posB.x + offNP.x * FXAA_QUALITY__P0; + posP.y = posB.y + offNP.y * FXAA_QUALITY__P0; + FxaaFloat subpixD = ((-2.0) * subpixC) + 3.0; + FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN)); + FxaaFloat subpixE = subpixC * subpixC; + FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP)); + /*--------------------------------------------------------------------------*/ + if (!pairN) lumaNN = lumaSS; + FxaaFloat gradientScaled = gradient * 1.0 / 4.0; + FxaaFloat lumaMM = lumaM - lumaNN * 0.5; + FxaaFloat subpixF = subpixD * subpixE; + FxaaBool lumaMLTZero = lumaMM < 0.0; + /*--------------------------------------------------------------------------*/ + lumaEndN -= lumaNN * 0.5; + lumaEndP -= lumaNN * 0.5; + FxaaBool doneN = abs(lumaEndN) >= gradientScaled; + FxaaBool doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P1; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P1; + FxaaBool doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P1; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P1; + /*--------------------------------------------------------------------------*/ + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P2; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P2; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P2; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P2; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 3) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P3; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P3; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P3; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P3; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 4) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P4; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P4; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P4; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P4; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 5) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P5; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P5; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P5; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P5; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 6) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P6; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P6; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P6; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P6; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 7) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P7; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P7; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P7; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P7; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 8) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P8; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P8; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P8; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P8; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 9) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P9; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P9; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P9; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P9; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 10) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P10; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P10; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P10; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P10; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 11) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P11; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P11; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P11; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P11; + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 12) + if (doneNP) { + if (!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if (!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if (!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if (!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) posN.x -= offNP.x * FXAA_QUALITY__P12; + if (!doneN) posN.y -= offNP.y * FXAA_QUALITY__P12; + doneNP = (!doneN) || (!doneP); + if (!doneP) posP.x += offNP.x * FXAA_QUALITY__P12; + if (!doneP) posP.y += offNP.y * FXAA_QUALITY__P12; + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } + /*--------------------------------------------------------------------------*/ + FxaaFloat dstN = posM.x - posN.x; + FxaaFloat dstP = posP.x - posM.x; + if (!horzSpan) dstN = posM.y - posN.y; + if (!horzSpan) dstP = posP.y - posM.y; + /*--------------------------------------------------------------------------*/ + FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; + FxaaFloat spanLength = (dstP + dstN); + FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; + FxaaFloat spanLengthRcp = 1.0 / spanLength; + /*--------------------------------------------------------------------------*/ + FxaaBool directionN = dstN < dstP; + FxaaFloat dst = min(dstN, dstP); + FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP; + FxaaFloat subpixG = subpixF * subpixF; + FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5; + FxaaFloat subpixH = subpixG * fxaaQualitySubpix; + /*--------------------------------------------------------------------------*/ + FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0; + FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH); + if (!horzSpan) posM.x += pixelOffsetSubpix * lengthSign; + if (horzSpan) posM.y += pixelOffsetSubpix * lengthSign; +# if (FXAA_DISCARD == 1) + return FxaaTexTop(tex, posM); +# else + return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM); +# endif } /*==========================================================================*/ #endif - - /*============================================================================ FXAA3 CONSOLE - PC VERSION - + ------------------------------------------------------------------------------ Instead of using this on PC, I'd suggest just using FXAA Quality with #define FXAA_QUALITY__PRESET 10 -Or +Or #define FXAA_QUALITY__PRESET 20 Either are higher qualilty and almost as fast as this on modern PC GPUs. ============================================================================*/ #if (FXAA_PC_CONSOLE == 1) /*--------------------------------------------------------------------------*/ FxaaFloat4 FxaaPixelShader( - // See FXAA Quality FxaaPixelShader() source for docs on Inputs! - FxaaFloat2 pos, - FxaaFloat4 fxaaConsolePosPos, - FxaaTex tex, - FxaaTex fxaaConsole360TexExpBiasNegOne, - FxaaTex fxaaConsole360TexExpBiasNegTwo, - FxaaFloat2 fxaaQualityRcpFrame, - FxaaFloat4 fxaaConsoleRcpFrameOpt, - FxaaFloat4 fxaaConsoleRcpFrameOpt2, - FxaaFloat4 fxaaConsole360RcpFrameOpt2, - FxaaFloat fxaaQualitySubpix, - FxaaFloat fxaaQualityEdgeThreshold, - FxaaFloat fxaaQualityEdgeThresholdMin, - FxaaFloat fxaaConsoleEdgeSharpness, - FxaaFloat fxaaConsoleEdgeThreshold, - FxaaFloat fxaaConsoleEdgeThresholdMin, - FxaaFloat4 fxaaConsole360ConstDir -) { -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaNw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xy)); - FxaaFloat lumaSw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xw)); - FxaaFloat lumaNe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zy)); - FxaaFloat lumaSe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zw)); -/*--------------------------------------------------------------------------*/ - FxaaFloat4 rgbyM = FxaaTexTop(tex, pos.xy); - #if (FXAA_GREEN_AS_LUMA == 0) - FxaaFloat lumaM = rgbyM.w; - #else - FxaaFloat lumaM = rgbyM.y; - #endif -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaMaxNwSw = max(lumaNw, lumaSw); - lumaNe += 1.0/384.0; - FxaaFloat lumaMinNwSw = min(lumaNw, lumaSw); -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaMaxNeSe = max(lumaNe, lumaSe); - FxaaFloat lumaMinNeSe = min(lumaNe, lumaSe); -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaMax = max(lumaMaxNeSe, lumaMaxNwSw); - FxaaFloat lumaMin = min(lumaMinNeSe, lumaMinNwSw); -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaMaxScaled = lumaMax * fxaaConsoleEdgeThreshold; -/*--------------------------------------------------------------------------*/ - FxaaFloat lumaMinM = min(lumaMin, lumaM); - FxaaFloat lumaMaxScaledClamped = max(fxaaConsoleEdgeThresholdMin, lumaMaxScaled); - FxaaFloat lumaMaxM = max(lumaMax, lumaM); - FxaaFloat dirSwMinusNe = lumaSw - lumaNe; - FxaaFloat lumaMaxSubMinM = lumaMaxM - lumaMinM; - FxaaFloat dirSeMinusNw = lumaSe - lumaNw; - if(lumaMaxSubMinM < lumaMaxScaledClamped) return rgbyM; -/*--------------------------------------------------------------------------*/ - FxaaFloat2 dir; - dir.x = dirSwMinusNe + dirSeMinusNw; - dir.y = dirSwMinusNe - dirSeMinusNw; -/*--------------------------------------------------------------------------*/ - FxaaFloat2 dir1 = normalize(dir.xy); - FxaaFloat4 rgbyN1 = FxaaTexTop(tex, pos.xy - dir1 * fxaaConsoleRcpFrameOpt.zw); - FxaaFloat4 rgbyP1 = FxaaTexTop(tex, pos.xy + dir1 * fxaaConsoleRcpFrameOpt.zw); -/*--------------------------------------------------------------------------*/ - FxaaFloat dirAbsMinTimesC = min(abs(dir1.x), abs(dir1.y)) * fxaaConsoleEdgeSharpness; - FxaaFloat2 dir2 = clamp(dir1.xy / dirAbsMinTimesC, -2.0, 2.0); -/*--------------------------------------------------------------------------*/ - FxaaFloat4 rgbyN2 = FxaaTexTop(tex, pos.xy - dir2 * fxaaConsoleRcpFrameOpt2.zw); - FxaaFloat4 rgbyP2 = FxaaTexTop(tex, pos.xy + dir2 * fxaaConsoleRcpFrameOpt2.zw); -/*--------------------------------------------------------------------------*/ - FxaaFloat4 rgbyA = rgbyN1 + rgbyP1; - FxaaFloat4 rgbyB = ((rgbyN2 + rgbyP2) * 0.25) + (rgbyA * 0.25); -/*--------------------------------------------------------------------------*/ - #if (FXAA_GREEN_AS_LUMA == 0) - FxaaBool twoTap = (rgbyB.w < lumaMin) || (rgbyB.w > lumaMax); - #else - FxaaBool twoTap = (rgbyB.y < lumaMin) || (rgbyB.y > lumaMax); - #endif - if(twoTap) rgbyB.xyz = rgbyA.xyz * 0.5; - return rgbyB; } + // See FXAA Quality FxaaPixelShader() source for docs on Inputs! + FxaaFloat2 pos, + FxaaFloat4 fxaaConsolePosPos, + FxaaTex tex, + FxaaTex fxaaConsole360TexExpBiasNegOne, + FxaaTex fxaaConsole360TexExpBiasNegTwo, + FxaaFloat2 fxaaQualityRcpFrame, + FxaaFloat4 fxaaConsoleRcpFrameOpt, + FxaaFloat4 fxaaConsoleRcpFrameOpt2, + FxaaFloat4 fxaaConsole360RcpFrameOpt2, + FxaaFloat fxaaQualitySubpix, + FxaaFloat fxaaQualityEdgeThreshold, + FxaaFloat fxaaQualityEdgeThresholdMin, + FxaaFloat fxaaConsoleEdgeSharpness, + FxaaFloat fxaaConsoleEdgeThreshold, + FxaaFloat fxaaConsoleEdgeThresholdMin, + FxaaFloat4 fxaaConsole360ConstDir) { + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaNw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xy)); + FxaaFloat lumaSw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xw)); + FxaaFloat lumaNe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zy)); + FxaaFloat lumaSe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zw)); + /*--------------------------------------------------------------------------*/ + FxaaFloat4 rgbyM = FxaaTexTop(tex, pos.xy); +# if (FXAA_GREEN_AS_LUMA == 0) + FxaaFloat lumaM = rgbyM.w; +# else + FxaaFloat lumaM = rgbyM.y; +# endif + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaMaxNwSw = max(lumaNw, lumaSw); + lumaNe += 1.0 / 384.0; + FxaaFloat lumaMinNwSw = min(lumaNw, lumaSw); + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaMaxNeSe = max(lumaNe, lumaSe); + FxaaFloat lumaMinNeSe = min(lumaNe, lumaSe); + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaMax = max(lumaMaxNeSe, lumaMaxNwSw); + FxaaFloat lumaMin = min(lumaMinNeSe, lumaMinNwSw); + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaMaxScaled = lumaMax * fxaaConsoleEdgeThreshold; + /*--------------------------------------------------------------------------*/ + FxaaFloat lumaMinM = min(lumaMin, lumaM); + FxaaFloat lumaMaxScaledClamped = max(fxaaConsoleEdgeThresholdMin, lumaMaxScaled); + FxaaFloat lumaMaxM = max(lumaMax, lumaM); + FxaaFloat dirSwMinusNe = lumaSw - lumaNe; + FxaaFloat lumaMaxSubMinM = lumaMaxM - lumaMinM; + FxaaFloat dirSeMinusNw = lumaSe - lumaNw; + if (lumaMaxSubMinM < lumaMaxScaledClamped) return rgbyM; + /*--------------------------------------------------------------------------*/ + FxaaFloat2 dir; + dir.x = dirSwMinusNe + dirSeMinusNw; + dir.y = dirSwMinusNe - dirSeMinusNw; + /*--------------------------------------------------------------------------*/ + FxaaFloat2 dir1 = normalize(dir.xy); + FxaaFloat4 rgbyN1 = FxaaTexTop(tex, pos.xy - dir1 * fxaaConsoleRcpFrameOpt.zw); + FxaaFloat4 rgbyP1 = FxaaTexTop(tex, pos.xy + dir1 * fxaaConsoleRcpFrameOpt.zw); + /*--------------------------------------------------------------------------*/ + FxaaFloat dirAbsMinTimesC = min(abs(dir1.x), abs(dir1.y)) * fxaaConsoleEdgeSharpness; + FxaaFloat2 dir2 = clamp(dir1.xy / dirAbsMinTimesC, -2.0, 2.0); + /*--------------------------------------------------------------------------*/ + FxaaFloat4 rgbyN2 = FxaaTexTop(tex, pos.xy - dir2 * fxaaConsoleRcpFrameOpt2.zw); + FxaaFloat4 rgbyP2 = FxaaTexTop(tex, pos.xy + dir2 * fxaaConsoleRcpFrameOpt2.zw); + /*--------------------------------------------------------------------------*/ + FxaaFloat4 rgbyA = rgbyN1 + rgbyP1; + FxaaFloat4 rgbyB = ((rgbyN2 + rgbyP2) * 0.25) + (rgbyA * 0.25); + /*--------------------------------------------------------------------------*/ +# if (FXAA_GREEN_AS_LUMA == 0) + FxaaBool twoTap = (rgbyB.w < lumaMin) || (rgbyB.w > lumaMax); +# else + FxaaBool twoTap = (rgbyB.y < lumaMin) || (rgbyB.y > lumaMax); +# endif + if (twoTap) rgbyB.xyz = rgbyA.xyz * 0.5; + return rgbyB; +} /*==========================================================================*/ #endif - /*============================================================================ - FXAA3 CONSOLE - 360 PIXEL SHADER + FXAA3 CONSOLE - 360 PIXEL SHADER ------------------------------------------------------------------------------ This optimized version thanks to suggestions from Andy Luedke. @@ -1351,88 +1354,88 @@ If it does not work, please let me know so I can fix it. ============================================================================*/ #if (FXAA_360 == 1) /*--------------------------------------------------------------------------*/ -[reduceTempRegUsage(4)] -float4 FxaaPixelShader( - // See FXAA Quality FxaaPixelShader() source for docs on Inputs! - FxaaFloat2 pos, - FxaaFloat4 fxaaConsolePosPos, - FxaaTex tex, - FxaaTex fxaaConsole360TexExpBiasNegOne, - FxaaTex fxaaConsole360TexExpBiasNegTwo, - FxaaFloat2 fxaaQualityRcpFrame, - FxaaFloat4 fxaaConsoleRcpFrameOpt, - FxaaFloat4 fxaaConsoleRcpFrameOpt2, - FxaaFloat4 fxaaConsole360RcpFrameOpt2, - FxaaFloat fxaaQualitySubpix, - FxaaFloat fxaaQualityEdgeThreshold, - FxaaFloat fxaaQualityEdgeThresholdMin, - FxaaFloat fxaaConsoleEdgeSharpness, - FxaaFloat fxaaConsoleEdgeThreshold, - FxaaFloat fxaaConsoleEdgeThresholdMin, - FxaaFloat4 fxaaConsole360ConstDir -) { -/*--------------------------------------------------------------------------*/ - float4 lumaNwNeSwSe; - #if (FXAA_GREEN_AS_LUMA == 0) - asm { +[reduceTempRegUsage(4)] float4 FxaaPixelShader( + // See FXAA Quality FxaaPixelShader() source for docs on Inputs! + FxaaFloat2 pos, + FxaaFloat4 fxaaConsolePosPos, + FxaaTex tex, + FxaaTex fxaaConsole360TexExpBiasNegOne, + FxaaTex fxaaConsole360TexExpBiasNegTwo, + FxaaFloat2 fxaaQualityRcpFrame, + FxaaFloat4 fxaaConsoleRcpFrameOpt, + FxaaFloat4 fxaaConsoleRcpFrameOpt2, + FxaaFloat4 fxaaConsole360RcpFrameOpt2, + FxaaFloat fxaaQualitySubpix, + FxaaFloat fxaaQualityEdgeThreshold, + FxaaFloat fxaaQualityEdgeThresholdMin, + FxaaFloat fxaaConsoleEdgeSharpness, + FxaaFloat fxaaConsoleEdgeThreshold, + FxaaFloat fxaaConsoleEdgeThresholdMin, + FxaaFloat4 fxaaConsole360ConstDir) { + /*--------------------------------------------------------------------------*/ + float4 lumaNwNeSwSe; +# if (FXAA_GREEN_AS_LUMA == 0) + asm { tfetch2D lumaNwNeSwSe.w___, tex, pos.xy, OffsetX = -0.5, OffsetY = -0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe._w__, tex, pos.xy, OffsetX = 0.5, OffsetY = -0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe.__w_, tex, pos.xy, OffsetX = -0.5, OffsetY = 0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe.___w, tex, pos.xy, OffsetX = 0.5, OffsetY = 0.5, UseComputedLOD=false - }; - #else - asm { + } + ; +# else + asm { tfetch2D lumaNwNeSwSe.y___, tex, pos.xy, OffsetX = -0.5, OffsetY = -0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe._y__, tex, pos.xy, OffsetX = 0.5, OffsetY = -0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe.__y_, tex, pos.xy, OffsetX = -0.5, OffsetY = 0.5, UseComputedLOD=false tfetch2D lumaNwNeSwSe.___y, tex, pos.xy, OffsetX = 0.5, OffsetY = 0.5, UseComputedLOD=false - }; - #endif -/*--------------------------------------------------------------------------*/ - lumaNwNeSwSe.y += 1.0/384.0; - float2 lumaMinTemp = min(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw); - float2 lumaMaxTemp = max(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw); - float lumaMin = min(lumaMinTemp.x, lumaMinTemp.y); - float lumaMax = max(lumaMaxTemp.x, lumaMaxTemp.y); -/*--------------------------------------------------------------------------*/ - float4 rgbyM = tex2Dlod(tex, float4(pos.xy, 0.0, 0.0)); - #if (FXAA_GREEN_AS_LUMA == 0) - float lumaMinM = min(lumaMin, rgbyM.w); - float lumaMaxM = max(lumaMax, rgbyM.w); - #else - float lumaMinM = min(lumaMin, rgbyM.y); - float lumaMaxM = max(lumaMax, rgbyM.y); - #endif - if((lumaMaxM - lumaMinM) < max(fxaaConsoleEdgeThresholdMin, lumaMax * fxaaConsoleEdgeThreshold)) return rgbyM; -/*--------------------------------------------------------------------------*/ - float2 dir; - dir.x = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.yyxx); - dir.y = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.xyxy); - dir = normalize(dir); -/*--------------------------------------------------------------------------*/ - float4 dir1 = dir.xyxy * fxaaConsoleRcpFrameOpt.xyzw; -/*--------------------------------------------------------------------------*/ - float4 dir2; - float dirAbsMinTimesC = min(abs(dir.x), abs(dir.y)) * fxaaConsoleEdgeSharpness; - dir2 = saturate(fxaaConsole360ConstDir.zzww * dir.xyxy / dirAbsMinTimesC + 0.5); - dir2 = dir2 * fxaaConsole360RcpFrameOpt2.xyxy + fxaaConsole360RcpFrameOpt2.zwzw; -/*--------------------------------------------------------------------------*/ - float4 rgbyN1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.xy, 0.0, 0.0)); - float4 rgbyP1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.zw, 0.0, 0.0)); - float4 rgbyN2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.xy, 0.0, 0.0)); - float4 rgbyP2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.zw, 0.0, 0.0)); -/*--------------------------------------------------------------------------*/ - float4 rgbyA = rgbyN1 + rgbyP1; - float4 rgbyB = rgbyN2 + rgbyP2 + rgbyA * 0.5; -/*--------------------------------------------------------------------------*/ - float4 rgbyR = ((FxaaLuma(rgbyB) - lumaMax) > 0.0) ? rgbyA : rgbyB; - rgbyR = ((FxaaLuma(rgbyB) - lumaMin) > 0.0) ? rgbyR : rgbyA; - return rgbyR; } + } + ; +# endif + /*--------------------------------------------------------------------------*/ + lumaNwNeSwSe.y += 1.0 / 384.0; + float2 lumaMinTemp = min(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw); + float2 lumaMaxTemp = max(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw); + float lumaMin = min(lumaMinTemp.x, lumaMinTemp.y); + float lumaMax = max(lumaMaxTemp.x, lumaMaxTemp.y); + /*--------------------------------------------------------------------------*/ + float4 rgbyM = tex2Dlod(tex, float4(pos.xy, 0.0, 0.0)); +# if (FXAA_GREEN_AS_LUMA == 0) + float lumaMinM = min(lumaMin, rgbyM.w); + float lumaMaxM = max(lumaMax, rgbyM.w); +# else + float lumaMinM = min(lumaMin, rgbyM.y); + float lumaMaxM = max(lumaMax, rgbyM.y); +# endif + if ((lumaMaxM - lumaMinM) < max(fxaaConsoleEdgeThresholdMin, lumaMax * fxaaConsoleEdgeThreshold)) return rgbyM; + /*--------------------------------------------------------------------------*/ + float2 dir; + dir.x = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.yyxx); + dir.y = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.xyxy); + dir = normalize(dir); + /*--------------------------------------------------------------------------*/ + float4 dir1 = dir.xyxy * fxaaConsoleRcpFrameOpt.xyzw; + /*--------------------------------------------------------------------------*/ + float4 dir2; + float dirAbsMinTimesC = min(abs(dir.x), abs(dir.y)) * fxaaConsoleEdgeSharpness; + dir2 = saturate(fxaaConsole360ConstDir.zzww * dir.xyxy / dirAbsMinTimesC + 0.5); + dir2 = dir2 * fxaaConsole360RcpFrameOpt2.xyxy + fxaaConsole360RcpFrameOpt2.zwzw; + /*--------------------------------------------------------------------------*/ + float4 rgbyN1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.xy, 0.0, 0.0)); + float4 rgbyP1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.zw, 0.0, 0.0)); + float4 rgbyN2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.xy, 0.0, 0.0)); + float4 rgbyP2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.zw, 0.0, 0.0)); + /*--------------------------------------------------------------------------*/ + float4 rgbyA = rgbyN1 + rgbyP1; + float4 rgbyB = rgbyN2 + rgbyP2 + rgbyA * 0.5; + /*--------------------------------------------------------------------------*/ + float4 rgbyR = ((FxaaLuma(rgbyB) - lumaMax) > 0.0) ? rgbyA : rgbyB; + rgbyR = ((FxaaLuma(rgbyB) - lumaMin) > 0.0) ? rgbyR : rgbyA; + return rgbyR; +} /*==========================================================================*/ #endif - /*============================================================================ FXAA3 CONSOLE - OPTIMIZED PS3 PIXEL SHADER (NO EARLY EXIT) @@ -1551,7 +1554,7 @@ Pass | Unit | uOp | PC: Op | | | 13 | SCT0 | mad | 48: ADDxc0_s rc, h2, h2.w---; | SCB0/1 | mul | 49: MOVh h0(NE0.xxxx), h1; - + Pass SCT TEX SCB 1: 0% 100% 25% 2: 0% 100% 25% @@ -1590,137 +1593,136 @@ Results 13 cycles, 3 r regs, 923,076,923 pixels/s ============================================================================*/ #if (FXAA_PS3 == 1) && (FXAA_EARLY_EXIT == 0) /*--------------------------------------------------------------------------*/ -#pragma regcount 7 -#pragma disablepc all -#pragma option O3 -#pragma option OutColorPrec=fp16 -#pragma texformat default RGBA8 +# pragma regcount 7 +# pragma disablepc all +# pragma option O3 +# pragma option OutColorPrec =fp16 +# pragma texformat default RGBA8 /*==========================================================================*/ half4 FxaaPixelShader( - // See FXAA Quality FxaaPixelShader() source for docs on Inputs! - FxaaFloat2 pos, - FxaaFloat4 fxaaConsolePosPos, - FxaaTex tex, - FxaaTex fxaaConsole360TexExpBiasNegOne, - FxaaTex fxaaConsole360TexExpBiasNegTwo, - FxaaFloat2 fxaaQualityRcpFrame, - FxaaFloat4 fxaaConsoleRcpFrameOpt, - FxaaFloat4 fxaaConsoleRcpFrameOpt2, - FxaaFloat4 fxaaConsole360RcpFrameOpt2, - FxaaFloat fxaaQualitySubpix, - FxaaFloat fxaaQualityEdgeThreshold, - FxaaFloat fxaaQualityEdgeThresholdMin, - FxaaFloat fxaaConsoleEdgeSharpness, - FxaaFloat fxaaConsoleEdgeThreshold, - FxaaFloat fxaaConsoleEdgeThresholdMin, - FxaaFloat4 fxaaConsole360ConstDir -) { -/*--------------------------------------------------------------------------*/ -// (1) - half4 dir; - half4 lumaNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - lumaNe.w += half(1.0/512.0); - dir.x = -lumaNe.w; - dir.z = -lumaNe.w; - #else - lumaNe.y += half(1.0/512.0); - dir.x = -lumaNe.y; - dir.z = -lumaNe.y; - #endif -/*--------------------------------------------------------------------------*/ -// (2) - half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - dir.x += lumaSw.w; - dir.z += lumaSw.w; - #else - dir.x += lumaSw.y; - dir.z += lumaSw.y; - #endif -/*--------------------------------------------------------------------------*/ -// (3) - half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - dir.x -= lumaNw.w; - dir.z += lumaNw.w; - #else - dir.x -= lumaNw.y; - dir.z += lumaNw.y; - #endif -/*--------------------------------------------------------------------------*/ -// (4) - half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - dir.x += lumaSe.w; - dir.z -= lumaSe.w; - #else - dir.x += lumaSe.y; - dir.z -= lumaSe.y; - #endif -/*--------------------------------------------------------------------------*/ -// (5) - half4 dir1_pos; - dir1_pos.xy = normalize(dir.xyz).xz; - half dirAbsMinTimesC = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS); -/*--------------------------------------------------------------------------*/ -// (6) - half4 dir2_pos; - dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimesC, half(-2.0), half(2.0)); - dir1_pos.zw = pos.xy; - dir2_pos.zw = pos.xy; - half4 temp1N; - temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; -/*--------------------------------------------------------------------------*/ -// (7) - temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0)); - half4 rgby1; - rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; -/*--------------------------------------------------------------------------*/ -// (8) - rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0)); - rgby1 = (temp1N + rgby1) * 0.5; -/*--------------------------------------------------------------------------*/ -// (9) - half4 temp2N; - temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; - temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0)); -/*--------------------------------------------------------------------------*/ -// (10) - half4 rgby2; - rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; - rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0)); - rgby2 = (temp2N + rgby2) * 0.5; -/*--------------------------------------------------------------------------*/ -// (11) - // compilier moves these scalar ops up to other cycles - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaMin = min(min(lumaNw.w, lumaSw.w), min(lumaNe.w, lumaSe.w)); - half lumaMax = max(max(lumaNw.w, lumaSw.w), max(lumaNe.w, lumaSe.w)); - #else - half lumaMin = min(min(lumaNw.y, lumaSw.y), min(lumaNe.y, lumaSe.y)); - half lumaMax = max(max(lumaNw.y, lumaSw.y), max(lumaNe.y, lumaSe.y)); - #endif - rgby2 = (rgby2 + rgby1) * 0.5; -/*--------------------------------------------------------------------------*/ -// (12) - #if (FXAA_GREEN_AS_LUMA == 0) - bool twoTapLt = rgby2.w < lumaMin; - bool twoTapGt = rgby2.w > lumaMax; - #else - bool twoTapLt = rgby2.y < lumaMin; - bool twoTapGt = rgby2.y > lumaMax; - #endif -/*--------------------------------------------------------------------------*/ -// (13) - if(twoTapLt || twoTapGt) rgby2 = rgby1; -/*--------------------------------------------------------------------------*/ - return rgby2; } + // See FXAA Quality FxaaPixelShader() source for docs on Inputs! + FxaaFloat2 pos, + FxaaFloat4 fxaaConsolePosPos, + FxaaTex tex, + FxaaTex fxaaConsole360TexExpBiasNegOne, + FxaaTex fxaaConsole360TexExpBiasNegTwo, + FxaaFloat2 fxaaQualityRcpFrame, + FxaaFloat4 fxaaConsoleRcpFrameOpt, + FxaaFloat4 fxaaConsoleRcpFrameOpt2, + FxaaFloat4 fxaaConsole360RcpFrameOpt2, + FxaaFloat fxaaQualitySubpix, + FxaaFloat fxaaQualityEdgeThreshold, + FxaaFloat fxaaQualityEdgeThresholdMin, + FxaaFloat fxaaConsoleEdgeSharpness, + FxaaFloat fxaaConsoleEdgeThreshold, + FxaaFloat fxaaConsoleEdgeThresholdMin, + FxaaFloat4 fxaaConsole360ConstDir) { + /*--------------------------------------------------------------------------*/ + // (1) + half4 dir; + half4 lumaNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + lumaNe.w += half(1.0 / 512.0); + dir.x = -lumaNe.w; + dir.z = -lumaNe.w; +# else + lumaNe.y += half(1.0 / 512.0); + dir.x = -lumaNe.y; + dir.z = -lumaNe.y; +# endif + /*--------------------------------------------------------------------------*/ + // (2) + half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + dir.x += lumaSw.w; + dir.z += lumaSw.w; +# else + dir.x += lumaSw.y; + dir.z += lumaSw.y; +# endif + /*--------------------------------------------------------------------------*/ + // (3) + half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + dir.x -= lumaNw.w; + dir.z += lumaNw.w; +# else + dir.x -= lumaNw.y; + dir.z += lumaNw.y; +# endif + /*--------------------------------------------------------------------------*/ + // (4) + half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + dir.x += lumaSe.w; + dir.z -= lumaSe.w; +# else + dir.x += lumaSe.y; + dir.z -= lumaSe.y; +# endif + /*--------------------------------------------------------------------------*/ + // (5) + half4 dir1_pos; + dir1_pos.xy = normalize(dir.xyz).xz; + half dirAbsMinTimesC = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS); + /*--------------------------------------------------------------------------*/ + // (6) + half4 dir2_pos; + dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimesC, half(-2.0), half(2.0)); + dir1_pos.zw = pos.xy; + dir2_pos.zw = pos.xy; + half4 temp1N; + temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; + /*--------------------------------------------------------------------------*/ + // (7) + temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0)); + half4 rgby1; + rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; + /*--------------------------------------------------------------------------*/ + // (8) + rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0)); + rgby1 = (temp1N + rgby1) * 0.5; + /*--------------------------------------------------------------------------*/ + // (9) + half4 temp2N; + temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; + temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0)); + /*--------------------------------------------------------------------------*/ + // (10) + half4 rgby2; + rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; + rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0)); + rgby2 = (temp2N + rgby2) * 0.5; + /*--------------------------------------------------------------------------*/ + // (11) + // compilier moves these scalar ops up to other cycles +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaMin = min(min(lumaNw.w, lumaSw.w), min(lumaNe.w, lumaSe.w)); + half lumaMax = max(max(lumaNw.w, lumaSw.w), max(lumaNe.w, lumaSe.w)); +# else + half lumaMin = min(min(lumaNw.y, lumaSw.y), min(lumaNe.y, lumaSe.y)); + half lumaMax = max(max(lumaNw.y, lumaSw.y), max(lumaNe.y, lumaSe.y)); +# endif + rgby2 = (rgby2 + rgby1) * 0.5; + /*--------------------------------------------------------------------------*/ + // (12) +# if (FXAA_GREEN_AS_LUMA == 0) + bool twoTapLt = rgby2.w < lumaMin; + bool twoTapGt = rgby2.w > lumaMax; +# else + bool twoTapLt = rgby2.y < lumaMin; + bool twoTapGt = rgby2.y > lumaMax; +# endif + /*--------------------------------------------------------------------------*/ + // (13) + if (twoTapLt || twoTapGt) rgby2 = rgby1; + /*--------------------------------------------------------------------------*/ + return rgby2; +} /*==========================================================================*/ #endif - /*============================================================================ FXAA3 CONSOLE - OPTIMIZED PS3 PIXEL SHADER (WITH EARLY EXIT) @@ -1856,7 +1858,7 @@ Pass | Unit | uOp | PC: Op | | | 15 | SCT0/1 | mul | 55: MOVh h0(NE0.wwww), h2; | SCB0/1 | mul | 56: MOVh h0(NE0.xxxx), h1; - + Pass SCT TEX SCB 1: 0% 100% 25% 2: 0% 100% 25% @@ -1899,150 +1901,150 @@ Results 15 cycles, 3 r regs, 800,000,000 pixels/s ============================================================================*/ #if (FXAA_PS3 == 1) && (FXAA_EARLY_EXIT == 1) /*--------------------------------------------------------------------------*/ -#pragma regcount 7 -#pragma disablepc all -#pragma option O2 -#pragma option OutColorPrec=fp16 -#pragma texformat default RGBA8 +# pragma regcount 7 +# pragma disablepc all +# pragma option O2 +# pragma option OutColorPrec =fp16 +# pragma texformat default RGBA8 /*==========================================================================*/ half4 FxaaPixelShader( - // See FXAA Quality FxaaPixelShader() source for docs on Inputs! - FxaaFloat2 pos, - FxaaFloat4 fxaaConsolePosPos, - FxaaTex tex, - FxaaTex fxaaConsole360TexExpBiasNegOne, - FxaaTex fxaaConsole360TexExpBiasNegTwo, - FxaaFloat2 fxaaQualityRcpFrame, - FxaaFloat4 fxaaConsoleRcpFrameOpt, - FxaaFloat4 fxaaConsoleRcpFrameOpt2, - FxaaFloat4 fxaaConsole360RcpFrameOpt2, - FxaaFloat fxaaQualitySubpix, - FxaaFloat fxaaQualityEdgeThreshold, - FxaaFloat fxaaQualityEdgeThresholdMin, - FxaaFloat fxaaConsoleEdgeSharpness, - FxaaFloat fxaaConsoleEdgeThreshold, - FxaaFloat fxaaConsoleEdgeThresholdMin, - FxaaFloat4 fxaaConsole360ConstDir -) { -/*--------------------------------------------------------------------------*/ -// (1) - half4 rgbyNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaNe = rgbyNe.w + half(1.0/512.0); - #else - half lumaNe = rgbyNe.y + half(1.0/512.0); - #endif -/*--------------------------------------------------------------------------*/ -// (2) - half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaSwNegNe = lumaSw.w - lumaNe; - #else - half lumaSwNegNe = lumaSw.y - lumaNe; - #endif -/*--------------------------------------------------------------------------*/ -// (3) - half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaMaxNwSw = max(lumaNw.w, lumaSw.w); - half lumaMinNwSw = min(lumaNw.w, lumaSw.w); - #else - half lumaMaxNwSw = max(lumaNw.y, lumaSw.y); - half lumaMinNwSw = min(lumaNw.y, lumaSw.y); - #endif -/*--------------------------------------------------------------------------*/ -// (4) - half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0)); - #if (FXAA_GREEN_AS_LUMA == 0) - half dirZ = lumaNw.w + lumaSwNegNe; - half dirX = -lumaNw.w + lumaSwNegNe; - #else - half dirZ = lumaNw.y + lumaSwNegNe; - half dirX = -lumaNw.y + lumaSwNegNe; - #endif -/*--------------------------------------------------------------------------*/ -// (5) - half3 dir; - dir.y = 0.0; - #if (FXAA_GREEN_AS_LUMA == 0) - dir.x = lumaSe.w + dirX; - dir.z = -lumaSe.w + dirZ; - half lumaMinNeSe = min(lumaNe, lumaSe.w); - #else - dir.x = lumaSe.y + dirX; - dir.z = -lumaSe.y + dirZ; - half lumaMinNeSe = min(lumaNe, lumaSe.y); - #endif -/*--------------------------------------------------------------------------*/ -// (6) - half4 dir1_pos; - dir1_pos.xy = normalize(dir).xz; - half dirAbsMinTimes8 = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS); -/*--------------------------------------------------------------------------*/ -// (7) - half4 dir2_pos; - dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimes8, half(-2.0), half(2.0)); - dir1_pos.zw = pos.xy; - dir2_pos.zw = pos.xy; - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaMaxNeSe = max(lumaNe, lumaSe.w); - #else - half lumaMaxNeSe = max(lumaNe, lumaSe.y); - #endif -/*--------------------------------------------------------------------------*/ -// (8) - half4 temp1N; - temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; - temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0)); - half lumaMax = max(lumaMaxNwSw, lumaMaxNeSe); - half lumaMin = min(lumaMinNwSw, lumaMinNeSe); -/*--------------------------------------------------------------------------*/ -// (9) - half4 rgby1; - rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; - rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0)); - rgby1 = (temp1N + rgby1) * 0.5; -/*--------------------------------------------------------------------------*/ -// (10) - half4 rgbyM = h4tex2Dlod(tex, half4(pos.xy, 0.0, 0.0)); - #if (FXAA_GREEN_AS_LUMA == 0) - half lumaMaxM = max(lumaMax, rgbyM.w); - half lumaMinM = min(lumaMin, rgbyM.w); - #else - half lumaMaxM = max(lumaMax, rgbyM.y); - half lumaMinM = min(lumaMin, rgbyM.y); - #endif -/*--------------------------------------------------------------------------*/ -// (11) - half4 temp2N; - temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; - temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0)); - half4 rgby2; - rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; - half lumaRangeM = (lumaMaxM - lumaMinM) / FXAA_CONSOLE__PS3_EDGE_THRESHOLD; -/*--------------------------------------------------------------------------*/ -// (12) - rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0)); - rgby2 = (temp2N + rgby2) * 0.5; -/*--------------------------------------------------------------------------*/ -// (13) - rgby2 = (rgby2 + rgby1) * 0.5; -/*--------------------------------------------------------------------------*/ -// (14) - #if (FXAA_GREEN_AS_LUMA == 0) - bool twoTapLt = rgby2.w < lumaMin; - bool twoTapGt = rgby2.w > lumaMax; - #else - bool twoTapLt = rgby2.y < lumaMin; - bool twoTapGt = rgby2.y > lumaMax; - #endif - bool earlyExit = lumaRangeM < lumaMax; - bool twoTap = twoTapLt || twoTapGt; -/*--------------------------------------------------------------------------*/ -// (15) - if(twoTap) rgby2 = rgby1; - if(earlyExit) rgby2 = rgbyM; -/*--------------------------------------------------------------------------*/ - return rgby2; } + // See FXAA Quality FxaaPixelShader() source for docs on Inputs! + FxaaFloat2 pos, + FxaaFloat4 fxaaConsolePosPos, + FxaaTex tex, + FxaaTex fxaaConsole360TexExpBiasNegOne, + FxaaTex fxaaConsole360TexExpBiasNegTwo, + FxaaFloat2 fxaaQualityRcpFrame, + FxaaFloat4 fxaaConsoleRcpFrameOpt, + FxaaFloat4 fxaaConsoleRcpFrameOpt2, + FxaaFloat4 fxaaConsole360RcpFrameOpt2, + FxaaFloat fxaaQualitySubpix, + FxaaFloat fxaaQualityEdgeThreshold, + FxaaFloat fxaaQualityEdgeThresholdMin, + FxaaFloat fxaaConsoleEdgeSharpness, + FxaaFloat fxaaConsoleEdgeThreshold, + FxaaFloat fxaaConsoleEdgeThresholdMin, + FxaaFloat4 fxaaConsole360ConstDir) { + /*--------------------------------------------------------------------------*/ + // (1) + half4 rgbyNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaNe = rgbyNe.w + half(1.0 / 512.0); +# else + half lumaNe = rgbyNe.y + half(1.0 / 512.0); +# endif + /*--------------------------------------------------------------------------*/ + // (2) + half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaSwNegNe = lumaSw.w - lumaNe; +# else + half lumaSwNegNe = lumaSw.y - lumaNe; +# endif + /*--------------------------------------------------------------------------*/ + // (3) + half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaMaxNwSw = max(lumaNw.w, lumaSw.w); + half lumaMinNwSw = min(lumaNw.w, lumaSw.w); +# else + half lumaMaxNwSw = max(lumaNw.y, lumaSw.y); + half lumaMinNwSw = min(lumaNw.y, lumaSw.y); +# endif + /*--------------------------------------------------------------------------*/ + // (4) + half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0)); +# if (FXAA_GREEN_AS_LUMA == 0) + half dirZ = lumaNw.w + lumaSwNegNe; + half dirX = -lumaNw.w + lumaSwNegNe; +# else + half dirZ = lumaNw.y + lumaSwNegNe; + half dirX = -lumaNw.y + lumaSwNegNe; +# endif + /*--------------------------------------------------------------------------*/ + // (5) + half3 dir; + dir.y = 0.0; +# if (FXAA_GREEN_AS_LUMA == 0) + dir.x = lumaSe.w + dirX; + dir.z = -lumaSe.w + dirZ; + half lumaMinNeSe = min(lumaNe, lumaSe.w); +# else + dir.x = lumaSe.y + dirX; + dir.z = -lumaSe.y + dirZ; + half lumaMinNeSe = min(lumaNe, lumaSe.y); +# endif + /*--------------------------------------------------------------------------*/ + // (6) + half4 dir1_pos; + dir1_pos.xy = normalize(dir).xz; + half dirAbsMinTimes8 = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS); + /*--------------------------------------------------------------------------*/ + // (7) + half4 dir2_pos; + dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimes8, half(-2.0), half(2.0)); + dir1_pos.zw = pos.xy; + dir2_pos.zw = pos.xy; +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaMaxNeSe = max(lumaNe, lumaSe.w); +# else + half lumaMaxNeSe = max(lumaNe, lumaSe.y); +# endif + /*--------------------------------------------------------------------------*/ + // (8) + half4 temp1N; + temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; + temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0)); + half lumaMax = max(lumaMaxNwSw, lumaMaxNeSe); + half lumaMin = min(lumaMinNwSw, lumaMinNeSe); + /*--------------------------------------------------------------------------*/ + // (9) + half4 rgby1; + rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw; + rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0)); + rgby1 = (temp1N + rgby1) * 0.5; + /*--------------------------------------------------------------------------*/ + // (10) + half4 rgbyM = h4tex2Dlod(tex, half4(pos.xy, 0.0, 0.0)); +# if (FXAA_GREEN_AS_LUMA == 0) + half lumaMaxM = max(lumaMax, rgbyM.w); + half lumaMinM = min(lumaMin, rgbyM.w); +# else + half lumaMaxM = max(lumaMax, rgbyM.y); + half lumaMinM = min(lumaMin, rgbyM.y); +# endif + /*--------------------------------------------------------------------------*/ + // (11) + half4 temp2N; + temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; + temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0)); + half4 rgby2; + rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw; + half lumaRangeM = (lumaMaxM - lumaMinM) / FXAA_CONSOLE__PS3_EDGE_THRESHOLD; + /*--------------------------------------------------------------------------*/ + // (12) + rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0)); + rgby2 = (temp2N + rgby2) * 0.5; + /*--------------------------------------------------------------------------*/ + // (13) + rgby2 = (rgby2 + rgby1) * 0.5; + /*--------------------------------------------------------------------------*/ + // (14) +# if (FXAA_GREEN_AS_LUMA == 0) + bool twoTapLt = rgby2.w < lumaMin; + bool twoTapGt = rgby2.w > lumaMax; +# else + bool twoTapLt = rgby2.y < lumaMin; + bool twoTapGt = rgby2.y > lumaMax; +# endif + bool earlyExit = lumaRangeM < lumaMax; + bool twoTap = twoTapLt || twoTapGt; + /*--------------------------------------------------------------------------*/ + // (15) + if (twoTap) rgby2 = rgby1; + if (earlyExit) rgby2 = rgbyM; + /*--------------------------------------------------------------------------*/ + return rgby2; +} /*==========================================================================*/ #endif \ No newline at end of file diff --git a/libs/sql_table/plugin/qad_sql_table.cpp b/libs/sql_table/plugin/qad_sql_table.cpp index 795bfb6..a1f00fb 100644 --- a/libs/sql_table/plugin/qad_sql_table.cpp +++ b/libs/sql_table/plugin/qad_sql_table.cpp @@ -1,6 +1,7 @@ #include "qad_sql_table.h" -#include "sql_table_plugin.h" + #include "sql_record_plugin.h" +#include "sql_table_plugin.h" QADSQLTable::QADSQLTable(QObject * parent): QObject(parent) { @@ -9,7 +10,7 @@ QADSQLTable::QADSQLTable(QObject * parent): QObject(parent) { } -QList QADSQLTable::customWidgets() const { +QList QADSQLTable::customWidgets() const { return m_widgets; } diff --git a/libs/sql_table/plugin/qad_sql_table.h b/libs/sql_table/plugin/qad_sql_table.h index bb59554..a7d5008 100644 --- a/libs/sql_table/plugin/qad_sql_table.h +++ b/libs/sql_table/plugin/qad_sql_table.h @@ -1,23 +1,24 @@ #ifndef QAD_SQL_TABLE_H #define QAD_SQL_TABLE_H -#include #include +#include -class QADSQLTable: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADSQLTable + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.sql_table") #endif + public: explicit QADSQLTable(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_SQL_TABLE_H diff --git a/libs/sql_table/plugin/sql_record_plugin.cpp b/libs/sql_table/plugin/sql_record_plugin.cpp index 031977d..bb25b8a 100644 --- a/libs/sql_table/plugin/sql_record_plugin.cpp +++ b/libs/sql_table/plugin/sql_record_plugin.cpp @@ -1,5 +1,7 @@ -#include "sql_record_widget.h" #include "sql_record_plugin.h" + +#include "sql_record_widget.h" + #include @@ -9,8 +11,7 @@ SQLRecordPlugin::SQLRecordPlugin(QObject * parent): QObject(parent) { void SQLRecordPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString SQLRecordPlugin::domXml() const { QString SQLRecordPlugin::includeFile() const { return QLatin1String("sql_record_widget.h"); } - diff --git a/libs/sql_table/plugin/sql_record_plugin.h b/libs/sql_table/plugin/sql_record_plugin.h index 8278f86..abdd08d 100644 --- a/libs/sql_table/plugin/sql_record_plugin.h +++ b/libs/sql_table/plugin/sql_record_plugin.h @@ -8,8 +8,9 @@ # include #endif -class SQLRecordPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class SQLRecordPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // SQLRECORDPLUGIN_H diff --git a/libs/sql_table/plugin/sql_table_plugin.cpp b/libs/sql_table/plugin/sql_table_plugin.cpp index 50e0969..b5613bd 100644 --- a/libs/sql_table/plugin/sql_table_plugin.cpp +++ b/libs/sql_table/plugin/sql_table_plugin.cpp @@ -1,5 +1,7 @@ -#include "sql_table_widget.h" #include "sql_table_plugin.h" + +#include "sql_table_widget.h" + #include @@ -9,8 +11,7 @@ SQLTablePlugin::SQLTablePlugin(QObject * parent): QObject(parent) { void SQLTablePlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString SQLTablePlugin::domXml() const { QString SQLTablePlugin::includeFile() const { return QLatin1String("sql_table_widget.h"); } - diff --git a/libs/sql_table/plugin/sql_table_plugin.h b/libs/sql_table/plugin/sql_table_plugin.h index e3ce3f1..5c7f27a 100644 --- a/libs/sql_table/plugin/sql_table_plugin.h +++ b/libs/sql_table/plugin/sql_table_plugin.h @@ -8,8 +8,9 @@ # include #endif -class SQLTablePlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class SQLTablePlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // SQLTABLEPLUGIN_H diff --git a/libs/sql_table/sql_record_widget.cpp b/libs/sql_table/sql_record_widget.cpp index 188b622..071b745 100644 --- a/libs/sql_table/sql_record_widget.cpp +++ b/libs/sql_table/sql_record_widget.cpp @@ -1,15 +1,16 @@ #include "sql_record_widget.h" -#include -#include -#include -#include + +#include +#include +#include #include #include -#include -#include #include -#include +#include +#include +#include #include +#include #include @@ -20,15 +21,14 @@ SQLRecordWidget::SQLRecordWidget(QWidget * parent): QWidget(parent) { } -SQLRecordWidget::~SQLRecordWidget() { -} +SQLRecordWidget::~SQLRecordWidget() {} void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) { - //qDebug() << (q.count() - hidden.size()) << (layout()->count() / 2); + // qDebug() << (q.count() - hidden.size()) << (layout()->count() / 2); if (full_update || (q.count() - hidden.size()) != (layout()->count() / 2)) createWidgets(q); for (int i = 0; i < q.count(); ++i) { - QSqlField f = q.field(i); + QSqlField f = q.field(i); QWidget * val = 0; for (int w = 0; w < cws.size(); ++w) if (cws[w]->objectName() == f.name()) { @@ -36,41 +36,41 @@ void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) { break; } if (val == 0) continue; - if (qobject_cast(val)) { + if (qobject_cast(val)) { if (relations.contains(f.name())) { bool ok = false; int sv(f.value().toInt(&ok)); if (!ok) - qobject_cast(val)->setText(""); + qobject_cast(val)->setText(""); else { - QList > & rv(relations[f.name()]); + QList> & rv(relations[f.name()]); for (int j = 0; j < rv.size(); ++j) { if (sv == rv[j].first) { - qobject_cast(val)->setText(rv[j].second); + qobject_cast(val)->setText(rv[j].second); break; } } } } else - qobject_cast(val)->setText(f.value().toString()); + qobject_cast(val)->setText(f.value().toString()); } - if (qobject_cast(val)) qobject_cast(val)->setChecked(f.value().toBool()); - if (qobject_cast(val)) qobject_cast(val)->setValue(f.value().toDouble()); - if (qobject_cast(val)) qobject_cast(val)->setColor(QColor::fromRgba(f.value().toUInt())); - if (qobject_cast(val)) { + if (qobject_cast(val)) qobject_cast(val)->setChecked(f.value().toBool()); + if (qobject_cast(val)) qobject_cast(val)->setValue(f.value().toDouble()); + if (qobject_cast(val)) qobject_cast(val)->setColor(QColor::fromRgba(f.value().toUInt())); + if (qobject_cast(val)) { QString s = f.value().toString(); - qobject_cast(val)->setValue(s.isEmpty() ? QStringList() : s.split(";")); + qobject_cast(val)->setValue(s.isEmpty() ? QStringList() : s.split(";")); } - if (qobject_cast(val)) { + if (qobject_cast(val)) { bool ok = false; int sv(f.value().toInt(&ok)); if (!ok) - ((QComboBox*)val)->setCurrentIndex(-1); + ((QComboBox *)val)->setCurrentIndex(-1); else { - QList > & rv(relations[f.name()]); + QList> & rv(relations[f.name()]); for (int j = 0; j < rv.size(); ++j) { if (sv == rv[j].first) { - ((QComboBox*)val)->setCurrentIndex(j); + ((QComboBox *)val)->setCurrentIndex(j); break; } } @@ -81,25 +81,39 @@ void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) { void SQLRecordWidget::setFixedValue(const QString & name, const QVariant & value) { - foreach (QWidget * w, cws) { + foreach(QWidget * w, cws) { if (w->objectName() != name) continue; - if (qobject_cast(w)) {qobject_cast(w)->setText(value.toString()); qobject_cast(w)->setReadOnly(true);} - if (qobject_cast(w)) {qobject_cast(w)->setChecked(value.toBool()); w->setEnabled(false);} - if (qobject_cast(w)) {qobject_cast(w)->setValue(value.toDouble()); qobject_cast(w)->setReadOnly(true);} - if (qobject_cast(w)) {qobject_cast(w)->setColor(QColor::fromRgba(value.toUInt())); qobject_cast(w)->setEnabled(false);} - if (qobject_cast(w)) {qobject_cast(w)->setValue(QStringList()); qobject_cast(w)->setEnabled(false);} + if (qobject_cast(w)) { + qobject_cast(w)->setText(value.toString()); + qobject_cast(w)->setReadOnly(true); + } + if (qobject_cast(w)) { + qobject_cast(w)->setChecked(value.toBool()); + w->setEnabled(false); + } + if (qobject_cast(w)) { + qobject_cast(w)->setValue(value.toDouble()); + qobject_cast(w)->setReadOnly(true); + } + if (qobject_cast(w)) { + qobject_cast(w)->setColor(QColor::fromRgba(value.toUInt())); + qobject_cast(w)->setEnabled(false); + } + if (qobject_cast(w)) { + qobject_cast(w)->setValue(QStringList()); + qobject_cast(w)->setEnabled(false); + } } - } void SQLRecordWidget::clearValues() { - foreach (QWidget * w, cws) { - if (qobject_cast(w)) qobject_cast(w)->setText(QString()); - if (qobject_cast(w)) qobject_cast(w)->setChecked(false); - if (qobject_cast(w)) qobject_cast(w)->setValue(0.); - if (qobject_cast(w)) qobject_cast(w)->setColor(Qt::black); - if (qobject_cast(w)) qobject_cast(w)->setValue(QStringList()); + foreach(QWidget * w, cws) { + if (qobject_cast(w)) qobject_cast(w)->setText(QString()); + if (qobject_cast(w)) qobject_cast(w)->setChecked(false); + if (qobject_cast(w)) qobject_cast(w)->setValue(0.); + if (qobject_cast(w)) qobject_cast(w)->setColor(Qt::black); + if (qobject_cast(w)) qobject_cast(w)->setValue(QStringList()); } } @@ -113,28 +127,26 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) { lay->setLabelAlignment(Qt::AlignRight); lay->setContentsMargins(0, 0, 0, 0); setLayout(lay); - //qDebug() << "createWidgets" << q.count(); + // qDebug() << "createWidgets" << q.count(); for (int i = 0; i < q.count(); ++i) { QSqlField f = q.field(i); if (hidden.contains(f.name())) continue; QPair ctr = trColumn(f.name()); - QWidget * val = 0; + QWidget * val = 0; if (relations.contains(f.name())) { if (ro) { val = new QLineEdit(); } else { val = new QComboBox(); - QList > & rv(relations[f.name()]); + QList> & rv(relations[f.name()]); bool ok = false; int sv(f.value().toInt(&ok)); for (int j = 0; j < rv.size(); ++j) { - ((QComboBox*)val)->addItem(rv[j].second, rv[j].first); + ((QComboBox *)val)->addItem(rv[j].second, rv[j].first); if (ok) - if (sv == rv[j].first) - ((QComboBox*)val)->setCurrentIndex(j); + if (sv == rv[j].first) ((QComboBox *)val)->setCurrentIndex(j); } - if (!ok) - ((QComboBox*)val)->setCurrentIndex(-1); + if (!ok) ((QComboBox *)val)->setCurrentIndex(-1); } } else { switch (fieldType(f)) { @@ -144,27 +156,25 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) { case QVariant::ULongLong: case QVariant::Double: val = new QDoubleSpinBox(); - ((QDoubleSpinBox*)val)->setRange(-1E+99, 1E+99); - ((QDoubleSpinBox*)val)->setDecimals(3); break; - case QVariant::String: - val = new QLineEdit(); break; - case QVariant::Bool: - val = new QCheckBox(); break; + ((QDoubleSpinBox *)val)->setRange(-1E+99, 1E+99); + ((QDoubleSpinBox *)val)->setDecimals(3); + break; + case QVariant::String: val = new QLineEdit(); break; + case QVariant::Bool: val = new QCheckBox(); break; case QVariant::Color: val = new ColorButton(); - ((ColorButton*)val)->setUseAlphaChannel(true); - ((ColorButton*)val)->setUseNativeDialog(true); - break; - case QVariant::StringList: - val = new StringListEdit(); + ((ColorButton *)val)->setUseAlphaChannel(true); + ((ColorButton *)val)->setUseNativeDialog(true); break; + case QVariant::StringList: val = new StringListEdit(); break; default: break; } if (f.type() == QVariant::String || f.type() == QVariant::StringList) val->setProperty("_string", true); } if (val != 0) { QString lt = ctr.first.left(1).toUpper() + ctr.first.right(ctr.first.length() - 1); - while (lt.endsWith("_")) lt.chop(1); + while (lt.endsWith("_")) + lt.chop(1); QLabel * lbl = new QLabel(lt + ":"); lbl->setToolTip(ctr.second); cws << lbl; @@ -172,8 +182,7 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) { cws << val; lay->addRow(lbl, val); } else { - if (!hidden.contains(ctr.first)) - hidden << ctr.first; + if (!hidden.contains(ctr.first)) hidden << ctr.first; } } updateWidgets(); @@ -182,13 +191,13 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) { void SQLRecordWidget::updateWidgets() { - foreach (QWidget * w, cws) { - if (qobject_cast(w)) qobject_cast(w)->setReadOnly(ro); - if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); - if (qobject_cast(w)) qobject_cast(w)->setReadOnly(ro); - if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); - if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); - if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); + foreach(QWidget * w, cws) { + if (qobject_cast(w)) qobject_cast(w)->setReadOnly(ro); + if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); + if (qobject_cast(w)) qobject_cast(w)->setReadOnly(ro); + if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); + if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); + if (qobject_cast(w)) qobject_cast(w)->setEnabled(!ro); } } @@ -212,7 +221,7 @@ QVariant::Type SQLRecordWidget::fieldType(const QSqlField & f) { void SQLRecordWidget::addTranslation(const QString & file) { QPIConfig conf(file, QIODevice::ReadOnly, QPIConfig::Config); QPIConfig::Branch ae = conf.allLeaves(); - foreach (QPIConfig::Entry * e, ae) + foreach(QPIConfig::Entry * e, ae) translates[e->name()] = QPair(e->value(), e->comment()); } @@ -220,50 +229,52 @@ void SQLRecordWidget::addTranslation(const QString & file) { QString SQLRecordWidget::getValuesQuery() const { QString ret("("); bool first = true; - foreach (QWidget * w, cws) { + foreach(QWidget * w, cws) { QWidget * vw(0); - if (qobject_cast(w)) {if (!qobject_cast(w)->text().isEmpty()) vw = w;} - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) { + if (!qobject_cast(w)->text().isEmpty()) vw = w; + } + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; if (vw == 0) continue; if (!first) ret += ","; first = false; ret += vw->objectName(); } ret += ") VALUES ("; - foreach (QWidget * w, cws) { + foreach(QWidget * w, cws) { QWidget * vw(0); - if (qobject_cast(w)) { - if (!qobject_cast(w)->text().isEmpty()) { - vw = w; + if (qobject_cast(w)) { + if (!qobject_cast(w)->text().isEmpty()) { + vw = w; bool q = w->property("_string").toBool(); if (q) ret += "'"; - ret += qobject_cast(w)->text(); + ret += qobject_cast(w)->text(); if (q) ret += "'"; } } - if (qobject_cast(w)) { + if (qobject_cast(w)) { vw = w; - ret += qobject_cast(w)->isChecked() ? "1" : "0"; + ret += qobject_cast(w)->isChecked() ? "1" : "0"; } - if (qobject_cast(w)) { + if (qobject_cast(w)) { vw = w; - ret += QString::number(qobject_cast(w)->value()); + ret += QString::number(qobject_cast(w)->value()); } - if (qobject_cast(w)) { + if (qobject_cast(w)) { vw = w; - ret += QString::number(qobject_cast(w)->color().rgba()); + ret += QString::number(qobject_cast(w)->color().rgba()); } - if (qobject_cast(w)) { + if (qobject_cast(w)) { vw = w; - ret += "'" + qobject_cast(w)->value().join(";") + "'"; + ret += "'" + qobject_cast(w)->value().join(";") + "'"; } - if (qobject_cast(w)) { + if (qobject_cast(w)) { vw = w; - ret += ((QComboBox*)w)->itemData(((QComboBox*)w)->currentIndex(), Qt::UserRole).toString(); + ret += ((QComboBox *)w)->itemData(((QComboBox *)w)->currentIndex(), Qt::UserRole).toString(); } if (vw == 0) continue; ret += ","; @@ -277,38 +288,34 @@ QString SQLRecordWidget::getValuesQuery() const { QString SQLRecordWidget::getUpdateQuery() const { QString ret; bool first = true; - foreach (QWidget * w, cws) { + foreach(QWidget * w, cws) { QWidget * vw(0); - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; - if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; + if (qobject_cast(w)) vw = w; if (vw == 0) continue; if (!first) ret += ","; first = false; ret += vw->objectName() + "="; - if (qobject_cast(w)) { - if (qobject_cast(w)->text().isEmpty()) + if (qobject_cast(w)) { + if (qobject_cast(w)->text().isEmpty()) ret += "null"; else { bool q = w->property("_string").toBool(); if (q) ret += "'"; - ret += qobject_cast(w)->text(); + ret += qobject_cast(w)->text(); if (q) ret += "'"; } } - if (qobject_cast(w)) - ret += qobject_cast(w)->isChecked() ? "1" : "0"; - if (qobject_cast(w)) - ret += QString::number(qobject_cast(w)->value()); - if (qobject_cast(w)) - ret += QString::number(qobject_cast(w)->color().rgba()); - if (qobject_cast(w)) - ret += "'" + qobject_cast(w)->value().join(";") + "'"; - if (qobject_cast(w)) { - QString cd = ((QComboBox*)w)->itemData(((QComboBox*)w)->currentIndex(), Qt::UserRole).toString(); + if (qobject_cast(w)) ret += qobject_cast(w)->isChecked() ? "1" : "0"; + if (qobject_cast(w)) ret += QString::number(qobject_cast(w)->value()); + if (qobject_cast(w)) ret += QString::number(qobject_cast(w)->color().rgba()); + if (qobject_cast(w)) ret += "'" + qobject_cast(w)->value().join(";") + "'"; + if (qobject_cast(w)) { + QString cd = ((QComboBox *)w)->itemData(((QComboBox *)w)->currentIndex(), Qt::UserRole).toString(); ret += cd.isEmpty() ? "null" : cd; } } @@ -327,29 +334,27 @@ void SQLRecordWidget::updateRelations() { if (!db.isOpen()) return; for (int i = 0; i < relations_src.size(); ++i) { QSqlQuery q(QString("SELECT %1,%2 FROM %3").arg(relations_src[i].key, relations_src[i].ocol, relations_src[i].table), db); - QList > cr; + QList> cr; while (q.next()) cr << QPair(q.value(0).toInt(), q.value(1).toString()); relations[relations_src[i].tcol] = cr; } - QFormLayout * lay = (QFormLayout*)layout(); + QFormLayout * lay = (QFormLayout *)layout(); if (!lay) return; for (int i = 0; i < lay->rowCount(); ++i) { QString name = lay->itemAt(i, QFormLayout::FieldRole)->widget()->objectName(); if (hidden.contains(name)) continue; - QComboBox * val = qobject_cast(lay->itemAt(i, QFormLayout::FieldRole)->widget()); + QComboBox * val = qobject_cast(lay->itemAt(i, QFormLayout::FieldRole)->widget()); if (!val) continue; if (!relations.contains(name)) continue; - QList > & rv(relations[name]); + QList> & rv(relations[name]); bool ok = false; int sv(val->itemData(val->currentIndex()).toInt()); val->clear(); for (int j = 0; j < rv.size(); ++j) { val->addItem(rv[j].second, rv[j].first); - if (sv == rv[j].first) - val->setCurrentIndex(j); + if (sv == rv[j].first) val->setCurrentIndex(j); } - if (!ok) - val->setCurrentIndex(-1); + if (!ok) val->setCurrentIndex(-1); } } diff --git a/libs/sql_table/sql_record_widget.h b/libs/sql_table/sql_record_widget.h index 1e0eb91..d3d5b13 100644 --- a/libs/sql_table/sql_record_widget.h +++ b/libs/sql_table/sql_record_widget.h @@ -1,85 +1,109 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SQL_RECORD_WIDGET_H #define SQL_RECORD_WIDGET_H -#include -#include -#include -#include +#include "qad_sql_table_export.h" + #include #include -#include "qad_sql_table_export.h" +#include +#include +#include +#include class QAD_SQL_TABLE_EXPORT SQLRecordWidget: public QWidget { Q_OBJECT + public: SQLRecordWidget(QWidget * parent = 0); ~SQLRecordWidget(); - + void setRecord(const QSqlRecord & q, bool full_update = false); - void setReadOnly(bool yes) {ro = yes; updateWidgets();} + void setReadOnly(bool yes) { + ro = yes; + updateWidgets(); + } void setFixedValue(const QString & name, const QVariant & value); - void setTypeForName(const QString & name, const QString & type) {ftypes[name] = type;} + void setTypeForName(const QString & name, const QString & type) { ftypes[name] = type; } void clearValues(); - void removeWidgets() {qDeleteAll(cws); cws.clear();} - - void hideColumn(const QString & col) {hidden << col;} - void showColumn(const QString & col) {hidden.remove(col);} - void showColumns() {hidden.clear();} - void addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) {relations_src << RelationSrc(this_column, other_table, other_key, other_column); updateRelations();} - void removeRelations() {relations_src.clear(); updateRelations();} + void removeWidgets() { + qDeleteAll(cws); + cws.clear(); + } + + void hideColumn(const QString & col) { hidden << col; } + void showColumn(const QString & col) { hidden.remove(col); } + void showColumns() { hidden.clear(); } + void addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) { + relations_src << RelationSrc(this_column, other_table, other_key, other_column); + updateRelations(); + } + void removeRelations() { + relations_src.clear(); + updateRelations(); + } void addTranslation(const QString & file); - void setConnectionName(const QString &conn_name) {connection_name = conn_name;} - QString connectionName() const {return connection_name;} + void setConnectionName(const QString & conn_name) { connection_name = conn_name; } + QString connectionName() const { return connection_name; } QString getValuesQuery() const; QString getUpdateQuery() const; bool isEmpty() const; - QWidget * valueWidget(const QString & name) const {foreach (QWidget * w, cws) if (w->objectName() == name) return w; return 0;} - + QWidget * valueWidget(const QString & name) const { + foreach(QWidget * w, cws) + if (w->objectName() == name) return w; + return 0; + } + void updateRelations(); - + protected: - QPair trColumn(const QString & n) {QPair trn = translates.value(n); if (trn.first.isEmpty()) return QPair(n, ""); return trn;} + QPair trColumn(const QString & n) { + QPair trn = translates.value(n); + if (trn.first.isEmpty()) return QPair(n, ""); + return trn; + } void createWidgets(const QSqlRecord & q); void updateWidgets(); QVariant::Type fieldType(const QSqlField & f); - + struct QAD_SQL_TABLE_EXPORT RelationSrc { - RelationSrc(const QString & v0 = QString(), const QString & v1 = QString(), const QString & v2 = QString(), const QString & v3 = QString()): - tcol(v0), - table(v1), - key(v2), - ocol(v3) - {} + RelationSrc(const QString & v0 = QString(), + const QString & v1 = QString(), + const QString & v2 = QString(), + const QString & v3 = QString()) + : tcol(v0) + , table(v1) + , key(v2) + , ocol(v3) {} QString tcol; QString table; QString key; QString ocol; }; - - QMap > translates; + + QMap> translates; QVector relations_src; - QMap > > relations; + QMap>> relations; QMap ftypes; QSet hidden; QWidgetList cws; @@ -89,7 +113,6 @@ protected: signals: void updateRequest(); void widgetsCreated(); - }; #endif // SQL_RECORD_WIDGET_H diff --git a/libs/sql_table/sql_table_widget.cpp b/libs/sql_table/sql_table_widget.cpp index b57b560..dd15a8d 100644 --- a/libs/sql_table/sql_table_widget.cpp +++ b/libs/sql_table/sql_table_widget.cpp @@ -1,29 +1,37 @@ #include "sql_table_widget.h" + +#include "qad_types.h" #include "ui_sql_table_widget.h" + +#include #include -#include #include #include -#include -#include "qad_types.h" +#include QString SQLTableWidget::_dir; -ColumnProperties::ColumnProperties(const QString & table_, const QString & type_, const QString & name_, const QString & def_, bool auto_, bool prim_, bool option_) { - visible = true; - table = table_; - name = name_; - def = def_; +ColumnProperties::ColumnProperties(const QString & table_, + const QString & type_, + const QString & name_, + const QString & def_, + bool auto_, + bool prim_, + bool option_) { + visible = true; + table = table_; + name = name_; + def = def_; auto_increment = auto_; - primary = prim_; - optional = option_; + primary = prim_; + optional = option_; int bs = type_.indexOf("("), bf = type_.indexOf(")"); - size = type_.mid(bs + 1, bf - bs - 1).toInt(); + size = type_.mid(bs + 1, bf - bs - 1).toInt(); key_column = 0; - type = typeFromString(type_.toLower()); - is_text = (type == ColumnProperties::Chars || type == ColumnProperties::Text); + type = typeFromString(type_.toLower()); + is_text = (type == ColumnProperties::Chars || type == ColumnProperties::Text); } @@ -33,19 +41,17 @@ ColumnProperties::DataType ColumnProperties::typeFromString(const QString & n) { if (n.indexOf("time") >= 0) return ColumnProperties::Time; if (n.indexOf("int") >= 0) return ColumnProperties::Int; if (n.indexOf("char") >= 0) return ColumnProperties::Chars; - if (n.indexOf("dec") >= 0 || n.indexOf("numeric") >= 0 || n.indexOf("real") >= 0 || - n.indexOf("float") >= 0 || n.indexOf("double") >= 0) return ColumnProperties::Float; + if (n.indexOf("dec") >= 0 || n.indexOf("numeric") >= 0 || n.indexOf("real") >= 0 || n.indexOf("float") >= 0 || n.indexOf("double") >= 0) + return ColumnProperties::Float; if (n.indexOf("text") >= 0) return ColumnProperties::Text; if (n.indexOf("blob") >= 0) return ColumnProperties::Binary; return ColumnProperties::Unknown; } - - QVariant SQLQueryModel::data(const QModelIndex & item, int role) const { QVariant var = QSqlQueryModel::data(item, role); - //QVariant::Type t = var.type(); + // QVariant::Type t = var.type(); /*if (t == QVariant::Date) return var.toDate().toString("dd.MM.yyyy"); if (t == QVariant::Time) return var.toTime().toString("hh:mm:ss"); if (t == QVariant::DateTime) return var.toDateTime().toString("dd.MM.yyyy hh:mm:ss");*/ @@ -53,25 +59,23 @@ QVariant SQLQueryModel::data(const QModelIndex & item, int role) const { } -bool SQLQueryModel::setData(const QModelIndex& index, const QVariant & value, int role) { +bool SQLQueryModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (value.isValid() && role == Qt::EditRole) { QSqlQuery q(QSqlDatabase::database(conn_name)); - int col = mapColumn(index.column()); + int col = mapColumn(index.column()); ColumnProperties::DataType t = column_props[col].type; - bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || - t == ColumnProperties::Date || t == ColumnProperties::Time || - t == ColumnProperties::ColumnProperties::DateTime); - QString val = value.toString(); + bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || t == ColumnProperties::Date || + t == ColumnProperties::Time || t == ColumnProperties::ColumnProperties::DateTime); + QString val = value.toString(); if (t == ColumnProperties::Date) val = value.toDate().toString("yyyy-MM-dd"); if (t == ColumnProperties::Time) val = value.toTime().toString("hh:mm:ss"); if (t == ColumnProperties::DateTime) val = value.toDateTime().toString("yyyy-MM-dd hh:mm:ss"); - if (!q.exec("UPDATE " + table_ + " SET " + column_props[col].name + "=" + - (quotes ? "'" : "") + val + (quotes ? "'" : "") + - " WHERE " + column_props[0].name + "=" + record(index.row()).value(0).toString() + ";")) { + if (!q.exec("UPDATE " + table_ + " SET " + column_props[col].name + "=" + (quotes ? "'" : "") + val + (quotes ? "'" : "") + + " WHERE " + column_props[0].name + "=" + record(index.row()).value(0).toString() + ";")) { qDebug() << "[UPDATE]" << q.lastQuery() << "Error:" << q.lastError(); return false; } - //qDebug() << "[UPDATE]" << q.lastQuery(); + // qDebug() << "[UPDATE]" << q.lastQuery(); dataChanged(index, index); updateTable(true); emit tableChanged(); @@ -81,19 +85,34 @@ bool SQLQueryModel::setData(const QModelIndex& index, const QVariant & value, in } - - -SQLUniEdit::SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop), connection_name(conn_name) { - wtext = 0; wint = 0; wfloat = 0; wdate = 0; wtime = 0; wdatetime = 0; wrelation = 0; +SQLUniEdit::SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent) + : QWidget(parent) + , prop_(prop) + , connection_name(conn_name) { + wtext = 0; + wint = 0; + wfloat = 0; + wdate = 0; + wtime = 0; + wdatetime = 0; + wrelation = 0; setProp(prop_); - w_ << (QWidget **)&wtext << (QWidget **)&wint << (QWidget **)&wfloat << (QWidget **)&wdate << (QWidget **)&wtime << (QWidget **)&wdatetime << (QWidget **)&wrelation; + w_ << (QWidget **)&wtext << (QWidget **)&wint << (QWidget **)&wfloat << (QWidget **)&wdate << (QWidget **)&wtime + << (QWidget **)&wdatetime << (QWidget **)&wrelation; } void SQLUniEdit::setProp(const ColumnProperties & p) { - for (int i = 0; i < w_.size(); ++i) deleteW(*w_[i]); - wtext = 0; wint = 0; wfloat = 0; wdate = 0; wtime = 0; wdatetime = 0; wrelation = 0; - prop_ = p; + for (int i = 0; i < w_.size(); ++i) + deleteW(*w_[i]); + wtext = 0; + wint = 0; + wfloat = 0; + wdate = 0; + wtime = 0; + wdatetime = 0; + wrelation = 0; + prop_ = p; if (prop_.isRelation()) { wrelation = new QComboBox(this); wrelation->installEventFilter(this); @@ -103,15 +122,44 @@ void SQLUniEdit::setProp(const ColumnProperties & p) { } else { ColumnProperties::DataType t = prop_.getType(); switch (t) { - case ColumnProperties::Int: wint = new QSpinBox(this); wint->setRange(-0x7FFFFFFF, 0x7FFFFFFF); connect(wint, SIGNAL(valueChanged(int)), this, SLOT(value_int(int))); break; - case ColumnProperties::Float: wfloat = new QDoubleSpinBox(this); wfloat->setRange(-1E+300, 1E+300); wfloat->setDecimals(2); connect(wfloat, SIGNAL(valueChanged(double)), this, SLOT(value_float(double))); break; - case ColumnProperties::Date: wdate = new QDateEdit(this); wdate->setDisplayFormat("dd.MM.yyyy"); wdate->setCalendarPopup(true); wdate->setDate(QDate::currentDate()); connect(wdate, SIGNAL(dateChanged(QDate)), this, SLOT(value_date(QDate))); break; - case ColumnProperties::Time: wtime = new QTimeEdit(this); wtime->setDisplayFormat("hh:mm:ss"); wtime->setTime(QTime::currentTime()); connect(wtime, SIGNAL(timeChanged(QTime)), this, SLOT(value_time(QTime))); break; - case ColumnProperties::DateTime: wdatetime = new QDateTimeEdit(this); wdatetime->setDisplayFormat("dd.MM.yyyy hh:mm:ss"); wdatetime->setCalendarPopup(true); wdatetime->setDateTime(QDateTime::currentDateTime()); connect(wdatetime, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(value_datetime(QDateTime))); break; + case ColumnProperties::Int: + wint = new QSpinBox(this); + wint->setRange(-0x7FFFFFFF, 0x7FFFFFFF); + connect(wint, SIGNAL(valueChanged(int)), this, SLOT(value_int(int))); + break; + case ColumnProperties::Float: + wfloat = new QDoubleSpinBox(this); + wfloat->setRange(-1E+300, 1E+300); + wfloat->setDecimals(2); + connect(wfloat, SIGNAL(valueChanged(double)), this, SLOT(value_float(double))); + break; + case ColumnProperties::Date: + wdate = new QDateEdit(this); + wdate->setDisplayFormat("dd.MM.yyyy"); + wdate->setCalendarPopup(true); + wdate->setDate(QDate::currentDate()); + connect(wdate, SIGNAL(dateChanged(QDate)), this, SLOT(value_date(QDate))); + break; + case ColumnProperties::Time: + wtime = new QTimeEdit(this); + wtime->setDisplayFormat("hh:mm:ss"); + wtime->setTime(QTime::currentTime()); + connect(wtime, SIGNAL(timeChanged(QTime)), this, SLOT(value_time(QTime))); + break; + case ColumnProperties::DateTime: + wdatetime = new QDateTimeEdit(this); + wdatetime->setDisplayFormat("dd.MM.yyyy hh:mm:ss"); + wdatetime->setCalendarPopup(true); + wdatetime->setDateTime(QDateTime::currentDateTime()); + connect(wdatetime, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(value_datetime(QDateTime))); + break; case ColumnProperties::Chars: case ColumnProperties::Text: case ColumnProperties::Unknown: - default: wtext = new QLineEdit(this); connect(wtext, SIGNAL(textChanged(QString)), this, SLOT(value_text(QString))); break; + default: + wtext = new QLineEdit(this); + connect(wtext, SIGNAL(textChanged(QString)), this, SLOT(value_text(QString))); + break; } } for (int i = 0; i < w_.size(); ++i) @@ -123,9 +171,8 @@ void SQLUniEdit::setProp(const ColumnProperties & p) { QString SQLUniEdit::value(bool for_insert) { QString ret; ColumnProperties::DataType t = (for_insert ? prop_.type : prop_.getType()); - bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || - t == ColumnProperties::Date || t == ColumnProperties::Time || - t == ColumnProperties::ColumnProperties::DateTime); + bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || t == ColumnProperties::Date || + t == ColumnProperties::Time || t == ColumnProperties::ColumnProperties::DateTime); if (quotes) ret = "'"; if (prop_.isRelation()) if (for_insert) @@ -133,15 +180,20 @@ QString SQLUniEdit::value(bool for_insert) { else ret += wrelation->currentText(); else { - if (wint != 0) ret += QString::number(wint->value()); + if (wint != 0) + ret += QString::number(wint->value()); else { - if (wfloat != 0) ret += QString::number(wfloat->value()); + if (wfloat != 0) + ret += QString::number(wfloat->value()); else { - if (wdate != 0) ret += wdate->date().toString("yyyy-MM-dd"); + if (wdate != 0) + ret += wdate->date().toString("yyyy-MM-dd"); else { - if (wtime != 0) ret += wtime->time().toString("hh:mm:ss"); + if (wtime != 0) + ret += wtime->time().toString("hh:mm:ss"); else { - if (wdatetime != 0) ret += wdatetime->dateTime().toString("yyyy-MM-dd hh:mm:ss"); + if (wdatetime != 0) + ret += wdatetime->dateTime().toString("yyyy-MM-dd hh:mm:ss"); else { ret += wtext->text(); } @@ -157,23 +209,27 @@ QString SQLUniEdit::value(bool for_insert) { bool SQLUniEdit::eventFilter(QObject * o, QEvent * e) { - if (e->type() == QEvent::MouseButtonPress) - updateRelation(); + if (e->type() == QEvent::MouseButtonPress) updateRelation(); return QWidget::eventFilter(o, e); } void SQLUniEdit::setValue(const QVariant & value) { if (prop_.isRelation()) return; - if (wint != 0) wint->setValue(value.toInt()); + if (wint != 0) + wint->setValue(value.toInt()); else { - if (wfloat != 0) wfloat->setValue(value.toDouble()); + if (wfloat != 0) + wfloat->setValue(value.toDouble()); else { - if (wdate != 0) wdate->setDate(value.toDate()); + if (wdate != 0) + wdate->setDate(value.toDate()); else { - if (wtime != 0) wtime->setTime(value.toTime()); + if (wtime != 0) + wtime->setTime(value.toTime()); else { - if (wdatetime != 0) wdatetime->setDateTime(value.toDateTime()); + if (wdatetime != 0) + wdatetime->setDateTime(value.toDateTime()); else { wtext->setText(value.toString()); } @@ -181,13 +237,12 @@ void SQLUniEdit::setValue(const QVariant & value) { } } } - } void SQLUniEdit::updateRelation() { prop_.relation_list = SQLTableWidget::getColumnValues(prop_.relation_table, prop_.relation_key, prop_.relation_column, connection_name); - int pi = wrelation->currentIndex(); + int pi = wrelation->currentIndex(); wrelation->blockSignals(true); wrelation->clear(); for (int i = 0; i < prop_.relation_list.size(); ++i) @@ -197,7 +252,6 @@ void SQLUniEdit::updateRelation() { } - SQLNewEdit::SQLNewEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop) { line = new SQLUniEdit(prop, conn_name); line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); @@ -224,14 +278,14 @@ void SQLNewEdit::setProp(const ColumnProperties & p) { } - SQLFilterEdit::SQLFilterEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop) { line = new SQLUniEdit(prop, conn_name); line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); combo = new QComboBox(); combo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QStringList sl; - sl << " " << "=" << QString::fromUtf8("≈") << QString::fromUtf8("≠") << ">" << QString::fromUtf8("≥") << "<" << QString::fromUtf8("≤"); + sl << " " + << "=" << QString::fromUtf8("≈") << QString::fromUtf8("≠") << ">" << QString::fromUtf8("≥") << "<" << QString::fromUtf8("≤"); combo->addItems(sl); combo->setCurrentIndex(0); connect(line, SIGNAL(valueChanged(QVariant)), this, SIGNAL(filterChanged())); @@ -275,14 +329,17 @@ QString SQLFilterEdit::filter() const { void SQLFilterEdit::clear() { line->setValue(QVariant()); combo->setCurrentIndex(0); - } - - -SQLItemDelegate::SQLItemDelegate(QList & cp, QVector & ci, bool & ro, const QString & conn_name, QObject * parent): - QStyledItemDelegate(parent), column_props(cp), column_indexes(ci), read_only(ro), connection_name(conn_name) {;} +SQLItemDelegate::SQLItemDelegate(QList & cp, QVector & ci, bool & ro, const QString & conn_name, QObject * parent) + : QStyledItemDelegate(parent) + , column_props(cp) + , column_indexes(ci) + , read_only(ro) + , connection_name(conn_name) { + ; +} QWidget * SQLItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const { @@ -290,19 +347,24 @@ QWidget * SQLItemDelegate::createEditor(QWidget * parent, const QStyleOptionView ColumnProperties & cp(column_props[mapColumn(index.column())]); if (cp.isRelation()) { cp.relation_list = SQLTableWidget::getColumnValues(cp.relation_table, cp.relation_key, cp.relation_column, connection_name); - QComboBox * w = new QComboBox(parent); + QComboBox * w = new QComboBox(parent); w->setGeometry(option.rect); for (int i = 0; i < cp.relation_list.size(); ++i) { w->addItem(cp.relation_list[i].second, cp.relation_list[i].first); - if (index.data().toString() == cp.relation_list[i].second) - w->setCurrentIndex(i); + if (index.data().toString() == cp.relation_list[i].second) w->setCurrentIndex(i); } return w; } else { QWidget * w = QStyledItemDelegate::createEditor(parent, option, index); - if (qobject_cast(w)) {qobject_cast(w)->setDisplayFormat("hh:mm:ss");} - else if (qobject_cast(w)) {qobject_cast(w)->setCalendarPopup(true); qobject_cast(w)->setDisplayFormat("dd.MM.yyyy");} - else if (qobject_cast(w)) {qobject_cast(w)->setCalendarPopup(true); qobject_cast(w)->setDisplayFormat("dd.MM.yyyy hh:mm:ss");} + if (qobject_cast(w)) { + qobject_cast(w)->setDisplayFormat("hh:mm:ss"); + } else if (qobject_cast(w)) { + qobject_cast(w)->setCalendarPopup(true); + qobject_cast(w)->setDisplayFormat("dd.MM.yyyy"); + } else if (qobject_cast(w)) { + qobject_cast(w)->setCalendarPopup(true); + qobject_cast(w)->setDisplayFormat("dd.MM.yyyy hh:mm:ss"); + } return w; } return 0; @@ -319,20 +381,19 @@ QString SQLItemDelegate::displayText(const QVariant & value, const QLocale & loc void SQLItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const { - if (qobject_cast(editor)) { - model->setData(index, qobject_cast(editor)->itemData(qobject_cast(editor)->currentIndex())); + if (qobject_cast(editor)) { + model->setData(index, qobject_cast(editor)->itemData(qobject_cast(editor)->currentIndex())); return; } QStyledItemDelegate::setModelData(editor, model, index); } - SQLTableWidget::SQLTableWidget(QWidget * parent): QWidget(parent), filters_group(this) { ui = new Ui::SQLTableWidget(); ui->setupUi(this); - model = 0; - timer = 0; + model = 0; + timer = 0; connection_name = QSqlDatabase::defaultConnection; filters_active = first_update = debug = true; table_opened = read_only = false; @@ -345,30 +406,33 @@ SQLTableWidget::SQLTableWidget(QWidget * parent): QWidget(parent), filters_group ui->view->setItemDelegate(new SQLItemDelegate(column_props, column_indexes, read_only, connection_name)); ui->view->horizontalHeader()->setItemDelegate(new QItemDelegate()); ui->view->verticalHeader()->setDefaultSectionSize(fontHeight(this) * 1.5); - //qDebug() << view->horizontalHeader()->itemDelegate(); - //qDebug() << fontMetrics().elidedText(, Qt::ElideNone, 30, Qt::TextWordWrap); + // qDebug() << view->horizontalHeader()->itemDelegate(); + // qDebug() << fontMetrics().elidedText(, Qt::ElideNone, 30, Qt::TextWordWrap); setTableVisible(false); connect(ui->view->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(header_sectionResized(int, int, int))); - connect(ui->view->horizontalHeader(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(header_sortIndicatorChanged(int, Qt::SortOrder))); + connect(ui->view->horizontalHeader(), + SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), + this, + SLOT(header_sortIndicatorChanged(int, Qt::SortOrder))); connect(ui->view->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrolled(int))); - - - //act_add.setText(tr("Add ...")); - //act_del.setText(tr("Remove selected")); + + + // act_add.setText(tr("Add ...")); + // act_del.setText(tr("Remove selected")); action_del = new QAction(QIcon(":/icons/edit-delete.png"), tr("Remove selected"), this); connect(action_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered())); popup_menu.addAction(action_del); ui->actionFilter_AND->setChecked(true); filters_group.addAction(ui->actionFilter_AND); filters_group.addAction(ui->actionFilter_OR); - connect(&filters_group, SIGNAL(triggered(QAction * )), this, SLOT(updateTable())); + connect(&filters_group, SIGNAL(triggered(QAction *)), this, SLOT(updateTable())); popup_filter.addAction(ui->actionFiltersClear); popup_filter.addSeparator(); popup_filter.addAction(ui->actionFilter_AND); popup_filter.addAction(ui->actionFilter_OR); ui->buttonFilterConfig->setMenu(&popup_filter); - //connect(&act_add, SIGNAL(triggered(bool)), this, SLOT(add_triggered())); - //connect(&act_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered())); + // connect(&act_add, SIGNAL(triggered(bool)), this, SLOT(add_triggered())); + // connect(&act_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered())); } @@ -381,14 +445,20 @@ SQLTableWidget::~SQLTableWidget() { bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) { if (o == ui->view) { if (e->type() == QEvent::KeyPress) { - QKeyEvent * ke = (QKeyEvent * )e; - if (ke->key() == Qt::Key_Home) {ui->view->selectRow(0); return true;} - if (ke->key() == Qt::Key_End) {ui->view->selectRow(ui->view->verticalHeader()->count() - 1); return true;} + QKeyEvent * ke = (QKeyEvent *)e; + if (ke->key() == Qt::Key_Home) { + ui->view->selectRow(0); + return true; + } + if (ke->key() == Qt::Key_End) { + ui->view->selectRow(ui->view->verticalHeader()->count() - 1); + return true; + } } } if (o == ui->view->viewport()) { if (e->type() == QEvent::MouseButtonPress) { - QMouseEvent * me = (QMouseEvent * )e; + QMouseEvent * me = (QMouseEvent *)e; if (me->button() == Qt::RightButton) { action_del->setVisible(!read_only); popup_menu.popup(me->globalPos()); @@ -396,24 +466,24 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) { } } if (o == ui->view->horizontalHeader()->viewport()) { - QMouseEvent * me = (QMouseEvent * )e; - if (e->type() == QEvent::MouseButtonPress) - pp = me->pos(); + QMouseEvent * me = (QMouseEvent *)e; + if (e->type() == QEvent::MouseButtonPress) pp = me->pos(); if (e->type() == QEvent::MouseButtonRelease) { if ((me->pos() - pp).manhattanLength() < QApplication::startDragDistance()) { if (me->button() == Qt::LeftButton) { int ci = ui->view->horizontalHeader()->logicalIndexAt(me->pos()), - ri = ui->view->horizontalHeader()->logicalIndexAt(me->pos() + QPoint(3, 0)), - li = ui->view->horizontalHeader()->logicalIndexAt(me->pos() - QPoint(3, 0)); - //qDebug() << ci << ri << li; - if ((ci < 0) || (ci >= ui->view->horizontalHeader()->count()) || (ci != ri) || (ci != li) || (tm.elapsed() <= QApplication::doubleClickInterval())) { + ri = ui->view->horizontalHeader()->logicalIndexAt(me->pos() + QPoint(3, 0)), + li = ui->view->horizontalHeader()->logicalIndexAt(me->pos() - QPoint(3, 0)); + // qDebug() << ci << ri << li; + if ((ci < 0) || (ci >= ui->view->horizontalHeader()->count()) || (ci != ri) || (ci != li) || + (tm.elapsed() <= QApplication::doubleClickInterval())) { tm.restart(); return QObject::eventFilter(o, e); } tm.restart(); Qt::SortOrder o = Qt::AscendingOrder; if (ui->view->horizontalHeader()->sortIndicatorSection() == ci && - ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder) + ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder) o = Qt::DescendingOrder; ui->view->horizontalHeader()->setSortIndicator(ci, o); return true; @@ -422,7 +492,7 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) { popup_col.clear(); for (int i = 0; i < column_props.size(); ++i) { QPair ctr = trColumn(column_props[i].name); - QAction * a = popup_col.addAction(ctr.first, this, SLOT(column_triggered(bool))); + QAction * a = popup_col.addAction(ctr.first, this, SLOT(column_triggered(bool))); a->setToolTip(ctr.second); a->setCheckable(true); a->setChecked(column_props[i].visible); @@ -431,14 +501,15 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) { popup_col.popup(me->globalPos()); return true; } - } else return true; + } else + return true; } } return QWidget::eventFilter(o, e); } -void SQLTableWidget::timerEvent(QTimerEvent * ) { +void SQLTableWidget::timerEvent(QTimerEvent *) { setTableName(table_); } @@ -446,12 +517,11 @@ void SQLTableWidget::timerEvent(QTimerEvent * ) { void SQLTableWidget::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - action_del->setText(tr("Remove selected")); - break; - default: - break; + case QEvent::LanguageChange: + ui->retranslateUi(this); + action_del->setText(tr("Remove selected")); + break; + default: break; } } @@ -461,7 +531,7 @@ void SQLTableWidget::setTableName(const QString & t) { stopTimer(); table_opened = false; first_update = true; - table_ = t; + table_ = t; if (!QSqlDatabase::database(connection_name).isOpen()) { if (debug) qDebug() << "[setTableName] Database in not opened!"; setTableVisible(false); @@ -471,15 +541,19 @@ void SQLTableWidget::setTableName(const QString & t) { model = new SQLQueryModel(table_, connection_name, column_props, column_indexes, this); connect(model, SIGNAL(updateTable(bool)), this, SLOT(updateTable(bool))); connect(model, SIGNAL(tableChanged()), this, SIGNAL(tableChanged())); - //model->setTable(table_); + // model->setTable(table_); cquery = "SELECT * FROM " + table_ + ";"; model->setQuery(cquery, QSqlDatabase::database(connection_name)); ui->view->setModel(model); - connect(ui->view->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SIGNAL(selectionChanged()), Qt::UniqueConnection); + connect(ui->view->selectionModel(), + SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), + this, + SIGNAL(selectionChanged()), + Qt::UniqueConnection); //((QSqlQueryModel * )model)->setQuery(QSqlQuery("SELECT id FROM " + table_ + ";")); setTableVisible(checkTable()); updateTable(); - foreach (const QString & wr, wait_rels) { + foreach(const QString & wr, wait_rels) { QStringList wrl = wr.split(";"); addRelation(wrl[0], wrl[1], wrl[2], wrl[3]); } @@ -492,59 +566,58 @@ void SQLTableWidget::setTableName(const QString & t) { bool SQLTableWidget::checkTable() { - table_opened = false; + table_opened = false; QSqlDatabase db = QSqlDatabase::database(connection_name); if (db.driver() == 0) return false; - bool te = db.tables(QSql::Tables).contains(table_, Qt::CaseInsensitive ); - //qDebug() << "tables:" << db.tables(QSql::Tables) << table_ << table_opened; + bool te = db.tables(QSql::Tables).contains(table_, Qt::CaseInsensitive); + // qDebug() << "tables:" << db.tables(QSql::Tables) << table_ << table_opened; if (!te) { timer = startTimer(1000); return false; } /*if (!q.exec("SHOW TABLES")) { - qDebug() << "[SHOW TABLES]" << q.lastError(); - timer = startTimer(1000); - return false; + qDebug() << "[SHOW TABLES]" << q.lastError(); + timer = startTimer(1000); + return false; } while (q.next()) { - //qDebug() << q.value(0); - if (q.value(0) == table_) - {table_opened = true; break;} + //qDebug() << q.value(0); + if (q.value(0) == table_) + {table_opened = true; break;} } if (!table_opened) { - timer = startTimer(1000); - return false; + timer = startTimer(1000); + return false; }*/ QSqlRecord header = db.record(table_); - QString pin = db.primaryIndex(table_).fieldName(0); - table_opened = true; + QString pin = db.primaryIndex(table_).fieldName(0); + table_opened = true; column_props.clear(); for (int i = 0; i < header.count(); ++i) { QSqlField f = header.field(i); column_props << ColumnProperties(table_, - f.type() == QVariant::String ? "text" : QVariant::typeToName(f.type()), - f.name(), - f.defaultValue().toString(), - f.isAutoValue(), - f.name() == pin, - f.requiredStatus() == QSqlField::Optional - ); + f.type() == QVariant::String ? "text" : QVariant::typeToName(f.type()), + f.name(), + f.defaultValue().toString(), + f.isAutoValue(), + f.name() == pin, + f.requiredStatus() == QSqlField::Optional); } /*if (!q.exec("DESCRIBE " + table_ + ";")) { - qDebug() << "[DESCRIBE " + table_ + "]" << q.lastError(); - timer = startTimer(1000); - return false; + qDebug() << "[DESCRIBE " + table_ + "]" << q.lastError(); + timer = startTimer(1000); + return false; } while (q.next()) { - column_props << ColumnProperties(table_, - q.value(1).toString().toLower(), - q.value(0).toString().toLower(), - q.value(4).toString().toLower(), - q.value(5).toString().toLower().indexOf("auto_increment") >= 0, - q.value(3).toString().toLower().indexOf("pri") >= 0); + column_props << ColumnProperties(table_, + q.value(1).toString().toLower(), + q.value(0).toString().toLower(), + q.value(4).toString().toLower(), + q.value(5).toString().toLower().indexOf("auto_increment") >= 0, + q.value(3).toString().toLower().indexOf("pri") >= 0); }*/ - //ui->labelNew->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); - //ui->labelFilter->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); + // ui->labelNew->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); + // ui->labelFilter->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); ui->scrollAreaNew->setFixedHeight(QLineEdit().sizeHint().height() + 2); ui->scrollAreaFilter->setFixedHeight(QLineEdit().sizeHint().height() + 2); qDeleteAll(column_news); @@ -571,7 +644,7 @@ bool SQLTableWidget::checkTable() { QStringList SQLTableWidget::getTableColumns(const QString & t) { QStringList ret; - QSqlDatabase db = QSqlDatabase::database(connection_name); + QSqlDatabase db = QSqlDatabase::database(connection_name); QSqlRecord header = db.record(t); for (int i = 0; i < header.count(); ++i) ret << header.field(i).name(); @@ -580,7 +653,7 @@ QStringList SQLTableWidget::getTableColumns(const QString & t) { QString SQLTableWidget::getColumnType(const QString & t, const QString & c) { - QSqlDatabase db = QSqlDatabase::database(connection_name); + QSqlDatabase db = QSqlDatabase::database(connection_name); QSqlRecord header = db.record(t); for (int i = 0; i < header.count(); ++i) { QSqlField f = header.field(i); @@ -591,11 +664,11 @@ QString SQLTableWidget::getColumnType(const QString & t, const QString & c) { } -QList > SQLTableWidget::getColumnValues(const QString &t, const QString &k, const QString &c, const QString &conn_name) { - QList > ret; +QList> +SQLTableWidget::getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name) { + QList> ret; QSqlQuery q(QSqlDatabase::database(conn_name)); - if (!q.exec("SELECT " + t + "." + k + "," + t + "." + c + " FROM " + t + ";")) - return ret; + if (!q.exec("SELECT " + t + "." + k + "," + t + "." + c + " FROM " + t + ";")) return ret; while (q.next()) ret << QPair(q.value(0).toString(), q.value(1).toString()); return ret; @@ -604,8 +677,7 @@ QList > SQLTableWidget::getColumnValues(const QString &t QPair SQLTableWidget::trColumn(const QString & n) { QPair ftr = fixed_translates.value(n); - if (!ftr.first.isEmpty()) - return ftr; + if (!ftr.first.isEmpty()) return ftr; QPair trn = translates.value(n); if (trn.first.isEmpty()) return QPair(n, ""); return trn; @@ -616,42 +688,39 @@ void SQLTableWidget::updateTable(bool save_selection) { if (!filters_active || !table_opened) return; int vp = ui->view->verticalScrollBar()->value(); int hp = ui->view->horizontalScrollBar()->value(); - //bool focus = view->hasFocus(); + // bool focus = view->hasFocus(); QModelIndex csi; QModelIndexList sl; if (save_selection) { csi = ui->view->selectionModel()->currentIndex(); - sl = ui->view->selectionModel()->selectedRows(); + sl = ui->view->selectionModel()->selectedRows(); } if (custom_query.isEmpty()) { QString cr = columnRelations(), cf = columnFilters(); bool where = !cr.isEmpty() || !cf.isEmpty(), and_ = !cr.isEmpty() && !cf.isEmpty(); - cquery = "SELECT " + columnNames() + " FROM " + tableNames() + - (where ? " WHERE " : "") + cr + (and_ ? " AND " : "") + cf + " ORDER BY " + - column_props[ui->view->horizontalHeader()->sortIndicatorSection()].fullName() + - (ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::DescendingOrder ? " DESC" : " ASC") + ";"; + cquery = "SELECT " + columnNames() + " FROM " + tableNames() + (where ? " WHERE " : "") + cr + (and_ ? " AND " : "") + cf + + " ORDER BY " + column_props[ui->view->horizontalHeader()->sortIndicatorSection()].fullName() + + (ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::DescendingOrder ? " DESC" : " ASC") + ";"; } else cquery = custom_query; - //qDebug() << cquery; + // qDebug() << cquery; model->setQuery(cquery, QSqlDatabase::database(connection_name)); - if (model->lastError().isValid()) - qDebug() << model->lastError(); + if (model->lastError().isValid()) qDebug() << model->lastError(); if (first_update) { ui->view->resizeColumnsToContents(); for (int i = 0; i < ui->view->horizontalHeader()->count(); ++i) - if (ui->view->horizontalHeader()->sectionSize(i) < 100) - ui->view->horizontalHeader()->resizeSection(i, 100); + if (ui->view->horizontalHeader()->sectionSize(i) < 100) ui->view->horizontalHeader()->resizeSection(i, 100); first_update = false; } - //ui->labelNew->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); - //ui->labelFilter->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); + // ui->labelNew->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); + // ui->labelFilter->setFixedWidth(qMax(ui->view->verticalHeader()->sizeHint().width() + 2, 16)); ui->layoutNew->invalidate(); if (save_selection) { QItemSelectionModel * sm = ui->view->selectionModel(); - foreach (const QModelIndex & i, sl) + foreach(const QModelIndex & i, sl) sm->select(i, QItemSelectionModel::Select | QItemSelectionModel::Rows); sm->setCurrentIndex(csi, QItemSelectionModel::Select); - //ui->view->setFocus(); + // ui->view->setFocus(); } if (custom_query.isEmpty()) { for (int i = 0; i < model->columnCount(); ++i) { @@ -663,7 +732,7 @@ void SQLTableWidget::updateTable(bool save_selection) { if (custom_col_names.isEmpty()) { QSqlRecord header = model->record(); for (int i = 0; i < header.count(); ++i) { - QSqlField f = header.field(i); + QSqlField f = header.field(i); QPair ctr = trColumn(f.name()); model->setHeaderData(i, Qt::Horizontal, ctr.first, Qt::DisplayRole); model->setHeaderData(i, Qt::Horizontal, ctr.second, Qt::ToolTipRole); @@ -678,7 +747,7 @@ void SQLTableWidget::updateTable(bool save_selection) { } ui->view->verticalScrollBar()->setValue(vp); ui->view->horizontalScrollBar()->setValue(hp); - //if (focus) view->setFocus(); + // if (focus) view->setFocus(); } @@ -693,10 +762,8 @@ QString SQLTableWidget::tableNames() { QSet rtables; for (int i = 0; i < column_props.size(); ++i) { ColumnProperties & cp(column_props[i]); - if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) - continue; - if (rtables.contains(cp.relation_table)) - continue; + if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) continue; + if (rtables.contains(cp.relation_table)) continue; rtables << cp.relation_table; ret.append("," + cp.relation_table); } @@ -712,14 +779,13 @@ QString SQLTableWidget::columnNames() { ColumnProperties & cp(column_props[i]); column_news[i]->setVisible(cp.visible); column_filters[i]->setVisible(cp.visible); - if (!cp.visible && !cp.primary) - continue; + if (!cp.visible && !cp.primary) continue; if (!first) ret.append(","); first = false; ret.append(cp.fullName()); if (i > 0) column_indexes.push_back(i); } - //qDebug() << column_indexes; + // qDebug() << column_indexes; return ret; } @@ -728,10 +794,8 @@ QString SQLTableWidget::columnFilters() { QString ret; bool and_ = ui->actionFilter_AND->isChecked(); for (int i = 0; i < column_props.size(); ++i) { - if (!column_filters[i]->isVisible() || column_filters[i]->isEmpty()) - continue; - if (!ret.isEmpty()) - ret.append(and_ ? " AND " : " OR "); + if (!column_filters[i]->isVisible() || column_filters[i]->isEmpty()) continue; + if (!ret.isEmpty()) ret.append(and_ ? " AND " : " OR "); ret.append(column_filters[i]->filter()); } if (!ret.isEmpty()) { @@ -746,10 +810,8 @@ QString SQLTableWidget::columnRelations() { QString ret; for (int i = 0; i < column_props.size(); ++i) { ColumnProperties & cp(column_props[i]); - if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) - continue; - if (!ret.isEmpty()) - ret.append(" AND "); + if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) continue; + if (!ret.isEmpty()) ret.append(" AND "); ret.append(table_ + "." + cp.name + "="); ret.append(cp.relation_table + "." + cp.relation_key); } @@ -792,13 +854,13 @@ void SQLTableWidget::on_buttonAdd_clicked() { emit tableChanged(); } else qDebug() << q.lastError(); - //qDebug() << q.lastQuery(); + // qDebug() << q.lastQuery(); } void SQLTableWidget::on_actionFiltersClear_triggered() { filters_active = false; - foreach (SQLFilterEdit * l, column_filters) + foreach(SQLFilterEdit * l, column_filters) l->clear(); filters_active = true; updateTable(); @@ -814,18 +876,18 @@ void SQLTableWidget::on_view_clicked(const QModelIndex & index) { void SQLTableWidget::del_triggered() { QModelIndexList si = ui->view->selectionModel()->selectedIndexes(); QSet ids; - foreach (const QModelIndex & i, si) + foreach(const QModelIndex & i, si) ids << model->index(i.row(), 0).data().toInt(); if (ids.isEmpty()) return; QString qs("DELETE FROM " + table_ + " WHERE " + column_props[0].name + " IN ("); bool first = true; - foreach (int i, ids) { + foreach(int i, ids) { if (!first) qs.append(","); qs.append(QString::number(i)); first = false; } qs.append(");"); - //qDebug() << qs; return; + // qDebug() << qs; return; QSqlQuery q(QSqlDatabase::database(connection_name)); if (q.exec(qs)) { updateTable(); @@ -842,7 +904,7 @@ void SQLTableWidget::setColumnVisible(int ind, bool visible) { ui->view->setColumnHidden(0, !visible); if (visible) ui->view->horizontalHeader()->resizeSection(0, ui->view->horizontalHeader()->defaultSectionSize()); } - //qDebug() << ind << on; + // qDebug() << ind << on; updateTable(); for (int i = 0; i < ui->view->horizontalHeader()->count(); ++i) { column_news[mapColumn(i)]->setFixedWidth(ui->view->horizontalHeader()->sectionSize(i)); @@ -851,16 +913,19 @@ void SQLTableWidget::setColumnVisible(int ind, bool visible) { } -bool SQLTableWidget::addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) { +bool SQLTableWidget::addRelation(const QString & this_column, + const QString & other_table, + const QString & other_key, + const QString & other_column) { QString wr = this_column + ";" + other_table + ";" + other_key + ";" + other_column; if (!wait_rels.contains(wr)) wait_rels << wr; - ColumnProperties * cp = const_cast(columnProperty(this_column)); + ColumnProperties * cp = const_cast(columnProperty(this_column)); if (cp == 0) return false; - cp->relation_table = other_table; - cp->relation_key = other_key; + cp->relation_table = other_table; + cp->relation_key = other_key; cp->relation_column = other_column; - cp->relation_type = ColumnProperties::typeFromString(getColumnType(other_table, other_column)); - cp->relation_list = getColumnValues(other_table, other_key, other_column, connection_name); + cp->relation_type = ColumnProperties::typeFromString(getColumnType(other_table, other_column)); + cp->relation_list = getColumnValues(other_table, other_key, other_column, connection_name); for (int i = 0; i < column_props.size(); ++i) column_news[i]->setProp(column_props[i]); for (int i = 0; i < column_props.size(); ++i) @@ -873,7 +938,7 @@ bool SQLTableWidget::addRelation(const QString & this_column, const QString & ot void SQLTableWidget::addTranslation(const QString & file) { QPIConfig conf(file, QIODevice::ReadOnly, QPIConfig::Config); QPIConfig::Branch ae = conf.allLeaves(); - foreach (QPIConfig::Entry * e, ae) + foreach(QPIConfig::Entry * e, ae) translates[e->name()] = QPair(e->value(), e->comment()); } @@ -894,8 +959,8 @@ void SQLTableWidget::selectId(int id) { } -void SQLTableWidget::setAdditionalActions(QList a) { - foreach (QAction * i, add_actions) +void SQLTableWidget::setAdditionalActions(QList a) { + foreach(QAction * i, add_actions) popup_menu.removeAction(i); add_actions = a; popup_menu.addActions(a); @@ -914,19 +979,17 @@ QString SQLTableWidget::preprocessScript(QString text) { int ce = 0; while (!s.atEnd()) { QString line = s.readLine(); - ce = line.indexOf("--"); - if (ce >= 0) - line.chop(line.length() - ce); + ce = line.indexOf("--"); + if (ce >= 0) line.chop(line.length() - ce); out.append(line).append("\n"); } int cs = out.indexOf("/*"); while (cs >= 0) { ce = out.indexOf("*/", cs); - if (ce > cs) - out.remove(cs, ce - cs + 2); + if (ce > cs) out.remove(cs, ce - cs + 2); cs = out.indexOf("/*"); } - //qDebug() << out; + // qDebug() << out; return out; } @@ -951,8 +1014,7 @@ bool SQLTableWidget::executeScript(const QString & text_, QSqlDatabase db, bool } else { if (!q.exec(line)) { qDebug() << q.lastError(); - if (!skip_errors) - return false; + if (!skip_errors) return false; } } ls = le + 1; @@ -969,10 +1031,10 @@ bool SQLTableWidget::executeScriptFile(const QString & file, QSqlDatabase db, bo qDebug() << "Can`t open file" << file << "!"; return false; } - QString pd = _dir; - _dir = QFileInfo(f).absolutePath() + "/"; + QString pd = _dir; + _dir = QFileInfo(f).absolutePath() + "/"; QByteArray ba = f.readAll(); - bool ok = executeScript(QString::fromUtf8(ba.data(), ba.size()), db, skip_errors, sqlite); + bool ok = executeScript(QString::fromUtf8(ba.data(), ba.size()), db, skip_errors, sqlite); f.close(); _dir = pd; return ok; @@ -980,7 +1042,7 @@ bool SQLTableWidget::executeScriptFile(const QString & file, QSqlDatabase db, bo void SQLTableWidget::column_triggered(bool on) { - setColumnVisible(((QAction * )sender())->data().toInt(), on); + setColumnVisible(((QAction *)sender())->data().toInt(), on); } @@ -1017,27 +1079,26 @@ bool SQLTableWidget::connectToDatabase(const QString & config, const QString & c } } } - if (!ok) - QSqlDatabase::removeDatabase(conn_name); + if (!ok) QSqlDatabase::removeDatabase(conn_name); /*QSqlQuery q; QString dbname = conf.getValue("database", "").stringValue(); bool dbex = false; if (!q.exec("SHOW DATABASES;")) { - qDebug() << "[SHOW DATABASES]" << q.lastError(); - return false; + qDebug() << "[SHOW DATABASES]" << q.lastError(); + return false; } while (q.next()) - if (q.value(0) == dbname) - {dbex = true; break;} + if (q.value(0) == dbname) + {dbex = true; break;} if (!dbex) { - if (!q.exec("CREATE DATABASE " + dbname + ";")) { - qDebug() << "[CREATE DATABASE]" << q.lastError(); - return false; - } + if (!q.exec("CREATE DATABASE " + dbname + ";")) { + qDebug() << "[CREATE DATABASE]" << q.lastError(); + return false; + } } if (!q.exec("USE " + dbname + ";")) { - qDebug() << "[USE]" << q.lastError(); - return false; + qDebug() << "[USE]" << q.lastError(); + return false; }*/ return ok; } diff --git a/libs/sql_table/sql_table_widget.h b/libs/sql_table/sql_table_widget.h index 024852b..247073b 100644 --- a/libs/sql_table/sql_table_widget.h +++ b/libs/sql_table/sql_table_widget.h @@ -1,64 +1,90 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SQL_TABLE_WIDGET_H #define SQL_TABLE_WIDGET_H +#include "qad_sql_table_export.h" +#include "qpiconfig.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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include "qpiconfig.h" -#include "qad_sql_table_export.h" +#include +#include struct QAD_SQL_TABLE_EXPORT ColumnProperties { - enum DataType {Unknown, Int, Float, Chars, Text, Binary, Date, Time, DateTime}; - ColumnProperties(const QString & table_, const QString & type_, const QString & name_, const QString & def_, bool auto_, bool prim_, bool option_); - bool isRelation() const {return (!relation_key.isEmpty() && !relation_column.isEmpty());} - QString shortName() const {if (!isRelation()) return name; return relation_column;} - QString fullName() const {if (!isRelation()) return table + "." + name; return (relation_table.isEmpty() ? "" : relation_table + ".") + relation_column;} - DataType getType() const {if (!isRelation()) return type; return relation_type;} + enum DataType { + Unknown, + Int, + Float, + Chars, + Text, + Binary, + Date, + Time, + DateTime + }; + ColumnProperties(const QString & table_, + const QString & type_, + const QString & name_, + const QString & def_, + bool auto_, + bool prim_, + bool option_); + bool isRelation() const { return (!relation_key.isEmpty() && !relation_column.isEmpty()); } + QString shortName() const { + if (!isRelation()) return name; + return relation_column; + } + QString fullName() const { + if (!isRelation()) return table + "." + name; + return (relation_table.isEmpty() ? "" : relation_table + ".") + relation_column; + } + DataType getType() const { + if (!isRelation()) return type; + return relation_type; + } static DataType typeFromString(const QString & n); - + DataType type; int size; bool auto_increment; @@ -71,33 +97,44 @@ struct QAD_SQL_TABLE_EXPORT ColumnProperties { QString relation_table; QString relation_key; QString relation_column; - QList > relation_list; // + QList> relation_list; // DataType relation_type; int key_column; QString def; }; - - struct QAD_SQL_TABLE_EXPORT TableColumns { - int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];} + int mapColumn(int abs_ind) const { + if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; + return column_indexes[abs_ind - 1]; + } QVector column_indexes; QList columns; }; - - class QAD_SQL_TABLE_EXPORT SQLQueryModel: public QSqlQueryModel { Q_OBJECT + public: - explicit SQLQueryModel(QString & t, QString & conn, QList & cp, QVector & ci, QObject* parent = 0): QSqlQueryModel(parent), table_(t), column_props(cp), column_indexes(ci), conn_name(conn) {;} + explicit SQLQueryModel(QString & t, QString & conn, QList & cp, QVector & ci, QObject * parent = 0) + : QSqlQueryModel(parent) + , table_(t) + , column_props(cp) + , column_indexes(ci) + , conn_name(conn) { + ; + } virtual QVariant data(const QModelIndex & item, int role = Qt::DisplayRole) const; + protected: - virtual Qt::ItemFlags flags(const QModelIndex & ) const {return (Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable);} - virtual bool setData(const QModelIndex & index, const QVariant& value, int role = Qt::EditRole); - int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];} + virtual Qt::ItemFlags flags(const QModelIndex &) const { return (Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable); } + virtual bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole); + int mapColumn(int abs_ind) const { + if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; + return column_indexes[abs_ind - 1]; + } QString & table_; QList & column_props; QVector & column_indexes; @@ -108,20 +145,30 @@ signals: }; - - class QAD_SQL_TABLE_EXPORT SQLUniEdit: public QWidget { Q_OBJECT + public: explicit SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0); - ~SQLUniEdit() {for (int i = 0; i < w_.size(); ++i) deleteW(*w_[i]);} + ~SQLUniEdit() { + for (int i = 0; i < w_.size(); ++i) + deleteW(*w_[i]); + } void setProp(const ColumnProperties & p); QString value(bool for_insert = false); - void clear() {setValue(QVariant());} + void clear() { setValue(QVariant()); } + private: - void deleteW(QWidget * w) {if (w != 0) delete w;} - void resizeW(QWidget * w) {if (w != 0) w->setGeometry(QRect(0, 0, width(), height()));} - void resizeEvent(QResizeEvent * ) {for (int i = 0; i < w_.size(); ++i) resizeW(*w_[i]);} + void deleteW(QWidget * w) { + if (w != 0) delete w; + } + void resizeW(QWidget * w) { + if (w != 0) w->setGeometry(QRect(0, 0, width(), height())); + } + void resizeEvent(QResizeEvent *) { + for (int i = 0; i < w_.size(); ++i) + resizeW(*w_[i]); + } bool eventFilter(QObject * o, QEvent * e); QLineEdit * wtext; QSpinBox * wint; @@ -130,36 +177,39 @@ private: QTimeEdit * wtime; QDateTimeEdit * wdatetime; QComboBox * wrelation; - QList w_; + QList w_; ColumnProperties prop_; QString connection_name; private slots: - void value_text(QString value) {valueChanged(value);} - void value_int(int value) {valueChanged(value);} - void value_float(double value) {valueChanged(value);} - void value_date(QDate value) {valueChanged(value);} - void value_time(QTime value) {valueChanged(value);} - void value_datetime(QDateTime value) {valueChanged(value);} + void value_text(QString value) { valueChanged(value); } + void value_int(int value) { valueChanged(value); } + void value_float(double value) { valueChanged(value); } + void value_date(QDate value) { valueChanged(value); } + void value_time(QTime value) { valueChanged(value); } + void value_datetime(QDateTime value) { valueChanged(value); } public slots: void setValue(const QVariant & value); void updateRelation(); signals: - void valueChanged(const QVariant & ); + void valueChanged(const QVariant &); }; - - class QAD_SQL_TABLE_EXPORT SQLNewEdit: public QWidget { Q_OBJECT friend class SQLTableWidget; + public: explicit SQLNewEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0); - ~SQLNewEdit() {delete line; delete check;} + ~SQLNewEdit() { + delete line; + delete check; + } void setProp(const ColumnProperties & p); - bool isEnabled() const {return check->isChecked();} - QString value() const {return line->value(true);} - void clear() {line->clear();} + bool isEnabled() const { return check->isChecked(); } + QString value() const { return line->value(true); } + void clear() { line->clear(); } + private: ColumnProperties prop_; SQLUniEdit * line; @@ -167,43 +217,54 @@ private: }; - - class QAD_SQL_TABLE_EXPORT SQLFilterEdit: public QWidget { Q_OBJECT friend class SQLTableWidget; + public: explicit SQLFilterEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0); - ~SQLFilterEdit() {delete line; delete combo;} - void setProp(const ColumnProperties & p) {prop_ = p; line->setProp(p);} + ~SQLFilterEdit() { + delete line; + delete combo; + } + void setProp(const ColumnProperties & p) { + prop_ = p; + line->setProp(p); + } QString filter() const; - bool isEmpty() const {return line->value().isEmpty() || combo->currentIndex() == 0;} + bool isEmpty() const { return line->value().isEmpty() || combo->currentIndex() == 0; } void clear(); + private: ColumnProperties prop_; SQLUniEdit * line; QComboBox * combo; private slots: - void value_changed() {if (combo->currentIndex() == 0) combo->setCurrentIndex(prop_.is_text ? 2 : 1);} + void value_changed() { + if (combo->currentIndex() == 0) combo->setCurrentIndex(prop_.is_text ? 2 : 1); + } public slots: signals: void filterChanged(); }; - - class QAD_SQL_TABLE_EXPORT SQLItemDelegate: public QStyledItemDelegate { Q_OBJECT + public: explicit SQLItemDelegate(QList & cp, QVector & ci, bool & ro, const QString & conn_name, QObject * parent = 0); - ~SQLItemDelegate() {;} + ~SQLItemDelegate() { ; } + private: QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const; QString displayText(const QVariant & value, const QLocale & locale) const; void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; - int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];} - void setConnectionName(const QString & conn_name) {connection_name = conn_name;} + int mapColumn(int abs_ind) const { + if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; + return column_indexes[abs_ind - 1]; + } + void setConnectionName(const QString & conn_name) { connection_name = conn_name; } QList & column_props; QVector & column_indexes; bool & read_only; @@ -215,12 +276,11 @@ signals: namespace Ui { - class SQLTableWidget; +class SQLTableWidget; } -class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget -{ +class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget { Q_OBJECT Q_PROPERTY(QString tableName READ tableName WRITE setTableName) Q_PROPERTY(QString connectionName READ connectionName WRITE setConnectionName) @@ -230,105 +290,165 @@ class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget Q_PROPERTY(bool debugEnabled READ isDebugEnabled WRITE setDebugEnabled) friend class SQLItemDelegate; friend class SQLUniEdit; + public: SQLTableWidget(QWidget * parent = 0); virtual ~SQLTableWidget(); - - bool isTableExists() const {return table_opened;} - const QString & tableName() const {return table_;} + + bool isTableExists() const { return table_opened; } + const QString & tableName() const { return table_; } QTableView * tableView(); - bool readOnly() const {return read_only;} + bool readOnly() const { return read_only; } - void setDebugEnabled(bool on) {debug = on;} - bool isDebugEnabled() const {return debug;} - - const ColumnProperties * columnProperty(int index) const {if (index < 0 || index >= column_props.count()) return 0; return &(column_props[index]);} - const ColumnProperties * columnProperty(const QString & name) const {return columnProperty(columnByName(name));} - const QList & columnProperties() const {return column_props;} - QStringList columnNames() const {QStringList sl; foreach (const ColumnProperties & i, column_props) sl << i.name; return sl;} - int columnsCount() const {return column_props.size();} - bool isColumnVisible(int ind) {if (!columnExists(ind)) return false; return column_props[ind].visible;} - bool isColumnVisible(const QString & name) {if (!columnExists(name)) return false; return column_props[columnByName(name)].visible;} - bool isColumnHidden(int ind) {if (!columnExists(ind)) return true; return !column_props[ind].visible;} - bool isColumnHidden(const QString & name) {if (!columnExists(name)) return true; return !column_props[columnByName(name)].visible;} + void setDebugEnabled(bool on) { debug = on; } + bool isDebugEnabled() const { return debug; } + + const ColumnProperties * columnProperty(int index) const { + if (index < 0 || index >= column_props.count()) return 0; + return &(column_props[index]); + } + const ColumnProperties * columnProperty(const QString & name) const { return columnProperty(columnByName(name)); } + const QList & columnProperties() const { return column_props; } + QStringList columnNames() const { + QStringList sl; + foreach(const ColumnProperties & i, column_props) + sl << i.name; + return sl; + } + int columnsCount() const { return column_props.size(); } + bool isColumnVisible(int ind) { + if (!columnExists(ind)) return false; + return column_props[ind].visible; + } + bool isColumnVisible(const QString & name) { + if (!columnExists(name)) return false; + return column_props[columnByName(name)].visible; + } + bool isColumnHidden(int ind) { + if (!columnExists(ind)) return true; + return !column_props[ind].visible; + } + bool isColumnHidden(const QString & name) { + if (!columnExists(name)) return true; + return !column_props[columnByName(name)].visible; + } void setColumnVisible(int ind, bool visible); - void setColumnVisible(const QString & name, bool visible) {col_vis[name] = visible; setColumnVisible(columnByName(name), visible);} - void setColumnHidden(int ind, bool hidden) {setColumnVisible(ind, !hidden);} - void setColumnHidden(const QString & name, bool hidden) {col_vis[name] = !hidden; setColumnVisible(columnByName(name), !hidden);} - + void setColumnVisible(const QString & name, bool visible) { + col_vis[name] = visible; + setColumnVisible(columnByName(name), visible); + } + void setColumnHidden(int ind, bool hidden) { setColumnVisible(ind, !hidden); } + void setColumnHidden(const QString & name, bool hidden) { + col_vis[name] = !hidden; + setColumnVisible(columnByName(name), !hidden); + } + bool lineNewVisible() const; bool lineFilterVisible() const; bool addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column); void addTranslation(const QString & file); void addFixedColumnTranslation(const QString & col_name, const QString & col_tr, const QString & col_tt = QString()); - void fetchMore() {if (model) model->fetchMore();} - void fetchAll() {if (model) while (model->canFetchMore()) model->fetchMore();} + void fetchMore() { + if (model) model->fetchMore(); + } + void fetchAll() { + if (model) + while (model->canFetchMore()) + model->fetchMore(); + } void selectId(int id); - void setAdditionalActions(QList a); - - QSqlRecord headerRecord() const {if (model) return model->record(); return QSqlRecord();} - QSqlRecord currentRecord() const; - - void setCustomQuery(const QString & q); - void setCustomColumnNames(const QStringList & cn) {custom_col_names = cn; updateTable();} - - static bool isTableExists(const QString & table, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {return QSqlDatabase::database(conn_name).tables().contains(table, Qt::CaseInsensitive);} + void setAdditionalActions(QList a); - static bool executeScript(const QString & text, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false); - static bool executeScriptFile(const QString & file, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false); - - static bool isConnectedToDatabase(const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {return QSqlDatabase::database(conn_name, false).isOpen();} + QSqlRecord headerRecord() const { + if (model) return model->record(); + return QSqlRecord(); + } + QSqlRecord currentRecord() const; + + void setCustomQuery(const QString & q); + void setCustomColumnNames(const QStringList & cn) { + custom_col_names = cn; + updateTable(); + } + + static bool isTableExists(const QString & table, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) { + return QSqlDatabase::database(conn_name).tables().contains(table, Qt::CaseInsensitive); + } + + static bool + executeScript(const QString & text, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false); + static bool + executeScriptFile(const QString & file, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false); + + static bool isConnectedToDatabase(const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) { + return QSqlDatabase::database(conn_name, false).isOpen(); + } static bool connectToDatabase(const QString & config, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)); - QString connectionName() const {return connection_name;} + QString connectionName() const { return connection_name; } private: static QString preprocessScript(QString text); - + bool eventFilter(QObject * o, QEvent * e); - void timerEvent(QTimerEvent * ); + void timerEvent(QTimerEvent *); void changeEvent(QEvent * e); - void stopTimer() {if (timer != 0) killTimer(timer); timer = 0;} + void stopTimer() { + if (timer != 0) killTimer(timer); + timer = 0; + } bool checkTable(); QStringList getTableColumns(const QString & t); QString getColumnType(const QString & t, const QString & c); - static QList > getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name); + static QList> + getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name); void setTableVisible(bool on); - int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];} - int columnByName(const QString & name) const {for (int i = 0; i < column_props.size(); ++i) if (column_props[i].name == name) return i; return -1;} - bool columnExists(int index) const {return (index >= 0 && index < column_props.size());} - bool columnExists(const QString & name) const {for (int i = 0; i < column_props.size(); ++i) if (column_props[i].name == name) return true; return false;} + int mapColumn(int abs_ind) const { + if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; + return column_indexes[abs_ind - 1]; + } + int columnByName(const QString & name) const { + for (int i = 0; i < column_props.size(); ++i) + if (column_props[i].name == name) return i; + return -1; + } + bool columnExists(int index) const { return (index >= 0 && index < column_props.size()); } + bool columnExists(const QString & name) const { + for (int i = 0; i < column_props.size(); ++i) + if (column_props[i].name == name) return true; + return false; + } QPair trColumn(const QString & n); QString tableNames(); QString columnNames(); QString columnFilters(); QString columnRelations(); - + Ui::SQLTableWidget * ui; QString table_, cquery, custom_query; QStringList custom_col_names; SQLQueryModel * model; - //QAction act_add, act_del; + // QAction act_add, act_del; QList column_props; - QList column_news; - QList column_filters; + QList column_news; + QList column_filters; QVector column_indexes; QStringList wait_rels; QMenu popup_menu, popup_col, popup_filter; QElapsedTimer tm; QActionGroup filters_group; QAction * action_del; - QList add_actions; - QMap > translates, fixed_translates; + QList add_actions; + QMap> translates, fixed_translates; QMap col_vis; int timer; bool filters_active, table_opened, read_only, first_update, debug; static QString _dir; QPoint pp; QString connection_name; - + public slots: void setTableName(const QString & t); @@ -336,7 +456,7 @@ public slots: void setLineFilterVisible(bool on); void setReadOnly(bool yes); void updateTable(bool save_selection = false); - void setConnectionName(const QString &conn_name); + void setConnectionName(const QString & conn_name); private slots: void on_buttonAdd_clicked(); @@ -347,13 +467,12 @@ private slots: void scrolled(int value); void del_triggered(); void column_triggered(bool on); - + signals: void rowClicked(int row); void recordClicked(QSqlRecord rec); void selectionChanged(); void tableChanged(); - }; diff --git a/libs/touch_widgets/plugin/qad_touch_widgets.cpp b/libs/touch_widgets/plugin/qad_touch_widgets.cpp index caf2bbe..8dc7f7b 100644 --- a/libs/touch_widgets/plugin/qad_touch_widgets.cpp +++ b/libs/touch_widgets/plugin/qad_touch_widgets.cpp @@ -1,7 +1,8 @@ #include "qad_touch_widgets.h" -#include "touchsliderplugin.h" + #include "touchbuttframeplugin.h" #include "touchbuttonplugin.h" +#include "touchsliderplugin.h" QADTouchWidgets::QADTouchWidgets(QObject * parent): QObject(parent) { @@ -11,7 +12,7 @@ QADTouchWidgets::QADTouchWidgets(QObject * parent): QObject(parent) { } -QList QADTouchWidgets::customWidgets() const { +QList QADTouchWidgets::customWidgets() const { return m_widgets; } diff --git a/libs/touch_widgets/plugin/qad_touch_widgets.h b/libs/touch_widgets/plugin/qad_touch_widgets.h index e7cbf2a..520a096 100644 --- a/libs/touch_widgets/plugin/qad_touch_widgets.h +++ b/libs/touch_widgets/plugin/qad_touch_widgets.h @@ -1,23 +1,24 @@ #ifndef QAD_TOUCH_WIDGETS_H #define QAD_TOUCH_WIDGETS_H -#include #include +#include -class QADTouchWidgets: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADTouchWidgets + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.touch_widgets") #endif + public: - explicit QADTouchWidgets(QObject *parent = 0); - virtual QList customWidgets() const; + explicit QADTouchWidgets(QObject * parent = 0); + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_TOUCH_WIDGETS_H diff --git a/libs/touch_widgets/plugin/touchbuttframeplugin.cpp b/libs/touch_widgets/plugin/touchbuttframeplugin.cpp index dee389b..26ca562 100644 --- a/libs/touch_widgets/plugin/touchbuttframeplugin.cpp +++ b/libs/touch_widgets/plugin/touchbuttframeplugin.cpp @@ -1,90 +1,76 @@ -#include "touchbuttframe.h" #include "touchbuttframeplugin.h" -#include +#include "touchbuttframe.h" + #include #include +#include -TouchButtFramePlugin::TouchButtFramePlugin(QObject *parent) - : QObject(parent) -{ - m_initialized = false; +TouchButtFramePlugin::TouchButtFramePlugin(QObject * parent): QObject(parent) { + m_initialized = false; } -void TouchButtFramePlugin::initialize(QDesignerFormEditorInterface * /*core*/ ) -{ - if (m_initialized) - return; +void TouchButtFramePlugin::initialize(QDesignerFormEditorInterface * /*core*/) { + if (m_initialized) return; - // Add extension registrations, etc. here - //core->propertyEditor()->property(); - m_initialized = true; + // Add extension registrations, etc. here + // core->propertyEditor()->property(); + m_initialized = true; } -bool TouchButtFramePlugin::isInitialized() const -{ - return m_initialized; +bool TouchButtFramePlugin::isInitialized() const { + return m_initialized; } -QWidget *TouchButtFramePlugin::createWidget(QWidget *parent) -{ - TouchButtFrame * tbw = new TouchButtFrame(parent); - QStringList l; - l.append("First"); - l.append("Second"); - tbw->setButtons(l); - return tbw; +QWidget * TouchButtFramePlugin::createWidget(QWidget * parent) { + TouchButtFrame * tbw = new TouchButtFrame(parent); + QStringList l; + l.append("First"); + l.append("Second"); + tbw->setButtons(l); + return tbw; } -QString TouchButtFramePlugin::name() const -{ - return QLatin1String("TouchButtFrame"); +QString TouchButtFramePlugin::name() const { + return QLatin1String("TouchButtFrame"); } -QString TouchButtFramePlugin::group() const -{ - return QLatin1String("Touch Widgets"); +QString TouchButtFramePlugin::group() const { + return QLatin1String("Touch Widgets"); } -QIcon TouchButtFramePlugin::icon() const -{ - return QIcon(":/icons/touchbuttframe.png"); +QIcon TouchButtFramePlugin::icon() const { + return QIcon(":/icons/touchbuttframe.png"); } -QString TouchButtFramePlugin::toolTip() const -{ - return QLatin1String(""); +QString TouchButtFramePlugin::toolTip() const { + return QLatin1String(""); } -QString TouchButtFramePlugin::whatsThis() const -{ - return QLatin1String(""); +QString TouchButtFramePlugin::whatsThis() const { + return QLatin1String(""); } -bool TouchButtFramePlugin::isContainer() const -{ - return false; +bool TouchButtFramePlugin::isContainer() const { + return false; } -QString TouchButtFramePlugin::domXml() const -{ - return QLatin1String("\n" - " \n" - " \n" - " \n" - " 0\n" - " 0\n" - " 100\n" - " 100\n" - " \n" - " \n" - " \n" - "\n"); +QString TouchButtFramePlugin::domXml() const { + return QLatin1String("\n" + " \n" + " \n" + " \n" + " 0\n" + " 0\n" + " 100\n" + " 100\n" + " \n" + " \n" + " \n" + "\n"); } -QString TouchButtFramePlugin::includeFile() const -{ - return QLatin1String("touchbuttframe.h"); +QString TouchButtFramePlugin::includeFile() const { + return QLatin1String("touchbuttframe.h"); } - diff --git a/libs/touch_widgets/plugin/touchbuttframeplugin.h b/libs/touch_widgets/plugin/touchbuttframeplugin.h index a4314b8..18e7fb1 100644 --- a/libs/touch_widgets/plugin/touchbuttframeplugin.h +++ b/libs/touch_widgets/plugin/touchbuttframeplugin.h @@ -8,28 +8,29 @@ # include #endif -class TouchButtFramePlugin : public QObject, public QDesignerCustomWidgetInterface -{ - Q_OBJECT - Q_INTERFACES(QDesignerCustomWidgetInterface) +class TouchButtFramePlugin + : public QObject + , public QDesignerCustomWidgetInterface { + Q_OBJECT + Q_INTERFACES(QDesignerCustomWidgetInterface) public: - TouchButtFramePlugin(QObject *parent = 0); + TouchButtFramePlugin(QObject * parent = 0); - bool isContainer() const; - bool isInitialized() const; - QIcon icon() const; - QString domXml() const; - QString group() const; - QString includeFile() const; - QString name() const; - QString toolTip() const; - QString whatsThis() const; - QWidget *createWidget(QWidget *parent); - void initialize(QDesignerFormEditorInterface *core); + bool isContainer() const; + bool isInitialized() const; + QIcon icon() const; + QString domXml() const; + QString group() const; + QString includeFile() const; + QString name() const; + QString toolTip() const; + QString whatsThis() const; + QWidget * createWidget(QWidget * parent); + void initialize(QDesignerFormEditorInterface * core); private: - bool m_initialized; + bool m_initialized; }; #endif diff --git a/libs/touch_widgets/plugin/touchbuttonplugin.cpp b/libs/touch_widgets/plugin/touchbuttonplugin.cpp index 9d977a0..0ddd401 100644 --- a/libs/touch_widgets/plugin/touchbuttonplugin.cpp +++ b/libs/touch_widgets/plugin/touchbuttonplugin.cpp @@ -1,74 +1,60 @@ -#include "touchbutton.h" #include "touchbuttonplugin.h" -#include +#include "touchbutton.h" + #include #include +#include -TouchButtonPlugin::TouchButtonPlugin(QObject *parent) - : QObject(parent) -{ - m_initialized = false; +TouchButtonPlugin::TouchButtonPlugin(QObject * parent): QObject(parent) { + m_initialized = false; } -void TouchButtonPlugin::initialize(QDesignerFormEditorInterface * /* core */) -{ - if (m_initialized) - return; +void TouchButtonPlugin::initialize(QDesignerFormEditorInterface * /* core */) { + if (m_initialized) return; - // Add extension registrations, etc. here + // Add extension registrations, etc. here - m_initialized = true; + m_initialized = true; } -bool TouchButtonPlugin::isInitialized() const -{ - return m_initialized; +bool TouchButtonPlugin::isInitialized() const { + return m_initialized; } -QWidget *TouchButtonPlugin::createWidget(QWidget *parent) -{ - return new TouchButton(parent); +QWidget * TouchButtonPlugin::createWidget(QWidget * parent) { + return new TouchButton(parent); } -QString TouchButtonPlugin::name() const -{ - return QLatin1String("TouchButton"); +QString TouchButtonPlugin::name() const { + return QLatin1String("TouchButton"); } -QString TouchButtonPlugin::group() const -{ - return QLatin1String("Touch Widgets"); +QString TouchButtonPlugin::group() const { + return QLatin1String("Touch Widgets"); } -QIcon TouchButtonPlugin::icon() const -{ - return QIcon(":/icons/touchbutton.png"); +QIcon TouchButtonPlugin::icon() const { + return QIcon(":/icons/touchbutton.png"); } -QString TouchButtonPlugin::toolTip() const -{ - return QLatin1String(""); +QString TouchButtonPlugin::toolTip() const { + return QLatin1String(""); } -QString TouchButtonPlugin::whatsThis() const -{ - return QLatin1String(""); +QString TouchButtonPlugin::whatsThis() const { + return QLatin1String(""); } -bool TouchButtonPlugin::isContainer() const -{ - return false; +bool TouchButtonPlugin::isContainer() const { + return false; } -QString TouchButtonPlugin::domXml() const -{ - return QLatin1String("\n\n"); +QString TouchButtonPlugin::domXml() const { + return QLatin1String("\n\n"); } -QString TouchButtonPlugin::includeFile() const -{ - return QLatin1String("touchbutton.h"); +QString TouchButtonPlugin::includeFile() const { + return QLatin1String("touchbutton.h"); } - diff --git a/libs/touch_widgets/plugin/touchbuttonplugin.h b/libs/touch_widgets/plugin/touchbuttonplugin.h index 423c164..cf38fa9 100644 --- a/libs/touch_widgets/plugin/touchbuttonplugin.h +++ b/libs/touch_widgets/plugin/touchbuttonplugin.h @@ -8,28 +8,29 @@ # include #endif -class TouchButtonPlugin : public QObject, public QDesignerCustomWidgetInterface -{ - Q_OBJECT - Q_INTERFACES(QDesignerCustomWidgetInterface) +class TouchButtonPlugin + : public QObject + , public QDesignerCustomWidgetInterface { + Q_OBJECT + Q_INTERFACES(QDesignerCustomWidgetInterface) public: - TouchButtonPlugin(QObject *parent = 0); + TouchButtonPlugin(QObject * parent = 0); - bool isContainer() const; - bool isInitialized() const; - QIcon icon() const; - QString domXml() const; - QString group() const; - QString includeFile() const; - QString name() const; - QString toolTip() const; - QString whatsThis() const; - QWidget *createWidget(QWidget *parent); - void initialize(QDesignerFormEditorInterface *core); + bool isContainer() const; + bool isInitialized() const; + QIcon icon() const; + QString domXml() const; + QString group() const; + QString includeFile() const; + QString name() const; + QString toolTip() const; + QString whatsThis() const; + QWidget * createWidget(QWidget * parent); + void initialize(QDesignerFormEditorInterface * core); private: - bool m_initialized; + bool m_initialized; }; #endif // TOUCHBUTTONPLUGIN_H diff --git a/libs/touch_widgets/plugin/touchsliderplugin.cpp b/libs/touch_widgets/plugin/touchsliderplugin.cpp index c49f321..805de43 100644 --- a/libs/touch_widgets/plugin/touchsliderplugin.cpp +++ b/libs/touch_widgets/plugin/touchsliderplugin.cpp @@ -1,81 +1,67 @@ -#include "touchslider.h" #include "touchsliderplugin.h" -#include +#include "touchslider.h" + #include #include +#include -TouchSliderPlugin::TouchSliderPlugin(QObject *parent) - : QObject(parent) -{ - m_initialized = false; +TouchSliderPlugin::TouchSliderPlugin(QObject * parent): QObject(parent) { + m_initialized = false; } -void TouchSliderPlugin::initialize(QDesignerFormEditorInterface * /* core */) -{ - if (m_initialized) - return; +void TouchSliderPlugin::initialize(QDesignerFormEditorInterface * /* core */) { + if (m_initialized) return; - // Add extension registrations, etc. here + // Add extension registrations, etc. here - m_initialized = true; + m_initialized = true; } -bool TouchSliderPlugin::isInitialized() const -{ - return m_initialized; +bool TouchSliderPlugin::isInitialized() const { + return m_initialized; } -QWidget *TouchSliderPlugin::createWidget(QWidget *parent) -{ - TouchSlider * ts = new TouchSlider(parent); - ts->setMinimum(-5.); - ts->setMaximum(5.); - ts->setPrecision(0.2); - ts->setValue(2.2); - ts->setPrefix("Distanse"); - ts->setSuffix("meters"); - return ts; +QWidget * TouchSliderPlugin::createWidget(QWidget * parent) { + TouchSlider * ts = new TouchSlider(parent); + ts->setMinimum(-5.); + ts->setMaximum(5.); + ts->setPrecision(0.2); + ts->setValue(2.2); + ts->setPrefix("Distanse"); + ts->setSuffix("meters"); + return ts; } -QString TouchSliderPlugin::name() const -{ - return QLatin1String("TouchSlider"); +QString TouchSliderPlugin::name() const { + return QLatin1String("TouchSlider"); } -QString TouchSliderPlugin::group() const -{ - return QLatin1String("Touch Widgets"); +QString TouchSliderPlugin::group() const { + return QLatin1String("Touch Widgets"); } -QIcon TouchSliderPlugin::icon() const -{ - return QIcon(":/icons/touchslider.png"); +QIcon TouchSliderPlugin::icon() const { + return QIcon(":/icons/touchslider.png"); } -QString TouchSliderPlugin::toolTip() const -{ - return QLatin1String(""); +QString TouchSliderPlugin::toolTip() const { + return QLatin1String(""); } -QString TouchSliderPlugin::whatsThis() const -{ - return QLatin1String(""); +QString TouchSliderPlugin::whatsThis() const { + return QLatin1String(""); } -bool TouchSliderPlugin::isContainer() const -{ - return false; +bool TouchSliderPlugin::isContainer() const { + return false; } -QString TouchSliderPlugin::domXml() const -{ - return QLatin1String("\n\n"); +QString TouchSliderPlugin::domXml() const { + return QLatin1String("\n\n"); } -QString TouchSliderPlugin::includeFile() const -{ - return QLatin1String("touchslider.h"); +QString TouchSliderPlugin::includeFile() const { + return QLatin1String("touchslider.h"); } - diff --git a/libs/touch_widgets/plugin/touchsliderplugin.h b/libs/touch_widgets/plugin/touchsliderplugin.h index 3ceaa34..d02bffc 100644 --- a/libs/touch_widgets/plugin/touchsliderplugin.h +++ b/libs/touch_widgets/plugin/touchsliderplugin.h @@ -8,28 +8,29 @@ # include #endif -class TouchSliderPlugin : public QObject, public QDesignerCustomWidgetInterface -{ - Q_OBJECT - Q_INTERFACES(QDesignerCustomWidgetInterface) +class TouchSliderPlugin + : public QObject + , public QDesignerCustomWidgetInterface { + Q_OBJECT + Q_INTERFACES(QDesignerCustomWidgetInterface) public: - TouchSliderPlugin(QObject *parent = 0); + TouchSliderPlugin(QObject * parent = 0); - bool isContainer() const; - bool isInitialized() const; - QIcon icon() const; - QString domXml() const; - QString group() const; - QString includeFile() const; - QString name() const; - QString toolTip() const; - QString whatsThis() const; - QWidget *createWidget(QWidget *parent); - void initialize(QDesignerFormEditorInterface *core); + bool isContainer() const; + bool isInitialized() const; + QIcon icon() const; + QString domXml() const; + QString group() const; + QString includeFile() const; + QString name() const; + QString toolTip() const; + QString whatsThis() const; + QWidget * createWidget(QWidget * parent); + void initialize(QDesignerFormEditorInterface * core); private: - bool m_initialized; + bool m_initialized; }; #endif diff --git a/libs/touch_widgets/touch_bar.h b/libs/touch_widgets/touch_bar.h index e2b6f7a..5b9805b 100644 --- a/libs/touch_widgets/touch_bar.h +++ b/libs/touch_widgets/touch_bar.h @@ -1,20 +1,20 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef TOUCH_BAR_H @@ -24,10 +24,10 @@ class touch_bar: public QProgressBar { Q_OBJECT + public: - touch_bar(QWidget * parent = 0): QProgressBar(parent) - { - //setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); + touch_bar(QWidget * parent = 0): QProgressBar(parent) { + // setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); } signals: void mouseMoveEvent(QMouseEvent * e); diff --git a/libs/touch_widgets/touchbuttframe.cpp b/libs/touch_widgets/touchbuttframe.cpp index 843525a..bb18d01 100644 --- a/libs/touch_widgets/touchbuttframe.cpp +++ b/libs/touch_widgets/touchbuttframe.cpp @@ -20,7 +20,7 @@ void TouchButtFrame::addButton(const QString & caption) { butt->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); butt->setCheckable(true); butt->setAutoExclusive(true); - //butt->setAutoFillBackground(true); + // butt->setAutoFillBackground(true); lay->addWidget(butt); this->setLayout(lay); connect(butt, SIGNAL(clickedID(int)), SLOT(butt_click(int))); @@ -49,8 +49,10 @@ void TouchButtFrame::setButtons(const QStringList & captions) { deleteButtons(); for (int i = 0; i < captions.size(); ++i) addButton(QString(captions.at(i)).replace("\\n", "\n")); - if (button(cur) != 0) button(cur)->setChecked(true); - else if (!captions.isEmpty()) button(0)->setChecked(true); + if (button(cur) != 0) + button(cur)->setChecked(true); + else if (!captions.isEmpty()) + button(0)->setChecked(true); resetColors(); } @@ -79,7 +81,6 @@ QStringList TouchButtFrame::buttons() { TouchButton * TouchButtFrame::button(int index) { - if (index >= 0 && index < lay->count()) - return (qobject_cast(lay->itemAt(index)->widget())); + if (index >= 0 && index < lay->count()) return (qobject_cast(lay->itemAt(index)->widget())); return 0; } diff --git a/libs/touch_widgets/touchbuttframe.h b/libs/touch_widgets/touchbuttframe.h index 9f52eac..bab96b5 100644 --- a/libs/touch_widgets/touchbuttframe.h +++ b/libs/touch_widgets/touchbuttframe.h @@ -1,34 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef TOUCHBUTTFRAME_H #define TOUCHBUTTFRAME_H -#include +#include "qad_touch_widgets_export.h" +#include "touchbutton.h" + #include #include -#include "touchbutton.h" -#include "qad_touch_widgets_export.h" +#include -class QAD_TOUCH_WIDGETS_EXPORT TouchButtFrame: public QFrame -{ +class QAD_TOUCH_WIDGETS_EXPORT TouchButtFrame: public QFrame { Q_OBJECT Q_PROPERTY(QColor colorYes READ colorYes WRITE setColorYes) Q_PROPERTY(QColor colorNo READ colorNo WRITE setColorNo) @@ -39,95 +39,189 @@ class QAD_TOUCH_WIDGETS_EXPORT TouchButtFrame: public QFrame Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) Q_PROPERTY(int clickID READ clickID WRITE setClickID) Q_PROPERTY(int setID READ setID WRITE setSetID) - + public: TouchButtFrame(QWidget * parent = 0, Qt::Orientation orientation = Qt::Horizontal); - - int clickID() const {return id_click;} - int setID() const {return id_set;} + + int clickID() const { return id_click; } + int setID() const { return id_set; } void setButtons(const QStringList & captions); QStringList buttons(); TouchButton * button(int index); - int buttonsCount() const {return lay->count();} + int buttonsCount() const { return lay->count(); } int currentButton(); - Qt::Orientation orientation() const {if (lay->direction() == 0) return Qt::Horizontal; else return Qt::Vertical;} - QColor colorYes() const {return colg;} - QColor colorNo() const {return colr;} - QColor colorGray() const {return colw;} - QColor colorDown() const {return colp;} - + Qt::Orientation orientation() const { + if (lay->direction() == 0) + return Qt::Horizontal; + else + return Qt::Vertical; + } + QColor colorYes() const { return colg; } + QColor colorNo() const { return colr; } + QColor colorGray() const { return colw; } + QColor colorDown() const { return colp; } + void setCurrentButton(int index); - void setColorYes(QColor col) {colg = col; resetColors();} - void setColorNo(QColor col) {colr = col; resetColors();} - void setColorGray(QColor col) {colw = col; resetColors();} - void setColorDown(QColor col) {colp = col; resetColors();} - void setOrientation(Qt::Orientation orientation) {if (orientation == Qt::Horizontal) lay->setDirection(QBoxLayout::LeftToRight); else lay->setDirection(QBoxLayout::TopToBottom);} + void setColorYes(QColor col) { + colg = col; + resetColors(); + } + void setColorNo(QColor col) { + colr = col; + resetColors(); + } + void setColorGray(QColor col) { + colw = col; + resetColors(); + } + void setColorDown(QColor col) { + colp = col; + resetColors(); + } + void setOrientation(Qt::Orientation orientation) { + if (orientation == Qt::Horizontal) + lay->setDirection(QBoxLayout::LeftToRight); + else + lay->setDirection(QBoxLayout::TopToBottom); + } private: void resetColors(); void deleteButtons(); void addButton(const QString & caption); - + int id_click, id_set; QColor colr, colg, colw, colp; QBoxLayout * lay; - //int count; + // int count; private slots: - void butt_click(int index) {emit clicked(index); emit clickedID(id_click, index);} - void butt_toggle(int index, bool checked) {emit toggled(index, checked); emit toggledID(id_click, index, checked);} + void butt_click(int index) { + emit clicked(index); + emit clickedID(id_click, index); + } + void butt_toggle(int index, bool checked) { + emit toggled(index, checked); + emit toggledID(id_click, index, checked); + } public slots: - void enable() {setEnabled(true);} - void disable() {setAllButtonsGray(); setEnabled(false);} - - void setClickID(int id) {id_click = id;} - void setSetID(int id) {id_set = id;} - - - void setButtonChecked(int index) {if (button(index) != 0) button(index)->setChecked(true);} - void setButtonUnchecked(int index) {if (button(index) != 0) button(index)->setChecked(false);} - void setButtonState(int index, TouchButton::State state) {if (button(index) != 0) button(index)->setState(state);} - void setButtonYes(int index) {if (button(index) != 0) button(index)->setStateYes();} - void setButtonNo(int index) {if (button(index) != 0) button(index)->setStateNo();} - void setButtonGray(int index) {if (button(index) != 0) button(index)->setStateGray();} - void setAllButtonsState(TouchButton::State state) {for (int i = 0; i < buttonsCount(); ++i) button(i)->setState(state);} - void setAllButtonsYes() {for (int i = 0; i < buttonsCount(); ++i) button(i)->setStateYes();} - void setAllButtonsNo() {for (int i = 0; i < buttonsCount(); ++i) button(i)->setStateNo();} - void setAllButtonsGray() {for (int i = 0; i < buttonsCount(); ++i) button(i)->setStateGray();} - - void hideButton(int index) {if (button(index) != 0) button(index)->hide();} - void showButton(int index) {if (button(index) != 0) button(index)->show();} - void enableButton(int index) {if (button(index) != 0) button(index)->enable();} - void disableButton(int index) {if (button(index) != 0) button(index)->disable();} + void enable() { setEnabled(true); } + void disable() { + setAllButtonsGray(); + setEnabled(false); + } - - void enableID(int set_id) {if (set_id == id_set) enable();} - void disableID(int set_id) {if (set_id == id_set) disable();} - - void setButtonCheckedID(int set_id, int index) {if (set_id == id_set) setButtonChecked(index);} - void setButtonUncheckedID(int set_id, int index) {if (set_id == id_set) setButtonUnchecked(index);} - void setButtonStateID(int set_id, int index, TouchButton::State state) {if (set_id == id_set) setButtonState(index, state);} - void setButtonYesID(int set_id, int index) {if (set_id == id_set) setButtonYes(index);} - void setButtonNoID(int set_id, int index) {if (set_id == id_set) setButtonNo(index);} - void setButtonGrayID(int set_id, int index) {if (set_id == id_set) setButtonGray(index);} - void setAllButtonsStateID(int set_id, TouchButton::State state) {if (set_id == id_set) setAllButtonsState(state);} - void setAllButtonsYesID(int set_id) {if (set_id == id_set) setAllButtonsYes();} - void setAllButtonsNoID(int set_id) {if (set_id == id_set) setAllButtonsNo();} - void setAllButtonsGrayID(int set_id) {if (set_id == id_set) setAllButtonsGray();} - - void hideButtonID(int set_id, int index) {if (set_id == id_set) hideButton(index);} - void showButtonID(int set_id, int index) {if (set_id == id_set) showButton(index);} - void enableButtonID(int set_id, int index) {if (set_id == id_set) enableButton(index);} - void disableButtonID(int set_id, int index) {if (set_id == id_set) disableButton(index);} + void setClickID(int id) { id_click = id; } + void setSetID(int id) { id_set = id; } + + + void setButtonChecked(int index) { + if (button(index) != 0) button(index)->setChecked(true); + } + void setButtonUnchecked(int index) { + if (button(index) != 0) button(index)->setChecked(false); + } + void setButtonState(int index, TouchButton::State state) { + if (button(index) != 0) button(index)->setState(state); + } + void setButtonYes(int index) { + if (button(index) != 0) button(index)->setStateYes(); + } + void setButtonNo(int index) { + if (button(index) != 0) button(index)->setStateNo(); + } + void setButtonGray(int index) { + if (button(index) != 0) button(index)->setStateGray(); + } + void setAllButtonsState(TouchButton::State state) { + for (int i = 0; i < buttonsCount(); ++i) + button(i)->setState(state); + } + void setAllButtonsYes() { + for (int i = 0; i < buttonsCount(); ++i) + button(i)->setStateYes(); + } + void setAllButtonsNo() { + for (int i = 0; i < buttonsCount(); ++i) + button(i)->setStateNo(); + } + void setAllButtonsGray() { + for (int i = 0; i < buttonsCount(); ++i) + button(i)->setStateGray(); + } + + void hideButton(int index) { + if (button(index) != 0) button(index)->hide(); + } + void showButton(int index) { + if (button(index) != 0) button(index)->show(); + } + void enableButton(int index) { + if (button(index) != 0) button(index)->enable(); + } + void disableButton(int index) { + if (button(index) != 0) button(index)->disable(); + } + + + void enableID(int set_id) { + if (set_id == id_set) enable(); + } + void disableID(int set_id) { + if (set_id == id_set) disable(); + } + + void setButtonCheckedID(int set_id, int index) { + if (set_id == id_set) setButtonChecked(index); + } + void setButtonUncheckedID(int set_id, int index) { + if (set_id == id_set) setButtonUnchecked(index); + } + void setButtonStateID(int set_id, int index, TouchButton::State state) { + if (set_id == id_set) setButtonState(index, state); + } + void setButtonYesID(int set_id, int index) { + if (set_id == id_set) setButtonYes(index); + } + void setButtonNoID(int set_id, int index) { + if (set_id == id_set) setButtonNo(index); + } + void setButtonGrayID(int set_id, int index) { + if (set_id == id_set) setButtonGray(index); + } + void setAllButtonsStateID(int set_id, TouchButton::State state) { + if (set_id == id_set) setAllButtonsState(state); + } + void setAllButtonsYesID(int set_id) { + if (set_id == id_set) setAllButtonsYes(); + } + void setAllButtonsNoID(int set_id) { + if (set_id == id_set) setAllButtonsNo(); + } + void setAllButtonsGrayID(int set_id) { + if (set_id == id_set) setAllButtonsGray(); + } + + void hideButtonID(int set_id, int index) { + if (set_id == id_set) hideButton(index); + } + void showButtonID(int set_id, int index) { + if (set_id == id_set) showButton(index); + } + void enableButtonID(int set_id, int index) { + if (set_id == id_set) enableButton(index); + } + void disableButtonID(int set_id, int index) { + if (set_id == id_set) disableButton(index); + } signals: void clicked(int index); void toggled(int index, bool checked); void clickedID(int id, int index); void toggledID(int id, int index, bool checked); - }; #endif // TOUCHBUTTFRAME_H diff --git a/libs/touch_widgets/touchbutton.cpp b/libs/touch_widgets/touchbutton.cpp index 7da1be1..e2b3d1a 100644 --- a/libs/touch_widgets/touchbutton.cpp +++ b/libs/touch_widgets/touchbutton.cpp @@ -13,8 +13,7 @@ TouchButton::TouchButton(int id__, const QString & text): QToolButton(0) { } -TouchButton::~TouchButton() { -} +TouchButton::~TouchButton() {} void TouchButton::init() { @@ -26,15 +25,15 @@ void TouchButton::init() { animation.setDuration(350); delay_blink = 500; anim = auto_gray = true; - state_ = Gray; + state_ = Gray; id_click = id_yes = id_no = -1; - timer = 0; - pal = palette(); - col_yes = QColor(Qt::green); - col_no = QColor(Qt::red); - col_down = QColor(Qt::yellow); + timer = 0; + pal = palette(); + col_yes = QColor(Qt::green); + col_no = QColor(Qt::red); + col_down = QColor(Qt::yellow); col_gray = col_cur = col_up = pal.button().color(); - col_dst = col_gray; + col_dst = col_gray; } @@ -81,7 +80,7 @@ void TouchButton::animateColor(const QColor & tc) { void TouchButton::applyState(State s) { if (s == state_) return; State ps = state_; - state_ = s; + state_ = s; emit stateChanged(state_, ps); emit stateChangedID(id_click, state_, ps); } diff --git a/libs/touch_widgets/touchbutton.h b/libs/touch_widgets/touchbutton.h index 56bd0fd..ed23275 100644 --- a/libs/touch_widgets/touchbutton.h +++ b/libs/touch_widgets/touchbutton.h @@ -1,37 +1,37 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef TOUCHBUTTON_H #define TOUCHBUTTON_H -#include +#include "qad_touch_widgets_export.h" + +#include #include #include #include -#include -#include "qad_touch_widgets_export.h" +#include -class QAD_TOUCH_WIDGETS_EXPORT TouchButton: public QToolButton -{ +class QAD_TOUCH_WIDGETS_EXPORT TouchButton: public QToolButton { Q_OBJECT - Q_ENUMS(State) + Q_ENUMS(State) Q_PROPERTY(QColor downColor READ downColor WRITE setDownColor) Q_PROPERTY(QColor upColor READ upColor WRITE setUpColor) Q_PROPERTY(QColor grayColor READ grayColor WRITE setGrayColor) @@ -52,36 +52,43 @@ public: explicit TouchButton(QWidget * parent = 0); TouchButton(int id, const QString & text = QString()); ~TouchButton(); - - enum State {Gray, Yes, No}; - int clickID() const {return id_click;} - int yesID() const {return id_yes;} - int noID() const {return id_no;} - - QColor downColor() const {return col_down;} - QColor upColor() const {return col_up;} - QColor grayColor() const {return col_gray;} - QColor yesColor() const {return col_yes;} - QColor noColor() const {return col_no;} - QColor currentColor() const {return col_cur;} - State state() const {return state_;} - bool autoGray() const {return auto_gray;} - bool animated() const {return anim;} - int animationDuration() const {return animation.duration();} - QEasingCurve::Type animationCurve() const {return animation.easingCurve().type();} - int blinkDelay() const {return delay_blink;} - + enum State { + Gray, + Yes, + No + }; + + int clickID() const { return id_click; } + int yesID() const { return id_yes; } + int noID() const { return id_no; } + + QColor downColor() const { return col_down; } + QColor upColor() const { return col_up; } + QColor grayColor() const { return col_gray; } + QColor yesColor() const { return col_yes; } + QColor noColor() const { return col_no; } + QColor currentColor() const { return col_cur; } + State state() const { return state_; } + bool autoGray() const { return auto_gray; } + bool animated() const { return anim; } + int animationDuration() const { return animation.duration(); } + QEasingCurve::Type animationCurve() const { return animation.easingCurve().type(); } + int blinkDelay() const { return delay_blink; } + void blink(const QColor & tc); private: void timerEvent(QTimerEvent * e); void mousePressEvent(QMouseEvent * e); void mouseReleaseEvent(QMouseEvent * e); - + void init(); void animateColor(const QColor & tc); - void applyColor() {pal.setColor(QPalette::Button, col_cur); setPalette(pal);} + void applyColor() { + pal.setColor(QPalette::Button, col_cur); + setPalette(pal); + } void applyState(State s); QPalette pal; @@ -90,74 +97,150 @@ private: State state_; int id_click, id_yes, id_no, delay_blink, timer; bool anim, auto_gray; - + private slots: - void _clicked() {emit clickedID(id_click);} - void _toggled(bool on) {if (!on && auto_gray) setStateGray(); emit toggledID(id_click, on);} + void _clicked() { emit clickedID(id_click); } + void _toggled(bool on) { + if (!on && auto_gray) setStateGray(); + emit toggledID(id_click, on); + } public slots: - void enable() {setEnabled(true);} - void disable() {setStateGray(); setEnabled(false);} - - void setClickID(int id) {id_click = id;} - void setYesID(int id) {id_yes = id;} - void setNoID(int id) {id_no = id;} - - void setDownColor(const QColor & col) {col_down = col;} - void setUpColor(const QColor & col) {col_up = col;} - void setGrayColor(const QColor & col) {col_gray = col;} - void setYesColor(const QColor & col) {col_yes = col;} - void setNoColor(const QColor & col) {col_no = col;} - - + void enable() { setEnabled(true); } + void disable() { + setStateGray(); + setEnabled(false); + } + + void setClickID(int id) { id_click = id; } + void setYesID(int id) { id_yes = id; } + void setNoID(int id) { id_no = id; } + + void setDownColor(const QColor & col) { col_down = col; } + void setUpColor(const QColor & col) { col_up = col; } + void setGrayColor(const QColor & col) { col_gray = col; } + void setYesColor(const QColor & col) { col_yes = col; } + void setNoColor(const QColor & col) { col_no = col; } + + void setState(State s); - void setStateGray() {col_dst = col_gray; applyState(Gray); animateColor(col_dst);} - void setStateYes() {col_dst = col_yes; applyState(Yes); animateColor(col_dst);} - void setStateNo() {col_dst = col_no; applyState(No); animateColor(col_dst);} - void setStateYesOrNo(bool yes) {if (yes) setStateYes(); else setStateNo();} - void setStateYesOrGray(bool yes) {if (yes) setStateYes(); else setStateGray();} - void setStateNoOrYes(bool no) {if (no) setStateNo(); else setStateYes();} - void setStateNoOrGray(bool no) {if (no) setStateNo(); else setStateGray();} - - void blinkYes() {blink(col_yes);} - void blinkNo() {blink(col_no);} - void blinkYesOrNo(bool yes) {blink(yes ? col_yes : col_no);} - void blinkNoOrYes(bool no) {blink(no ? col_no : col_yes);} - - - void enableID(int yes_id) {if (yes_id == id_yes) enable();} - void disableID(int yes_id) {if (yes_id == id_yes) disable();} - - void setStateID(int yes_id, State s) {if (yes_id == id_yes) setState(s);} - void setStateGrayID(int yes_id) {if (yes_id == id_yes) setStateGray();} - void setStateYesID(int yes_id) {if (yes_id == id_yes) setStateYes();} - void setStateNoID(int no_id) {if (no_id == id_no) setStateNo();} - void setStateYesOrNoID(int yes_id, bool yes) {if (yes_id == id_yes) setStateYesOrNo(yes);} - void setStateYesOrGrayID(int yes_id, bool yes) {if (yes_id == id_yes) setStateYesOrGray(yes);} - void setStateNoOrYesID(int no_id, bool no) {if (no_id == id_no) setStateNoOrYes(no);} - void setStateNoOrGrayID(int no_id, bool no) {if (no_id == id_no) setStateNoOrGray(no);} - - void blinkYesID(int yes_id) {if (yes_id == id_yes) blinkYes();} - void blinkNoID(int no_id) {if (no_id == id_no) blinkNo();} - void blinkYesOrNoID(int yes_id, bool yes) {if (yes_id == id_yes) blinkYesOrNo(yes);} - void blinkNoOrYesID(int no_id, bool no) {if (no_id == id_no) blinkNoOrYes(no);} - - - void setColor(const QColor & col) {col_dst = col; animateColor(col_dst);} - void setCurrentColor(const QColor & col) {col_cur = col; applyColor();} - - void setAutoGray(bool yes) {auto_gray = yes;} - void setAnimated(bool yes) {anim = yes;} - void setAnimationDuration(int dur) {animation.setDuration(dur);} - void setAnimationCurve(QEasingCurve::Type curve) {animation.setEasingCurve(QEasingCurve(curve));} - void setBlinkDelay(int dur) {delay_blink = dur;} - - void delayedClick() {QMetaObject::invokeMethod(this, "click", Qt::QueuedConnection);} - void delayedToggle() {QMetaObject::invokeMethod(this, "toggle", Qt::QueuedConnection);} - - void delayedClickID(int yes_id) {if (yes_id == id_yes) delayedClick();} - void delayedToggleID(int yes_id) {if (yes_id == id_yes) delayedToggle();} - + void setStateGray() { + col_dst = col_gray; + applyState(Gray); + animateColor(col_dst); + } + void setStateYes() { + col_dst = col_yes; + applyState(Yes); + animateColor(col_dst); + } + void setStateNo() { + col_dst = col_no; + applyState(No); + animateColor(col_dst); + } + void setStateYesOrNo(bool yes) { + if (yes) + setStateYes(); + else + setStateNo(); + } + void setStateYesOrGray(bool yes) { + if (yes) + setStateYes(); + else + setStateGray(); + } + void setStateNoOrYes(bool no) { + if (no) + setStateNo(); + else + setStateYes(); + } + void setStateNoOrGray(bool no) { + if (no) + setStateNo(); + else + setStateGray(); + } + + void blinkYes() { blink(col_yes); } + void blinkNo() { blink(col_no); } + void blinkYesOrNo(bool yes) { blink(yes ? col_yes : col_no); } + void blinkNoOrYes(bool no) { blink(no ? col_no : col_yes); } + + + void enableID(int yes_id) { + if (yes_id == id_yes) enable(); + } + void disableID(int yes_id) { + if (yes_id == id_yes) disable(); + } + + void setStateID(int yes_id, State s) { + if (yes_id == id_yes) setState(s); + } + void setStateGrayID(int yes_id) { + if (yes_id == id_yes) setStateGray(); + } + void setStateYesID(int yes_id) { + if (yes_id == id_yes) setStateYes(); + } + void setStateNoID(int no_id) { + if (no_id == id_no) setStateNo(); + } + void setStateYesOrNoID(int yes_id, bool yes) { + if (yes_id == id_yes) setStateYesOrNo(yes); + } + void setStateYesOrGrayID(int yes_id, bool yes) { + if (yes_id == id_yes) setStateYesOrGray(yes); + } + void setStateNoOrYesID(int no_id, bool no) { + if (no_id == id_no) setStateNoOrYes(no); + } + void setStateNoOrGrayID(int no_id, bool no) { + if (no_id == id_no) setStateNoOrGray(no); + } + + void blinkYesID(int yes_id) { + if (yes_id == id_yes) blinkYes(); + } + void blinkNoID(int no_id) { + if (no_id == id_no) blinkNo(); + } + void blinkYesOrNoID(int yes_id, bool yes) { + if (yes_id == id_yes) blinkYesOrNo(yes); + } + void blinkNoOrYesID(int no_id, bool no) { + if (no_id == id_no) blinkNoOrYes(no); + } + + + void setColor(const QColor & col) { + col_dst = col; + animateColor(col_dst); + } + void setCurrentColor(const QColor & col) { + col_cur = col; + applyColor(); + } + + void setAutoGray(bool yes) { auto_gray = yes; } + void setAnimated(bool yes) { anim = yes; } + void setAnimationDuration(int dur) { animation.setDuration(dur); } + void setAnimationCurve(QEasingCurve::Type curve) { animation.setEasingCurve(QEasingCurve(curve)); } + void setBlinkDelay(int dur) { delay_blink = dur; } + + void delayedClick() { QMetaObject::invokeMethod(this, "click", Qt::QueuedConnection); } + void delayedToggle() { QMetaObject::invokeMethod(this, "toggle", Qt::QueuedConnection); } + + void delayedClickID(int yes_id) { + if (yes_id == id_yes) delayedClick(); + } + void delayedToggleID(int yes_id) { + if (yes_id == id_yes) delayedToggle(); + } + signals: void clickedID(int id); void pressedID(int id); @@ -165,7 +248,6 @@ signals: void toggledID(int id, bool on); void stateChanged(State state, State prev_state); void stateChangedID(int id, State state, State prev_state); - }; #endif // TOUCHBUTTON_H diff --git a/libs/touch_widgets/touchslider.cpp b/libs/touch_widgets/touchslider.cpp index e84caca..7e0f1f4 100644 --- a/libs/touch_widgets/touchslider.cpp +++ b/libs/touch_widgets/touchslider.cpp @@ -1,16 +1,17 @@ #include "touchslider.h" + #include "ui_touchslider.h" TouchSlider::TouchSlider(QWidget * parent): QGroupBox(parent), ui(new Ui::TouchSlider) { ui->setupUi(this); ui->barNeg->setMinimum(0); - prec = 1; + prec = 1; id_click = id_set = -1; - hasZero = true; - m_readOnly = false; - m_showMinMax = true; - m_showIncDec = true; + hasZero = true; + m_readOnly = false; + m_showMinMax = true; + m_showIncDec = true; } @@ -68,7 +69,8 @@ void TouchSlider::setValue(double val) { double TouchSlider::value() const { if (ui->barNeg->value() <= ui->barNeg->minimum()) return (double)(ui->barPos->value()) * prec; - else return -(double)(ui->barNeg->value()) * prec; + else + return -(double)(ui->barNeg->value()) * prec; } @@ -117,7 +119,7 @@ void TouchSlider::setPrecision(double precision) { double min = minimum(); double max = maximum(); double val = value(); - prec = precision; + prec = precision; setMinimum(min); setMaximum(max); setValue(val); @@ -144,9 +146,9 @@ void TouchSlider::on_barPos_mouseMoveEvent(QMouseEvent * e) { if (m_readOnly) return; int tx = #if QT_VERSION_MAJOR <= 5 - e->x(); + e->x(); #else - e->position().toPoint().x(); + e->position().toPoint().x(); #endif if (tx > ui->barPos->width()) tx = ui->barPos->width(); if (tx < 0) { @@ -160,7 +162,8 @@ void TouchSlider::on_barPos_mouseMoveEvent(QMouseEvent * e) { } tx = 0; } - ui->barPos->setValue(ui->barPos->minimum() + qRound((double)(tx * (ui->barPos->maximum() - ui->barPos->minimum())) / (double)(ui->barPos->width()))); + ui->barPos->setValue(ui->barPos->minimum() + + qRound((double)(tx * (ui->barPos->maximum() - ui->barPos->minimum())) / (double)(ui->barPos->width()))); ui->barNeg->setValue(ui->barNeg->minimum()); } @@ -169,9 +172,9 @@ void TouchSlider::on_barNeg_mouseMoveEvent(QMouseEvent * e) { if (m_readOnly) return; int tx = #if QT_VERSION_MAJOR <= 5 - e->x(); + e->x(); #else - e->position().toPoint().x(); + e->position().toPoint().x(); #endif if (tx < 0) tx = 0; if (tx > ui->barNeg->width()) { @@ -192,11 +195,12 @@ void TouchSlider::on_barPos_mousePressEvent(QMouseEvent * e) { if (m_readOnly) return; int tx = #if QT_VERSION_MAJOR <= 5 - e->x(); + e->x(); #else - e->position().toPoint().x(); + e->position().toPoint().x(); #endif - ui->barPos->setValue(ui->barPos->minimum() + qRound((double)(tx * (ui->barPos->maximum() - ui->barPos->minimum())) / (double)(ui->barPos->width()))); + ui->barPos->setValue(ui->barPos->minimum() + + qRound((double)(tx * (ui->barPos->maximum() - ui->barPos->minimum())) / (double)(ui->barPos->width()))); ui->barNeg->setValue(ui->barNeg->minimum()); } @@ -205,9 +209,9 @@ void TouchSlider::on_barNeg_mousePressEvent(QMouseEvent * e) { if (m_readOnly) return; int tx = #if QT_VERSION_MAJOR <= 5 - e->x(); + e->x(); #else - e->position().toPoint().x(); + e->position().toPoint().x(); #endif ui->barNeg->setValue(ui->barNeg->maximum() - qRound((double)(tx * ui->barNeg->maximum()) / (double)(ui->barNeg->width()))); ui->barPos->setValue(ui->barPos->minimum()); @@ -226,19 +230,17 @@ void TouchSlider::on_barPos_valueChanged(int) { void TouchSlider::setReadOnly(bool arg) { QBoxLayout * bl = qobject_cast(layout()); - m_readOnly = arg; + m_readOnly = arg; if (arg) { ui->pbDec->hide(); ui->pbInc->hide(); - if (hasZero) - ui->pbZero->hide(); + if (hasZero) ui->pbZero->hide(); bl->setStretchFactor(ui->pbMin, 2); bl->setStretchFactor(ui->pbMax, 2); } else { ui->pbDec->show(); ui->pbInc->show(); - if (hasZero) - ui->pbZero->show(); + if (hasZero) ui->pbZero->show(); bl->setStretchFactor(ui->pbMin, 1); bl->setStretchFactor(ui->pbMax, 1); } @@ -247,7 +249,7 @@ void TouchSlider::setReadOnly(bool arg) { void TouchSlider::setShowMinMax(bool arg) { QBoxLayout * bl = qobject_cast(layout()); - m_showMinMax = arg; + m_showMinMax = arg; if (arg) { ui->pbMin->show(); ui->pbMax->show(); @@ -266,19 +268,17 @@ void TouchSlider::setShowMinMax(bool arg) { void TouchSlider::setShowIncDec(bool arg) { QBoxLayout * bl = qobject_cast(layout()); - m_showIncDec = arg; + m_showIncDec = arg; if (arg) { ui->pbDec->show(); ui->pbInc->show(); - if (hasZero) - ui->pbZero->show(); + if (hasZero) ui->pbZero->show(); bl->setStretchFactor(ui->pbMin, 2); bl->setStretchFactor(ui->pbMax, 2); } else { ui->pbDec->hide(); ui->pbInc->hide(); - if (hasZero) - ui->pbZero->hide(); + if (hasZero) ui->pbZero->hide(); bl->setStretchFactor(ui->pbMin, 1); bl->setStretchFactor(ui->pbMax, 1); } diff --git a/libs/touch_widgets/touchslider.h b/libs/touch_widgets/touchslider.h index 6fc57ac..cd55e15 100644 --- a/libs/touch_widgets/touchslider.h +++ b/libs/touch_widgets/touchslider.h @@ -1,37 +1,37 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef TOUCHSLIDER_H #define TOUCHSLIDER_H +#include "qad_touch_widgets_export.h" + #include #include -#include "qad_touch_widgets_export.h" namespace Ui { - class TouchSlider; +class TouchSlider; } -class QAD_TOUCH_WIDGETS_EXPORT TouchSlider: public QGroupBox -{ +class QAD_TOUCH_WIDGETS_EXPORT TouchSlider: public QGroupBox { Q_OBJECT Q_PROPERTY(bool readOnly READ readOnly WRITE setReadOnly) Q_PROPERTY(bool showMinMax READ showMinMax WRITE setShowMinMax) @@ -46,26 +46,26 @@ class QAD_TOUCH_WIDGETS_EXPORT TouchSlider: public QGroupBox Q_PROPERTY(int setID READ setID WRITE setSetID) public: - explicit TouchSlider(QWidget *parent = 0); + explicit TouchSlider(QWidget * parent = 0); ~TouchSlider(); - - int clickID() const {return id_click;} - int setID() const {return id_set;} + + int clickID() const { return id_click; } + int setID() const { return id_set; } double minimum() const; double maximum() const; double value() const; double precision() const; - QString prefix() const {return pref;} - QString suffix() const {return suff;} - bool readOnly() const {return m_readOnly;} - bool showMinMax() const {return m_showMinMax;} - bool showIncDec() const {return m_showIncDec;} + QString prefix() const { return pref; } + QString suffix() const { return suff; } + bool readOnly() const { return m_readOnly; } + bool showMinMax() const { return m_showMinMax; } + bool showIncDec() const { return m_showIncDec; } private: void updateCaption(); - - Ui::TouchSlider *ui; + + Ui::TouchSlider * ui; bool hasZero; bool m_readOnly; bool m_showMinMax; @@ -75,46 +75,60 @@ private: QString pref, suff; public slots: - void enable() {setEnabled(true);} - void disable() {setEnabled(false);} - - void setClickID(int id) {id_click = id;} - void setSetID(int id) {id_set = id;} - - void setSuffix(const QString & text) {suff = text; updateCaption();} - void setPrefix(const QString & text) {pref = text; updateCaption();} + void enable() { setEnabled(true); } + void disable() { setEnabled(false); } + + void setClickID(int id) { id_click = id; } + void setSetID(int id) { id_set = id; } + + void setSuffix(const QString & text) { + suff = text; + updateCaption(); + } + void setPrefix(const QString & text) { + pref = text; + updateCaption(); + } void setPrecision(double precision); - void setPrecision(int precision) {setPrecision((double)precision);} + void setPrecision(int precision) { setPrecision((double)precision); } void setMinimum(double min); - void setMinimum(int min) {setMinimum((double)min);} + void setMinimum(int min) { setMinimum((double)min); } void setMaximum(double max); - void setMaximum(int max) {setMaximum((double)max);} + void setMaximum(int max) { setMaximum((double)max); } void setReadOnly(bool yes); void setShowMinMax(bool yes); void setShowIncDec(bool yes); - + void setValue(double val); - void setValue(int val) {setValue((double)val);} - - void enableID(int set_id) {if (set_id == id_set) enable();} - void disableID(int set_id) {if (set_id == id_set) disable();} - - void setValueID(int set_id, double val) {if (set_id == id_set) setValue(val);} - void setValueID(int set_id, int val) {if (set_id == id_set) setValue(val);} - - void clickMin() {on_pbMin_clicked();} - void clickMax() {on_pbMax_clicked();} - void clickInc() {on_pbInc_clicked();} - void clickDec() {on_pbDec_clicked();} - void clickZero() {on_pbZero_clicked();} + void setValue(int val) { setValue((double)val); } + + void enableID(int set_id) { + if (set_id == id_set) enable(); + } + void disableID(int set_id) { + if (set_id == id_set) disable(); + } + + void setValueID(int set_id, double val) { + if (set_id == id_set) setValue(val); + } + void setValueID(int set_id, int val) { + if (set_id == id_set) setValue(val); + } + + void clickMin() { on_pbMin_clicked(); } + void clickMax() { on_pbMax_clicked(); } + void clickInc() { on_pbInc_clicked(); } + void clickDec() { on_pbDec_clicked(); } + void clickZero() { on_pbZero_clicked(); } private slots: void on_barPos_valueChanged(int value); void on_barNeg_valueChanged(int value); - void on_barNeg_mousePressEvent(QMouseEvent*); - void on_barPos_mousePressEvent(QMouseEvent*); - void on_barNeg_mouseMoveEvent(QMouseEvent*); - void on_barPos_mouseMoveEvent(QMouseEvent*); + void on_barNeg_mousePressEvent(QMouseEvent *); + void on_barPos_mousePressEvent(QMouseEvent *); + void on_barNeg_mouseMoveEvent(QMouseEvent *); + void on_barPos_mouseMoveEvent(QMouseEvent *); void on_pbZero_clicked(); void on_pbDec_clicked(); void on_pbInc_clicked(); diff --git a/libs/utils/chunkstream.cpp b/libs/utils/chunkstream.cpp index b84ac6c..88e4cbf 100644 --- a/libs/utils/chunkstream.cpp +++ b/libs/utils/chunkstream.cpp @@ -3,7 +3,7 @@ void ChunkStream::setSource(const QByteArray & data) { stream_.setVersion(QDataStream::Qt_4_8); - data_ = const_cast(&data); + data_ = const_cast(&data); _init(); } @@ -25,13 +25,11 @@ void ChunkStream::setSource(QDataStream & str) { int ChunkStream::read() { switch (version_) { - case Version_1: - stream_ >> last_id >> last_data; - break; + case Version_1: stream_ >> last_id >> last_data; break; case Version_2: last_id = readVInt(stream_); last_data.resize(readVInt(stream_)); - //piCout << last_id << last_data.size(); + // piCout << last_id << last_data.size(); stream_.readRawData(last_data.data(), last_data.size()); break; default: break; @@ -49,9 +47,7 @@ void ChunkStream::readAll() { } -ChunkStream::~ChunkStream() { - -} +ChunkStream::~ChunkStream() {} void ChunkStream::_init() { @@ -66,7 +62,10 @@ void ChunkStream::_init() { if ((v & 0x80) == 0x80) { v &= 0x7f; switch (v) { - case 2: version_ = (uchar)Version_2; stream_.skipRawData(1); break; + case 2: + version_ = (uchar)Version_2; + stream_.skipRawData(1); + break; default: version_ = Version_1; break; } } else @@ -77,15 +76,17 @@ void ChunkStream::_init() { uint ChunkStream::readVInt(QDataStream & s) { if (s.atEnd()) return 0; - uchar bytes[4]; s >> bytes[0]; + uchar bytes[4]; + s >> bytes[0]; uchar abc = 0; for (abc = 0; abc < 3; ++abc) { uchar mask = (0x80 >> abc); if ((bytes[0] & mask) == mask) { - //if (s.isEmpty()) return 0; + // if (s.isEmpty()) return 0; bytes[0] &= (mask - 1); s >> bytes[abc + 1]; - } else break; + } else + break; } uint ret = 0; for (int i = 0; i <= abc; ++i) { diff --git a/libs/utils/chunkstream.h b/libs/utils/chunkstream.h index b7b850b..f330e4b 100644 --- a/libs/utils/chunkstream.h +++ b/libs/utils/chunkstream.h @@ -1,89 +1,97 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CHUNKSTREAM_H #define CHUNKSTREAM_H -#include -#include -#include -#include -#include #include "qad_utils_export.h" +#include +#include +#include +#include +#include -class QAD_UTILS_EXPORT ChunkStream -{ + +class QAD_UTILS_EXPORT ChunkStream { public: enum Version { Version_1 /*! First, old version */, Version_2 /*! Second, more optimized version */ = 2, }; - ChunkStream(const QByteArray & data): version_(Version_2) {setSource(data);} - ChunkStream(QDataStream & str): version_(Version_2) {setSource(str);} - ChunkStream(QByteArray * data = 0, Version v = Version_2): version_(v) {setSource(data);} - ChunkStream(Version v): version_(v) {setSource(0);} + ChunkStream(const QByteArray & data): version_(Version_2) { setSource(data); } + ChunkStream(QDataStream & str): version_(Version_2) { setSource(str); } + ChunkStream(QByteArray * data = 0, Version v = Version_2): version_(v) { setSource(data); } + ChunkStream(Version v): version_(v) { setSource(0); } ~ChunkStream(); - template + template struct Chunk { Chunk(int i, const T & d): id(i), data(d) {} int id; T data; }; - template + template struct ChunkConst { ChunkConst(int i, const T & d): id(i), data(d) {} int id; const T & data; }; - template static ChunkConst chunk(int id, const T & data) {return ChunkConst(id, data);} + template + static ChunkConst chunk(int id, const T & data) { + return ChunkConst(id, data); + } - template ChunkStream & add(int id, const T & data) {*this << ChunkConst(id, data); return *this;} + template + ChunkStream & add(int id, const T & data) { + *this << ChunkConst(id, data); + return *this; + } void setSource(const QByteArray & data); void setSource(QDataStream & str); void setSource(QByteArray * data); - QDataStream & dataStream() {return stream_;} - QByteArray data() const {return tmp_data;} - bool atEnd() const {return stream_.atEnd();} - Version version() const {return (Version)version_;} - + QDataStream & dataStream() { return stream_; } + QByteArray data() const { return tmp_data; } + bool atEnd() const { return stream_.atEnd(); } + Version version() const { return (Version)version_; } int read(); void readAll(); - int getID() {return last_id;} + int getID() { return last_id; } - template - void get(T & v) const {v = getData();} + template + void get(T & v) const { + v = getData(); + } - template typename std::enable_if::value, T>::type - getData() const { + template + typename std::enable_if::value, T>::type getData() const { QDataStream s(last_data); s.setVersion(QDataStream::Qt_4_8); T ret; s >> ret; return ret; } - template typename std::enable_if::value, T>::type - getData() const { + template + typename std::enable_if::value, T>::type getData() const { QDataStream s(last_data); s.setVersion(QDataStream::Qt_4_8); typename std::underlying_type::type ret; @@ -91,8 +99,8 @@ public: return (T)ret; } - template typename std::enable_if::value, const ChunkStream &>::type - get(int id, T & v) const { + template + typename std::enable_if::value, const ChunkStream &>::type get(int id, T & v) const { QByteArray ba = data_map.value(id); if (!ba.isEmpty()) { QDataStream s(ba); @@ -101,8 +109,8 @@ public: } return *this; } - template typename std::enable_if::value, const ChunkStream &>::type - get(int id, T & v) const { + template + typename std::enable_if::value, const ChunkStream &>::type get(int id, T & v) const { QByteArray ba = data_map.value(id); if (!ba.isEmpty()) { QDataStream s(ba); @@ -122,53 +130,52 @@ private: int last_id; uchar version_; - QByteArray * data_, last_data, tmp_data; + QByteArray *data_, last_data, tmp_data; QBuffer buffer; QDataStream stream_; QMap data_map; - template friend ChunkStream & operator <<(ChunkStream & s, const ChunkStream::Chunk & c); - template friend ChunkStream & operator <<(ChunkStream & s, const ChunkStream::ChunkConst & c); + template + friend ChunkStream & operator<<(ChunkStream & s, const ChunkStream::Chunk & c); + template + friend ChunkStream & operator<<(ChunkStream & s, const ChunkStream::ChunkConst & c); }; -template typename std::enable_if::value, void>::type -__writeChunkData(QByteArray & ba, const ChunkStream::Chunk & c) { +template +typename std::enable_if::value, void>::type __writeChunkData(QByteArray & ba, const ChunkStream::Chunk & c) { QDataStream bas(&ba, QIODevice::WriteOnly); bas.setVersion(QDataStream::Qt_4_8); bas << c.data; } -template typename std::enable_if::value, void>::type -__writeChunkData(QByteArray & ba, const ChunkStream::Chunk & c) { +template +typename std::enable_if::value, void>::type __writeChunkData(QByteArray & ba, const ChunkStream::Chunk & c) { QDataStream bas(&ba, QIODevice::WriteOnly); bas.setVersion(QDataStream::Qt_4_8); typename std::underlying_type::type iv = c.data; bas << iv; } -template typename std::enable_if::value, void>::type -__writeChunkConstData(QByteArray & ba, const ChunkStream::ChunkConst & c) { +template +typename std::enable_if::value, void>::type __writeChunkConstData(QByteArray & ba, const ChunkStream::ChunkConst & c) { QDataStream bas(&ba, QIODevice::WriteOnly); bas.setVersion(QDataStream::Qt_4_8); bas << c.data; } -template typename std::enable_if::value, void>::type -__writeChunkConstData(QByteArray & ba, const ChunkStream::ChunkConst & c) { +template +typename std::enable_if::value, void>::type __writeChunkConstData(QByteArray & ba, const ChunkStream::ChunkConst & c) { QDataStream bas(&ba, QIODevice::WriteOnly); bas.setVersion(QDataStream::Qt_4_8); typename std::underlying_type::type iv = c.data; bas << iv; } -template -ChunkStream & operator <<(ChunkStream & s, const ChunkStream::Chunk & c) { +template +ChunkStream & operator<<(ChunkStream & s, const ChunkStream::Chunk & c) { QByteArray ba; __writeChunkData(ba, c); switch (s.version_) { - case ChunkStream::Version_1: - s.stream_ << c.id << ba; - break; + case ChunkStream::Version_1: s.stream_ << c.id << ba; break; case ChunkStream::Version_2: - if (s.data_->isEmpty()) - s.stream_ << uchar(uchar(s.version_) | 0x80); + if (s.data_->isEmpty()) s.stream_ << uchar(uchar(s.version_) | 0x80); ChunkStream::writeVInt(s.stream_, c.id); ChunkStream::writeVInt(s.stream_, ba.size()); s.stream_.writeRawData(ba.data(), ba.size()); @@ -178,17 +185,14 @@ ChunkStream & operator <<(ChunkStream & s, const ChunkStream::Chunk & c) { return s; } -template -ChunkStream & operator <<(ChunkStream & s, const ChunkStream::ChunkConst & c) { +template +ChunkStream & operator<<(ChunkStream & s, const ChunkStream::ChunkConst & c) { QByteArray ba; __writeChunkConstData(ba, c); switch (s.version_) { - case ChunkStream::Version_1: - s.stream_ << c.id << ba; - break; + case ChunkStream::Version_1: s.stream_ << c.id << ba; break; case ChunkStream::Version_2: - if (s.data_->isEmpty()) - s.stream_ << uchar(uchar(s.version_) | 0x80); + if (s.data_->isEmpty()) s.stream_ << uchar(uchar(s.version_) | 0x80); ChunkStream::writeVInt(s.stream_, c.id); ChunkStream::writeVInt(s.stream_, ba.size()); s.stream_.writeRawData(ba.data(), ba.size()); diff --git a/libs/utils/plugin/qad_utils.cpp b/libs/utils/plugin/qad_utils.cpp index 0b70ed0..f1005fe 100644 --- a/libs/utils/plugin/qad_utils.cpp +++ b/libs/utils/plugin/qad_utils.cpp @@ -1,12 +1,12 @@ -//#include "qpiconfigplugin.h" +// #include "qpiconfigplugin.h" #include "qad_utils.h" QADUtils::QADUtils(QObject * parent): QObject(parent) { - //m_widgets.append(new QPIConfigPlugin(this)); + // m_widgets.append(new QPIConfigPlugin(this)); } -QList QADUtils::customWidgets() const { +QList QADUtils::customWidgets() const { return m_widgets; } diff --git a/libs/utils/plugin/qad_utils.h b/libs/utils/plugin/qad_utils.h index 4c825f5..2017667 100644 --- a/libs/utils/plugin/qad_utils.h +++ b/libs/utils/plugin/qad_utils.h @@ -1,24 +1,25 @@ #ifndef QAD_UTILS_H #define QAD_UTILS_H -#include #include +#include -class QADUtils: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADUtils + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT - //Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetInterface") + // Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetInterface") #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.utils") #endif Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) + public: explicit QADUtils(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_UTILS_H diff --git a/libs/utils/propertystorage.cpp b/libs/utils/propertystorage.cpp index ef9ef1a..5b1faa7 100644 --- a/libs/utils/propertystorage.cpp +++ b/libs/utils/propertystorage.cpp @@ -1,6 +1,7 @@ -#include #include "qad_types.h" +#include + PropertyStorage::PropertyStorage(const QVariantMap & pl) { QMapIterator it(pl); @@ -13,7 +14,7 @@ PropertyStorage::PropertyStorage(const QVariantMap & pl) { QVariantMap PropertyStorage::toVariantMap() const { QVariantMap ret; - foreach (const Property & p, props) + foreach(const Property & p, props) ret[p.name] = p.value; return ret; } @@ -21,8 +22,7 @@ QVariantMap PropertyStorage::toVariantMap() const { bool PropertyStorage::isPropertyExists(const QString & _name) const { for (int i = 0; i < props.size(); ++i) - if (props[i].name == _name) - return true; + if (props[i].name == _name) return true; return false; } @@ -57,33 +57,29 @@ void PropertyStorage::removePropertiesByFlag(int flag) { void PropertyStorage::updateProperties(const QList & properties_, int flag_ignore) { QVariantMap values; - foreach (const PropertyStorage::Property & p, props) - if (((p.flags & flag_ignore) != flag_ignore) || (flag_ignore == 0)) - values[p.name] = p.value; + foreach(const PropertyStorage::Property & p, props) + if (((p.flags & flag_ignore) != flag_ignore) || (flag_ignore == 0)) values[p.name] = p.value; props = properties_; for (int i = 0; i < props.size(); ++i) { PropertyStorage::Property & p(props[i]); if (values.contains(p.name)) { QVariant pv = values[p.name]; - if (pv.userType() == p.value.userType()) - p.value = pv; + if (pv.userType() == p.value.userType()) p.value = pv; } } } PropertyStorage::Property PropertyStorage::propertyByName(const QString & name) const { - foreach (const Property & p, props) - if (p.name == name) - return p; + foreach(const Property & p, props) + if (p.name == name) return p; return Property(); } QVariant PropertyStorage::propertyValueByName(const QString & name) const { - foreach (const Property & p, props) - if (p.name == name) - return p.value; + foreach(const Property & p, props) + if (p.name == name) return p.value; return QVariant(); } @@ -120,8 +116,8 @@ PropertyStorage::Property PropertyStorage::parsePropertyLine(QString l) { QString pn, pc, pt("s"), pv; if (l.contains('#')) { int i = l.indexOf('#'); - pn = l.left(i).trimmed(); - pc = l.right(l.length() - i - 1).trimmed(); + pn = l.left(i).trimmed(); + pc = l.right(l.length() - i - 1).trimmed(); } else { if (l.contains('(')) { int bs = l.indexOf('('), be = l.indexOf(')'); @@ -130,7 +126,7 @@ PropertyStorage::Property PropertyStorage::parsePropertyLine(QString l) { l.remove(bs, be - bs + 1); } else { pc = l.right(l.length() - bs - 1).trimmed(); - l = l.left(bs); + l = l.left(bs); } } pn = l.trimmed(); @@ -141,36 +137,42 @@ PropertyStorage::Property PropertyStorage::parsePropertyLine(QString l) { } if (pn.contains('=')) { int i = pn.indexOf('='); - pv = pn.right(pn.length() - i - 1).trimmed(); + pv = pn.right(pn.length() - i - 1).trimmed(); pn.truncate(i); pn = pn.trimmed(); } - ret.name = pn; + ret.name = pn; ret.comment = pc; - ret.value = QVariant(typeFromLetter(pt)); + ret.value = QVariant(typeFromLetter(pt)); if (!pv.isEmpty()) { - //qDebug() << "set value !" << pv; + // qDebug() << "set value !" << pv; #if QT_VERSION_MAJOR <= 5 switch (ret.value.type()) { - case QVariant::Bool: pv = pv.toLower(); ret.value = (pv == "on" || pv == "true" || pv == "enable" || pv == "enabled" || pv.toInt() > 0 ? true : false); break; - case QVariant::Int: ret.value = pv.toInt(); break; - case QVariant::UInt: ret.value = pv.toUInt(); break; - case QVariant::LongLong: ret.value = pv.toLongLong(); break; - case QVariant::ULongLong: ret.value = pv.toULongLong(); break; - case QVariant::Double: ret.value = pv.toDouble(); break; - case QVariant::Color: ret.value = QColor(pv); break; - default: ret.value = pv; break; + case QVariant::Bool: + pv = pv.toLower(); + ret.value = (pv == "on" || pv == "true" || pv == "enable" || pv == "enabled" || pv.toInt() > 0 ? true : false); + break; + case QVariant::Int: ret.value = pv.toInt(); break; + case QVariant::UInt: ret.value = pv.toUInt(); break; + case QVariant::LongLong: ret.value = pv.toLongLong(); break; + case QVariant::ULongLong: ret.value = pv.toULongLong(); break; + case QVariant::Double: ret.value = pv.toDouble(); break; + case QVariant::Color: ret.value = QColor(pv); break; + default: ret.value = pv; break; }; #else switch (ret.value.metaType().id()) { - case QMetaType::Bool: pv = pv.toLower(); ret.value = (pv == "on" || pv == "true" || pv == "enable" || pv == "enabled" || pv.toInt() > 0 ? true : false); break; - case QMetaType::Int: ret.value = pv.toInt(); break; - case QMetaType::UInt: ret.value = pv.toUInt(); break; - case QMetaType::LongLong: ret.value = pv.toLongLong(); break; - case QMetaType::ULongLong: ret.value = pv.toULongLong(); break; - case QMetaType::Double: ret.value = pv.toDouble(); break; - case QMetaType::QColor: ret.value = QColor(pv); break; - default: ret.value = pv; break; + case QMetaType::Bool: + pv = pv.toLower(); + ret.value = (pv == "on" || pv == "true" || pv == "enable" || pv == "enabled" || pv.toInt() > 0 ? true : false); + break; + case QMetaType::Int: ret.value = pv.toInt(); break; + case QMetaType::UInt: ret.value = pv.toUInt(); break; + case QMetaType::LongLong: ret.value = pv.toLongLong(); break; + case QMetaType::ULongLong: ret.value = pv.toULongLong(); break; + case QMetaType::Double: ret.value = pv.toDouble(); break; + case QMetaType::QColor: ret.value = QColor(pv); break; + default: ret.value = pv; break; }; #endif } @@ -180,8 +182,7 @@ PropertyStorage::Property PropertyStorage::parsePropertyLine(QString l) { PropertyStorage::Property & PropertyStorage::operator[](const QString & name) { for (int i = 0; i < props.size(); ++i) - if (props[i].name == name) - return props[i]; + if (props[i].name == name) return props[i]; addProperty(name, ""); return props.back(); } @@ -189,7 +190,6 @@ PropertyStorage::Property & PropertyStorage::operator[](const QString & name) { const PropertyStorage::Property PropertyStorage::operator[](const QString & name) const { for (int i = 0; i < props.size(); ++i) - if (props[i].name == name) - return props[i]; + if (props[i].name == name) return props[i]; return Property(); } diff --git a/libs/utils/propertystorage.h b/libs/utils/propertystorage.h index 86c8f82..691b79c 100644 --- a/libs/utils/propertystorage.h +++ b/libs/utils/propertystorage.h @@ -1,92 +1,98 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef PROPERTYSTORAGE_H #define PROPERTYSTORAGE_H +#include "chunkstream.h" + +#include +#include #include #include -#include -#include #include -#include -#include "chunkstream.h" +#include class QAD_UTILS_EXPORT PropertyStorage { public: PropertyStorage() {} - + struct QAD_UTILS_EXPORT Property { - Property(const QString & n = QString(), const QString & c = QString(), const QVariant & v = QVariant(), int f = 0): - name(n), comment(c), value(v), flags(f) {} - bool toBool() const {return value.toBool();} - int toInt() const {return value.toInt();} - float toFloat() const {return value.toFloat();} - double toDouble() const {return value.toDouble();} - QString toString() const {return value.toString();} + Property(const QString & n = QString(), const QString & c = QString(), const QVariant & v = QVariant(), int f = 0) + : name(n) + , comment(c) + , value(v) + , flags(f) {} + bool toBool() const { return value.toBool(); } + int toInt() const { return value.toInt(); } + float toFloat() const { return value.toFloat(); } + double toDouble() const { return value.toDouble(); } + QString toString() const { return value.toString(); } QString name; QString comment; QVariant value; int flags; }; - - PropertyStorage(const QList & pl) {props = pl;} + + PropertyStorage(const QList & pl) { props = pl; } PropertyStorage(const QVariantMap & pl); - + typedef QList::const_iterator const_iterator; typedef QList::iterator iterator; - - iterator begin() {return props.begin();} - const_iterator begin() const {return props.begin();} - iterator end() {return props.end();} - const_iterator end() const {return props.end();} - - int count() const {return props.count();} - int length() const {return props.length();} - int size() const {return props.size();} - bool isEmpty() const {return props.isEmpty();} - Property & first() {return props.first();} - const Property & first() const {return props.first();} - Property & front() {return props.front();} - const Property & front() const {return props.front();} - Property & last() {return props.last();} - const Property & last() const {return props.last();} - Property & back() {return props.back();} - const Property & back() const {return props.back();} - void removeFirst() {props.removeFirst();} - void removeLast() {props.removeLast();} - void removeAt(int i) {props.removeAt(i);} - Property value(int i) const {return props.value(i);} - Property value(int i, const Property & defaultValue) const {return props.value(i, defaultValue);} - void clear() {props.clear();} - - PropertyStorage copy() const {return PropertyStorage(*this);} - int propertiesCount() const {return props.size();} - QList & properties() {return props;} - const QList & properties() const {return props;} - const PropertyStorage & propertyStorage() const {return *this;} + + iterator begin() { return props.begin(); } + const_iterator begin() const { return props.begin(); } + iterator end() { return props.end(); } + const_iterator end() const { return props.end(); } + + int count() const { return props.count(); } + int length() const { return props.length(); } + int size() const { return props.size(); } + bool isEmpty() const { return props.isEmpty(); } + Property & first() { return props.first(); } + const Property & first() const { return props.first(); } + Property & front() { return props.front(); } + const Property & front() const { return props.front(); } + Property & last() { return props.last(); } + const Property & last() const { return props.last(); } + Property & back() { return props.back(); } + const Property & back() const { return props.back(); } + void removeFirst() { props.removeFirst(); } + void removeLast() { props.removeLast(); } + void removeAt(int i) { props.removeAt(i); } + Property value(int i) const { return props.value(i); } + Property value(int i, const Property & defaultValue) const { return props.value(i, defaultValue); } + void clear() { props.clear(); } + + PropertyStorage copy() const { return PropertyStorage(*this); } + int propertiesCount() const { return props.size(); } + QList & properties() { return props; } + const QList & properties() const { return props; } + const PropertyStorage & propertyStorage() const { return *this; } QVariantMap toVariantMap() const; bool isPropertyExists(const QString & _name) const; - void clearProperties() {props.clear();} + void clearProperties() { props.clear(); } void addProperty(const Property & p); - void addProperty(const QString & _name, const QVariant & _def_value, const QString & _comment = QString(), int _flags = 0) {addProperty(Property(_name, _comment, _def_value, _flags));} + void addProperty(const QString & _name, const QVariant & _def_value, const QString & _comment = QString(), int _flags = 0) { + addProperty(Property(_name, _comment, _def_value, _flags)); + } void removeProperty(const QString & _name); void removePropertiesByFlag(int flag); void updateProperties(const QList & properties_, int flag_ignore = 0); @@ -95,31 +101,42 @@ public: void setPropertyValue(const QString & name, const QVariant & value); void setPropertyComment(const QString & name, const QString & comment); void setPropertyFlags(const QString & name, int flags); - - PropertyStorage & operator <<(const PropertyStorage::Property & p) {props << p; return *this;} - PropertyStorage & operator <<(const QList & p) {props << p; return *this;} - PropertyStorage & operator <<(const PropertyStorage & p) {props << p.props; return *this;} - Property & operator[](int i) {return props[i];} - const Property & operator[](int i) const {return props[i];} + + PropertyStorage & operator<<(const PropertyStorage::Property & p) { + props << p; + return *this; + } + PropertyStorage & operator<<(const QList & p) { + props << p; + return *this; + } + PropertyStorage & operator<<(const PropertyStorage & p) { + props << p.props; + return *this; + } + Property & operator[](int i) { return props[i]; } + const Property & operator[](int i) const { return props[i]; } Property & operator[](const QString & name); const Property operator[](const QString & name) const; static Property parsePropertyLine(QString l); - + protected: QList props; - }; -inline QDebug operator <<(QDebug s, const PropertyStorage::Property & p) {s.nospace() << p.name << " (0x" << QString::number(p.flags, 16) << ") = " << p.value; return s.space();} +inline QDebug operator<<(QDebug s, const PropertyStorage::Property & p) { + s.nospace() << p.name << " (0x" << QString::number(p.flags, 16) << ") = " << p.value; + return s.space(); +} -inline QDataStream & operator <<(QDataStream & s, const PropertyStorage::Property & p) { +inline QDataStream & operator<<(QDataStream & s, const PropertyStorage::Property & p) { ChunkStream cs; cs << cs.chunk(1, p.name) << cs.chunk(2, p.comment) << cs.chunk(3, p.value) << cs.chunk(4, p.flags); s << cs.data(); return s; } -inline QDataStream & operator >>(QDataStream & s, PropertyStorage::Property & p) { +inline QDataStream & operator>>(QDataStream & s, PropertyStorage::Property & p) { ChunkStream cs(s); while (!cs.atEnd()) { switch (cs.read()) { @@ -132,8 +149,14 @@ inline QDataStream & operator >>(QDataStream & s, PropertyStorage::Property & p) return s; } -inline QDataStream & operator <<(QDataStream & s, const PropertyStorage & p) {s << p.properties(); return s;} -inline QDataStream & operator >>(QDataStream & s, PropertyStorage & p) {s >> p.properties(); return s;} +inline QDataStream & operator<<(QDataStream & s, const PropertyStorage & p) { + s << p.properties(); + return s; +} +inline QDataStream & operator>>(QDataStream & s, PropertyStorage & p) { + s >> p.properties(); + return s; +} #endif // PROPERTYSTORAGE_H diff --git a/libs/utils/qad_locations.cpp b/libs/utils/qad_locations.cpp index a65eb81..b77d67a 100644 --- a/libs/utils/qad_locations.cpp +++ b/libs/utils/qad_locations.cpp @@ -1,9 +1,10 @@ #include "qad_locations.h" + +#include +#include #include #include #include -#include -#include #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) # include #else @@ -17,10 +18,11 @@ class __QADTranslators__ { public: - static QList & translators() { - static QList ret; + static QList & translators() { + static QList ret; return ret; } + private: }; @@ -29,25 +31,24 @@ QString QAD::userPath(QAD::LocationType loc, QString name) { QString dir, ext; switch (loc) { case ltConfig: ext = ".conf"; break; - case ltCache : ext = ".cache"; break; + case ltCache: ext = ".cache"; break; } #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QStandardPaths::StandardLocation l = QStandardPaths::AppConfigLocation; switch (loc) { case ltConfig: l = QStandardPaths::AppConfigLocation; break; - case ltCache : l = QStandardPaths::CacheLocation; break; + case ltCache: l = QStandardPaths::CacheLocation; break; } dir = QStandardPaths::writableLocation(l); #else QDesktopServices::StandardLocation l = QDesktopServices::DataLocation; switch (loc) { case ltConfig: l = QDesktopServices::DataLocation; break; - case ltCache : l = QDesktopServices::CacheLocation; break; + case ltCache: l = QDesktopServices::CacheLocation; break; } dir = QDesktopServices::storageLocation(l); #endif - if (!QDir(dir).exists()) - QDir().mkpath(dir); + if (!QDir(dir).exists()) QDir().mkpath(dir); return dir + "/" + name + ext; } @@ -70,22 +71,20 @@ QStringList QAD::resourcePaths(QString type) { void QAD::loadTranslations(QString lang) { unloadTranslations(); - if (lang.isEmpty()) - lang = QLocale().bcp47Name(); + if (lang.isEmpty()) lang = QLocale().bcp47Name(); QString short_lang = lang.left(2); - QStringList dirs = resourcePaths("lang"); + QStringList dirs = resourcePaths("lang"); for (const QString & d: dirs) { QDirIterator dit(d); while (dit.hasNext()) { dit.next(); if (!dit.filePath().endsWith(".qm")) continue; - if (!dit.fileInfo().baseName().endsWith(lang) && - !dit.fileInfo().baseName().endsWith(short_lang)) continue; + if (!dit.fileInfo().baseName().endsWith(lang) && !dit.fileInfo().baseName().endsWith(short_lang)) continue; QTranslator * tr = new QTranslator(); if (tr->load(dit.filePath())) { qApp->installTranslator(tr); __QADTranslators__::translators() << tr; - //qDebug() << "Add tr" << dit.fileName(); + // qDebug() << "Add tr" << dit.fileName(); } else { qDebug() << "Can`t load translation" << dit.fileName(); delete tr; @@ -96,14 +95,13 @@ void QAD::loadTranslations(QString lang) { void QAD::unloadTranslations() { - //qDebug() << "removeTranslator ..."; + // qDebug() << "removeTranslator ..."; for (QTranslator * t: __QADTranslators__::translators()) { qApp->removeTranslator(t); delete t; } __QADTranslators__::translators().clear(); - //qDebug() << "removeTranslator done"; - + // qDebug() << "removeTranslator done"; } @@ -129,8 +127,7 @@ QStringList QAD::availableTranslations() { } for (int i = 0; i < 2; ++i) { QLocale loc(lang[i]); - if (loc.language() != QLocale::C) - ret << lang[i]; + if (loc.language() != QLocale::C) ret << lang[i]; } } delete tr; diff --git a/libs/utils/qad_locations.h b/libs/utils/qad_locations.h index 1390be0..8ff22eb 100644 --- a/libs/utils/qad_locations.h +++ b/libs/utils/qad_locations.h @@ -1,60 +1,61 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QAD_LOCATIONS_H #define QAD_LOCATIONS_H -#include #include "qad_utils_export.h" +#include + namespace QAD { - enum LocationType { - ltConfig, - ltCache, - }; +enum LocationType { + ltConfig, + ltCache, +}; - //! Create QStandardPaths::writableLocation() directory - //! and returns file name ".". - //! Extension is selected by "loc": - //! * ltConfig - "conf" - //! * ltCache - "cache" - QAD_UTILS_EXPORT QString userPath(LocationType loc, QString name = QString()); +//! Create QStandardPaths::writableLocation() directory +//! and returns file name ".". +//! Extension is selected by "loc": +//! * ltConfig - "conf" +//! * ltCache - "cache" +QAD_UTILS_EXPORT QString userPath(LocationType loc, QString name = QString()); - //! Returns search directories for resource "type" - //! * / presents on all platforms - //! * :/ on mobile platforms - //! * <.app>/Resources/ on MacOS - //! * /usr/share/[organizationName/]/ on Linux - QAD_UTILS_EXPORT QStringList resourcePaths(QString type); +//! Returns search directories for resource "type" +//! * / presents on all platforms +//! * :/ on mobile platforms +//! * <.app>/Resources/ on MacOS +//! * /usr/share/[organizationName/]/ on Linux +QAD_UTILS_EXPORT QStringList resourcePaths(QString type); - QAD_UTILS_EXPORT void loadTranslations(QString lang = QString()); - QAD_UTILS_EXPORT void unloadTranslations(); +QAD_UTILS_EXPORT void loadTranslations(QString lang = QString()); +QAD_UTILS_EXPORT void unloadTranslations(); - QAD_UTILS_EXPORT QStringList availableTranslations(); - - -} +QAD_UTILS_EXPORT QStringList availableTranslations(); + + +} // namespace QAD #endif // QAD_LOCATIONS_H diff --git a/libs/utils/qad_types.cpp b/libs/utils/qad_types.cpp index fc446c3..f9fde7e 100644 --- a/libs/utils/qad_types.cpp +++ b/libs/utils/qad_types.cpp @@ -1,11 +1,12 @@ #include "qad_types.h" + #include #include #include #include #if QT_VERSION >= 0x050000 -# include # include +# include #endif @@ -16,7 +17,7 @@ __QADTypesRegistrator__::__QADTypesRegistrator__(int) { instance()->_inited = true; } -__QADTypesRegistrator__ *__QADTypesRegistrator__::instance() { +__QADTypesRegistrator__ * __QADTypesRegistrator__::instance() { static __QADTypesRegistrator__ ret; return &ret; } @@ -65,7 +66,7 @@ QAD::Enum::Enum(const QMetaEnum & meta, int selected) { int QAD::Enum::selectedValue() const { - for (const Enumerator & e : enum_list) { + for (const Enumerator & e: enum_list) { if (e.name == selected) return e.value; } return 0; @@ -73,7 +74,7 @@ int QAD::Enum::selectedValue() const { bool QAD::Enum::selectValue(int v) { - for (const Enumerator & e : enum_list) { + for (const Enumerator & e: enum_list) { if (e.value == v) { selected = e.name; return true; @@ -84,7 +85,7 @@ bool QAD::Enum::selectValue(int v) { bool QAD::Enum::selectName(const QString & n) { - for (const Enumerator & e : enum_list) { + for (const Enumerator & e: enum_list) { if (e.name == n) { selected = e.name; return true; @@ -95,7 +96,7 @@ bool QAD::Enum::selectName(const QString & n) { int QAD::Enum::value(const QString & n) const { - for (const Enumerator & e : enum_list) { + for (const Enumerator & e: enum_list) { if (e.name == n) return e.value; } return 0; @@ -103,7 +104,7 @@ int QAD::Enum::value(const QString & n) const { QString QAD::Enum::name(int v) const { - for (const Enumerator & e : enum_list) { + for (const Enumerator & e: enum_list) { if (e.value == v) return e.name; } return QString(); @@ -112,38 +113,39 @@ QString QAD::Enum::name(int v) const { QList QAD::Enum::values() const { QList ret; - for (const Enumerator & e : enum_list) ret << e.value; + for (const Enumerator & e: enum_list) + ret << e.value; return ret; } QStringList QAD::Enum::names() const { QStringList ret; - for (const Enumerator & e : enum_list) ret << e.name; + for (const Enumerator & e: enum_list) + ret << e.name; return ret; } -QAD::Enum & QAD::Enum::operator <<(const QAD::Enumerator & v) { +QAD::Enum & QAD::Enum::operator<<(const QAD::Enumerator & v) { enum_list << v; return *this; } -QAD::Enum & QAD::Enum::operator <<(const QString & v) { +QAD::Enum & QAD::Enum::operator<<(const QString & v) { enum_list << Enumerator(enum_list.size(), v); return *this; } -QAD::Enum & QAD::Enum::operator <<(const QStringList & v) { - for (const QString & s : v) (*this) << s; +QAD::Enum & QAD::Enum::operator<<(const QStringList & v) { + for (const QString & s: v) + (*this) << s; return *this; } - - QString QAD::IODevice::toString() const { QString s; if (__QADTypesRegistrator__::instance()->toString_funcs.contains(qMetaTypeId())) { @@ -155,14 +157,12 @@ QString QAD::IODevice::toString() const { } - - #if QT_VERSION_MAJOR <= 5 QVariant::Type #else QMetaType #endif - typeFromLetter(const QString & l) { +typeFromLetter(const QString & l) { #if QT_VERSION_MAJOR <= 5 if (l.isEmpty()) return QVariant::String; QString ft = l.left(1); @@ -185,19 +185,19 @@ QMetaType #else if (l.isEmpty()) return QMetaType::fromType(); QString ft = l.left(1); - if (ft == "l") return QMetaType::fromType(); - if (ft == "b") return QMetaType::fromType(); - if (ft == "n") return QMetaType::fromType(); - if (ft == "f") return QMetaType::fromType(); - if (ft == "c") return QMetaType::fromType(); - if (ft == "r") return QMetaType::fromType(); - if (ft == "a") return QMetaType::fromType(); - if (ft == "p") return QMetaType::fromType(); - if (ft == "v") return QMetaType::fromType(); - if (ft == "e") return QMetaType::fromType(); - if (ft == "F") return QMetaType::fromType(); - if (ft == "D") return QMetaType::fromType(); - if (ft == "d") return QMetaType::fromType(); + if (ft == "l") return QMetaType::fromType(); + if (ft == "b") return QMetaType::fromType(); + if (ft == "n") return QMetaType::fromType(); + if (ft == "f") return QMetaType::fromType(); + if (ft == "c") return QMetaType::fromType(); + if (ft == "r") return QMetaType::fromType(); + if (ft == "a") return QMetaType::fromType(); + if (ft == "p") return QMetaType::fromType(); + if (ft == "v") return QMetaType::fromType(); + if (ft == "e") return QMetaType::fromType(); + if (ft == "F") return QMetaType::fromType(); + if (ft == "D") return QMetaType::fromType(); + if (ft == "d") return QMetaType::fromType(); if (ft == "V") return QMetaType::fromType(); if (ft == "M") return QMetaType::fromType(); return QMetaType::fromType(); @@ -212,10 +212,11 @@ QString uniqueName(QString n, const QStringList & names) { if (n.right(1)[0].isDigit()) { num.push_front(n.right(1)); n.chop(1); - } else break; + } else + break; } if (!n.endsWith('_') && num.isEmpty()) n += '_'; - int in = num.toInt() + 1; + int in = num.toInt() + 1; QString nn = n + QString::number(in); while (names.contains(nn)) nn = n + QString::number(++in); @@ -233,7 +234,7 @@ int fontHeight(const QWidget * window) { # else double add_scale = 1.0; # endif - //qDebug() << "fontHeight" << w; + // qDebug() << "fontHeight" << w; if (window) { QWidget * pw = window->window(); if (pw) return QFontMetrics(pw->font()).height() * add_scale; diff --git a/libs/utils/qad_types.h b/libs/utils/qad_types.h index 1534231..412a0b0 100644 --- a/libs/utils/qad_types.h +++ b/libs/utils/qad_types.h @@ -1,33 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QAD_TYPES_H #define QAD_TYPES_H -#include #include "propertystorage.h" #include "qad_utils_export.h" +#include + //! Set QCoreApplication properties from CMake "deploy_properties" //! Affect applicationName, organizationName and applicationVersion -#define QAD_SETUP_APPLICATION \ - QCoreApplication::setApplicationName(__TARGET_NAME__); \ +#define QAD_SETUP_APPLICATION \ + QCoreApplication::setApplicationName(__TARGET_NAME__); \ QCoreApplication::setOrganizationName(__TARGET_COMPANY__); \ QCoreApplication::setApplicationVersion(__TARGET_VERSION__); @@ -35,7 +36,7 @@ # define QT_MID_BUTTON Qt::MidButton # include template -using QMultiMapIterator = QMapIterator; +using QMultiMapIterator = QMapIterator; #else # define QT_MID_BUTTON Qt::MiddleButton #endif @@ -46,133 +47,211 @@ class QMetaEnum; namespace QAD { - struct QAD_UTILS_EXPORT Enumerator { - Enumerator(int v = 0, const QString & n = QString()): value(v), name(n) {} - int value; - QString name; - }; +struct QAD_UTILS_EXPORT Enumerator { + Enumerator(int v = 0, const QString & n = QString()): value(v), name(n) {} + int value; + QString name; +}; - struct QAD_UTILS_EXPORT Enum { - Enum(const QString & n = QString()): enum_name(n) {} - Enum(const QMetaEnum & meta, int selected = 0); - int selectedValue() const; - QString selectedName() const {return selected;} - bool selectValue(int v); - bool selectName(const QString & n); - int value(const QString & n) const; - QString name(int v) const; - QList values() const; - QStringList names() const; - int size() const {return enum_list.size();} - QString enum_name; - QString selected; - QList enum_list; - Enum & operator <<(const Enumerator & v); - Enum & operator <<(const QString & v); - Enum & operator <<(const QStringList & v); - }; +struct QAD_UTILS_EXPORT Enum { + Enum(const QString & n = QString()): enum_name(n) {} + Enum(const QMetaEnum & meta, int selected = 0); + int selectedValue() const; + QString selectedName() const { return selected; } + bool selectValue(int v); + bool selectName(const QString & n); + int value(const QString & n) const; + QString name(int v) const; + QList values() const; + QStringList names() const; + int size() const { return enum_list.size(); } + QString enum_name; + QString selected; + QList enum_list; + Enum & operator<<(const Enumerator & v); + Enum & operator<<(const QString & v); + Enum & operator<<(const QStringList & v); +}; - struct QAD_UTILS_EXPORT File { - File(const QString & p = QString(), const QString & f = QString(), bool abs = false, bool save_mode = false): - file(p), filter(f), is_abs(abs), is_save(save_mode) {} - QString toString() const {return file;} - QString file; - QString filter; - bool is_abs; - bool is_save; - }; +struct QAD_UTILS_EXPORT File { + File(const QString & p = QString(), const QString & f = QString(), bool abs = false, bool save_mode = false) + : file(p) + , filter(f) + , is_abs(abs) + , is_save(save_mode) {} + QString toString() const { return file; } + QString file; + QString filter; + bool is_abs; + bool is_save; +}; - struct QAD_UTILS_EXPORT Dir { - Dir(const QString & d = QString(), bool abs = false): - dir(d), is_abs(abs) {} - QString toString() const {return dir;} - QString dir; - bool is_abs; - }; +struct QAD_UTILS_EXPORT Dir { + Dir(const QString & d = QString(), bool abs = false): dir(d), is_abs(abs) {} + QString toString() const { return dir; } + QString dir; + bool is_abs; +}; - struct QAD_UTILS_EXPORT IODevice { - IODevice(const QString & device_prefix = QString(), const PropertyStorage & device_properties = PropertyStorage(), - int open_mode = QIODevice::ReadWrite, int device_options = 0) - : prefix(device_prefix), mode(open_mode), options(device_options), props(device_properties) {} - QString toString() const; - bool isValid() const {return !prefix.isEmpty();} - QString prefix; - int mode; - int options; - PropertyStorage props; - }; +struct QAD_UTILS_EXPORT IODevice { + IODevice(const QString & device_prefix = QString(), + const PropertyStorage & device_properties = PropertyStorage(), + int open_mode = QIODevice::ReadWrite, + int device_options = 0) + : prefix(device_prefix) + , mode(open_mode) + , options(device_options) + , props(device_properties) {} + QString toString() const; + bool isValid() const { return !prefix.isEmpty(); } + QString prefix; + int mode; + int options; + PropertyStorage props; +}; - struct QAD_UTILS_EXPORT MathVector { - MathVector(const QVector & vec = QVector()) {v = vec;} - QVector v; - }; +struct QAD_UTILS_EXPORT MathVector { + MathVector(const QVector & vec = QVector()) { v = vec; } + QVector v; +}; - struct QAD_UTILS_EXPORT MathMatrix { - MathMatrix(const QVector > & mat = QVector > ()) {m = mat;} - QVector > m; // [Row][Column] - }; +struct QAD_UTILS_EXPORT MathMatrix { + MathMatrix(const QVector> & mat = QVector>()) { m = mat; } + QVector> m; // [Row][Column] +}; - class QAD_UTILS_EXPORT CursorOverrider { - public: - CursorOverrider(const QCursor & c = Qt::WaitCursor) {QApplication::setOverrideCursor(c);} - ~CursorOverrider() {QApplication::restoreOverrideCursor();} - }; +class QAD_UTILS_EXPORT CursorOverrider { +public: + CursorOverrider(const QCursor & c = Qt::WaitCursor) { QApplication::setOverrideCursor(c); } + ~CursorOverrider() { QApplication::restoreOverrideCursor(); } +}; -} +} // namespace QAD Q_DECLARE_METATYPE(QAD::Enumerator) -inline QDataStream & operator <<(QDataStream & s, const QAD::Enumerator & v) {s << v.value << v.name; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::Enumerator & v) {s >> v.value >> v.name; return s;} -inline QDebug operator <<(QDebug s, const QAD::Enumerator & v) {s.nospace() << v.name << "(" << v.value << ")"; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::Enumerator & v) { + s << v.value << v.name; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::Enumerator & v) { + s >> v.value >> v.name; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::Enumerator & v) { + s.nospace() << v.name << "(" << v.value << ")"; + return s.space(); +} Q_DECLARE_METATYPE(QAD::Enum) -inline QDataStream & operator <<(QDataStream & s, const QAD::Enum & v) {s << v.enum_name << v.selected << v.enum_list; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::Enum & v) {s >> v.enum_name >> v.selected >> v.enum_list; return s;} -inline QDebug operator <<(QDebug s, const QAD::Enum & v) {s.nospace() << v.selected; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::Enum & v) { + s << v.enum_name << v.selected << v.enum_list; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::Enum & v) { + s >> v.enum_name >> v.selected >> v.enum_list; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::Enum & v) { + s.nospace() << v.selected; + return s.space(); +} Q_DECLARE_METATYPE(QAD::File) -inline QDataStream & operator <<(QDataStream & s, const QAD::File & v) {s << v.file << v.filter << uchar((v.is_abs ? 1 : 0) + (v.is_save ? 2 : 0)); return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::File & v) {uchar f(0); s >> v.file >> v.filter >> f; v.is_abs = ((f & 1) == 1); v.is_save = ((f & 2) == 2); return s;} -inline QDebug operator <<(QDebug s, const QAD::File & v) {s.nospace() << v.file; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::File & v) { + s << v.file << v.filter << uchar((v.is_abs ? 1 : 0) + (v.is_save ? 2 : 0)); + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::File & v) { + uchar f(0); + s >> v.file >> v.filter >> f; + v.is_abs = ((f & 1) == 1); + v.is_save = ((f & 2) == 2); + return s; +} +inline QDebug operator<<(QDebug s, const QAD::File & v) { + s.nospace() << v.file; + return s.space(); +} Q_DECLARE_METATYPE(QAD::Dir) -inline QDataStream & operator <<(QDataStream & s, const QAD::Dir & v) {s << v.dir << v.is_abs; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::Dir & v) {s >> v.dir >> v.is_abs; return s;} -inline QDebug operator <<(QDebug s, const QAD::Dir & v) {s.nospace() << v.dir; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::Dir & v) { + s << v.dir << v.is_abs; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::Dir & v) { + s >> v.dir >> v.is_abs; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::Dir & v) { + s.nospace() << v.dir; + return s.space(); +} Q_DECLARE_METATYPE(QAD::IODevice) -inline QDataStream & operator <<(QDataStream & s, const QAD::IODevice & v) {s << v.prefix << v.mode << v.options << v.props; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::IODevice & v) {s >> v.prefix >> v.mode >> v.options >> v.props; return s;} -inline QDebug operator <<(QDebug s, const QAD::IODevice & v) {s.nospace() << v.toString(); return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::IODevice & v) { + s << v.prefix << v.mode << v.options << v.props; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::IODevice & v) { + s >> v.prefix >> v.mode >> v.options >> v.props; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::IODevice & v) { + s.nospace() << v.toString(); + return s.space(); +} Q_DECLARE_METATYPE(QAD::MathVector) -inline QDataStream & operator <<(QDataStream & s, const QAD::MathVector & v) {s << v.v; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::MathVector & v) {s >> v.v; return s;} -inline QDebug operator <<(QDebug s, const QAD::MathVector & v) {s.nospace() << "Vector " << v.v; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::MathVector & v) { + s << v.v; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::MathVector & v) { + s >> v.v; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::MathVector & v) { + s.nospace() << "Vector " << v.v; + return s.space(); +} Q_DECLARE_METATYPE(QAD::MathMatrix) -inline QDataStream & operator <<(QDataStream & s, const QAD::MathMatrix & v) {s << v.m; return s;} -inline QDataStream & operator >>(QDataStream & s, QAD::MathMatrix & v) {s >> v.m; return s;} -inline QDebug operator <<(QDebug s, const QAD::MathMatrix & v) {s.nospace() << "Matrix " << v.m; return s.space();} +inline QDataStream & operator<<(QDataStream & s, const QAD::MathMatrix & v) { + s << v.m; + return s; +} +inline QDataStream & operator>>(QDataStream & s, QAD::MathMatrix & v) { + s >> v.m; + return s; +} +inline QDebug operator<<(QDebug s, const QAD::MathMatrix & v) { + s.nospace() << "Matrix " << v.m; + return s.space(); +} class QAD_UTILS_EXPORT __QADTypesRegistrator__ { public: __QADTypesRegistrator__(int); static __QADTypesRegistrator__ * instance(); - QMap toString_funcs; + QMap toString_funcs; + private: __QADTypesRegistrator__(); static bool _inited; }; -inline qreal quantize(qreal x, qreal q = 10.f) {return qRound(x / q) * q;} -inline QPointF quantize(QPointF x, qreal q = 10.f) {return QPointF(quantize(x.x(), q), quantize(x.y(), q));} +inline qreal quantize(qreal x, qreal q = 10.f) { + return qRound(x / q) * q; +} +inline QPointF quantize(QPointF x, qreal q = 10.f) { + return QPointF(quantize(x.x(), q), quantize(x.y(), q)); +} inline qreal distPointToLine(const QPointF & lp0, const QPointF & lp1, const QPointF & p) { QLineF a(lp0, lp1), b(lp0, p), c(lp1, p); - qreal f = qAbs(a.dx()*b.dy() - a.dy()*b.dx()) / a.length(), s = b.length() + c.length() - a.length(); + qreal f = qAbs(a.dx() * b.dy() - a.dy() * b.dx()) / a.length(), s = b.length() + c.length() - a.length(); return qMax(f, s); } inline QPointF nearestPointOnLine(const QPointF & lp0, const QPointF & lp1, const QPointF & p) { @@ -180,10 +259,11 @@ inline QPointF nearestPointOnLine(const QPointF & lp0, const QPointF & lp1, cons return a.pointAt(b.length() / a.length()); } inline QRectF enlargedRect(const QRectF & r, qreal dx, qreal dy, qreal v) { - return QRectF(r.left() - v + dx, r.top() - v + dy, r.width() + v+v, r.height() + v+v); + return QRectF(r.left() - v + dx, r.top() - v + dy, r.width() + v + v, r.height() + v + v); } -template QSet QList2QSet(const QList & l) { +template +QSet QList2QSet(const QList & l) { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) return QSet(l.begin(), l.end()); #else @@ -191,17 +271,16 @@ template QSet QList2QSet(const QList & l) { #endif } -template +template void addToMap(QMap & into, const QMap & what) { QMapIterator it(what); while (it.hasNext()) { it.next(); - if (!into.contains(it.key())) - into[it.key()] = it.value(); + if (!into.contains(it.key())) into[it.key()] = it.value(); } } -template +template void addToMapOverwrite(QMap & into, const QMap & what) { QMapIterator it(what); while (it.hasNext()) { @@ -212,11 +291,11 @@ void addToMapOverwrite(QMap & into, const QMap & what) { QAD_UTILS_EXPORT #if QT_VERSION_MAJOR <= 5 - QVariant::Type +QVariant::Type #else - QMetaType +QMetaType #endif - typeFromLetter(const QString & l); +typeFromLetter(const QString & l); QAD_UTILS_EXPORT QString uniqueName(QString n, const QStringList & names); QAD_UTILS_EXPORT int fontHeight(const QWidget * window = nullptr); diff --git a/libs/utils/qpiconfig.cpp b/libs/utils/qpiconfig.cpp index 7b3a289..2e24df4 100644 --- a/libs/utils/qpiconfig.cpp +++ b/libs/utils/qpiconfig.cpp @@ -1,6 +1,7 @@ #include "qpiconfig.h" -#include + #include +#include int QString2int(const QString & string) { @@ -14,17 +15,17 @@ int QString2int(const QString & string) { QRect QString2QRect(const QString & string) { int sl, st, sw, sh; int s = 0, e; - e = string.indexOf(";"); - sl = string.mid(s, e - s).toInt(); - s = e + 1; - e = string.indexOf(";", s); - st = string.mid(s, e - s).toInt(); - s = e + 1; - e = string.indexOf(";", s); - sw = string.mid(s, e - s).toInt(); - s = e + 1; - e = string.length(); - sh = string.mid(s, e - s).toInt(); + e = string.indexOf(";"); + sl = string.mid(s, e - s).toInt(); + s = e + 1; + e = string.indexOf(";", s); + st = string.mid(s, e - s).toInt(); + s = e + 1; + e = string.indexOf(";", s); + sw = string.mid(s, e - s).toInt(); + s = e + 1; + e = string.length(); + sh = string.mid(s, e - s).toInt(); return QRect(sl, st, sw, sh); } @@ -32,17 +33,17 @@ QRect QString2QRect(const QString & string) { QRectF QString2QRectF(const QString & string) { double sl, st, sw, sh; int s = 0, e; - e = string.indexOf(";"); - sl = string.mid(s, e - s).toDouble(); - s = e + 1; - e = string.indexOf(";", s); - st = string.mid(s, e - s).toDouble(); - s = e + 1; - e = string.indexOf(";", s); - sw = string.mid(s, e - s).toDouble(); - s = e + 1; - e = string.length(); - sh = string.mid(s, e - s).toDouble(); + e = string.indexOf(";"); + sl = string.mid(s, e - s).toDouble(); + s = e + 1; + e = string.indexOf(";", s); + st = string.mid(s, e - s).toDouble(); + s = e + 1; + e = string.indexOf(";", s); + sw = string.mid(s, e - s).toDouble(); + s = e + 1; + e = string.length(); + sh = string.mid(s, e - s).toDouble(); return QRectF(sl, st, sw, sh); } @@ -50,11 +51,11 @@ QRectF QString2QRectF(const QString & string) { QPoint QString2QPoint(const QString & string) { int sx, sy; int s = 0, e; - e = string.indexOf(";"); - sx = string.mid(s, e - s).toInt(); - s = e + 1; - e = string.length(); - sy = string.mid(s, e - s).toInt(); + e = string.indexOf(";"); + sx = string.mid(s, e - s).toInt(); + s = e + 1; + e = string.length(); + sy = string.mid(s, e - s).toInt(); return QPoint(sx, sy); } @@ -62,28 +63,24 @@ QPoint QString2QPoint(const QString & string) { QPointF QString2QPointF(const QString & string) { double sx, sy; int s = 0, e; - e = string.indexOf(";"); - sx = string.mid(s, e - s).toDouble(); - s = e + 1; - e = string.length(); - sy = string.mid(s, e - s).toDouble(); + e = string.indexOf(";"); + sx = string.mid(s, e - s).toDouble(); + s = e + 1; + e = string.length(); + sy = string.mid(s, e - s).toDouble(); return QPointF(sx, sy); } QString QRect2QString(const QRect & rect) { - return QString::number(rect.left()) + ";" + - QString::number(rect.top()) + ";" + - QString::number(rect.width()) + ";" + - QString::number(rect.height()); + return QString::number(rect.left()) + ";" + QString::number(rect.top()) + ";" + QString::number(rect.width()) + ";" + + QString::number(rect.height()); } QString QRectF2QString(const QRectF & rect) { - return QString::number(rect.left()) + ";" + - QString::number(rect.top()) + ";" + - QString::number(rect.width()) + ";" + - QString::number(rect.height()); + return QString::number(rect.left()) + ";" + QString::number(rect.top()) + ";" + QString::number(rect.width()) + ";" + + QString::number(rect.height()); } @@ -94,9 +91,11 @@ QPIConfig::Entry QPIConfig::Entry::_empty; QPIConfig::Branch QPIConfig::Branch::allLeaves() { Branch b; b.delim = delim; - foreach (Entry * i, *this) { - if (i->isLeaf()) b << i; - else allLeaves(b, i); + foreach(Entry * i, *this) { + if (i->isLeaf()) + b << i; + else + allLeaves(b, i); } return b; } @@ -110,27 +109,27 @@ QPIConfig::Entry & QPIConfig::Branch::getValue(const QString & vname, const QStr return _empty; } QStringList tree = vname.split(delim); - QString name = tree.front(); + QString name = tree.front(); tree.pop_front(); Entry * ce = 0; - foreach (Entry * i, *this) + foreach(Entry * i, *this) if (i->_name == name) { ce = i; break; } if (ce == 0) { - _empty._name = vname; + _empty._name = vname; _empty._value = def; - _empty.delim = delim; + _empty.delim = delim; if (exist != 0) *exist = false; return _empty; } - foreach (QString i, tree) { + foreach(QString i, tree) { ce = ce->findChild(i); if (ce == 0) { - _empty._name = vname; + _empty._name = vname; _empty._value = def; - _empty.delim = delim; + _empty.delim = delim; if (exist != 0) *exist = false; return _empty; } @@ -143,14 +142,12 @@ QPIConfig::Entry & QPIConfig::Branch::getValue(const QString & vname, const QStr QPIConfig::Branch QPIConfig::Branch::getValues(const QString & name) { Branch b; b.delim = delim; - foreach (Entry * i, *this) { + foreach(Entry * i, *this) { if (i->isLeaf()) { - if (i->_name.indexOf(name) >= 0) - b << i; + if (i->_name.indexOf(name) >= 0) b << i; } else { - foreach (Entry * j, i->_children) - if (j->_name.indexOf(name) >= 0) - b << j; + foreach(Entry * j, i->_children) + if (j->_name.indexOf(name) >= 0) b << j; } } return b; @@ -160,9 +157,8 @@ QPIConfig::Branch QPIConfig::Branch::getValues(const QString & name) { QPIConfig::Branch QPIConfig::Branch::getLeaves() { Branch b; b.delim = delim; - foreach (Entry * i, *this) - if (i->isLeaf()) - b << i; + foreach(Entry * i, *this) + if (i->isLeaf()) b << i; return b; } @@ -170,9 +166,8 @@ QPIConfig::Branch QPIConfig::Branch::getLeaves() { QPIConfig::Branch QPIConfig::Branch::getBranches() { Branch b; b.delim = delim; - foreach (Entry * i, *this) - if (!i->isLeaf()) - b << i; + foreach(Entry * i, *this) + if (!i->isLeaf()) b << i; return b; } @@ -190,10 +185,12 @@ QPIConfig::Branch & QPIConfig::Branch::filter(const QString & f) { bool QPIConfig::Branch::entryExists(const Entry * e, const QString & name) const { if (e->_children.isEmpty()) { - if (e->_name == name) return true; - else return false; + if (e->_name == name) + return true; + else + return false; } - foreach (Entry * i, e->_children) + foreach(Entry * i, e->_children) if (entryExists(i, name)) return true; return false; } @@ -201,13 +198,13 @@ bool QPIConfig::Branch::entryExists(const Entry * e, const QString & name) const QPIConfig::Entry & QPIConfig::Entry::getValue(const QString & vname, const QString & def, bool * exist) { QStringList tree = vname.split(delim); - Entry * ce = this; - foreach (QString i, tree) { + Entry * ce = this; + foreach(QString i, tree) { ce = ce->findChild(i); if (ce == 0) { - _empty._name = vname; + _empty._name = vname; _empty._value = def; - _empty.delim = delim; + _empty.delim = delim; if (exist != 0) *exist = false; return _empty; } @@ -220,19 +217,20 @@ QPIConfig::Entry & QPIConfig::Entry::getValue(const QString & vname, const QStri QPIConfig::Branch QPIConfig::Entry::getValues(const QString & vname) { Branch b; b.delim = delim; - foreach (Entry * i, _children) - if (i->_name.indexOf(vname) >= 0) - b << i; + foreach(Entry * i, _children) + if (i->_name.indexOf(vname) >= 0) b << i; return b; }; bool QPIConfig::Entry::entryExists(const Entry * e, const QString & name) const { if (e->_children.isEmpty()) { - if (e->_name == name) return true; - else return false; + if (e->_name == name) + return true; + else + return false; } - foreach (Entry * i, e->_children) + foreach(Entry * i, e->_children) if (entryExists(i, name)) return true; return false; } @@ -273,7 +271,7 @@ QPIConfig::QPIConfig(const QString & path, QPIConfig::FileType type_): QFile(pat QPIConfig::QPIConfig(QString * str, QPIConfig::FileType type_) { init(); - type = type_; + type = type_; buffer = str; parse(); } @@ -281,9 +279,9 @@ QPIConfig::QPIConfig(QString * str, QPIConfig::FileType type_) { QPIConfig::QPIConfig(const QString & path, QStringList dirs) { init(); - type = Config; + type = Config; internal = true; - dev = new QFile(path); + dev = new QFile(path); dev->open(QIODevice::ReadOnly); incdirs = dirs; incdirs << QFileInfo(path).absoluteDir().path(); @@ -313,7 +311,7 @@ QPIConfig::QPIConfig(const QString & path, QStringList dirs) { QPIConfig::~QPIConfig() { stream.setDevice(0); root.deleteBranch(); - foreach (QPIConfig * c, inc_devs) + foreach(QPIConfig * c, inc_devs) delete c; inc_devs.clear(); includes.clear(); @@ -321,13 +319,13 @@ QPIConfig::~QPIConfig() { void QPIConfig::init() { - internal = false; - buffer = 0; - dev = 0; - delim = "."; - root._name = "root"; - root.delim = delim; - empty.delim = delim; + internal = false; + buffer = 0; + dev = 0; + delim = "."; + root._name = "root"; + root.delim = delim; + empty.delim = delim; empty._parent = 0; } @@ -335,8 +333,7 @@ void QPIConfig::init() { void QPIConfig::setFile(const QString & path, QIODevice::OpenMode mode) { buffer = 0; setFileName(path); - if (open(mode)) - parse(); + if (open(mode)) parse(); } @@ -357,26 +354,27 @@ void QPIConfig::setupCodec() { #if QT_VERSION_MAJOR <= 5 stream.setCodec(codec.toLatin1().data()); #else - QString cn = codec.toLower().remove(' ').remove('-').trimmed(); + QString cn = codec.toLower().remove(' ').remove('-').trimmed(); QStringConverter::Encoding sc = QStringConverter::System; - if (cn == "utf8" ) sc = QStringConverter::Utf8 ; - else if (cn == "utf16") sc = QStringConverter::Utf16; + if (cn == "utf8") + sc = QStringConverter::Utf8; + else if (cn == "utf16") + sc = QStringConverter::Utf16; stream.setEncoding(sc); #endif - } QPIConfig::Entry & QPIConfig::getValue(const QString & vname, const QString & def, bool * exist) { QStringList tree = vname.split(delim); - Entry * ce = &root; - foreach (QString i, tree) { + Entry * ce = &root; + foreach(QString i, tree) { ce = ce->findChild(i); if (ce == 0) { if (exist != 0) *exist = false; - empty._name = vname; + empty._name = vname; empty._value = def; - empty.delim = delim; + empty.delim = delim; return empty; } } @@ -388,82 +386,85 @@ QPIConfig::Entry & QPIConfig::getValue(const QString & vname, const QString & de QPIConfig::Branch QPIConfig::getValues(const QString & vname) { Branch b; b.delim = delim; - foreach (Entry * i, root._children) - if (i->_name.indexOf(vname) >= 0) - b << i; + foreach(Entry * i, root._children) + if (i->_name.indexOf(vname) >= 0) b << i; return b; } QPIConfig::Entry & QPIConfig::addEntry(const QString & name, const QString & value, const QString & type, bool write, bool node) { - if (getValue(name)._parent != 0) - return empty; - QString sn = name, tn; + if (getValue(name)._parent != 0) return empty; + QString sn = name, tn; bool toRoot = false; - while (sn.indexOf(delim) == 0) sn.remove(0, delim.length()); + while (sn.indexOf(delim) == 0) + sn.remove(0, delim.length()); QStringList tree = sn.split(delim); - QString ename = tree.back(); - tn = tree.front(); + QString ename = tree.back(); + tn = tree.front(); tree.pop_back(); - Entry * te, * ce, * entry = &root; + Entry *te, *ce, *entry = &root; if (tree.isEmpty()) toRoot = true; - foreach (QString i, tree) { + foreach(QString i, tree) { te = entry->findChild(i); if (te == 0) { - ce = new Entry(); - ce->delim = delim; - ce->_tab = entry->_tab; - ce->_line = entry->_line; - ce->_name = i; - ce->_parent = entry; - //qDebug() << " [QPIC] add " + tn; + ce = new Entry(); + ce->delim = delim; + ce->_tab = entry->_tab; + ce->_line = entry->_line; + ce->_name = i; + ce->_parent = entry; + // qDebug() << " [QPIC] add " + tn; ce->_full_name = tn; entry->_children << ce; entry = ce; - } else entry = te; + } else + entry = te; tn += delim + i; } QPIConfig::Branch ch = entry->_children; -#if QT_VERSION < QT_VERSION_CHECK(5,13,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) qSort #else std::sort #endif - (ch.begin(), ch.end(), QPIConfig::Entry::compare); - te = (entry->isLeaf() ? 0 : ch.back()); - ce = new Entry(); + (ch.begin(), ch.end(), QPIConfig::Entry::compare); + te = (entry->isLeaf() ? 0 : ch.back()); + ce = new Entry(); ce->delim = delim; ce->_name = ename; if (!node) ce->_value = value; ce->_type = type; if (te == 0) { - //qDebug() << "[QPIC] te == 0"; + // qDebug() << "[QPIC] te == 0"; ce->_tab = entry->_tab; - if (toRoot) ce->_line = other.size(); + if (toRoot) + ce->_line = other.size(); else { ch = entry->_parent->_children; -#if QT_VERSION < QT_VERSION_CHECK(5,13,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) qSort #else std::sort #endif - (ch.begin(), ch.end(), QPIConfig::Entry::compare); + (ch.begin(), ch.end(), QPIConfig::Entry::compare); ce->_line = ch.back()->_line + 1; } } else { ce->_tab = te->_tab; - if (toRoot) ce->_line = other.size(); - else ce->_line = te->_line + 1; + if (toRoot) + ce->_line = other.size(); + else + ce->_line = te->_line + 1; } - //qDebug() << "[QPIC] add " + sn + " at line " << ce->_line << ", parent " << entry->_name; + // qDebug() << "[QPIC] add " + sn + " at line " << ce->_line << ", parent " << entry->_name; ce->_full_name = sn; - ce->_parent = entry; + ce->_parent = entry; entry->_children << ce; - //qDebug() << "[QPIC] children " << entry->childCount(); + // qDebug() << "[QPIC] children " << entry->childCount(); if (!node) { other.insert(ce->_line, ""); - Branch b = allLeaves(); - //qDebug() << "[QPIC] allLeaves " << b.size(); + Branch b = allLeaves(); + // qDebug() << "[QPIC] allLeaves " << b.size(); bool found = false; for (int i = 0; i < b.size(); ++i) { if (found) { @@ -473,13 +474,12 @@ QPIConfig::Entry & QPIConfig::addEntry(const QString & name, const QString & val if (b[i] == ce) { found = true; if (i > 0) - if (b[i - 1]->_line == b[i]->_line) - b[i - 1]->_line++; + if (b[i - 1]->_line == b[i]->_line) b[i - 1]->_line++; } - //qDebug() << b[i]->_line; + // qDebug() << b[i]->_line; } } - //qDebug() << "[QPIC] add " + sn + " at line " << ce->_line << ", parent " + entry->_name; + // qDebug() << "[QPIC] add " + sn + " at line " << ce->_line << ", parent " + entry->_name; if (write) writeAll(); return *ce; } @@ -492,7 +492,7 @@ void QPIConfig::setValue(const QString & name, const QString & value, const QStr return; } e._value = value; - e._type = type; + e._type = type; if (write) writeAll(); } @@ -500,23 +500,22 @@ void QPIConfig::setValue(const QString & name, const QString & value, const QStr QPIConfig::Branch QPIConfig::allLeaves() { Branch b; allLeaves(b, &root); -#if QT_VERSION < QT_VERSION_CHECK(5,13,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) qSort #else std::sort #endif - (b.begin(), b.end(), Entry::compare); + (b.begin(), b.end(), Entry::compare); return b; } int QPIConfig::entryIndex(const QString & name) { QStringList tree = name.split(delim); - Entry * ce = &root; - foreach (QString i, tree) { + Entry * ce = &root; + foreach(QString i, tree) { ce = ce->findChild(i); - if (ce == 0) - return -1; + if (ce == 0) return -1; } Branch b = allLeaves(); return allLeaves().indexOf(ce); @@ -575,7 +574,7 @@ void QPIConfig::removeEntry(uint number, bool write) { void QPIConfig::removeEntry(Branch & b, QPIConfig::Entry * e) { bool leaf = true; - //qDebug() << " before " << b.size(); + // qDebug() << " before " << b.size(); if (e->isLeaf()) other.removeAt(e->_line); if (!e->isLeaf() && !e->_value.isEmpty()) { e->_value.clear(); @@ -597,7 +596,7 @@ void QPIConfig::removeEntry(Branch & b, QPIConfig::Entry * e) { if (ti >= 0) e->_parent->_children.remove(ti); ti = b.indexOf(e); if (ti >= 0) b.remove(ti); - //qDebug() << " after " << b.size(); + // qDebug() << " after " << b.size(); delete e; } @@ -628,8 +627,7 @@ void QPIConfig::writeAll() { tprefix = getPrefixFromLine(other[i], &isPrefix); if (isPrefix) { prefix = tprefix; - if (!prefix.isEmpty()) - prefix += delim; + if (!prefix.isEmpty()) prefix += delim; } if (i < other.size() - 1) stream << '\n'; } @@ -638,24 +636,28 @@ void QPIConfig::writeAll() { tprefix = getPrefixFromLine(other[i], &isPrefix); if (isPrefix) { prefix = tprefix; - if (!prefix.isEmpty()) - prefix += delim; + if (!prefix.isEmpty()) prefix += delim; } if (i < other.size() - 1) stream << '\n'; } } - if (buffer == 0) - flush(); + if (buffer == 0) flush(); readAll(); } QString QPIConfig::getPrefixFromLine(QString line, bool * exists) { line = line.trimmed(); - if (line.left(1) == "#") {if (exists) *exists = false; return QString();} + if (line.left(1) == "#") { + if (exists) *exists = false; + return QString(); + } int ci = line.indexOf("#"); if (ci >= 0) line = line.left(ci).trimmed(); - if (line.indexOf("=") >= 0) {if (exists) *exists = false; return QString();} + if (line.indexOf("=") >= 0) { + if (exists) *exists = false; + return QString(); + } if (line.indexOf("[") >= 0 && line.indexOf("]") >= 0) { if (exists) *exists = true; line.remove(0, 1); @@ -671,7 +673,7 @@ QString QPIConfig::writeAllToString() { QTextStream s(&str); buildFullNames(&root); Branch b = allLeaves(); - int j = 0; + int j = 0; for (int i = 0; i < other.size(); ++i) { if (j >= 0 && j < b.size()) { if (b[j]->_line == i) { @@ -709,18 +711,19 @@ void QPIConfig::clear() { void QPIConfig::readAll() { - if (buffer == 0) - flush(); + if (buffer == 0) flush(); parse(); } bool QPIConfig::entryExists(const Entry * e, const QString & name) const { if (e->_children.isEmpty()) { - if (e->_name == name) return true; - else return false; + if (e->_name == name) + return true; + else + return false; } - foreach (Entry * i, e->_children) + foreach(Entry * i, e->_children) if (entryExists(i, name)) return true; return false; } @@ -729,7 +732,7 @@ bool QPIConfig::entryExists(const Entry * e, const QString & name) const { void QPIConfig::updateIncludes() { if (internal) return; all_includes.clear(); - foreach (QPIConfig * c, includes) + foreach(QPIConfig * c, includes) all_includes << c->allLeaves(); } @@ -739,17 +742,17 @@ QString QPIConfig::parseLine(QString v) { while (1) { i = v.indexOf("${"); if (i < 0) break; - l = v.indexOf("}", i + 1); - QString w = v.mid(i + 2, l - i - 2), r; - l = w.length() + 3; - w = parseLine(w); - w = w.trimmed(); - bool ex = false; + l = v.indexOf("}", i + 1); + QString w = v.mid(i + 2, l - i - 2), r; + l = w.length() + 3; + w = parseLine(w); + w = w.trimmed(); + bool ex = false; QPIConfig::Entry & me = getValue(w, "", &ex); if (ex) { r = me._value; } else { - foreach (QPIConfig::Entry * e, all_includes) { + foreach(QPIConfig::Entry * e, all_includes) { if (e->_full_name == w) { r = e->_value; break; @@ -767,10 +770,10 @@ void QPIConfig::parse(QString content) { root.clear(); QString src, str, tab, comm, all, name, type, prefix, tprefix; QStringList tree; - Entry * entry = 0, * te = 0, * ce = 0; + Entry *entry = 0, *te = 0, *ce = 0; int ind, sind; bool isNew = false, isPrefix = false, wasMultiline = false, isMultiline = false; - foreach (QPIConfig * c, inc_devs) + foreach(QPIConfig * c, inc_devs) delete c; inc_devs.clear(); includes.clear(); @@ -790,15 +793,14 @@ void QPIConfig::parse(QString content) { while (!stream.atEnd()) { other.push_back(QString()); src = str = parseLine(stream.readLine()); - tprefix = getPrefixFromLine(src, &isPrefix); + tprefix = getPrefixFromLine(src, &isPrefix); if (isPrefix) { prefix = tprefix; - if (!prefix.isEmpty()) - prefix += delim; + if (!prefix.isEmpty()) prefix += delim; } - tab = str.left(str.indexOf(str.trimmed().left(1))); - str = str.trimmed(); - all = str; + tab = str.left(str.indexOf(str.trimmed().left(1))); + str = str.trimmed(); + all = str; sind = str.indexOf('#'); if (sind > 0) { @@ -806,7 +808,8 @@ void QPIConfig::parse(QString content) { if (comm.length() > 0) { type = comm[0]; comm = comm.mid(1).trimmed(); - } else type = "s"; + } else + type = "s"; str = str.left(sind).trimmed(); } else { type = "s"; @@ -831,11 +834,11 @@ void QPIConfig::parse(QString content) { ce = 0; wasMultiline = isMultiline; - ind = str.indexOf('='); + ind = str.indexOf('='); if ((ind > 0) && !(str[0] == '#')) { tree = (prefix + str.left(ind).trimmed()).split(delim); if (tree.front() == "include") { - name = str.mid(ind + 1).trimmed(); + name = str.mid(ind + 1).trimmed(); QPIConfig * iconf = new QPIConfig(name, incdirs); if (!iconf->dev) { delete iconf; @@ -849,39 +852,41 @@ void QPIConfig::parse(QString content) { name = tree.back(); tree.pop_back(); entry = &root; - foreach (QString i, tree) { + foreach(QString i, tree) { te = entry->findChild(i); if (te == 0) { - ce = new Entry(); - ce->delim = delim; - ce->_tab = tab; - ce->_line = lines; - ce->_name = i; + ce = new Entry(); + ce->delim = delim; + ce->_tab = tab; + ce->_line = lines; + ce->_name = i; ce->_parent = entry; entry->_children << ce; entry = ce; - } else entry = te; + } else + entry = te; } isNew = false; - ce = entry->findChild(name); + ce = entry->findChild(name); if (ce == 0) { - ce = new Entry(); + ce = new Entry(); isNew = true; } - ce->delim = delim; - ce->_tab = tab; - ce->_name = name; - ce->_value = str.mid(ind + 1).trimmed(); - ce->_type = type; + ce->delim = delim; + ce->_tab = tab; + ce->_name = name; + ce->_value = str.mid(ind + 1).trimmed(); + ce->_type = type; ce->_comment = comm; - ce->_line = lines; - ce->_all = all; + ce->_line = lines; + ce->_all = all; if (isNew) { ce->_parent = entry; entry->_children << ce; } } - } else other.back() = src; + } else + other.back() = src; lines++; } setEntryDelim(&root, delim); diff --git a/libs/utils/qpiconfig.h b/libs/utils/qpiconfig.h index 5ef47cc..1a2fa3e 100644 --- a/libs/utils/qpiconfig.h +++ b/libs/utils/qpiconfig.h @@ -1,20 +1,20 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONFIG_H @@ -305,7 +305,7 @@ public: bool toBool() const { return (_value.toLower().trimmed() == "true" || _value.toLower().trimmed() == "yes" || _value.toLower().trimmed() == "on" || - _value.toInt() > 0); + _value.toInt() > 0); } char toChar() const { return (_value.isEmpty() ? 0 : _value[0].toLatin1()); } short toShort() const { return _value.toShort(); } diff --git a/libs/widgets/chardialog.cpp b/libs/widgets/chardialog.cpp index c6e9b5e..267e65e 100644 --- a/libs/widgets/chardialog.cpp +++ b/libs/widgets/chardialog.cpp @@ -1,4 +1,5 @@ #include "chardialog.h" + #include "ui_chardialog.h" @@ -11,20 +12,18 @@ CharDialog::CharDialog(QWidget * parent): QDialog(parent) { for (int j = 0; j < 256; ++j) { c = QChar(j, i); k = c.category(); - if (chars.size() <= k) - chars.resize(k + 1); + if (chars.size() <= k) chars.resize(k + 1); if (!c.isPrint()) continue; - + chars[k].push_back(c); } } size = 30; QStringList cat; - cat << tr("No Category") << tr("Mark NonSpacing") << tr("Mark SpacingCombining") << tr("Mark Enclosing") - << tr("Number DecimalDigit") << tr("Number Letter") << tr("Number Other") << tr("Separator Space") - << tr("Separator Line") << tr("Separator Paragraph") << tr("Other Control") << tr("Other Format") - << tr("Other Surrogate") << tr("Other PrivateUse") << tr("Other NotAssigned") << tr("Letter Uppercase") - << tr("Letter Lowercase") << tr("Letter Titlecase") << tr("Letter Modifier") << tr("Letter Other") + cat << tr("No Category") << tr("Mark NonSpacing") << tr("Mark SpacingCombining") << tr("Mark Enclosing") << tr("Number DecimalDigit") + << tr("Number Letter") << tr("Number Other") << tr("Separator Space") << tr("Separator Line") << tr("Separator Paragraph") + << tr("Other Control") << tr("Other Format") << tr("Other Surrogate") << tr("Other PrivateUse") << tr("Other NotAssigned") + << tr("Letter Uppercase") << tr("Letter Lowercase") << tr("Letter Titlecase") << tr("Letter Modifier") << tr("Letter Other") << tr("Punctuation Connector") << tr("Punctuation Dash") << tr("Punctuation Open") << tr("Punctuation Close") << tr("Punctuation InitialQuote") << tr("Punctuation FinalQuote") << tr("Punctuation Other") << tr("Symbol Math") << tr("Symbol Currency") << tr("Symbol Modifier") << tr("Symbol Other"); @@ -53,13 +52,12 @@ void CharDialog::changeEvent(QEvent * e) { ui->retranslateUi(this); QStringList cat; cat << tr("No Category") << tr("Mark NonSpacing") << tr("Mark SpacingCombining") << tr("Mark Enclosing") - << tr("Number DecimalDigit") << tr("Number Letter") << tr("Number Other") << tr("Separator Space") - << tr("Separator Line") << tr("Separator Paragraph") << tr("Other Control") << tr("Other Format") - << tr("Other Surrogate") << tr("Other PrivateUse") << tr("Other NotAssigned") << tr("Letter Uppercase") - << tr("Letter Lowercase") << tr("Letter Titlecase") << tr("Letter Modifier") << tr("Letter Other") - << tr("Punctuation Connector") << tr("Punctuation Dash") << tr("Punctuation Open") << tr("Punctuation Close") - << tr("Punctuation InitialQuote") << tr("Punctuation FinalQuote") << tr("Punctuation Other") << tr("Symbol Math") - << tr("Symbol Currency") << tr("Symbol Modifier") << tr("Symbol Other"); + << tr("Number DecimalDigit") << tr("Number Letter") << tr("Number Other") << tr("Separator Space") << tr("Separator Line") + << tr("Separator Paragraph") << tr("Other Control") << tr("Other Format") << tr("Other Surrogate") << tr("Other PrivateUse") + << tr("Other NotAssigned") << tr("Letter Uppercase") << tr("Letter Lowercase") << tr("Letter Titlecase") + << tr("Letter Modifier") << tr("Letter Other") << tr("Punctuation Connector") << tr("Punctuation Dash") + << tr("Punctuation Open") << tr("Punctuation Close") << tr("Punctuation InitialQuote") << tr("Punctuation FinalQuote") + << tr("Punctuation Other") << tr("Symbol Math") << tr("Symbol Currency") << tr("Symbol Modifier") << tr("Symbol Other"); int pi = ui->comboCategory->currentIndex(); ui->comboCategory->clear(); ui->comboCategory->addItems(cat); @@ -71,15 +69,14 @@ void CharDialog::changeEvent(QEvent * e) { bool CharDialog::eventFilter(QObject * o, QEvent * e) { if (o == ui->tableChars->viewport()) { - if (e->type() != QEvent::Wheel) - return QDialog::eventFilter(o, e); + if (e->type() != QEvent::Wheel) return QDialog::eventFilter(o, e); qApp->sendEvent(ui->verticalScroll, e); } return QDialog::eventFilter(o, e); } -void CharDialog::resizeEvent(QResizeEvent * ) { +void CharDialog::resizeEvent(QResizeEvent *) { int r = ui->tableChars->contentsRect().height() / csize, c = ui->tableChars->contentsRect().width() / csize; ui->tableChars->setRowCount(r); ui->tableChars->setColumnCount(c); @@ -120,15 +117,17 @@ void CharDialog::on_verticalScroll_valueChanged(int index) { for (int i = 0; i < ui->tableChars->rowCount(); ++i) { for (int j = 0; j < ui->tableChars->columnCount(); ++j) { ++ci; - if (cur->size() > ci) ui->tableChars->item(i, j)->setText(cur->at(ci)); - else ui->tableChars->item(i, j)->setText(QString()); + if (cur->size() > ci) + ui->tableChars->item(i, j)->setText(cur->at(ci)); + else + ui->tableChars->item(i, j)->setText(QString()); } } } void CharDialog::on_spinSize_valueChanged(int index) { - size = index; + size = index; csize = size * 2; ui->tableChars->horizontalHeader()->setDefaultSectionSize(csize); ui->tableChars->verticalHeader()->setDefaultSectionSize(csize); diff --git a/libs/widgets/chardialog.h b/libs/widgets/chardialog.h index 2c28174..a1d25dc 100644 --- a/libs/widgets/chardialog.h +++ b/libs/widgets/chardialog.h @@ -1,52 +1,53 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CHARDIALOG_H #define CHARDIALOG_H #include "qad_widgets_export.h" + #include namespace Ui { - class CharDialog; +class CharDialog; } -class QAD_WIDGETS_EXPORT CharDialog: public QDialog -{ +class QAD_WIDGETS_EXPORT CharDialog: public QDialog { Q_OBJECT + public: explicit CharDialog(QWidget * parent = nullptr); ~CharDialog() override; - - QChar selectedChar() {return sel_char;} + + QChar selectedChar() { return sel_char; } void setCharFont(const QFont & f); - + private slots: void on_comboCategory_currentIndexChanged(int index); void on_verticalScroll_valueChanged(int index); void on_spinSize_valueChanged(int index); void on_tableChars_cellPressed(int row, int column); - void on_tableChars_cellDoubleClicked(int , int ) {on_buttonBox_accepted();} + void on_tableChars_cellDoubleClicked(int, int) { on_buttonBox_accepted(); } void on_buttonBox_accepted(); - void on_buttonBox_rejected() {reject();} + void on_buttonBox_rejected() { reject(); } signals: void charSelected(QChar ch); @@ -56,9 +57,9 @@ private: bool eventFilter(QObject * o, QEvent * e) override; void resizeEvent(QResizeEvent *) override; void clear(); - + Ui::CharDialog * ui; - QVector > chars; + QVector> chars; QVector * cur; QChar sel_char; int size, csize; diff --git a/libs/widgets/clineedit.cpp b/libs/widgets/clineedit.cpp index 917a33f..fa1f057 100644 --- a/libs/widgets/clineedit.cpp +++ b/libs/widgets/clineedit.cpp @@ -1,5 +1,7 @@ #include "clineedit.h" + #include "qad_types.h" + #include #include @@ -12,7 +14,7 @@ CLineEdit::CLineEdit(QWidget * parent): QLineEdit(parent) { cw->hide(); cw->installEventFilter(this); connect(this, &QLineEdit::textChanged, this, &CLineEdit::textChangedSlot); - int is = fontHeight(this); + int is = fontHeight(this); QMargins m = textMargins(); m.setRight(m.right() + (is * 1.2)); setTextMargins(m); @@ -26,13 +28,9 @@ CLineEdit::~CLineEdit() { bool CLineEdit::eventFilter(QObject * o, QEvent * e) { switch (e->type()) { - case QEvent::MouseButtonRelease: - clearMouseRelease(static_cast(e)); - break; - case QEvent::Paint: - cwPaintEvent(); - break; - default : break; + case QEvent::MouseButtonRelease: clearMouseRelease(static_cast(e)); break; + case QEvent::Paint: cwPaintEvent(); break; + default: break; } return QLineEdit::eventFilter(o, e); } @@ -73,7 +71,7 @@ void CLineEdit::setDefaultText(const QString & t, bool set_text) { } -void CLineEdit::clearMouseRelease(QMouseEvent *e) { +void CLineEdit::clearMouseRelease(QMouseEvent * e) { if (cw->rect().contains(e->pos())) { clearClick(); } diff --git a/libs/widgets/clineedit.h b/libs/widgets/clineedit.h index 539e19c..092b8f6 100644 --- a/libs/widgets/clineedit.h +++ b/libs/widgets/clineedit.h @@ -1,48 +1,54 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef CLINEEDIT_H #define CLINEEDIT_H #include "qad_widgets_export.h" + #include -class QAD_WIDGETS_EXPORT CLineEdit: public QLineEdit -{ +class QAD_WIDGETS_EXPORT CLineEdit: public QLineEdit { Q_OBJECT Q_PROPERTY(QString defaultText READ defaultText WRITE setDefaultText) + public: explicit CLineEdit(QWidget * parent = nullptr); ~CLineEdit() override; - - const QString & defaultText() const {return dt;} + + const QString & defaultText() const { return dt; } public slots: - void clearClick() {if (!isEnabled()) return; setText(dt); emit cleared(); emit textEdited(dt);} + void clearClick() { + if (!isEnabled()) return; + setText(dt); + emit cleared(); + emit textEdited(dt); + } void setDefaultText(const QString & t, bool set_text = false); signals: void cleared(); private slots: - void clearMouseRelease(QMouseEvent *e); + void clearMouseRelease(QMouseEvent * e); void textChangedSlot(QString text); private: diff --git a/libs/widgets/colorbutton.cpp b/libs/widgets/colorbutton.cpp index 0602ff9..8bb966a 100644 --- a/libs/widgets/colorbutton.cpp +++ b/libs/widgets/colorbutton.cpp @@ -1,19 +1,21 @@ #include "colorbutton.h" + #include "qclipboard.h" #include "qcolor.h" #include "qmenu.h" -#include -#include -#include -#include -#include + #include +#include +#include +#include +#include +#include ColorButton::ColorButton(QWidget * parent): QPushButton(parent), menu(new QMenu(this)) { - frame = false; + frame = false; options = QColorDialog::ShowAlphaChannel; - back = new QWidget(this); + back = new QWidget(this); back->setAutoFillBackground(true); back->show(); pal = back->palette(); @@ -23,8 +25,8 @@ ColorButton::ColorButton(QWidget * parent): QPushButton(parent), menu(new QMenu( label->setAutoFillBackground(true); label->setFrameStyle(QFrame::Panel | QFrame::Sunken); label->show(); - pal = label->palette(); - a_copy = menu->addAction(QIcon(":/icons/edit-copy.png"), tr("Copy"), this, SLOT(copy())); + pal = label->palette(); + a_copy = menu->addAction(QIcon(":/icons/edit-copy.png"), tr("Copy"), this, SLOT(copy())); a_paste = menu->addAction(QIcon(":/icons/edit-paste.png"), tr("Paste"), this, SLOT(paste())); menu->addSeparator(); a_mix = menu->addAction(tr("Mix with clipboard"), this, SLOT(mix())); @@ -38,7 +40,7 @@ ColorButton::~ColorButton() { } -void ColorButton::resizeEvent(QResizeEvent * ) { +void ColorButton::resizeEvent(QResizeEvent *) { if (frame) { back->setGeometry(rect()); } else { @@ -53,11 +55,11 @@ void ColorButton::mousePressEvent(QMouseEvent * e) { if (e->buttons().testFlag(Qt::RightButton)) { menu->popup( #if QT_VERSION_MAJOR <= 5 - static_cast(e)->globalPos() + static_cast(e)->globalPos() #else - static_cast(e)->globalPosition().toPoint() + static_cast(e)->globalPosition().toPoint() #endif - ); + ); return; } QPushButton::mousePressEvent(e); @@ -68,7 +70,7 @@ void ColorButton::mouseMoveEvent(QMouseEvent * e) { if (e->buttons().testFlag(Qt::LeftButton)) { if ((e->pos() - pp).manhattanLength() > QApplication::startDragDistance()) { setDown(false); - QDrag * drag = new QDrag(this); + QDrag * drag = new QDrag(this); QMimeData * data = new QMimeData(); data->setColorData(color()); drag->setMimeData(data); @@ -88,7 +90,7 @@ void ColorButton::dragEnterEvent(QDragEnterEvent * e) { void ColorButton::dropEvent(QDropEvent * e) { const QMimeData * data = e->mimeData(); - QColor c = qvariant_cast(data->colorData()); + QColor c = qvariant_cast(data->colorData()); if (c.isValid()) { setColor(c); return; @@ -105,13 +107,12 @@ void ColorButton::dropEvent(QDropEvent * e) { void ColorButton::changeEvent(QEvent * e) { QPushButton::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - a_copy->setText(tr("Copy")); - a_paste->setText(tr("Paste")); - a_mix->setText(tr("Mix with clipboard")); - break; - default: - break; + case QEvent::LanguageChange: + a_copy->setText(tr("Copy")); + a_paste->setText(tr("Paste")); + a_mix->setText(tr("Mix with clipboard")); + break; + default: break; } } @@ -198,4 +199,3 @@ void ColorButton::paste() { void ColorButton::copy() { QApplication::clipboard()->setText(color().name()); } - diff --git a/libs/widgets/colorbutton.h b/libs/widgets/colorbutton.h index f71d8b9..d727b65 100644 --- a/libs/widgets/colorbutton.h +++ b/libs/widgets/colorbutton.h @@ -1,39 +1,40 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef COLORBUTTON_H #define COLORBUTTON_H #include "qad_widgets_export.h" + #include class QFrame; -class QAD_WIDGETS_EXPORT ColorButton: public QPushButton -{ +class QAD_WIDGETS_EXPORT ColorButton: public QPushButton { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(bool useNativeDialog READ useNativeDialog WRITE setUseNativeDialog) Q_PROPERTY(bool useAlphaChannel READ useAlphaChannel WRITE setUseAlphaChannel) Q_PROPERTY(bool frameOnly READ frameOnly WRITE setFrameOnly) + public: explicit ColorButton(QWidget * parent = nullptr); ~ColorButton() override; @@ -41,7 +42,7 @@ public: QColor color() const; bool useNativeDialog() const; bool useAlphaChannel() const; - bool frameOnly() const {return frame;} + bool frameOnly() const { return frame; } public slots: void setColor(const QColor & col); @@ -64,11 +65,11 @@ private: void resizeEvent(QResizeEvent *) override; void dragEnterEvent(QDragEnterEvent * e) override; void dropEvent(QDropEvent * e) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent * e) override; QFrame * label; QWidget * back; - QAction * a_copy, * a_paste, * a_mix; + QAction *a_copy, *a_paste, *a_mix; QPalette pal; QPoint pp; QMenu * menu; diff --git a/libs/widgets/ecombobox.cpp b/libs/widgets/ecombobox.cpp index 744f284..6a1224f 100644 --- a/libs/widgets/ecombobox.cpp +++ b/libs/widgets/ecombobox.cpp @@ -1,14 +1,16 @@ #include "ecombobox.h" + #include "clineedit.h" #include "qabstractitemview.h" #include "qad_types.h" #include "qwidget.h" + #include #include -#include -#include #include #include +#include +#include class EModel: public QStandardItemModel { @@ -18,6 +20,7 @@ public: setSupportedDragActions(Qt::MoveAction); #endif } + protected: virtual Qt::ItemFlags flags(const QModelIndex & index) const override { Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled; @@ -25,20 +28,18 @@ protected: return f; } #if QT_VERSION >= 0x050000 - Qt::DropActions supportedDragActions() const override {return Qt::MoveAction;} - Qt::DropActions supportedDropActions() const override {return Qt::MoveAction;} + Qt::DropActions supportedDragActions() const override { return Qt::MoveAction; } + Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; } #endif }; - EComboBox::EComboBox(QWidget * parent) : QComboBox(parent) , iv(new QTreeView(this)) , header(new QWidget(this)) , icon(new QLabel(this)) - , filter(new CLineEdit(this)) -{ + , filter(new CLineEdit(this)) { setView(iv); setModel(new EModel()); iv->setTextElideMode(Qt::ElideMiddle); @@ -64,9 +65,7 @@ EComboBox::EComboBox(QWidget * parent) header->layout()->addWidget(icon); header->layout()->addWidget(filter); header->setParent(iv->header()); - connect(filter, &CLineEdit::textChanged, this, [this](const QString & text){ - EComboBox::filterChanged(text, false); - }); + connect(filter, &CLineEdit::textChanged, this, [this](const QString & text) { EComboBox::filterChanged(text, false); }); connect(model(), &EModel::layoutChanged, this, &EComboBox::rowsChanged); } @@ -91,13 +90,12 @@ void EComboBox::showPopup() { void EComboBox::changeEvent(QEvent * e) { QComboBox::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: + case QEvent::LanguageChange: #if QT_VERSION >= 0x040700 - filter->setPlaceholderText(tr("Filter")); + filter->setPlaceholderText(tr("Filter")); #endif - break; - default: - break; + break; + default: break; } } @@ -110,7 +108,7 @@ void EComboBox::filterChanged(const QString & text, bool first) { } iv->hide(); QModelIndex pi = iv->rootIndex(); - int row_count = iv->model()->rowCount(); + int row_count = iv->model()->rowCount(); if (text.isEmpty()) { for (int i = 0; i < row_count; ++i) { iv->setRowHidden(i, pi, false); @@ -126,13 +124,15 @@ void EComboBox::filterChanged(const QString & text, bool first) { return; } for (int i = 0; i < row_count; ++i) { - iv->setRowHidden(i, pi, !iv->model()->index(i, 0, pi).data().toString().contains( - #if QT_VERSION_MAJOR <= 5 - QRegExp(text, Qt::CaseInsensitive) - #else - QRegularExpression(text, QRegularExpression::CaseInsensitiveOption) - #endif - )); + iv->setRowHidden(i, + pi, + !iv->model()->index(i, 0, pi).data().toString().contains( +#if QT_VERSION_MAJOR <= 5 + QRegExp(text, Qt::CaseInsensitive) +#else + QRegularExpression(text, QRegularExpression::CaseInsensitiveOption) +#endif + )); iv->model()->setData(iv->model()->index(i, 0), iv->model()->index(i, 0, pi).data().toString(), Qt::ToolTipRole); } iv->show(); diff --git a/libs/widgets/ecombobox.h b/libs/widgets/ecombobox.h index c1333ba..837c123 100644 --- a/libs/widgets/ecombobox.h +++ b/libs/widgets/ecombobox.h @@ -1,26 +1,27 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef ECOMBOBOX_H #define ECOMBOBOX_H #include "qad_widgets_export.h" + #include @@ -29,12 +30,12 @@ class QLabel; class QTreeView; -class QAD_WIDGETS_EXPORT EComboBox: public QComboBox -{ +class QAD_WIDGETS_EXPORT EComboBox: public QComboBox { Q_OBJECT + public: explicit EComboBox(QWidget * parent = nullptr); - + QSize sizeHint() const override; public slots: @@ -47,7 +48,7 @@ signals: void rowsChanged(); private: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent * e) override; QTreeView * iv; QWidget * header; diff --git a/libs/widgets/evalspinbox.cpp b/libs/widgets/evalspinbox.cpp index bb07f42..ae55e17 100644 --- a/libs/widgets/evalspinbox.cpp +++ b/libs/widgets/evalspinbox.cpp @@ -1,14 +1,16 @@ #include "evalspinbox.h" + #include "qad_types.h" #include "qpievaluator_p.h" -#include -#include + #include +#include +#include +#include #include -#include #include #include -#include +#include #if QT_VERSION_MAJOR <= 5 # include #else @@ -17,10 +19,10 @@ EvalSpinBox::EvalSpinBox(QWidget * parent): QAbstractSpinBox(parent) { - status = new QWidget(lineEdit()); - cw = new QWidget(lineEdit()); - label = new QLabel(lineEdit()); - eval = new QPIEvaluator(); + status = new QWidget(lineEdit()); + cw = new QWidget(lineEdit()); + label = new QLabel(lineEdit()); + eval = new QPIEvaluator(); precision_ = -1; clear_im.load(":/icons/edit-clear-locationbar-rtl.png"); icon_ok.load(":/icons/dialog-ok-apply.png"); @@ -33,7 +35,7 @@ EvalSpinBox::EvalSpinBox(QWidget * parent): QAbstractSpinBox(parent) { cw->setCursor(Qt::ArrowCursor); cw->setToolTip(tr("Clear")); cw->hide(); - cw_visible = false; + cw_visible = false; calc_visible = true; cw->installEventFilter(this); status->installEventFilter(this); @@ -66,7 +68,7 @@ bool EvalSpinBox::eventFilter(QObject * o, QEvent * e) { cwPaintEvent(); } break; - default : break; + default: break; } return QAbstractSpinBox::eventFilter(o, e); } @@ -77,13 +79,13 @@ void EvalSpinBox::resizeIcons() { int tm = (lineEdit()->height() - is + 1) / 2; QStyleOptionFrame so; so.initFrom(lineEdit()); - QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &so, lineEdit()); + QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &so, lineEdit()); QMargins m = lineEdit()->textMargins(); - int lwh = label->sizeHint().width(); + int lwh = label->sizeHint().width(); label->setGeometry(lineEdit()->width() - m.left() - lwh + r.x() - 2, - m.top() + r.y() + (r.height() - fontMetrics().height() + 1) / 2, - lwh,// - 2*tm - (is * 1.2) * ((status->isVisible() ? 1 : 0) + (cw->isVisible() ? 1 : 0)), - lineEdit()->height() - 2*tm); + m.top() + r.y() + (r.height() - fontMetrics().height() + 1) / 2, + lwh, // - 2*tm - (is * 1.2) * ((status->isVisible() ? 1 : 0) + (cw->isVisible() ? 1 : 0)), + lineEdit()->height() - 2 * tm); status->setGeometry(lineEdit()->width() - (is + tm) * (cw->isVisible() ? 2 : 1), tm, is, is); cw->setGeometry(lineEdit()->width() - (is + tm) * 1, tm, is, is); m.setRight((is * 1.2) * ((status->isVisible() ? 1 : 0) + (cw->isVisible() ? 1 : 0))); @@ -139,10 +141,10 @@ void EvalSpinBox::textChanged_(const QString & text) { eval->evaluate(); if (td) { icon = icon_calc; - status->setToolTip("Enter to calc -> "+QString::number(value(), 'G', 10)); + status->setToolTip("Enter to calc -> " + QString::number(value(), 'G', 10)); } else { icon = icon_ok; - status->setToolTip("OK -> "+QString::number(value(), 'G', 10)); + status->setToolTip("OK -> " + QString::number(value(), 'G', 10)); } if (pv != value()) { emit valueChanged(value()); @@ -156,7 +158,7 @@ void EvalSpinBox::textChanged_(const QString & text) { void EvalSpinBox::setExpressionSlot() { - bool td = false; + bool td = false; double pv = value(); QString t = text(); if (t.endsWith('=')) { @@ -174,8 +176,10 @@ void EvalSpinBox::setExpressionSlot() { status->setToolTip(eval->error()); } if (!label->isHidden()) { - if (eval->expression() != QString::number(value(), 'G', 10) && eval->expression() != QString::number(value(), 'G', 11) && eval->isCorrect()) - label->setText("

-> " + QString::number(value(), 'G', 10) + "

"); + if (eval->expression() != QString::number(value(), 'G', 10) && eval->expression() != QString::number(value(), 'G', 11) && + eval->isCorrect()) + label->setText("

-> " + QString::number(value(), 'G', 10) + + "

"); else label->setText(""); lineEdit()->blockSignals(true); @@ -265,8 +269,10 @@ void EvalSpinBox::focusInEvent(QFocusEvent * event) { void EvalSpinBox::focusOutEvent(QFocusEvent * event) { QAbstractSpinBox::focusOutEvent(event); - if (eval->expression() != QString::number(value(), 'G', 10) && eval->expression() != QString::number(value(), 'G', 11) && eval->isCorrect()) { - label->setText("

-> " + QString::number(value(), 'G', 10) + "

"); + if (eval->expression() != QString::number(value(), 'G', 10) && eval->expression() != QString::number(value(), 'G', 11) && + eval->isCorrect()) { + label->setText("

-> " + QString::number(value(), 'G', 10) + + "

"); } else { label->setText(""); } @@ -274,8 +280,10 @@ void EvalSpinBox::focusOutEvent(QFocusEvent * event) { label->show(); } lineEdit()->blockSignals(true); - if (!eval->isCorrect()) lineEdit()->setStyleSheet("color: darkred;"); - else status->hide(); + if (!eval->isCorrect()) + lineEdit()->setStyleSheet("color: darkred;"); + else + status->hide(); lineEdit()->blockSignals(false); resizeIcons(); } @@ -285,11 +293,13 @@ void EvalSpinBox::wheelEvent(QWheelEvent * event) { if (event->modifiers().testFlag(Qt::ShiftModifier)) { stepByDouble( #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - event->delta() + event->delta() #else - event->angleDelta().y() + event->angleDelta().y() #endif - > 0 ? 0.1 : -0.1); + > 0 + ? 0.1 + : -0.1); } else { QAbstractSpinBox::wheelEvent(event); } @@ -311,20 +321,20 @@ void EvalSpinBox::stepByDouble(double steps) { t.insert(pos, QString::number(v)); } else { double v = steps; - t = QString::number(v) + t; + t = QString::number(v) + t; } #else QRegularExpression re("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)"); QRegularExpressionMatchIterator i = re.globalMatch(t); if (i.hasNext()) { QRegularExpressionMatch match = i.next(); - double v = t.mid(match.capturedStart(), match.capturedLength()).toDouble(); + double v = t.mid(match.capturedStart(), match.capturedLength()).toDouble(); v += steps; t.remove(match.capturedStart(), match.capturedLength()); t.insert(match.capturedStart(), QString::number(v)); } else { double v = steps; - t = QString::number(v) + t; + t = QString::number(v) + t; } #endif eval->check(t); diff --git a/libs/widgets/evalspinbox.h b/libs/widgets/evalspinbox.h index de62b4f..776d1d2 100644 --- a/libs/widgets/evalspinbox.h +++ b/libs/widgets/evalspinbox.h @@ -1,26 +1,27 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef EVALSPINBOX_H #define EVALSPINBOX_H #include "qad_widgets_export.h" + #include @@ -28,8 +29,7 @@ class QPIEvaluator; class QLabel; -class QAD_WIDGETS_EXPORT EvalSpinBox: public QAbstractSpinBox -{ +class QAD_WIDGETS_EXPORT EvalSpinBox: public QAbstractSpinBox { Q_OBJECT Q_PROPERTY(double value READ value WRITE setValue NOTIFY valueChanged USER true) Q_PROPERTY(QString expression READ expression WRITE setExpression USER true) @@ -44,11 +44,11 @@ public: double value() const; const QString & expression() const; - const QString & defaultText() const {return dt;} - bool isClearButtonVisible() const {return cw_visible;} - bool isCalculationVisible() const {return calc_visible;} + const QString & defaultText() const { return dt; } + bool isClearButtonVisible() const { return cw_visible; } + bool isCalculationVisible() const { return calc_visible; } bool isCleared() const; - int precision() const {return precision_;} + int precision() const { return precision_; } void stepBy(int steps) override; void clear() override; @@ -60,15 +60,15 @@ public slots: void setDefaultText(const QString & t); void setClearButtonVisible(bool visible); void setCalculationVisible(bool visible); - void setPrecision(int precision) {precision_ = precision;} + void setPrecision(int precision) { precision_ = precision; } protected: - QString text() const {return QAbstractSpinBox::text();} + QString text() const { return QAbstractSpinBox::text(); } StepEnabled stepEnabled() const override; - void focusInEvent(QFocusEvent *event) override; - void focusOutEvent(QFocusEvent *event) override; - void wheelEvent(QWheelEvent *event) override; + void focusInEvent(QFocusEvent * event) override; + void focusOutEvent(QFocusEvent * event) override; + void wheelEvent(QWheelEvent * event) override; void stepByDouble(double steps); @@ -84,7 +84,7 @@ signals: private: bool eventFilter(QObject * o, QEvent * e) override; - void resizeEvent(QResizeEvent * ) override; + void resizeEvent(QResizeEvent *) override; void changeEvent(QEvent * e) override; void statusPaintEvent(); void cwPaintEvent(); diff --git a/libs/widgets/iconedlabel.cpp b/libs/widgets/iconedlabel.cpp index 2606088..4e6f683 100644 --- a/libs/widgets/iconedlabel.cpp +++ b/libs/widgets/iconedlabel.cpp @@ -1,8 +1,10 @@ #include "iconedlabel.h" + #include "qad_types.h" + +#include #include #include -#include IconedLabel::IconedLabel(QWidget * parent): QFrame(parent) { @@ -45,8 +47,8 @@ void IconedLabel::checkSpacing() { } else { QStyle * s = style(); if (s) { - layout()->setSpacing(s->layoutSpacing(QSizePolicy::Label, QSizePolicy::Label, - dir_ <= Direction::RightToLeft ? Qt::Horizontal : Qt::Vertical)); + layout()->setSpacing( + s->layoutSpacing(QSizePolicy::Label, QSizePolicy::Label, dir_ <= Direction::RightToLeft ? Qt::Horizontal : Qt::Vertical)); } } } @@ -72,7 +74,7 @@ void IconedLabel::setIcon(const QIcon & i) { void IconedLabel::setIconSize(const QSize & s) { - size_ = s; + size_ = s; QSize sz = realIconSize(); icon_.setPixmap(sicon_.pixmap(sz)); icon_.setFixedSize(sz); diff --git a/libs/widgets/iconedlabel.h b/libs/widgets/iconedlabel.h index 8ea5952..0b185ed 100644 --- a/libs/widgets/iconedlabel.h +++ b/libs/widgets/iconedlabel.h @@ -1,49 +1,55 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef ICONEDLABEL_H #define ICONEDLABEL_H #include "qad_widgets_export.h" -#include + #include +#include -class QAD_WIDGETS_EXPORT IconedLabel: public QFrame -{ +class QAD_WIDGETS_EXPORT IconedLabel: public QFrame { Q_OBJECT Q_ENUMS(Direction) Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QIcon icon READ icon WRITE setIcon) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) Q_PROPERTY(Direction direction READ direction WRITE setDirection) + public: - enum Direction {LeftToRight = 0, RightToLeft = 1, TopToBottom = 2, BottomToTop = 3}; + enum Direction { + LeftToRight = 0, + RightToLeft = 1, + TopToBottom = 2, + BottomToTop = 3 + }; explicit IconedLabel(QWidget * parent = nullptr); QString text() const; QIcon icon() const; - QSize iconSize() const {return size_;} - Direction direction() const {return dir_;} + QSize iconSize() const { return size_; } + Direction direction() const { return dir_; } - QLabel * textLabel() {return &label_;} + QLabel * textLabel() { return &label_; } public slots: void setText(const QString & t); diff --git a/libs/widgets/image_view.cpp b/libs/widgets/image_view.cpp index dc778b8..e3637aa 100644 --- a/libs/widgets/image_view.cpp +++ b/libs/widgets/image_view.cpp @@ -1,12 +1,13 @@ #include "image_view.h" + +#include +#include +#include #include #include -#include -#include #include -#include #include -#include +#include #include @@ -23,7 +24,7 @@ ImageView::ImageView(QWidget * parent): QGraphicsView(parent), item(new QGraphic scene()->addItem(item); viewport()->setAutoFillBackground(false); viewport()->installEventFilter(this); - autofit_ = true; + autofit_ = true; interactive_ = false; } @@ -57,7 +58,8 @@ void ImageView::setImage(const QImage & i, bool save) { return; } if (save) { - QBuffer b(&im_data); b.open(QIODevice::ReadWrite); + QBuffer b(&im_data); + b.open(QIODevice::ReadWrite); i.save(&b, "png"); b.close(); } @@ -99,7 +101,7 @@ void ImageView::mousePressEvent(QMouseEvent * e) { void ImageView::wheelEvent(QWheelEvent * e) { if (!e->modifiers().testFlag(Qt::ControlModifier) || !viewInteractive()) return; double scl = 1. + e->angleDelta().y() / 500.; - autofit_ = false; + autofit_ = false; scale(scl, scl); } @@ -107,13 +109,10 @@ void ImageView::wheelEvent(QWheelEvent * e) { bool ImageView::eventFilter(QObject * o, QEvent * e) { QMouseEvent * me = reinterpret_cast(e); switch (e->type()) { - case QEvent::Resize: - adjustView(); - break; + case QEvent::Resize: adjustView(); break; case QEvent::MouseButtonPress: prev_pos = me->pos(); - if (me->buttons().testFlag(Qt::RightButton) && !autofit_ && viewInteractive()) - viewport()->setCursor(Qt::ClosedHandCursor); + if (me->buttons().testFlag(Qt::RightButton) && !autofit_ && viewInteractive()) viewport()->setCursor(Qt::ClosedHandCursor); break; case QEvent::MouseButtonRelease: viewport()->unsetCursor(); diff --git a/libs/widgets/image_view.h b/libs/widgets/image_view.h index b8d346f..1c95fdf 100644 --- a/libs/widgets/image_view.h +++ b/libs/widgets/image_view.h @@ -1,46 +1,47 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef IMAGE_VIEW_H #define IMAGE_VIEW_H #include "qad_widgets_export.h" + #include class QGraphicsPixmapItem; -class QAD_WIDGETS_EXPORT ImageView: public QGraphicsView -{ +class QAD_WIDGETS_EXPORT ImageView: public QGraphicsView { Q_OBJECT Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool viewInteractive READ viewInteractive WRITE setViewInteractive) + public: ImageView(QWidget * parent = nullptr); ~ImageView() override; void setImage(const QImage & i, bool save = true); void setImage(const QByteArray & i); - QByteArray image() const {return im_data;} + QByteArray image() const { return im_data; } QPixmap pixmap() const; - bool viewInteractive() const {return interactive_;} + bool viewInteractive() const { return interactive_; } void clear(); public slots: diff --git a/libs/widgets/mathmatrixedit.cpp b/libs/widgets/mathmatrixedit.cpp index 8f5f52e..d7bdaae 100644 --- a/libs/widgets/mathmatrixedit.cpp +++ b/libs/widgets/mathmatrixedit.cpp @@ -1,7 +1,9 @@ #include "mathmatrixedit.h" + #include "matrixedit.h" -#include "qvariantedit_custom.h" #include "qad_types.h" +#include "qvariantedit_custom.h" + #include @@ -39,12 +41,10 @@ void MathMatrixEdit::setReadOnly(bool yes) { } - - class MathMatrixEditFactory: public QVariantEditorFactoryBase { public: MathMatrixEditFactory() {} - QWidget * createEditor() override {return new MathMatrixEdit();} + QWidget * createEditor() override { return new MathMatrixEdit(); } }; diff --git a/libs/widgets/mathmatrixedit.h b/libs/widgets/mathmatrixedit.h index e77952e..566f437 100644 --- a/libs/widgets/mathmatrixedit.h +++ b/libs/widgets/mathmatrixedit.h @@ -1,28 +1,29 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef MATH_MATRIX_EDIT_H #define MATH_MATRIX_EDIT_H #include "qad_widgets_export.h" -#include + #include +#include class MatrixEdit; @@ -32,10 +33,11 @@ class QAD_WIDGETS_EXPORT MathMatrixEdit: public QWidget { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + public: explicit MathMatrixEdit(QWidget * parent = nullptr); ~MathMatrixEdit() override; - + QVariant value() const; bool isReadOnly() const; diff --git a/libs/widgets/mathvectoredit.cpp b/libs/widgets/mathvectoredit.cpp index d56fd98..376861d 100644 --- a/libs/widgets/mathvectoredit.cpp +++ b/libs/widgets/mathvectoredit.cpp @@ -1,7 +1,9 @@ #include "mathvectoredit.h" -#include "qvariantedit_custom.h" -#include "qad_types.h" + #include "matrixedit.h" +#include "qad_types.h" +#include "qvariantedit_custom.h" + #include @@ -39,12 +41,10 @@ void MathVectorEdit::setReadOnly(bool yes) { } - - class MathVectorEditFactory: public QVariantEditorFactoryBase { public: MathVectorEditFactory() {} - virtual QWidget * createEditor() override {return new MathVectorEdit();} + virtual QWidget * createEditor() override { return new MathVectorEdit(); } }; diff --git a/libs/widgets/mathvectoredit.h b/libs/widgets/mathvectoredit.h index 63b47f2..fa2075b 100644 --- a/libs/widgets/mathvectoredit.h +++ b/libs/widgets/mathvectoredit.h @@ -1,28 +1,29 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef MATH_VECTOR_EDIT_H #define MATH_VECTOR_EDIT_H #include "qad_widgets_export.h" -#include + #include +#include class MatrixEdit; @@ -32,13 +33,14 @@ class QAD_WIDGETS_EXPORT MathVectorEdit: public QWidget { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + public: explicit MathVectorEdit(QWidget * parent = nullptr); ~MathVectorEdit() override; - + QVariant value() const; bool isReadOnly() const; - + public slots: void setValue(const QVariant & v); void setReadOnly(bool yes); diff --git a/libs/widgets/matrixedit.cpp b/libs/widgets/matrixedit.cpp index a2fd009..2a963e1 100644 --- a/libs/widgets/matrixedit.cpp +++ b/libs/widgets/matrixedit.cpp @@ -1,5 +1,7 @@ #include "matrixedit.h" + #include "ui_matrixedit.h" + #include @@ -9,7 +11,7 @@ MatrixEdit::MatrixEdit(QWidget * parent): QWidget(parent) { #if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) ui->table->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); #endif - connect(ui->table, SIGNAL(cellChanged(int,int)), this, SIGNAL(changed())); + connect(ui->table, SIGNAL(cellChanged(int, int)), this, SIGNAL(changed())); ro = false; } @@ -52,18 +54,14 @@ void MatrixEdit::clear(bool ident) { i->setText((ident && (r == c)) ? "1" : "0"); } } - } void MatrixEdit::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } @@ -84,8 +82,8 @@ QVector MatrixEdit::vector() const { } -QVector > MatrixEdit::matrix() const { - QVector > ret; +QVector> MatrixEdit::matrix() const { + QVector> ret; if (ui->table->columnCount() < 1 || ui->table->rowCount() < 1) return ret; int cc = ui->table->columnCount(); ret.resize(ui->table->rowCount()); @@ -123,7 +121,7 @@ void MatrixEdit::setVector(const QVector & v) { } -void MatrixEdit::setMatrix(const QVector > & v) { +void MatrixEdit::setMatrix(const QVector> & v) { clear(); if (v.isEmpty()) return; if (v[0].isEmpty()) return; diff --git a/libs/widgets/matrixedit.h b/libs/widgets/matrixedit.h index 57c7e66..8ca08f3 100644 --- a/libs/widgets/matrixedit.h +++ b/libs/widgets/matrixedit.h @@ -1,36 +1,38 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef MATRIXEDIT_H #define MATRIXEDIT_H #include "qad_widgets_export.h" + #include namespace Ui { - class MatrixEdit; +class MatrixEdit; } class QAD_WIDGETS_EXPORT MatrixEdit: public QWidget { Q_OBJECT + public: explicit MatrixEdit(QWidget * parent = nullptr); ~MatrixEdit() override; @@ -39,9 +41,9 @@ public: void setReadOnly(bool yes); QVector vector() const; - QVector > matrix() const; + QVector> matrix() const; void setVector(const QVector & v); - void setMatrix(const QVector > & v); + void setMatrix(const QVector> & v); private slots: void on_spinRows_valueChanged(int cnt); diff --git a/libs/widgets/plugin/clineeditplugin.cpp b/libs/widgets/plugin/clineeditplugin.cpp index 7315985..303e1d3 100644 --- a/libs/widgets/plugin/clineeditplugin.cpp +++ b/libs/widgets/plugin/clineeditplugin.cpp @@ -1,5 +1,7 @@ -#include "clineedit.h" #include "clineeditplugin.h" + +#include "clineedit.h" + #include @@ -9,8 +11,7 @@ CLineEditPlugin::CLineEditPlugin(QObject * parent): QObject(parent) { void CLineEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString CLineEditPlugin::domXml() const { QString CLineEditPlugin::includeFile() const { return QLatin1String("clineedit.h"); } - diff --git a/libs/widgets/plugin/clineeditplugin.h b/libs/widgets/plugin/clineeditplugin.h index 148461d..089597e 100644 --- a/libs/widgets/plugin/clineeditplugin.h +++ b/libs/widgets/plugin/clineeditplugin.h @@ -8,8 +8,9 @@ # include #endif -class CLineEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class CLineEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // CLINEEDITPLUGIN_H diff --git a/libs/widgets/plugin/colorbuttonplugin.cpp b/libs/widgets/plugin/colorbuttonplugin.cpp index 84e8574..3dca00b 100644 --- a/libs/widgets/plugin/colorbuttonplugin.cpp +++ b/libs/widgets/plugin/colorbuttonplugin.cpp @@ -1,5 +1,7 @@ -#include "colorbutton.h" #include "colorbuttonplugin.h" + +#include "colorbutton.h" + #include @@ -9,8 +11,7 @@ ColorButtonPlugin::ColorButtonPlugin(QObject * parent): QObject(parent) { void ColorButtonPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString ColorButtonPlugin::domXml() const { QString ColorButtonPlugin::includeFile() const { return QLatin1String("colorbutton.h"); } - diff --git a/libs/widgets/plugin/colorbuttonplugin.h b/libs/widgets/plugin/colorbuttonplugin.h index 82fb9e9..041aa4a 100644 --- a/libs/widgets/plugin/colorbuttonplugin.h +++ b/libs/widgets/plugin/colorbuttonplugin.h @@ -8,8 +8,9 @@ # include #endif -class ColorButtonPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class ColorButtonPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // COLORBUTTONPLUGIN_H diff --git a/libs/widgets/plugin/ecomboboxplugin.cpp b/libs/widgets/plugin/ecomboboxplugin.cpp index c0079d4..ddd8c34 100644 --- a/libs/widgets/plugin/ecomboboxplugin.cpp +++ b/libs/widgets/plugin/ecomboboxplugin.cpp @@ -1,5 +1,7 @@ -#include "ecombobox.h" #include "ecomboboxplugin.h" + +#include "ecombobox.h" + #include @@ -9,8 +11,7 @@ EComboBoxPlugin::EComboBoxPlugin(QObject * parent): QObject(parent) { void EComboBoxPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString EComboBoxPlugin::domXml() const { QString EComboBoxPlugin::includeFile() const { return QLatin1String("ecombobox.h"); } - diff --git a/libs/widgets/plugin/ecomboboxplugin.h b/libs/widgets/plugin/ecomboboxplugin.h index afccea3..de805cf 100644 --- a/libs/widgets/plugin/ecomboboxplugin.h +++ b/libs/widgets/plugin/ecomboboxplugin.h @@ -8,8 +8,9 @@ # include #endif -class EComboBoxPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class EComboBoxPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // ECOMBOBOXPLUGIN_H diff --git a/libs/widgets/plugin/evalspinboxplugin.cpp b/libs/widgets/plugin/evalspinboxplugin.cpp index 7356dc8..0e57164 100644 --- a/libs/widgets/plugin/evalspinboxplugin.cpp +++ b/libs/widgets/plugin/evalspinboxplugin.cpp @@ -1,5 +1,7 @@ -#include "evalspinbox.h" #include "evalspinboxplugin.h" + +#include "evalspinbox.h" + #include @@ -9,8 +11,7 @@ EvalSpinBoxPlugin::EvalSpinBoxPlugin(QObject * parent): QObject(parent) { void EvalSpinBoxPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString EvalSpinBoxPlugin::domXml() const { QString EvalSpinBoxPlugin::includeFile() const { return QLatin1String("evalspinbox.h"); } - diff --git a/libs/widgets/plugin/evalspinboxplugin.h b/libs/widgets/plugin/evalspinboxplugin.h index d0949f0..a90c6b2 100644 --- a/libs/widgets/plugin/evalspinboxplugin.h +++ b/libs/widgets/plugin/evalspinboxplugin.h @@ -8,8 +8,9 @@ # include #endif -class EvalSpinBoxPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class EvalSpinBoxPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // EVALSPINBOXPLUGIN_H diff --git a/libs/widgets/plugin/iconedlabelplugin.h b/libs/widgets/plugin/iconedlabelplugin.h index 50ce287..ec8f809 100644 --- a/libs/widgets/plugin/iconedlabelplugin.h +++ b/libs/widgets/plugin/iconedlabelplugin.h @@ -8,8 +8,9 @@ # include #endif -class IconedLabelPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class IconedLabelPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // ICONEDLABEPLUGIN_H diff --git a/libs/widgets/plugin/imageviewplugin.cpp b/libs/widgets/plugin/imageviewplugin.cpp index e4d0b26..433ea89 100644 --- a/libs/widgets/plugin/imageviewplugin.cpp +++ b/libs/widgets/plugin/imageviewplugin.cpp @@ -1,5 +1,7 @@ -#include "image_view.h" #include "imageviewplugin.h" + +#include "image_view.h" + #include @@ -9,8 +11,7 @@ ImageViewPlugin::ImageViewPlugin(QObject * parent): QObject(parent) { void ImageViewPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString ImageViewPlugin::domXml() const { QString ImageViewPlugin::includeFile() const { return QLatin1String("image_view.h"); } - diff --git a/libs/widgets/plugin/imageviewplugin.h b/libs/widgets/plugin/imageviewplugin.h index cc7a704..6db8fd3 100644 --- a/libs/widgets/plugin/imageviewplugin.h +++ b/libs/widgets/plugin/imageviewplugin.h @@ -8,8 +8,9 @@ # include #endif -class ImageViewPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class ImageViewPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif diff --git a/libs/widgets/plugin/lconedlabelplugin.cpp b/libs/widgets/plugin/lconedlabelplugin.cpp index a24f3e2..e07a983 100644 --- a/libs/widgets/plugin/lconedlabelplugin.cpp +++ b/libs/widgets/plugin/lconedlabelplugin.cpp @@ -1,5 +1,6 @@ #include "iconedlabel.h" #include "iconedlabelplugin.h" + #include @@ -9,8 +10,7 @@ IconedLabelPlugin::IconedLabelPlugin(QObject * parent): QObject(parent) { void IconedLabelPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +66,3 @@ QString IconedLabelPlugin::domXml() const { QString IconedLabelPlugin::includeFile() const { return QLatin1String("iconedlabel.h"); } - diff --git a/libs/widgets/plugin/qad_widgets.cpp b/libs/widgets/plugin/qad_widgets.cpp index bb243ee..c0c3ab9 100644 --- a/libs/widgets/plugin/qad_widgets.cpp +++ b/libs/widgets/plugin/qad_widgets.cpp @@ -1,21 +1,22 @@ #include "qad_widgets.h" -#include "spinsliderplugin.h" -#include "colorbuttonplugin.h" -#include "shortcutsplugin.h" + #include "clineeditplugin.h" +#include "colorbuttonplugin.h" +#include "ecomboboxplugin.h" +#include "evalspinboxplugin.h" +#include "iconedlabelplugin.h" +#include "imageviewplugin.h" +#include "qcodeeditplugin.h" #include "qipeditplugin.h" +#include "qpiconfigplugin.h" +#include "qpiconsoleplugin.h" #include "qpointeditplugin.h" #include "qrecteditplugin.h" -#include "ecomboboxplugin.h" -#include "qpiconsoleplugin.h" -#include "iconedlabelplugin.h" -#include "qcodeeditplugin.h" #include "qvarianteditplugin.h" -#include "qpiconfigplugin.h" -#include "evalspinboxplugin.h" -#include "imageviewplugin.h" -#include "scroll_spin_boxplugin.h" #include "rangesliderplugin.h" +#include "scroll_spin_boxplugin.h" +#include "shortcutsplugin.h" +#include "spinsliderplugin.h" QADWidgets::QADWidgets(QObject * parent): QObject(parent) { @@ -39,7 +40,7 @@ QADWidgets::QADWidgets(QObject * parent): QObject(parent) { } -QList QADWidgets::customWidgets() const { +QList QADWidgets::customWidgets() const { return m_widgets; } diff --git a/libs/widgets/plugin/qad_widgets.h b/libs/widgets/plugin/qad_widgets.h index e18e8f9..0627c95 100644 --- a/libs/widgets/plugin/qad_widgets.h +++ b/libs/widgets/plugin/qad_widgets.h @@ -1,23 +1,24 @@ #ifndef QAD_WIDGETS_H #define QAD_WIDGETS_H -#include #include +#include -class QADWidgets: public QObject, public QDesignerCustomWidgetCollectionInterface -{ +class QADWidgets + : public QObject + , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "qad.widgets") #endif + public: explicit QADWidgets(QObject * parent = 0); - virtual QList customWidgets() const; + virtual QList customWidgets() const; private: - QList m_widgets; - + QList m_widgets; }; #endif // QAD_WIDGETS_H diff --git a/libs/widgets/plugin/qcodeeditplugin.cpp b/libs/widgets/plugin/qcodeeditplugin.cpp index 1bd7aaa..7f8b145 100644 --- a/libs/widgets/plugin/qcodeeditplugin.cpp +++ b/libs/widgets/plugin/qcodeeditplugin.cpp @@ -1,5 +1,7 @@ -#include "qcodeedit.h" #include "qcodeeditplugin.h" + +#include "qcodeedit.h" + #include @@ -9,8 +11,7 @@ QCodeEditPlugin::QCodeEditPlugin(QObject * parent): QObject(parent) { void QCodeEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QCodeEditPlugin::domXml() const { QString QCodeEditPlugin::includeFile() const { return QLatin1String("qcodeedit.h"); } - diff --git a/libs/widgets/plugin/qcodeeditplugin.h b/libs/widgets/plugin/qcodeeditplugin.h index 7f733c9..52a1c94 100644 --- a/libs/widgets/plugin/qcodeeditplugin.h +++ b/libs/widgets/plugin/qcodeeditplugin.h @@ -8,8 +8,9 @@ # include #endif -class QCodeEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QCodeEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QCODEEDITPLUGIN_H diff --git a/libs/widgets/plugin/qipeditplugin.cpp b/libs/widgets/plugin/qipeditplugin.cpp index 7cc94dd..3da666b 100644 --- a/libs/widgets/plugin/qipeditplugin.cpp +++ b/libs/widgets/plugin/qipeditplugin.cpp @@ -1,5 +1,7 @@ -#include "qipedit.h" #include "qipeditplugin.h" + +#include "qipedit.h" + #include @@ -9,8 +11,7 @@ QIPEditPlugin::QIPEditPlugin(QObject * parent): QObject(parent) { void QIPEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QIPEditPlugin::domXml() const { QString QIPEditPlugin::includeFile() const { return QLatin1String("qipedit.h"); } - diff --git a/libs/widgets/plugin/qipeditplugin.h b/libs/widgets/plugin/qipeditplugin.h index 7ed24b1..c6c2436 100644 --- a/libs/widgets/plugin/qipeditplugin.h +++ b/libs/widgets/plugin/qipeditplugin.h @@ -8,8 +8,9 @@ # include #endif -class QIPEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QIPEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QIPEDITPLUGIN_H diff --git a/libs/widgets/plugin/qpiconfigplugin.cpp b/libs/widgets/plugin/qpiconfigplugin.cpp index 8fee953..69d238d 100644 --- a/libs/widgets/plugin/qpiconfigplugin.cpp +++ b/libs/widgets/plugin/qpiconfigplugin.cpp @@ -1,5 +1,7 @@ -#include "qpiconfigwidget.h" #include "qpiconfigplugin.h" + +#include "qpiconfigwidget.h" + #include @@ -9,8 +11,7 @@ QPIConfigPlugin::QPIConfigPlugin(QObject * parent): QObject(parent) { void QPIConfigPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QPIConfigPlugin::domXml() const { QString QPIConfigPlugin::includeFile() const { return QLatin1String("qpiconfigwidget.h"); } - diff --git a/libs/widgets/plugin/qpiconfigplugin.h b/libs/widgets/plugin/qpiconfigplugin.h index 77a8b9f..00b140f 100644 --- a/libs/widgets/plugin/qpiconfigplugin.h +++ b/libs/widgets/plugin/qpiconfigplugin.h @@ -8,8 +8,9 @@ # include #endif -class QPIConfigPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QPIConfigPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QPICONFIGPLUGIN_H diff --git a/libs/widgets/plugin/qpiconsoleplugin.cpp b/libs/widgets/plugin/qpiconsoleplugin.cpp index ad1f615..c158070 100644 --- a/libs/widgets/plugin/qpiconsoleplugin.cpp +++ b/libs/widgets/plugin/qpiconsoleplugin.cpp @@ -1,5 +1,7 @@ -#include "qpiconsole.h" #include "qpiconsoleplugin.h" + +#include "qpiconsole.h" + #include @@ -9,8 +11,7 @@ QPIConsolePlugin::QPIConsolePlugin(QObject * parent): QObject(parent) { void QPIConsolePlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QPIConsolePlugin::domXml() const { QString QPIConsolePlugin::includeFile() const { return QLatin1String("qpiconsole.h"); } - diff --git a/libs/widgets/plugin/qpiconsoleplugin.h b/libs/widgets/plugin/qpiconsoleplugin.h index d8a50d7..cd47fea 100644 --- a/libs/widgets/plugin/qpiconsoleplugin.h +++ b/libs/widgets/plugin/qpiconsoleplugin.h @@ -8,8 +8,9 @@ # include #endif -class QPIConsolePlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QPIConsolePlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QPICONSOLEPLUGIN_H diff --git a/libs/widgets/plugin/qpointeditplugin.cpp b/libs/widgets/plugin/qpointeditplugin.cpp index fb4cf8d..493a460 100644 --- a/libs/widgets/plugin/qpointeditplugin.cpp +++ b/libs/widgets/plugin/qpointeditplugin.cpp @@ -1,5 +1,7 @@ -#include "qpointedit.h" #include "qpointeditplugin.h" + +#include "qpointedit.h" + #include @@ -9,8 +11,7 @@ QPointEditPlugin::QPointEditPlugin(QObject * parent): QObject(parent) { void QPointEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QPointEditPlugin::domXml() const { QString QPointEditPlugin::includeFile() const { return QLatin1String("qpointedit.h"); } - diff --git a/libs/widgets/plugin/qpointeditplugin.h b/libs/widgets/plugin/qpointeditplugin.h index b69811d..cec6833 100644 --- a/libs/widgets/plugin/qpointeditplugin.h +++ b/libs/widgets/plugin/qpointeditplugin.h @@ -8,8 +8,9 @@ # include #endif -class QPointEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QPointEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QPOINTEDITPLUGIN_H diff --git a/libs/widgets/plugin/qrecteditplugin.cpp b/libs/widgets/plugin/qrecteditplugin.cpp index 1ed5a2c..44ae1cc 100644 --- a/libs/widgets/plugin/qrecteditplugin.cpp +++ b/libs/widgets/plugin/qrecteditplugin.cpp @@ -1,5 +1,7 @@ -#include "qrectedit.h" #include "qrecteditplugin.h" + +#include "qrectedit.h" + #include @@ -9,8 +11,7 @@ QRectEditPlugin::QRectEditPlugin(QObject * parent): QObject(parent) { void QRectEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QRectEditPlugin::domXml() const { QString QRectEditPlugin::includeFile() const { return QLatin1String("qrectedit.h"); } - diff --git a/libs/widgets/plugin/qrecteditplugin.h b/libs/widgets/plugin/qrecteditplugin.h index 419fbd3..6094900 100644 --- a/libs/widgets/plugin/qrecteditplugin.h +++ b/libs/widgets/plugin/qrecteditplugin.h @@ -8,8 +8,9 @@ # include #endif -class QRectEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QRectEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QRECTEDITPLUGIN_H diff --git a/libs/widgets/plugin/qvarianteditplugin.cpp b/libs/widgets/plugin/qvarianteditplugin.cpp index 733eb88..4792eee 100644 --- a/libs/widgets/plugin/qvarianteditplugin.cpp +++ b/libs/widgets/plugin/qvarianteditplugin.cpp @@ -1,5 +1,7 @@ -#include "qvariantedit.h" #include "qvarianteditplugin.h" + +#include "qvariantedit.h" + #include @@ -9,8 +11,7 @@ QVariantEditPlugin::QVariantEditPlugin(QObject * parent): QObject(parent) { void QVariantEditPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString QVariantEditPlugin::domXml() const { QString QVariantEditPlugin::includeFile() const { return QLatin1String("qvariantedit.h"); } - diff --git a/libs/widgets/plugin/qvarianteditplugin.h b/libs/widgets/plugin/qvarianteditplugin.h index 79eb699..f081025 100644 --- a/libs/widgets/plugin/qvarianteditplugin.h +++ b/libs/widgets/plugin/qvarianteditplugin.h @@ -8,8 +8,9 @@ # include #endif -class QVariantEditPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class QVariantEditPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // QVARIANTEDITPLUGIN_H diff --git a/libs/widgets/plugin/rangesliderplugin.cpp b/libs/widgets/plugin/rangesliderplugin.cpp index e8e743a..333fc9a 100644 --- a/libs/widgets/plugin/rangesliderplugin.cpp +++ b/libs/widgets/plugin/rangesliderplugin.cpp @@ -1,5 +1,7 @@ -#include "rangeslider.h" #include "rangesliderplugin.h" + +#include "rangeslider.h" + #include @@ -9,8 +11,7 @@ RangeSliderPlugin::RangeSliderPlugin(QObject * parent): QObject(parent) { void RangeSliderPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString RangeSliderPlugin::domXml() const { QString RangeSliderPlugin::includeFile() const { return QLatin1String("rangeslider.h"); } - diff --git a/libs/widgets/plugin/rangesliderplugin.h b/libs/widgets/plugin/rangesliderplugin.h index b53d297..3b2ffce 100644 --- a/libs/widgets/plugin/rangesliderplugin.h +++ b/libs/widgets/plugin/rangesliderplugin.h @@ -8,8 +8,9 @@ # include #endif -class RangeSliderPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class RangeSliderPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // RANGESLIDERPLUGIN_H diff --git a/libs/widgets/plugin/scroll_spin_boxplugin.cpp b/libs/widgets/plugin/scroll_spin_boxplugin.cpp index e7c0cd8..55e05fd 100644 --- a/libs/widgets/plugin/scroll_spin_boxplugin.cpp +++ b/libs/widgets/plugin/scroll_spin_boxplugin.cpp @@ -1,5 +1,7 @@ -#include "scroll_spin_box.h" #include "scroll_spin_boxplugin.h" + +#include "scroll_spin_box.h" + #include @@ -9,8 +11,7 @@ ScrollSpinBoxPlugin::ScrollSpinBoxPlugin(QObject * parent): QObject(parent) { void ScrollSpinBoxPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString ScrollSpinBoxPlugin::domXml() const { QString ScrollSpinBoxPlugin::includeFile() const { return QLatin1String("scroll_spin_box.h"); } - diff --git a/libs/widgets/plugin/scroll_spin_boxplugin.h b/libs/widgets/plugin/scroll_spin_boxplugin.h index 3c92283..43236e2 100644 --- a/libs/widgets/plugin/scroll_spin_boxplugin.h +++ b/libs/widgets/plugin/scroll_spin_boxplugin.h @@ -8,8 +8,9 @@ # include #endif -class ScrollSpinBoxPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class ScrollSpinBoxPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif // SCROLLSPINBOXPLUGIN_H diff --git a/libs/widgets/plugin/shortcutsplugin.cpp b/libs/widgets/plugin/shortcutsplugin.cpp index c5eb5e9..1386775 100644 --- a/libs/widgets/plugin/shortcutsplugin.cpp +++ b/libs/widgets/plugin/shortcutsplugin.cpp @@ -1,5 +1,7 @@ -#include "shortcuts.h" #include "shortcutsplugin.h" + +#include "shortcuts.h" + #include @@ -9,8 +11,7 @@ ShortcutsPlugin::ShortcutsPlugin(QObject * parent): QObject(parent) { void ShortcutsPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString ShortcutsPlugin::domXml() const { QString ShortcutsPlugin::includeFile() const { return QLatin1String("shortcuts.h"); } - diff --git a/libs/widgets/plugin/shortcutsplugin.h b/libs/widgets/plugin/shortcutsplugin.h index 7fcc0d0..b15a80e 100644 --- a/libs/widgets/plugin/shortcutsplugin.h +++ b/libs/widgets/plugin/shortcutsplugin.h @@ -8,8 +8,9 @@ # include #endif -class ShortcutsPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class ShortcutsPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif diff --git a/libs/widgets/plugin/spinsliderplugin.cpp b/libs/widgets/plugin/spinsliderplugin.cpp index 683312d..b28e554 100644 --- a/libs/widgets/plugin/spinsliderplugin.cpp +++ b/libs/widgets/plugin/spinsliderplugin.cpp @@ -1,5 +1,7 @@ -#include "spinslider.h" #include "spinsliderplugin.h" + +#include "spinslider.h" + #include @@ -9,8 +11,7 @@ SpinSliderPlugin::SpinSliderPlugin(QObject * parent): QObject(parent) { void SpinSliderPlugin::initialize(QDesignerFormEditorInterface * /* core */) { - if (m_initialized) - return; + if (m_initialized) return; // Add extension registrations, etc. here @@ -66,4 +67,3 @@ QString SpinSliderPlugin::domXml() const { QString SpinSliderPlugin::includeFile() const { return QLatin1String("spinslider.h"); } - diff --git a/libs/widgets/plugin/spinsliderplugin.h b/libs/widgets/plugin/spinsliderplugin.h index 858e383..68d23c6 100644 --- a/libs/widgets/plugin/spinsliderplugin.h +++ b/libs/widgets/plugin/spinsliderplugin.h @@ -8,8 +8,9 @@ # include #endif -class SpinSliderPlugin: public QObject, public QDesignerCustomWidgetInterface -{ +class SpinSliderPlugin + : public QObject + , public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) @@ -30,7 +31,6 @@ public: private: bool m_initialized; - }; #endif diff --git a/libs/widgets/propertystorage_editor.cpp b/libs/widgets/propertystorage_editor.cpp index ced6557..07caae2 100644 --- a/libs/widgets/propertystorage_editor.cpp +++ b/libs/widgets/propertystorage_editor.cpp @@ -1,6 +1,8 @@ #include "propertystorage_editor.h" + #include "propertystorage.h" #include "qvariantedit.h" + #include #include @@ -24,7 +26,7 @@ void PropertyStorageEditor::clear() { bool PropertyStorageEditor::isEmpty() const { - return static_cast(layout())->count() == 0; + return static_cast(layout())->count() == 0; } @@ -32,9 +34,9 @@ void PropertyStorageEditor::setStorage(PropertyStorage * s) { clear(); storage = s; if (!storage) return; - int r = 0; - auto layoutProps = static_cast(layout()); - for (const PropertyStorage::Property & p : *storage) { + int r = 0; + auto layoutProps = static_cast(layout()); + for (const PropertyStorage::Property & p: *storage) { auto lbl = new QLabel(p.name); _widgets << lbl; lbl->setAlignment(Qt::AlignVCenter | Qt::AlignRight); @@ -44,9 +46,12 @@ void PropertyStorageEditor::setStorage(PropertyStorage * s) { ve->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); ve->setMinimumWidth(50); connect(ve, SIGNAL(valueChanged(QVariant)), this, SIGNAL(changed())); - layoutProps->addWidget(ve, r, 1); _widgets << ve; - lbl = new QLabel(p.comment); lbl->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); - layoutProps->addWidget(lbl, r, 2); _widgets << lbl; + layoutProps->addWidget(ve, r, 1); + _widgets << ve; + lbl = new QLabel(p.comment); + lbl->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); + layoutProps->addWidget(lbl, r, 2); + _widgets << lbl; ++r; } } @@ -55,13 +60,13 @@ void PropertyStorageEditor::setStorage(PropertyStorage * s) { void PropertyStorageEditor::applyProperties() { if (!storage) return; QList & props(storage->properties()); - auto layoutProps = static_cast(layout()); + auto layoutProps = static_cast(layout()); for (int r = 0; r < layoutProps->rowCount(); ++r) { if (layoutProps->itemAtPosition(r, 0) == nullptr || layoutProps->itemAtPosition(r, 1) == nullptr) { continue; } - QLabel * lbl = qobject_cast(layoutProps->itemAtPosition(r, 0)->widget()); - QVariantEdit * ve = qobject_cast(layoutProps->itemAtPosition(r, 1)->widget()); + QLabel * lbl = qobject_cast(layoutProps->itemAtPosition(r, 0)->widget()); + QVariantEdit * ve = qobject_cast(layoutProps->itemAtPosition(r, 1)->widget()); if (lbl == nullptr || ve == nullptr) { continue; } diff --git a/libs/widgets/propertystorage_editor.h b/libs/widgets/propertystorage_editor.h index 260a9e4..e0e6758 100644 --- a/libs/widgets/propertystorage_editor.h +++ b/libs/widgets/propertystorage_editor.h @@ -1,49 +1,51 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef PROPERTYSTORAGEEDITOR_H #define PROPERTYSTORAGEEDITOR_H -#include #include "qad_widgets_export.h" +#include + class PropertyStorage; class QAD_WIDGETS_EXPORT PropertyStorageEditor: public QWidget { Q_OBJECT + public: explicit PropertyStorageEditor(QWidget * parent = nullptr); ~PropertyStorageEditor() override; - + void clear(); bool isEmpty() const; void setStorage(PropertyStorage * s); void applyProperties(); - + signals: - void resetStorageRequest(PropertyStorage * ); + void resetStorageRequest(PropertyStorage *); void changed(); private: - QList _widgets; + QList _widgets; PropertyStorage * storage; }; diff --git a/libs/widgets/qcodeedit.cpp b/libs/widgets/qcodeedit.cpp index 2d49827..386ae75 100644 --- a/libs/widgets/qcodeedit.cpp +++ b/libs/widgets/qcodeedit.cpp @@ -1,23 +1,25 @@ #include "qcodeedit.h" -#include "ui_qcodeedit.h" -#include "qcodeedit_completer_p.h" + #include "ecombobox.h" -#include "qad_types.h" #include "iconedlabel.h" -#include +#include "qad_types.h" +#include "qcodeedit_completer_p.h" +#include "ui_qcodeedit.h" + +#include +#include #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, 0, 0) # include #endif @@ -39,21 +41,20 @@ public: } QCodeEdit * ce; - }; QCodeEdit::QCodeEdit(QWidget * parent): QWidget(parent), ui(new Ui::QCodeEdit) { overlay = nullptr; prev_lc = auto_comp_pl = cur_search_ind = pos_press = pos_el_press = -1; - timer_parse = 0; + timer_parse = 0; _ignore_focus_out = _destructor = _replacing = cursor_state = block_sel_state = false; - _first = true; - comment_text = "//"; + _first = true; + comment_text = "//"; qRegisterMetaType(); qRegisterMetaType(); ui->setupUi(this); - overlay = new _QCE_Viewport(ui->textCode->viewport()); + overlay = new _QCE_Viewport(ui->textCode->viewport()); overlay->ce = this; overlay->show(); ui->widgetSearch->hide(); @@ -86,7 +87,7 @@ QCodeEdit::QCodeEdit(QWidget * parent): QWidget(parent), ui(new Ui::QCodeEdit) { lbl_help[lhF1]->setIcon(QIcon(":/icons/f1.png")); lbl_help[lhF1]->setText(tr("Press F1 for details")); help_visible = true; - completer = new QCodeEditCompleter(); + completer = new QCodeEditCompleter(); cursor_width = qMax(qRound(fontHeight(this) / 10.), 1); ui->textCode->setCursorWidth(0); @@ -98,28 +99,34 @@ QCodeEdit::QCodeEdit(QWidget * parent): QWidget(parent), ui(new Ui::QCodeEdit) { #else ui->textLines->setFixedWidth(ui->textLines->fontMetrics().width(" ")); #endif - - QAction * a = new QAction(this); ui->textCode->addAction(a); + + QAction * a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Shift+Tab")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(deindent())); - a = new QAction(this); ui->textCode->addAction(a); + a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Ctrl+D")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(deleteLine())); - a = new QAction(this); ui->textCode->addAction(a); + a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Ctrl+Return")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(newLine())); - a = new QAction(this); ui->textCode->addAction(a); + a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Ctrl+Up")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(scrollUp())); - a = new QAction(this); ui->textCode->addAction(a); + a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Ctrl+Down")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(scrollDown())); - a = new QAction(this); ui->textCode->addAction(a); + a = new QAction(this); + ui->textCode->addAction(a); a->setShortcut(QKeySequence("Ctrl+Shift+Return")); a->setShortcutContext(Qt::WidgetShortcut); connect(a, SIGNAL(triggered()), this, SLOT(newLineBefore())); @@ -135,7 +142,7 @@ QCodeEdit::QCodeEdit(QWidget * parent): QWidget(parent), ui(new Ui::QCodeEdit) { connect(a, SIGNAL(triggered(bool)), this, SLOT(search_triggered())); addAction(a); - connect(completer, SIGNAL(itemDoubleClicked(QTreeWidgetItem * ,int)), this, SLOT(commitCompletition())); + connect(completer, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(commitCompletition())); connect(completer, SIGNAL(commit()), this, SLOT(commitCompletition())); connect(completer, SIGNAL(gotoHRef(QCodeEdit::ACEntry)), this, SLOT(gotoHelpHRef(QCodeEdit::ACEntry))); connect(ui->textCode->verticalScrollBar(), SIGNAL(valueChanged(int)), ui->textLines->verticalScrollBar(), SLOT(setValue(int))); @@ -150,7 +157,12 @@ QCodeEdit::QCodeEdit(QWidget * parent): QWidget(parent), ui(new Ui::QCodeEdit) { connect(ui->comboSearch->lineEdit(), SIGNAL(returnPressed()), this, SLOT(searchNext())); connect(ui->comboReplace->lineEdit(), SIGNAL(returnPressed()), this, SLOT(on_buttonReplaceSearch_clicked())); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - connect(qApp, &QGuiApplication::focusWindowChanged, this, [this](QWindow*w){if (w == nullptr) {hideHelp(); completer->hide();}}); + connect(qApp, &QGuiApplication::focusWindowChanged, this, [this](QWindow * w) { + if (w == nullptr) { + hideHelp(); + completer->hide(); + } + }); #endif updateLines(); timer_blink = startTimer(QApplication::cursorFlashTime() / 2); @@ -191,8 +203,7 @@ void QCodeEdit::setDocument(QTextDocument * doc) { documentChanged(nullptr); return; } - if (!qobject_cast(doc->documentLayout())) - doc->setDocumentLayout(new QPlainTextDocumentLayout(doc)); + if (!qobject_cast(doc->documentLayout())) doc->setDocumentLayout(new QPlainTextDocumentLayout(doc)); ui->textCode->setDocument(doc); cursor_width = qMax(qRound(fontHeight(this) / 10.), 1); ui->textCode->setCursorWidth(0); @@ -303,14 +314,26 @@ void QCodeEdit::registerAutoCompletitionClass(int id, QCodeEdit::ACClassType ac_ int QCodeEdit::skipRange(const QString & s, int pos, QChar oc, QChar cc, QChar sc) { - int cnt = 0; + int cnt = 0; bool skip = false; for (int i = pos - 1; i >= 0; --i) { QChar c = s[i]; - if (skip) {skip = false; continue;} - if (c == sc) {skip = true; continue;} - if (c == cc) {cnt++; continue;} - if (c == oc) {cnt--; if (cnt == 0) return i;} + if (skip) { + skip = false; + continue; + } + if (c == sc) { + skip = true; + continue; + } + if (c == cc) { + cnt++; + continue; + } + if (c == oc) { + cnt--; + if (cnt == 0) return i; + } } return -1; } @@ -320,7 +343,7 @@ int QCodeEdit::skipCWord(const QString & s, int pos) { QChar pc(0), c(0); for (int i = pos - 1; i >= 0; --i) { pc = c; - c = s[i]; + c = s[i]; if (c.isLetterOrNumber() || (c.toLatin1() == '_')) continue; if (pc.isLetter() || (pc.toLatin1() == '_')) return i + 1; return -1; @@ -339,8 +362,15 @@ bool QCodeEdit::matchWritten(QString s, QString w) { bool ns = false, bl = true; while (sp < s.size()) { if (ns || s[sp].toLatin1() == '_') { - if (s[sp].toLatin1() == '_') {sp++; bl = false; continue;} - if (s[sp].isLower() && bl) {sp++; continue;} + if (s[sp].toLatin1() == '_') { + sp++; + bl = false; + continue; + } + if (s[sp].isLower() && bl) { + sp++; + continue; + } if (s[sp].toLower() != wc) return false; } if (s[sp].toLower() == wc) break; @@ -384,7 +414,7 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { if (!isEnabled()) { break; } - tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); + tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); tc.movePosition(QTextCursor::EndOfLine); pos_el_press = tc.anchor(); tc.movePosition(QTextCursor::StartOfLine); @@ -397,7 +427,7 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { return true; case QEvent::MouseMove: if (!isEnabled()) break; - tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); + tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); tc.movePosition(QTextCursor::StartOfLine); if (pos_press == tc.anchor()) { if (!tc.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor)) { @@ -425,16 +455,15 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { } } if (o == completer) { - //qDebug() << o << e; - if (e->type() == QEvent::WindowActivate) - _ignore_focus_out = true; - //qDebug() << e; + // qDebug() << o << e; + if (e->type() == QEvent::WindowActivate) _ignore_focus_out = true; + // qDebug() << e; return QWidget::eventFilter(o, e); } if (o == ui->comboSearch || o == ui->comboReplace) { - //qDebug() << o << e; + // qDebug() << o << e; if (e->type() == QEvent::KeyPress) { - if (static_cast(e)->key() == Qt::Key_Escape) { + if (static_cast(e)->key() == Qt::Key_Escape) { hideHelp(); if (completer->isVisible()) completer->hide(); @@ -442,7 +471,7 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { hideSearch(); } } - //qDebug() << e; + // qDebug() << e; return QWidget::eventFilter(o, e); } if (ui->textCode) { @@ -452,75 +481,62 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { cancelBlockSelection(); completer->hide(); hideHelp(); - auto me = static_cast(e); + auto me = static_cast(e); if (me->modifiers().testFlag(Qt::ControlModifier) && (me->button() == Qt::LeftButton)) - if (!hasBlockSelection() && !ui->textCode->textCursor().hasSelection()) - gotoLink(); - } break; + if (!hasBlockSelection() && !ui->textCode->textCursor().hasSelection()) gotoLink(); + } break; case QEvent::MouseMove: { if (!completer->isHidden()) break; - auto me = static_cast(e); - if (me->buttons() != 0) - switchBlockSelection(); + auto me = static_cast(e); + if (me->buttons() != 0) switchBlockSelection(); if (me->modifiers().testFlag(Qt::ControlModifier)) - if (!hasBlockSelection() && !ui->textCode->textCursor().hasSelection()) - showLink(); - } break; - case QEvent::Paint: - resizeOverlay(); - break; + if (!hasBlockSelection() && !ui->textCode->textCursor().hasSelection()) showLink(); + } break; + case QEvent::Paint: resizeOverlay(); break; case QEvent::DragMove: if (!isEnabled()) break; drag_cursor = ui->textCode->cursorForPosition( #if QT_VERSION_MAJOR <= 5 - static_cast(e)->pos() + static_cast(e)->pos() #else - static_cast(e)->position().toPoint() + static_cast(e)->position().toPoint() #endif - ); + ); repaintCursor(); break; case QEvent::MouseButtonRelease: case QEvent::DragLeave: - case QEvent::Drop: - cancelDragCursor(); - break; + case QEvent::Drop: cancelDragCursor(); break; default: break; } return QWidget::eventFilter(o, e); } if (o == ui->textCode) { - //qDebug() << e; + // qDebug() << e; QMetaObject::invokeMethod(this, "syncScrolls", Qt::QueuedConnection); switch (e->type()) { case QEvent::ToolTip: if (completer->isHidden()) { - QTextCursor tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); + QTextCursor tc = ui->textCode->cursorForPosition(static_cast(e)->pos()); tc.select(QTextCursor::WordUnderCursor); raiseHelp(tc); } break; case QEvent::KeyPress: - //qDebug() << "key" << ke; - if (codeKeyEvent(static_cast(e))) - return true; - break; - case QEvent::KeyRelease: - hideLink(); + // qDebug() << "key" << ke; + if (codeKeyEvent(static_cast(e))) return true; break; + case QEvent::KeyRelease: hideLink(); break; case QEvent::FocusOut: if (_ignore_focus_out) { _ignore_focus_out = false; break; } - case QEvent::FocusIn: - createBlockSelection(); - break; + case QEvent::FocusIn: createBlockSelection(); break; case QEvent::Hide: - case QEvent::HideToParent: - hideLink(); + case QEvent::HideToParent: hideLink(); case QEvent::MouseButtonPress: - //qDebug() << e; + // qDebug() << e; completer->hide(); hideHelp(); default: break; @@ -531,7 +547,7 @@ bool QCodeEdit::eventFilter(QObject * o, QEvent * e) { } -void QCodeEdit::showEvent(QShowEvent * ) { +void QCodeEdit::showEvent(QShowEvent *) { if (!_first) return; _first = false; completer->installEventFilter(this); @@ -564,12 +580,11 @@ void QCodeEdit::leaveEvent(QEvent * e) { void QCodeEdit::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - lbl_help[lhF1]->setText(tr("Press F1 for details")); - break; - default: - break; + case QEvent::LanguageChange: + ui->retranslateUi(this); + lbl_help[lhF1]->setText(tr("Press F1 for details")); + break; + default: break; } } @@ -707,7 +722,8 @@ bool QCodeEdit::codeKeyEvent(QKeyEvent * ke) { default: break; } if (!ke->text().isEmpty()) { - if (hasBlockSelection() && (ke->modifiers() == 0 || ke->modifiers() == Qt::ShiftModifier || ke->modifiers() == Qt::KeypadModifier)) { + if (hasBlockSelection() && + (ke->modifiers() == 0 || ke->modifiers() == Qt::ShiftModifier || ke->modifiers() == Qt::KeypadModifier)) { insertBlockSelection(ke->text()); return true; } @@ -728,9 +744,9 @@ bool QCodeEdit::codeKeyEvent(QKeyEvent * ke) { void QCodeEdit::toggleComment() { QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); @@ -741,7 +757,7 @@ void QCodeEdit::toggleComment() { tc.movePosition(QTextCursor::StartOfLine); ss = tc.position(); tc.setPosition(se); - tc.movePosition(QTextCursor::EndOfLine ); + tc.movePosition(QTextCursor::EndOfLine); se = tc.position(); tc.setPosition(ss); bool need_comment = false; @@ -754,7 +770,7 @@ void QCodeEdit::toggleComment() { comms[line] = true; } else { need_comment = true; - comms[line] = false; + comms[line] = false; } } else { comms[line] = false; @@ -816,25 +832,25 @@ void QCodeEdit::highlightBrackets() { QTextEdit::ExtraSelection es; stc.setPosition(stc.position()); QTextCursor::MoveOperation mop[2] = {QTextCursor::Left, QTextCursor::Right}; - QString mbr[2] = {")]}>", "([{<"}; + QString mbr[2] = {")]}>", "([{<"}; for (int d = 0; d < 2; ++d) { tc = stc; tc.movePosition(mop[d], QTextCursor::KeepAnchor); if (!tc.selectedText().isEmpty()) { char ch = tc.selectedText()[0].toLatin1(); if (mbr[d].contains(ch)) { - es = es_bracket; + es = es_bracket; es.cursor = tc; es_brackets << es; QTextCursor ftc = tc; - int bcnt = 1; - char fch = antiBracket(ch); + int bcnt = 1; + char fch = antiBracket(ch); while (bcnt > 0) { ftc.setPosition(ftc.position()); if (!ftc.movePosition(mop[d], QTextCursor::KeepAnchor)) break; - //qDebug() << tc.selectedText(); + // qDebug() << tc.selectedText(); if (ftc.selectedText().isEmpty()) break; - if (ftc.selectedText()[0].toLatin1() == ch) ++bcnt; + if (ftc.selectedText()[0].toLatin1() == ch) ++bcnt; if (ftc.selectedText()[0].toLatin1() == fch) --bcnt; } if (bcnt == 0) { @@ -853,9 +869,8 @@ void QCodeEdit::highlightBrackets() { void QCodeEdit::applyExtraSelection() { - ui->textCode->setExtraSelections(QList() << es_line << es_selected - << es_custom << es_brackets << es_search_list << es_cursor - << es_link << es_blockselection); + ui->textCode->setExtraSelections(QList() << es_line << es_selected << es_custom << es_brackets + << es_search_list << es_cursor << es_link << es_blockselection); } @@ -911,20 +926,20 @@ QRect QCodeEdit::blockSelectionRect() { QPoint ps(block_start_cursor.positionInBlock(), block_start_cursor.blockNumber()); QPoint pe(tc.positionInBlock(), tc.blockNumber()); return (ui->textCode->cursorRect(tc) | ui->textCode->cursorRect(block_start_cursor)) - .translated(ui->textCode->horizontalScrollBar()->value(), 0); + .translated(ui->textCode->horizontalScrollBar()->value(), 0); } QVector QCodeEdit::blockSelectionCursors(QRect bsr) { QVector ret; - //qDebug() << bsr; + // qDebug() << bsr; int sline = ui->textCode->cursorForPosition(bsr.topLeft()).blockNumber(); int eline = ui->textCode->cursorForPosition(bsr.bottomRight()).blockNumber(); for (int l = sline; l <= eline; ++l) { QTextCursor stc(ui->textCode->document()->findBlockByNumber(l)), etc; QRect stc_rect = ui->textCode->cursorRect(stc); - stc = ui->textCode->cursorForPosition(stc_rect.center() + QPoint(bsr.left() , 0)); - etc = ui->textCode->cursorForPosition(stc_rect.center() + QPoint(bsr.right(), 0)); + stc = ui->textCode->cursorForPosition(stc_rect.center() + QPoint(bsr.left(), 0)); + etc = ui->textCode->cursorForPosition(stc_rect.center() + QPoint(bsr.right(), 0)); stc.setPosition(etc.position(), QTextCursor::KeepAnchor); ret << stc; } @@ -941,8 +956,8 @@ void QCodeEdit::drawCursor() { if (!isEnabled() || !ui->textCode->hasFocus()) return; QPainter p(overlay); QTextCursor tc = textCursor(); - //qDebug() << block_start_cursor.position() << tc.position(); - QRect line = cursorRect(); + // qDebug() << block_start_cursor.position() << tc.position(); + QRect line = cursorRect(); if (cursor_state && ui->textCode->hasFocus()) { line.adjust(0, 1, 0, -1); p.setCompositionMode(QPainter::CompositionMode_Difference); @@ -964,7 +979,7 @@ bool QCodeEdit::hasBlockSelection() const { void QCodeEdit::startBlockSelection() { if (!hasBlockSelection()) { - QTextCursor tc = textCursor(); + QTextCursor tc = textCursor(); block_start_cursor = tc; block_start_cursor.setPosition(tc.selectionStart()); } @@ -985,16 +1000,16 @@ void QCodeEdit::switchBlockSelection(QKeyEvent * ke) { } if (alt) { startBlockSelection(); - QTextCursor tc = ui->textCode->textCursor(); + QTextCursor tc = ui->textCode->textCursor(); QTextCursor::MoveOperation op = QTextCursor::NoMove; if (!ke) { return; } switch (ke->key()) { - case Qt::Key_Left : op = QTextCursor::Left ; break; + case Qt::Key_Left: op = QTextCursor::Left; break; case Qt::Key_Right: op = QTextCursor::Right; break; - case Qt::Key_Up : op = QTextCursor::Up ; break; - case Qt::Key_Down : op = QTextCursor::Down ; break; + case Qt::Key_Up: op = QTextCursor::Up; break; + case Qt::Key_Down: op = QTextCursor::Down; break; default: break; } if (op != QTextCursor::NoMove) { @@ -1013,7 +1028,7 @@ bool QCodeEdit::removeBlockSelection(bool is_del) { return false; } QRect bsr = blockSelectionRect(); - bool del = false; + bool del = false; bool back = false; if (bsr.width() <= 1) { if (is_del) { @@ -1023,19 +1038,19 @@ bool QCodeEdit::removeBlockSelection(bool is_del) { } } QVector clist = blockSelectionCursors(bsr); - QTextCursor tc = ui->textCode->textCursor(); + QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int bspx = ui->textCode->cursorRect(block_start_cursor).center().x(); + int bspx = ui->textCode->cursorRect(block_start_cursor).center().x(); int nullw = ui->textCode->fontMetrics(). #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) - horizontalAdvance + horizontalAdvance #else - width + width #endif - (" "); + (" "); int min_dist = nullw / 2; - int new_pos = -1; - for (QTextCursor & c : clist) { + int new_pos = -1; + for (QTextCursor & c: clist) { if (del || back) { if (qAbs(bspx - ui->textCode->cursorRect(c).center().x()) > min_dist) { continue; @@ -1045,7 +1060,7 @@ bool QCodeEdit::removeBlockSelection(bool is_del) { if (line != c.blockNumber()) { continue; } - //qDebug() << qAbs(bspx - ui->textCode->cursorRect(c).center().x()) << min_dist; + // qDebug() << qAbs(bspx - ui->textCode->cursorRect(c).center().x()) << min_dist; } c.removeSelectedText(); if (c.blockNumber() == tc.blockNumber()) { @@ -1064,24 +1079,24 @@ void QCodeEdit::insertBlockSelection(QString text) { return; } QTextCursor tc = ui->textCode->textCursor(); - QRect bsr = blockSelectionRect(); - //qDebug() << "___" << bsr; - int scrl = ui->textCode->horizontalScrollBar()->value(); + QRect bsr = blockSelectionRect(); + // qDebug() << "___" << bsr; + int scrl = ui->textCode->horizontalScrollBar()->value(); if (bsr.width() > 1) { removeBlockSelection(false); bsr = blockSelectionRect(); - //qDebug() << "del" << bsr; + // qDebug() << "del" << bsr; } tc.beginEditBlock(); int nullw = ui->textCode->fontMetrics(). #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) - horizontalAdvance + horizontalAdvance #else - width + width #endif - (" "); + (" "); QVector clist = blockSelectionCursors(bsr); - for (QTextCursor & c : clist) { + for (QTextCursor & c: clist) { c.removeSelectedText(); int spcnt = (bsr.left() - ui->textCode->cursorRect(c).center().x() - scrl) / nullw; if (spcnt > 0) { @@ -1102,7 +1117,7 @@ void QCodeEdit::createBlockSelection() { es.format.setForeground(palette().brush(QPalette::HighlightedText)); es.format.setBackground(palette().brush(QPalette::Highlight)); QVector clist = blockSelectionCursors(blockSelectionRect()); - for (QTextCursor & c : clist) { + for (QTextCursor & c: clist) { es.cursor = c; es_blockselection << es; } @@ -1145,7 +1160,7 @@ void QCodeEdit::searchAll() { void QCodeEdit::search_triggered() { QTextCursor tc = ui->textCode->textCursor(); - QString st = tc.selectedText(); + QString st = tc.selectedText(); if (st.isEmpty()) { tc.select(QTextCursor::WordUnderCursor); st = tc.selectedText(); @@ -1159,7 +1174,8 @@ void QCodeEdit::search_triggered() { void QCodeEdit::syncScrolls() { ui->textLines->verticalScrollBar()->setValue(ui->textCode->verticalScrollBar()->value()); - ui->textLines->setHorizontalScrollBarPolicy(ui->textCode->horizontalScrollBar()->isVisible() ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff); + ui->textLines->setHorizontalScrollBarPolicy(ui->textCode->horizontalScrollBar()->isVisible() ? Qt::ScrollBarAlwaysOn + : Qt::ScrollBarAlwaysOff); } @@ -1196,9 +1212,9 @@ void QCodeEdit::deleteLine() { void QCodeEdit::copyLineUp() { QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); @@ -1237,9 +1253,9 @@ void QCodeEdit::copyLineUp() { void QCodeEdit::copyLineDown() { QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); @@ -1281,10 +1297,10 @@ void QCodeEdit::copyLineDown() { void QCodeEdit::moveLineUp() { QTextCursor tc = ui->textCode->textCursor(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); - QString st_ = tc.selection().toPlainText(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); + QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); se--; @@ -1333,10 +1349,10 @@ void QCodeEdit::moveLineUp() { void QCodeEdit::moveLineDown() { QTextCursor tc = ui->textCode->textCursor(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); - QString st_ = tc.selection().toPlainText(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); + QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); se--; @@ -1387,9 +1403,9 @@ void QCodeEdit::moveLineDown() { void QCodeEdit::indent() { QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); @@ -1421,9 +1437,9 @@ void QCodeEdit::indent() { void QCodeEdit::deindent() { QTextCursor tc = ui->textCode->textCursor(); tc.beginEditBlock(); - int ss = tc.selectionStart(); - int ss_ = ss; - int se = tc.selectionEnd(); + int ss = tc.selectionStart(); + int ss_ = ss; + int se = tc.selectionEnd(); QString st_ = tc.selection().toPlainText(); if (st_.endsWith("\n")) { st_.chop(1); @@ -1461,8 +1477,7 @@ void QCodeEdit::deindent() { } se_ -= rs; tc.movePosition(QTextCursor::StartOfLine); - if (!tc.movePosition(QTextCursor::Down)) - break; + if (!tc.movePosition(QTextCursor::Down)) break; } tc.setPosition(ss_); tc.setPosition(se_, QTextCursor::KeepAnchor); @@ -1472,7 +1487,7 @@ void QCodeEdit::deindent() { void QCodeEdit::autoIndent() { - QTextCursor tc = ui->textCode->textCursor(); + QTextCursor tc = ui->textCode->textCursor(); QTextCursor stc = tc; tc.movePosition(QTextCursor::StartOfLine); if (!tc.movePosition(QTextCursor::Up)) { @@ -1517,7 +1532,7 @@ void QCodeEdit::showLink() { es_link.cursor = tc; overlay->setCursor(tc.isNull() ? Qt::IBeamCursor : Qt::PointingHandCursor); applyExtraSelection(); - //qDebug() << "showLink" << tc.selectedText() << link_entry.type << link_entry.name; + // qDebug() << "showLink" << tc.selectedText() << link_entry.type << link_entry.name; } @@ -1526,7 +1541,7 @@ void QCodeEdit::hideLink() { overlay->setCursor(Qt::IBeamCursor); link_entry = ACEntry(); applyExtraSelection(); - //qDebug() << "hideLink"; + // qDebug() << "hideLink"; } @@ -1619,7 +1634,7 @@ QString QCodeEdit::selectArg(QString s, int arg) { s.chop(1); } QStringList al = s.split(","); - QString ret = ss + "("; + QString ret = ss + "("; for (int i = 0; i < al.size(); ++i) { if (i > 0) { ret += ", "; @@ -1638,7 +1653,7 @@ QString QCodeEdit::selectArg(QString s, int arg) { QCodeEdit::ACEntry QCodeEdit::findEntryOnCursor(QTextCursor tc, int arg, ACClass * acc, QPair * scope) { - bool ok = false; + bool ok = false; QPair sc = getScope(tc, &ok); if (scope) { *scope = sc; @@ -1652,10 +1667,10 @@ QCodeEdit::ACEntry QCodeEdit::findEntryOnCursor(QTextCursor tc, int arg, ACClass } ok = false; ACList acl(autoCompletitionList(sc.first, sc.second)); - for (const ACSection & i : acl) { - for (const ACEntry & s : i.second) { + for (const ACSection & i: acl) { + for (const ACEntry & s: i.second) { QString ts = s.name; - //qDebug() << ts << st; + // qDebug() << ts << st; if (ts != st) { if (ts.startsWith(st)) { ts.remove(0, st.size()); @@ -1669,7 +1684,7 @@ QCodeEdit::ACEntry QCodeEdit::findEntryOnCursor(QTextCursor tc, int arg, ACClass continue; } } - //qDebug() << s.second << st; + // qDebug() << s.second << st; if (acc) { *acc = ac_classes.value(i.first); } @@ -1696,10 +1711,10 @@ void QCodeEdit::raiseHelp(QTextCursor tc, int arg) { } lbl_help[lhHint]->setText(hint); lbl_help[lhHint]->setHidden(hint.isEmpty()); - //qDebug() << "help found" << tc.selectionStart() << tc.selectionEnd(); + // qDebug() << "help found" << tc.selectionStart() << tc.selectionEnd(); es_cursor.cursor = tc; applyExtraSelection(); - //tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor); + // tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor); lbl_help[lhMain]->setFont(font()); lbl_help[lhF1]->setVisible(!e.help_href.isEmpty() && help_visible); qApp->processEvents(); @@ -1715,14 +1730,14 @@ void QCodeEdit::raiseHelp(QTextCursor tc, int arg) { QPoint whp; whp.setX(whr.left() - whr.width() - (widget_help->width() - whr.width()) / 2); whp.setY(whr.top() - widget_help->height() - (fontHeight(this) / 3)); - //qDebug() << whr << whp << widget_help->width() << ", " << st; + // qDebug() << whr << whp << widget_help->width() << ", " << st; widget_help->move(ui->textCode->viewport()->mapToGlobal(whp)); widget_help->show(); widget_help->raise(); - help_entry = e; + help_entry = e; cursor_scope = scope.first; cursor_scope << scope.second; - //qDebug() << "tooltip" << st; + // qDebug() << "tooltip" << st; } @@ -1774,7 +1789,7 @@ QTextCursor QCodeEdit::functionStart(QTextCursor tc, int * arg) { } QTextCursor ret(ui->textCode->document()); ret.setPosition(i); - //qDebug() << "found" << i << a; + // qDebug() << "found" << i << a; return ret; } @@ -1801,7 +1816,7 @@ QCodeEdit::ACList QCodeEdit::wordsCompletitionList(const QString & written) cons acwl.removeDuplicates(); ACSection acl; acl.first = -1; - for (const QString & s : acwl) { + for (const QString & s: acwl) { acl.second << ACEntry("", s); } ret << acl; @@ -1831,14 +1846,14 @@ QPair QCodeEdit::getScope(QTextCursor tc, bool * ok) { return ret; } } - QString doc = ui->textCode->toPlainText(); + QString doc = ui->textCode->toPlainText(); auto_comp_pl = line; completer->clear(); int spos = tc.position(), cpos = spos; tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor); QStringList scope; QString written = tc.selectedText().trimmed(); - //qDebug() << "\n*** invokeAutoCompletition ***"; + // qDebug() << "\n*** invokeAutoCompletition ***"; if (written != "_" && !written.leftJustified(1)[0].isLetterOrNumber()) { written.clear(); } else { @@ -1849,13 +1864,13 @@ QPair QCodeEdit::getScope(QTextCursor tc, bool * ok) { } while (cpos >= 0) { cpos--; - //qDebug() << "char =" << doc.mid(cpos, 1); + // qDebug() << "char =" << doc.mid(cpos, 1); if (doc.mid(cpos, 1) != ".") break; - QChar c = doc.mid(cpos - 1, 1).leftJustified(1)[0]; + QChar c = doc.mid(cpos - 1, 1).leftJustified(1)[0]; int ppos = cpos; if (c == '\"' || c == ')' || c == ']') { cpos = skipRange(doc, cpos, pairChar(c), c, '\\'); - //qDebug() << "range" << cpos; + // qDebug() << "range" << cpos; if (cpos < 0) break; } int npos = skipCWord(doc, cpos); @@ -1863,7 +1878,7 @@ QPair QCodeEdit::getScope(QTextCursor tc, bool * ok) { scope.push_front(doc.mid(npos, ppos - npos)); cpos = npos; } - ret.first = scope; + ret.first = scope; ret.second = written; if (ok) *ok = true; return ret; @@ -1871,17 +1886,17 @@ QPair QCodeEdit::getScope(QTextCursor tc, bool * ok) { void QCodeEdit::invokeAutoCompletition(bool force) { - int arg = -1; + int arg = -1; QTextCursor htc = functionStart(ui->textCode->textCursor(), &arg); if (!htc.isNull()) { - //qDebug() << "raise"; + // qDebug() << "raise"; raiseHelp(htc, arg); } bool ok; QPair scope = getScope(ui->textCode->textCursor(), &ok); if (!ok) return; ACList acl(autoCompletitionList(scope.first, scope.second)); - //qDebug() << written << scope << acl.size(); + // qDebug() << written << scope << acl.size(); if (scope.first.isEmpty() && scope.second.isEmpty() && !force) { completer->hide(); hideHelp(); @@ -1892,7 +1907,7 @@ void QCodeEdit::invokeAutoCompletition(bool force) { } QFont bf(font()); bf.setBold(true); - foreach (const ACSection & ac, acl) { + foreach(const ACSection & ac, acl) { if (ac.second.isEmpty()) { continue; } @@ -1970,7 +1985,7 @@ void QCodeEdit::commitCompletition() { void QCodeEdit::textEdit_cursorPositionChanged() { es_line.cursor = ui->textCode->textCursor(); - //qDebug() << "cursorPositionChanged" << es_line.cursor.position(); + // qDebug() << "cursorPositionChanged" << es_line.cursor.position(); es_line.cursor.select(QTextCursor::LineUnderCursor); es_line.cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); highlightBrackets(); @@ -1978,7 +1993,7 @@ void QCodeEdit::textEdit_cursorPositionChanged() { if (timer_blink) { killTimer(timer_blink); } - timer_blink = startTimer(QApplication::cursorFlashTime() / 2); + timer_blink = startTimer(QApplication::cursorFlashTime() / 2); cursor_state = true; createBlockSelection(); } @@ -1996,8 +2011,8 @@ void QCodeEdit::textEdit_textChanged() { void QCodeEdit::textEdit_selectionChanged() { if (hasBlockSelection()) { QTextCursor tc = ui->textCode->textCursor(); - //qDebug() << block_start_cursor.selectionStart() << tc.selectionEnd(); - bool bs = ui->textCode->blockSignals(true); + // qDebug() << block_start_cursor.selectionStart() << tc.selectionEnd(); + bool bs = ui->textCode->blockSignals(true); tc.clearSelection(); ui->textCode->setTextCursor(tc); ui->textCode->blockSignals(bs); @@ -2032,8 +2047,8 @@ void QCodeEdit::textEdit_redoAvailable(bool available) { void QCodeEdit::setShowSpaces(bool yes) { - spaces_ = yes; - QTextOption to = ui->textCode->document()->defaultTextOption(); + spaces_ = yes; + QTextOption to = ui->textCode->document()->defaultTextOption(); QTextOption::Flags tof = to.flags(); if (yes) { tof |= QTextOption::ShowTabsAndSpaces; @@ -2122,8 +2137,6 @@ void QCodeEdit::on_buttonReplaceAll_clicked() { } - - QString QCodeEdit::ACEntry::declaration() const { if (declaration_pos < 0 || declaration_file.isEmpty()) { return QString(); diff --git a/libs/widgets/qcodeedit.h b/libs/widgets/qcodeedit.h index 2a741d5..c5bdae9 100644 --- a/libs/widgets/qcodeedit.h +++ b/libs/widgets/qcodeedit.h @@ -1,33 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QCODEEDIT_H #define QCODEEDIT_H #include "qad_widgets_export.h" + +#include #include #include -#include namespace Ui { - class QCodeEdit; +class QCodeEdit; } class QPlainTextEdit; @@ -36,8 +37,7 @@ class IconedLabel; class _QCE_Viewport; -class QAD_WIDGETS_EXPORT QCodeEdit: public QWidget -{ +class QAD_WIDGETS_EXPORT QCodeEdit: public QWidget { Q_OBJECT Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(bool showSpaces READ showSpaces WRITE setShowSpaces) @@ -47,24 +47,34 @@ class QAD_WIDGETS_EXPORT QCodeEdit: public QWidget friend class QCodeEditCompleter; friend class _QCE_Viewport; - + public: QCodeEdit(QWidget * parent = nullptr); ~QCodeEdit() override; - + enum ACClassType { Keyword, Function, Namespace }; struct QAD_WIDGETS_EXPORT ACEntry { - ACEntry(const QString & t = QString(), const QString & n = QString(), const QString & h = QString()): - type(t), name(n), hint(h) {declaration_pos = -1;} - bool isNull() const {return type.isEmpty() && name.isEmpty();} + ACEntry(const QString & t = QString(), const QString & n = QString(), const QString & h = QString()): type(t), name(n), hint(h) { + declaration_pos = -1; + } + bool isNull() const { return type.isEmpty() && name.isEmpty(); } QString declaration() const; - ACEntry & addHint(QString h) {hint = h; return *this;} - ACEntry & addHelpHRef(QUrl h) {help_href = h; return *this;} - ACEntry & addCustomData(QVariant d) {custom_data = d; return *this;} + ACEntry & addHint(QString h) { + hint = h; + return *this; + } + ACEntry & addHelpHRef(QUrl h) { + help_href = h; + return *this; + } + ACEntry & addCustomData(QVariant d) { + custom_data = d; + return *this; + } QString type; QString name; QString hint; @@ -86,7 +96,7 @@ public: QRect cursorRect(const QTextCursor & cursor) const; QString text() const; QStringList cursorScope() const; - bool showSpaces() const {return spaces_;} + bool showSpaces() const { return spaces_; } bool showLineNumbers() const; void setHelpHintVisible(bool on); bool isHelpHintVisible() const; @@ -95,23 +105,23 @@ public: void setEditorFont(QFont f); QFont editorFont() const; - + QPlainTextEdit * textEdit() const; - + void registerAutoCompletitionClass(int id, ACClassType ac_class, const QString & name, const QIcon & icon = QIcon()); - bool wordCompletitionEnabled() const {return word_complete;} + bool wordCompletitionEnabled() const { return word_complete; } protected: typedef QPair StringsPair; - typedef QPair > ACSection; // section, ACClass.id -> list of entries - typedef QList ACList; // list of sections - - virtual ACList autoCompletitionList(const QStringList & scope, const QString & written) const {return ACList();} + typedef QPair> ACSection; // section, ACClass.id -> list of entries + typedef QList ACList; // list of sections + + virtual ACList autoCompletitionList(const QStringList & scope, const QString & written) const { return ACList(); } virtual void parse() {} virtual void documentUnset() {} virtual void documentChanged(QTextDocument * d) {} virtual void linkClicked(ACEntry entry) {} - virtual bool linkValidate(ACEntry e) {return true;} + virtual bool linkValidate(ACEntry e) { return true; } QString selectArg(QString s, int arg); void raiseHelp(QTextCursor tc, int arg = -1); @@ -124,7 +134,7 @@ protected: static QChar pairChar(QChar c); private slots: - void _activateLink(QCodeEdit::ACEntry e) {linkClicked(e);} + void _activateLink(QCodeEdit::ACEntry e) { linkClicked(e); } void gotoHelpHRef(QCodeEdit::ACEntry e); void resizeOverlay(); void syncScrolls(); @@ -166,18 +176,22 @@ public slots: void setShowLineNumbers(bool yes); void search(const QString & t); void searchNext(bool next); - void searchNext() {searchNext(true);} + void searchNext() { searchNext(true); } void searchPrevious(); void hideSearch(); - void setWordCompletitionEnabled(bool on) {word_complete = on;} + void setWordCompletitionEnabled(bool on) { word_complete = on; } signals: void textChanged(); void parseRequest(); - + private: struct QAD_WIDGETS_EXPORT ACClass { - ACClass(int i = -2, ACClassType c = QCodeEdit::Keyword, const QString & n = QString(), const QIcon & ic = QIcon()): id(i), class_(c), name(n), icon(ic) {} + ACClass(int i = -2, ACClassType c = QCodeEdit::Keyword, const QString & n = QString(), const QIcon & ic = QIcon()) + : id(i) + , class_(c) + , name(n) + , icon(ic) {} int id; ACClassType class_; QString name; @@ -191,9 +205,9 @@ private: }; bool eventFilter(QObject * o, QEvent * e) override; - void showEvent(QShowEvent * ) override; - void timerEvent(QTimerEvent * ) override; - void leaveEvent(QEvent * ) override; + void showEvent(QShowEvent *) override; + void timerEvent(QTimerEvent *) override; + void leaveEvent(QEvent *) override; void changeEvent(QEvent * e) override; bool codeKeyEvent(QKeyEvent * ke); void toggleComment(); diff --git a/libs/widgets/qcodeedit_completer_p.cpp b/libs/widgets/qcodeedit_completer_p.cpp index 28198fe..3add9a4 100644 --- a/libs/widgets/qcodeedit_completer_p.cpp +++ b/libs/widgets/qcodeedit_completer_p.cpp @@ -1,7 +1,9 @@ #include "qcodeedit_completer_p.h" + #include "qad_types.h" -#include + #include +#include QCodeEditCompleter::QCodeEditCompleter(QWidget * parent): QTreeWidget(parent) { @@ -17,17 +19,16 @@ QCodeEditCompleter::QCodeEditCompleter(QWidget * parent): QTreeWidget(parent) { header()->setDefaultAlignment(Qt::AlignCenter); header()-> #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - setSectionResizeMode + setSectionResizeMode #else - setResizeMode + setResizeMode #endif - (QHeaderView::ResizeToContents); + (QHeaderView::ResizeToContents); header()->setStretchLastSection(false); } -QCodeEditCompleter::~QCodeEditCompleter() { -} +QCodeEditCompleter::~QCodeEditCompleter() {} void QCodeEditCompleter::nextCompletition() { @@ -63,7 +64,7 @@ void QCodeEditCompleter::addItems(QFont f, const QCodeEdit::ACClass & cl, const gi->setFlags(Qt::ItemIsEnabled); addTopLevelItem(gi); gi->setFirstColumnSpanned(true); - foreach (const auto & s, items.second) { + foreach(const auto & s, items.second) { QTreeWidgetItem * ni = new QTreeWidgetItem(); ni->setIcon(0, cl.icon); ni->setText(0, s.type); @@ -74,7 +75,6 @@ void QCodeEditCompleter::addItems(QFont f, const QCodeEdit::ACClass & cl, const } - void QCodeEditCompleter::invoke(QPoint global_pos) { setCurrentItem(topLevelItem(1)); if (isHidden()) move(global_pos); @@ -101,12 +101,8 @@ QString QCodeEditCompleter::currentValue() const { void QCodeEditCompleter::keyPressEvent(QKeyEvent * e) { switch (e->key()) { - case Qt::Key_Escape: - hide(); - break; - case Qt::Key_Return: - emit commit(); - break; + case Qt::Key_Escape: hide(); break; + case Qt::Key_Return: emit commit(); break; case Qt::Key_F1: if (currentItem()) { QString href = currentItem()->data(0, Qt::UserRole).toString(); diff --git a/libs/widgets/qcodeedit_completer_p.h b/libs/widgets/qcodeedit_completer_p.h index 75890cd..cabee26 100644 --- a/libs/widgets/qcodeedit_completer_p.h +++ b/libs/widgets/qcodeedit_completer_p.h @@ -1,32 +1,33 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QCODEEDIT_COMPLETER_P_H #define QCODEEDIT_COMPLETER_P_H #include "qcodeedit.h" + #include -class QCodeEditCompleter: public QTreeWidget -{ +class QCodeEditCompleter: public QTreeWidget { Q_OBJECT + public: QCodeEditCompleter(QWidget * parent = nullptr); ~QCodeEditCompleter() override; diff --git a/libs/widgets/qipedit.cpp b/libs/widgets/qipedit.cpp index 05c5661..0bbe0ed 100644 --- a/libs/widgets/qipedit.cpp +++ b/libs/widgets/qipedit.cpp @@ -1,9 +1,11 @@ #include "qipedit.h" + #include "qalgorithms.h" -#include -#include + #include #include +#include +#include QIPEdit::QIPEdit(QWidget * parent, const QString & ip): QWidget(parent) { @@ -44,10 +46,10 @@ void QIPEdit::setIP(const QString & text) { s = str.left(str.indexOf('.')); edits[0]->setText(s == "" ? "0" : s); str = str.right(str.length() - s.length() - 1); - s = str.left(str.indexOf('.')); + s = str.left(str.indexOf('.')); edits[1]->setText(s == "" ? "0" : s); str = str.right(str.length() - s.length() - 1); - s = str.left(str.indexOf('.')); + s = str.left(str.indexOf('.')); edits[2]->setText(s == "" ? "0" : s); str = str.right(str.length() - s.length() - 1); edits[3]->setText(str == "" ? "0" : str); @@ -56,14 +58,22 @@ void QIPEdit::setIP(const QString & text) { QString QIPEdit::IP() { QString s; - if (edits[0]->text() == "") s = "0."; - else s = edits[0]->text() + "."; - if (edits[1]->text() == "") s += "0."; - else s += edits[1]->text() + "."; - if (edits[2]->text() == "") s += "0."; - else s += edits[2]->text() + "."; - if (edits[3]->text() == "") s += "0"; - else s += edits[3]->text(); + if (edits[0]->text() == "") + s = "0."; + else + s = edits[0]->text() + "."; + if (edits[1]->text() == "") + s += "0."; + else + s += edits[1]->text() + "."; + if (edits[2]->text() == "") + s += "0."; + else + s += edits[2]->text() + "."; + if (edits[3]->text() == "") + s += "0"; + else + s += edits[3]->text(); return s; } @@ -76,7 +86,7 @@ void QIPEdit::returnPress(int index) { } -inline void QIPEdit::textChange(int index, const QString &text) { +inline void QIPEdit::textChange(int index, const QString & text) { if (text.length() == 3 && isVisible()) { returnPress(index); } diff --git a/libs/widgets/qipedit.h b/libs/widgets/qipedit.h index c7727f4..ed745ca 100644 --- a/libs/widgets/qipedit.h +++ b/libs/widgets/qipedit.h @@ -1,26 +1,27 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QIPEDIT_H #define QIPEDIT_H #include "qad_widgets_export.h" + #include @@ -29,40 +30,39 @@ class QLineEdit; class QLabel; -class QAD_WIDGETS_EXPORT QIPEdit: public QWidget -{ +class QAD_WIDGETS_EXPORT QIPEdit: public QWidget { Q_OBJECT Q_PROPERTY(QString IP READ IP WRITE setIP) - + public: QIPEdit(QWidget * parent = nullptr, const QString & ip = ""); - + QString IP(); - + public slots: void setIP(const QString & text); - + private slots: - void returnPressed0() {returnPress(0);} - void returnPressed1() {returnPress(1);} - void returnPressed2() {returnPress(2);} - void returnPressed3() {returnPress(3);} - void textChanged0(const QString & text) {textChange(0, text);} - void textChanged1(const QString & text) {textChange(1, text);} - void textChanged2(const QString & text) {textChange(2, text);} - void textChanged3(const QString & text) {textChange(3, text);} - + void returnPressed0() { returnPress(0); } + void returnPressed1() { returnPress(1); } + void returnPressed2() { returnPress(2); } + void returnPressed3() { returnPress(3); } + void textChanged0(const QString & text) { textChange(0, text); } + void textChanged1(const QString & text) { textChange(1, text); } + void textChanged2(const QString & text) { textChange(2, text); } + void textChanged3(const QString & text) { textChange(3, text); } + signals: void valueChanged(QString); private: void returnPress(int index); - void textChange(int index, const QString &text); + void textChange(int index, const QString & text); int cind; QBoxLayout * layout; - QList edits; - QList dots; + QList edits; + QList dots; }; #endif // QIPEDIT_H diff --git a/libs/widgets/qpiconfignewdialog.cpp b/libs/widgets/qpiconfignewdialog.cpp index e84eccd..19adebd 100644 --- a/libs/widgets/qpiconfignewdialog.cpp +++ b/libs/widgets/qpiconfignewdialog.cpp @@ -1,11 +1,12 @@ #include "qpiconfignewdialog.h" + #include "ui_qpiconfignewdialog.h" QPIConfigNewDialog::QPIConfigNewDialog(QWidget * parent): QDialog(parent) { ui = new Ui::QPIConfigNewDialog(); ui->setupUi(this); - radios = findChildren(); + radios = findChildren(); ui->widgetValue->hideAll(); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } @@ -14,17 +15,14 @@ QPIConfigNewDialog::QPIConfigNewDialog(QWidget * parent): QDialog(parent) { void QPIConfigNewDialog::changeEvent(QEvent * e) { QDialog::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } void QPIConfigNewDialog::typeChanged() { - for (const QRadioButton * i : radios) { + for (const QRadioButton * i: radios) { if (i->isChecked()) { ui->widgetValue->setType(i->property("type").toString()); return; @@ -34,7 +32,7 @@ void QPIConfigNewDialog::typeChanged() { QString QPIConfigNewDialog::type() { - for (const QRadioButton * i : radios) { + for (const QRadioButton * i: radios) { if (i->isChecked()) { return i->property("type").toString(); } diff --git a/libs/widgets/qpiconfignewdialog.h b/libs/widgets/qpiconfignewdialog.h index 3b9cf40..2b48ec9 100644 --- a/libs/widgets/qpiconfignewdialog.h +++ b/libs/widgets/qpiconfignewdialog.h @@ -1,60 +1,59 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONFIGNEWDIALOG_H #define QPICONFIGNEWDIALOG_H -#include #include "qad_widgets_export.h" +#include + namespace Ui { - class QPIConfigNewDialog; +class QPIConfigNewDialog; } class QRadioButton; -class QAD_WIDGETS_EXPORT QPIConfigNewDialog: public QDialog -{ +class QAD_WIDGETS_EXPORT QPIConfigNewDialog: public QDialog { Q_OBJECT - + public: QPIConfigNewDialog(QWidget * parent = nullptr); - + QString type(); QString name(); QString value(); QString comment(); void reset(bool node = false); - + protected: void changeEvent(QEvent * e) override; - + private slots: void on_lineName_textChanged(const QString & text); void typeChanged(); private: Ui::QPIConfigNewDialog * ui; - QList radios; - + QList radios; }; #endif // QPICONFIGNEWDIALOG_H diff --git a/libs/widgets/qpiconfigvaluewidget.cpp b/libs/widgets/qpiconfigvaluewidget.cpp index 4e60b7e..66c2092 100644 --- a/libs/widgets/qpiconfigvaluewidget.cpp +++ b/libs/widgets/qpiconfigvaluewidget.cpp @@ -1,4 +1,5 @@ #include "qpiconfigvaluewidget.h" + #include "qpievaluator_p.h" @@ -35,44 +36,175 @@ ConfigValueWidget::ConfigValueWidget(QWidget * parent): QWidget(parent), lay(QBo void ConfigValueWidget::setType(const QString & t) { hideAll(); - type = t.left(1); + type = t.left(1); active = false; - if (type == "e") {QStringList en_sl = QPIEvaluator::inBrackets(comment).split(';'); - if (en_sl.size()>1) { - w_enum.show(); w_enum.addItems(en_sl); setValue(value); active = true; return; - } else {type = "s";}} - if (type == "s") {w_string.show(); setValue(value); active = true; return;} - if (type == "l") {w_list.show(); setValue(value); active = true; return;} - if (type == "b") {w_bool.show(); setValue(value); active = true; return;} - if (type == "n") {w_integer.show(); setValue(value); active = true; return;} - if (type == "f") {w_float.show(); setValue(value); active = true; return;} - if (type == "c") {w_color.show(); setValue(value); active = true; return;} - if (type == "r") {w_rect.show(); w_rect.setDecimals(0); setValue(value); active = true; return;} - if (type == "a") {w_rect.show(); w_rect.setDecimals(3); setValue(value); active = true; return;} - if (type == "p") {w_point.show(); w_point.setDecimals(0); setValue(value); active = true; return;} - if (type == "v") {w_point.show(); w_point.setDecimals(3); setValue(value); active = true; return;} - if (type == "i") {w_ip.show(); setValue(value); active = true; return;} - if (type == "F") {w_path.show(); setValue(value); active = true; return;} - if (type == "D") {w_path.show(); setValue(value); active = true; return;} + if (type == "e") { + QStringList en_sl = QPIEvaluator::inBrackets(comment).split(';'); + if (en_sl.size() > 1) { + w_enum.show(); + w_enum.addItems(en_sl); + setValue(value); + active = true; + return; + } else { + type = "s"; + } + } + if (type == "s") { + w_string.show(); + setValue(value); + active = true; + return; + } + if (type == "l") { + w_list.show(); + setValue(value); + active = true; + return; + } + if (type == "b") { + w_bool.show(); + setValue(value); + active = true; + return; + } + if (type == "n") { + w_integer.show(); + setValue(value); + active = true; + return; + } + if (type == "f") { + w_float.show(); + setValue(value); + active = true; + return; + } + if (type == "c") { + w_color.show(); + setValue(value); + active = true; + return; + } + if (type == "r") { + w_rect.show(); + w_rect.setDecimals(0); + setValue(value); + active = true; + return; + } + if (type == "a") { + w_rect.show(); + w_rect.setDecimals(3); + setValue(value); + active = true; + return; + } + if (type == "p") { + w_point.show(); + w_point.setDecimals(0); + setValue(value); + active = true; + return; + } + if (type == "v") { + w_point.show(); + w_point.setDecimals(3); + setValue(value); + active = true; + return; + } + if (type == "i") { + w_ip.show(); + setValue(value); + active = true; + return; + } + if (type == "F") { + w_path.show(); + setValue(value); + active = true; + return; + } + if (type == "D") { + w_path.show(); + setValue(value); + active = true; + return; + } } void ConfigValueWidget::setValue(const QString & v) { - value = v; + value = v; active = false; - if (type == "l") {w_list.setValue(v.split("%|%")); active = true; return;} - if (type == "b") {w_bool.setChecked(v.toInt() > 0 || v.toLower().trimmed() == "true"); active = true; return;} - if (type == "n") {w_integer.setValue(QString2int(v)); active = true; return;} - if (type == "f") {w_float.setValue(v.toDouble()); active = true; return;} - if (type == "c") {w_color.setColor(QString2QColor(v)); active = true; return;} - if (type == "r") {w_rect.setValue(QString2QRectF(v)); active = true; return;} - if (type == "a") {w_rect.setValue(QString2QRectF(v)); active = true; return;} - if (type == "p") {w_point.setValue(QString2QPointF(v)); active = true; return;} - if (type == "v") {w_point.setValue(QString2QPointF(v)); active = true; return;} - if (type == "i") {w_ip.setIP(v); active = true; return;} - if (type == "e") {w_enum.setCurrentIndex(w_enum.findText(v)); active = true; return;} - if (type == "F") {w_path.is_dir = false; w_path.setValue(v); active = true; return;} - if (type == "D") {w_path.is_dir = true; w_path.setValue(v); active = true; return;} + if (type == "l") { + w_list.setValue(v.split("%|%")); + active = true; + return; + } + if (type == "b") { + w_bool.setChecked(v.toInt() > 0 || v.toLower().trimmed() == "true"); + active = true; + return; + } + if (type == "n") { + w_integer.setValue(QString2int(v)); + active = true; + return; + } + if (type == "f") { + w_float.setValue(v.toDouble()); + active = true; + return; + } + if (type == "c") { + w_color.setColor(QString2QColor(v)); + active = true; + return; + } + if (type == "r") { + w_rect.setValue(QString2QRectF(v)); + active = true; + return; + } + if (type == "a") { + w_rect.setValue(QString2QRectF(v)); + active = true; + return; + } + if (type == "p") { + w_point.setValue(QString2QPointF(v)); + active = true; + return; + } + if (type == "v") { + w_point.setValue(QString2QPointF(v)); + active = true; + return; + } + if (type == "i") { + w_ip.setIP(v); + active = true; + return; + } + if (type == "e") { + w_enum.setCurrentIndex(w_enum.findText(v)); + active = true; + return; + } + if (type == "F") { + w_path.is_dir = false; + w_path.setValue(v); + active = true; + return; + } + if (type == "D") { + w_path.is_dir = true; + w_path.setValue(v); + active = true; + return; + } w_string.setText(v); active = true; } @@ -80,19 +212,71 @@ void ConfigValueWidget::setValue(const QString & v) { void ConfigValueWidget::valueChanged() { if (!active) return; - if (type == "l") {value = w_list.value().join("%|%"); emit changed(this, value); return;} - if (type == "b") {value = w_bool.isChecked() ? "true" : "false"; emit changed(this, value); return;} - if (type == "n") {value = QString::number(w_integer.value()); emit changed(this, value); return;} - if (type == "f") {value = QString::number(w_float.value()); emit changed(this, value); return;} - if (type == "c") {value = QColor2QString(w_color.color()); emit changed(this, value); return;} - if (type == "r") {value = QRectF2QString(w_rect.value()); emit changed(this, value); return;} - if (type == "a") {value = QRectF2QString(w_rect.value()); emit changed(this, value); return;} - if (type == "p") {value = QPointF2QString(w_point.value()); emit changed(this, value); return;} - if (type == "v") {value = QPointF2QString(w_point.value()); emit changed(this, value); return;} - if (type == "i") {value = w_ip.IP(); emit changed(this, value); return;} - if (type == "e") {value = w_enum.currentText(); emit changed(this, value); return;} - if (type == "F") {value = w_path.value(); emit changed(this, value); return;} - if (type == "D") {value = w_path.value(); emit changed(this, value); return;} + if (type == "l") { + value = w_list.value().join("%|%"); + emit changed(this, value); + return; + } + if (type == "b") { + value = w_bool.isChecked() ? "true" : "false"; + emit changed(this, value); + return; + } + if (type == "n") { + value = QString::number(w_integer.value()); + emit changed(this, value); + return; + } + if (type == "f") { + value = QString::number(w_float.value()); + emit changed(this, value); + return; + } + if (type == "c") { + value = QColor2QString(w_color.color()); + emit changed(this, value); + return; + } + if (type == "r") { + value = QRectF2QString(w_rect.value()); + emit changed(this, value); + return; + } + if (type == "a") { + value = QRectF2QString(w_rect.value()); + emit changed(this, value); + return; + } + if (type == "p") { + value = QPointF2QString(w_point.value()); + emit changed(this, value); + return; + } + if (type == "v") { + value = QPointF2QString(w_point.value()); + emit changed(this, value); + return; + } + if (type == "i") { + value = w_ip.IP(); + emit changed(this, value); + return; + } + if (type == "e") { + value = w_enum.currentText(); + emit changed(this, value); + return; + } + if (type == "F") { + value = w_path.value(); + emit changed(this, value); + return; + } + if (type == "D") { + value = w_path.value(); + emit changed(this, value); + return; + } value = w_string.text(); emit changed(this, value); } diff --git a/libs/widgets/qpiconfigvaluewidget.h b/libs/widgets/qpiconfigvaluewidget.h index 6ddadbe..50bc5de 100644 --- a/libs/widgets/qpiconfigvaluewidget.h +++ b/libs/widgets/qpiconfigvaluewidget.h @@ -1,57 +1,75 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONFIGVALUEWIDGET_H #define QPICONFIGVALUEWIDGET_H -#include -#include -#include -#include -#include "qpiconfig.h" -#include "qvariantedit.h" -#include "qrectedit.h" -#include "qpointedit.h" #include "colorbutton.h" #include "ecombobox.h" -#include "qipedit.h" -#include "limits.h" #include "float.h" +#include "limits.h" #include "qad_widgets_export.h" +#include "qipedit.h" +#include "qpiconfig.h" +#include "qpointedit.h" +#include "qrectedit.h" +#include "qvariantedit.h" + +#include +#include +#include +#include -class QAD_WIDGETS_EXPORT ConfigValueWidget: public QWidget -{ +class QAD_WIDGETS_EXPORT ConfigValueWidget: public QWidget { Q_OBJECT friend class QPIConfigWidget; friend class QPIConfigNewDialog; + public: ConfigValueWidget(QWidget * parent = 0); - ~ConfigValueWidget() {hide();} - + ~ConfigValueWidget() { hide(); } + void setType(const QString & t); void setValue(const QString & v); - void setEntry(QPIConfig::Entry * e) {value = e->value(); full_name = e->_full_name; comment = e->comment(); setType(e->type());} - + void setEntry(QPIConfig::Entry * e) { + value = e->value(); + full_name = e->_full_name; + comment = e->comment(); + setType(e->type()); + } + private: - void hideAll() {w_string.hide(); w_list.hide(); w_bool.hide(); w_integer.hide(); w_float.hide(); w_color.hide(); w_rect.hide(); w_point.hide(); w_ip.hide(); w_enum.hide(); w_path.hide();} - + void hideAll() { + w_string.hide(); + w_list.hide(); + w_bool.hide(); + w_integer.hide(); + w_float.hide(); + w_color.hide(); + w_rect.hide(); + w_point.hide(); + w_ip.hide(); + w_enum.hide(); + w_path.hide(); + } + QString type, value, full_name, comment; bool active; QBoxLayout lay; @@ -66,13 +84,12 @@ private: QIPEdit w_ip; QComboBox w_enum; PathEdit w_path; - + private slots: void valueChanged(); - + signals: - void changed(ConfigValueWidget * , QString ); - + void changed(ConfigValueWidget *, QString); }; #endif // QPICONFIGVALUEWIDGET_H diff --git a/libs/widgets/qpiconfigwidget.cpp b/libs/widgets/qpiconfigwidget.cpp index 18bbd88..b2889ec 100644 --- a/libs/widgets/qpiconfigwidget.cpp +++ b/libs/widgets/qpiconfigwidget.cpp @@ -1,14 +1,22 @@ #include "qpiconfigwidget.h" + #include "qalgorithms.h" #include "qpiconfigvaluewidget.h" -#include + #include +#include #include -QPIConfigWidget::QPIConfigWidget(QWidget * parent, QPIConfig * c, bool on): QTreeWidget(parent), actionAddItem(this), actionAddNode(this), - actionToItem(this), actionToNode(this), actionRemove(this), - actionExpandAll(this), actionCollapseAll(this) { +QPIConfigWidget::QPIConfigWidget(QWidget * parent, QPIConfig * c, bool on) + : QTreeWidget(parent) + , actionAddItem(this) + , actionAddNode(this) + , actionToItem(this) + , actionToNode(this) + , actionRemove(this) + , actionExpandAll(this) + , actionCollapseAll(this) { active = on; if (active) { setColumnCount(4); @@ -32,8 +40,8 @@ QPIConfigWidget::QPIConfigWidget(QWidget * parent, QPIConfig * c, bool on): QTre popupMenu.addAction(&actionExpandAll); popupMenu.addAction(&actionCollapseAll); viewport()->installEventFilter(this); - connect(this, SIGNAL(itemClicked(QTreeWidgetItem * , int)), this, SLOT(itemClicked(QTreeWidgetItem * , int))); - connect(this, SIGNAL(itemChanged(QTreeWidgetItem * , int)), this, SLOT(itemChanged(QTreeWidgetItem * , int))); + connect(this, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(itemClicked(QTreeWidgetItem *, int))); + connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(itemChanged(QTreeWidgetItem *, int))); connect(&actionAddItem, SIGNAL(triggered()), this, SLOT(on_actionAddItem_triggered())); connect(&actionAddNode, SIGNAL(triggered()), this, SLOT(on_actionAddNode_triggered())); connect(&actionRemove, SIGNAL(triggered()), this, SLOT(on_actionRemove_triggered())); @@ -58,18 +66,18 @@ void QPIConfigWidget::changeEvent(QEvent * e) { bool QPIConfigWidget::eventFilter(QObject * o, QEvent * e) { if (e->type() == QEvent::MouseButtonPress) { - if (viewport() == qobject_cast(o)) { - pi = itemAt(((QMouseEvent * )e)->pos()); - if (((QMouseEvent * )e)->buttons() == Qt::RightButton) { + if (viewport() == qobject_cast(o)) { + pi = itemAt(((QMouseEvent *)e)->pos()); + if (((QMouseEvent *)e)->buttons() == Qt::RightButton) { qApp->processEvents(); itemClicked(pi, 1); popupMenu.popup( - #if QT_VERSION_MAJOR <= 5 - ((QMouseEvent * )e)->globalPos() - #else - ((QMouseEvent * )e)->globalPosition().toPoint() - #endif - ); +#if QT_VERSION_MAJOR <= 5 + ((QMouseEvent *)e)->globalPos() +#else + ((QMouseEvent *)e)->globalPosition().toPoint() +#endif + ); } } } @@ -103,7 +111,7 @@ void QPIConfigWidget::itemChanged(QTreeWidgetItem * item, int column) { if (item != c_pi) { c_pi = item; if (item) { - c_name = item->text(0); + c_name = item->text(0); c_comment = item->text(3); } return; @@ -114,7 +122,7 @@ void QPIConfigWidget::itemChanged(QTreeWidgetItem * item, int column) { if (c_name == item->text(0) && c_comment == item->text(3)) { return; } - //qDebug() << "change" << item->text(0); + // qDebug() << "change" << item->text(0); QPIConfig::Entry * e = itemEntry(item); if (e == nullptr) { return; @@ -123,12 +131,12 @@ void QPIConfigWidget::itemChanged(QTreeWidgetItem * item, int column) { buildFullNames(item); e->setName(item->text(column)); conf->buildFullNames(e->parent()); - //qDebug() << itemCWidget(item)->full_name; + // qDebug() << itemCWidget(item)->full_name; } if (column == 3) { e->setComment(item->text(column)); } - c_name = item->text(0); + c_name = item->text(0); c_comment = item->text(3); emit changed(); } @@ -164,10 +172,10 @@ void QPIConfigWidget::on_actionAddItem_triggered() { } QPIConfig::Entry * e; if (pi->childCount() == 0) { - //qDebug() << "pi empty, remove " << itemCWidget(pi)->full_name; + // qDebug() << "pi empty, remove " << itemCWidget(pi)->full_name; conf->removeEntry(itemCWidget(pi)->full_name, false); } - //qDebug() << "add " << fp + new_dialog.name(); + // qDebug() << "add " << fp + new_dialog.name(); e = &(conf->addEntry(fp + new_dialog.name(), new_dialog.value().isEmpty() ? "0" : new_dialog.value(), new_dialog.type(), false)); expandItem(pi); pi = addEntry(pi, e); @@ -212,18 +220,18 @@ void QPIConfigWidget::on_actionRemove_triggered() { if (conf == nullptr || !active) { return; } - QList si = selectedItems(); + QList si = selectedItems(); conf->buildFullNames(&(conf->root)); QPIConfig::Entry * e; - for (QTreeWidgetItem * i : si) { + for (QTreeWidgetItem * i: si) { e = itemEntry(i); if (e == nullptr) continue; - //qDebug() << "remove " + e->_full_name; + // qDebug() << "remove " + e->_full_name; conf->removeEntry(e->_full_name, false); deleteEntry(i); } emit changed(); - //show(); + // show(); } @@ -254,7 +262,7 @@ void QPIConfigWidget::buildTree() { void QPIConfigWidget::setReadOnlyValue(bool yes) { read_only_value = yes; - for (ConfigValueWidget * i : w_values) { + for (ConfigValueWidget * i: w_values) { i->setEnabled(!yes); } } @@ -262,7 +270,7 @@ void QPIConfigWidget::setReadOnlyValue(bool yes) { void QPIConfigWidget::setReadOnlyType(bool yes) { read_only_type = yes; - for (QComboBox * i : w_types) { + for (QComboBox * i: w_types) { i->setEnabled(!yes); i->setFrame(!yes); } @@ -270,17 +278,17 @@ void QPIConfigWidget::setReadOnlyType(bool yes) { void QPIConfigWidget::buildEntry(QTreeWidgetItem * i, QPIConfig::Entry * e) { - for (QPIConfig::Entry * j : e->children()) { + for (QPIConfig::Entry * j: e->children()) { buildEntry(addEntry(i, j, !j->isLeaf()), j); } } void QPIConfigWidget::buildFullNames(QTreeWidgetItem * i) { - ConfigValueWidget * cw, * pw; + ConfigValueWidget *cw, *pw; cw = itemCWidget(i); if (i->parent()) { - pw = itemCWidget(i->parent()); + pw = itemCWidget(i->parent()); cw->full_name = pw->full_name + conf->delim + i->text(0); } else { cw->full_name = i->text(0); @@ -315,9 +323,9 @@ QTreeWidgetItem * QPIConfigWidget::addEntry(QTreeWidgetItem * i, QPIConfig::Entr w_types.back()->setProperty("qpic_widget", QVariant(reinterpret_cast(w_values.back()))); w_types.back()->setEnabled(!read_only_type); w_types.back()->setFrame(!read_only_type); - connect(w_types.back(), SIGNAL(currentIndexChanged(int, UComboBox * )), this, SLOT(typeChange(int,UComboBox * ))); + connect(w_types.back(), SIGNAL(currentIndexChanged(int, UComboBox *)), this, SLOT(typeChange(int, UComboBox *))); } - connect(w_values.back(), SIGNAL(changed(ConfigValueWidget * , QString)), this, SLOT(valueChange(ConfigValueWidget * , QString))); + connect(w_values.back(), SIGNAL(changed(ConfigValueWidget *, QString)), this, SLOT(valueChange(ConfigValueWidget *, QString))); i->addChild(ti); setItemWidget(ti, 1, w_values.back()); if (!node) { @@ -338,8 +346,8 @@ void QPIConfigWidget::deleteEntry(QTreeWidgetItem * i) { for (int j = 0; j < cc; ++j) { deleteEntry(i->child(0)); } - vw = qobject_cast(itemWidget(i, 1)); - cb = qobject_cast(itemWidget(i, 2)); + vw = qobject_cast(itemWidget(i, 1)); + cb = qobject_cast(itemWidget(i, 2)); if (vw) { w_values.remove(w_values.indexOf(vw)); delete vw; @@ -373,8 +381,8 @@ bool QPIConfigWidget::filterItem(const QString & f, QTreeWidgetItem * i) { return true; } bool ret = (!isColumnHidden(0) && i->text(0).indexOf(f, 0, Qt::CaseInsensitive) >= 0) || - (!isColumnHidden(1) && itemCWidget(i)->value.indexOf(f, 0, Qt::CaseInsensitive) >= 0) || - (!isColumnHidden(3) && i->text(3).indexOf(f, 0, Qt::CaseInsensitive) >= 0); + (!isColumnHidden(1) && itemCWidget(i)->value.indexOf(f, 0, Qt::CaseInsensitive) >= 0) || + (!isColumnHidden(3) && i->text(3).indexOf(f, 0, Qt::CaseInsensitive) >= 0); if (itemTWidget(i)) { ret = ret || (!isColumnHidden(2) && itemTWidget(i)->currentText().indexOf(f, 0, Qt::CaseInsensitive) >= 0); } @@ -434,12 +442,12 @@ void QPIConfigWidget::readFromString(QString str) { } -UComboBox::UComboBox(QWidget *parent) : QComboBox(parent) { +UComboBox::UComboBox(QWidget * parent): QComboBox(parent) { connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(indexChange(int))); } -void QPIConfigWidget::filter(const QString &f) { +void QPIConfigWidget::filter(const QString & f) { if (!active) { return; } @@ -499,23 +507,23 @@ void QPIConfigWidget::setReadOnlyName(bool yes) { } -ConfigValueWidget *QPIConfigWidget::itemCWidget(QTreeWidgetItem *i) { +ConfigValueWidget * QPIConfigWidget::itemCWidget(QTreeWidgetItem * i) { return qobject_cast(itemWidget(i, 1)); } -UComboBox *QPIConfigWidget::itemTWidget(QTreeWidgetItem *i) { +UComboBox * QPIConfigWidget::itemTWidget(QTreeWidgetItem * i) { return qobject_cast(itemWidget(i, 2)); } -void QPIConfigWidget::addTrEntry(const QString &s, const QString &f) { +void QPIConfigWidget::addTrEntry(const QString & s, const QString & f) { types.insert(s, f); s_types << f; } -void QPIConfigWidget::setQPIConfig(QPIConfig *c) { +void QPIConfigWidget::setQPIConfig(QPIConfig * c) { conf = c; buildTree(); } @@ -524,4 +532,3 @@ void QPIConfigWidget::setQPIConfig(QPIConfig *c) { void UComboBox::indexChange(int i) { emit currentIndexChanged(i, this); } - diff --git a/libs/widgets/qpiconfigwidget.h b/libs/widgets/qpiconfigwidget.h index f1f0293..d659eb4 100644 --- a/libs/widgets/qpiconfigwidget.h +++ b/libs/widgets/qpiconfigwidget.h @@ -1,20 +1,20 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONFIGWIDGET_H @@ -23,31 +23,31 @@ #include "qad_widgets_export.h" #include "qpiconfig.h" #include "qpiconfignewdialog.h" -#include -#include + #include +#include #include +#include class ConfigValueWidget; -class QAD_WIDGETS_EXPORT UComboBox: public QComboBox -{ +class QAD_WIDGETS_EXPORT UComboBox: public QComboBox { Q_OBJECT + public: - UComboBox(QWidget *parent = nullptr); + UComboBox(QWidget * parent = nullptr); private slots: void indexChange(int i); signals: - void currentIndexChanged(int, UComboBox * ); + void currentIndexChanged(int, UComboBox *); }; -class QAD_WIDGETS_EXPORT QPIConfigWidget: public QTreeWidget -{ +class QAD_WIDGETS_EXPORT QPIConfigWidget: public QTreeWidget { Q_OBJECT Q_PROPERTY(bool readOnlyName READ readOnlyName WRITE setReadOnlyName) Q_PROPERTY(bool readOnlyValue READ readOnlyValue WRITE setReadOnlyValue) @@ -57,28 +57,29 @@ class QAD_WIDGETS_EXPORT QPIConfigWidget: public QTreeWidget Q_PROPERTY(bool columnValueVisible READ columnValueVisible WRITE setColumnValueVisible) Q_PROPERTY(bool columnTypeVisible READ columnTypeVisible WRITE setColumnTypeVisible) Q_PROPERTY(bool columnCommentVisible READ columnCommentVisible WRITE setColumnCommentVisible) + public: QPIConfigWidget(QWidget * parent = nullptr, QPIConfig * c = nullptr, bool on = true); - ~QPIConfigWidget() override {clear();} + ~QPIConfigWidget() override { clear(); } - void setQPIConfig(QPIConfig *c); - bool readOnlyName() {return read_only_name;} - bool readOnlyValue() {return read_only_value;} - bool readOnlyType() {return read_only_type;} - bool readOnlyComment() {return read_only_comment;} - bool columnNameVisible() {return !c_hidden[0];} - bool columnValueVisible() {return !c_hidden[1];} - bool columnTypeVisible() {return !c_hidden[2];} - bool columnCommentVisible() {return !c_hidden[3];} + void setQPIConfig(QPIConfig * c); + bool readOnlyName() { return read_only_name; } + bool readOnlyValue() { return read_only_value; } + bool readOnlyType() { return read_only_type; } + bool readOnlyComment() { return read_only_comment; } + bool columnNameVisible() { return !c_hidden[0]; } + bool columnValueVisible() { return !c_hidden[1]; } + bool columnTypeVisible() { return !c_hidden[2]; } + bool columnCommentVisible() { return !c_hidden[3]; } QString writeToString(); void readFromString(QString str); - + public slots: void parse(); void write(); void clear(); void buildTree(); - void filter(const QString &f); + void filter(const QString & f); void setReadOnlyName(bool yes); void setReadOnlyValue(bool yes); void setReadOnlyType(bool yes); @@ -96,7 +97,7 @@ private slots: void on_actionAddItem_triggered(); void on_actionAddNode_triggered(); void on_actionRemove_triggered(); - + signals: void changed(); @@ -106,25 +107,25 @@ private: void buildEntry(QTreeWidgetItem * i, QPIConfig::Entry * e); void buildFullNames(QTreeWidgetItem * i); QPIConfig::Entry * itemEntry(QTreeWidgetItem * i); - ConfigValueWidget *itemCWidget(QTreeWidgetItem *i); - UComboBox *itemTWidget(QTreeWidgetItem *i); + ConfigValueWidget * itemCWidget(QTreeWidgetItem * i); + UComboBox * itemTWidget(QTreeWidgetItem * i); QTreeWidgetItem * addEntry(QTreeWidgetItem * i, QPIConfig::Entry * e, bool node = false); void deleteEntry(QTreeWidgetItem * i); bool filter(const QString & f, QTreeWidgetItem * i); bool filterItem(const QString & f, QTreeWidgetItem * i); void translate(); - void addTrEntry(const QString &s, const QString &f); + void addTrEntry(const QString & s, const QString & f); QPIConfig * conf; QPIConfigNewDialog new_dialog; QAction actionAddItem, actionAddNode, actionToItem, actionToNode, actionRemove, actionExpandAll, actionCollapseAll; QMenu popupMenu; QString c_name, c_comment; - QTreeWidgetItem * pi, * ti, * c_pi; + QTreeWidgetItem *pi, *ti, *c_pi; QHash types; QStringList s_types; - QVector w_values; - QVector w_types; + QVector w_values; + QVector w_types; QVector c_hidden; bool active, read_only_name, read_only_value, read_only_type, read_only_comment; }; diff --git a/libs/widgets/qpiconsole.cpp b/libs/widgets/qpiconsole.cpp index 1b0d555..7c8d85a 100644 --- a/libs/widgets/qpiconsole.cpp +++ b/libs/widgets/qpiconsole.cpp @@ -4,11 +4,11 @@ QPIConsole::QPIConsole(QWidget * parent): QTabWidget(parent) { connect(this, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); cur_tab = timer = -1; - def_align = Qt::AlignCenter; + def_align = Qt::AlignCenter; } -void QPIConsole::timerEvent(QTimerEvent * ) { +void QPIConsole::timerEvent(QTimerEvent *) { for (int i = 0; i < columns().size(); ++i) { Column & ccol(tabs[cur_tab].columns[i]); QVector & cvars(ccol.variables); @@ -38,21 +38,23 @@ void QPIConsole::timerEvent(QTimerEvent * ) { if (tv.type <= 0 && tv.ptr == 0) continue; if (tv.ptr != 0) { switch (tv.type) { - case 0: tv.widget->setText((tv.ptr != 0 ? *(const QString*)tv.ptr : QString())); break; - case 1: tv.widget->setText((tv.ptr != 0 ? *(const bool*)tv.ptr : false) ? "true" : "false"); break; - case 2: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const int*)tv.ptr : 0, tv.format)); break; - case 3: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const long*)tv.ptr : 0l, tv.format)); break; - case 4: tv.widget->setText(QString(tv.ptr != 0 ? *(const char*)tv.ptr : char(0))); break; - case 5: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const float*)tv.ptr : 0.f, tv.format)); break; - case 6: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const double*)tv.ptr : 0., tv.format)); break; - case 7: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const short*)tv.ptr : short(0), tv.format)); break; - case 8: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const uint*)tv.ptr : 0u, tv.format)); break; - case 9: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ulong*)tv.ptr : 0ul, tv.format)); break; - case 10: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ushort*)tv.ptr : ushort(0), tv.format)); break; - case 11: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const uchar*)tv.ptr : uchar(0), tv.format)); break; - case 12: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const llong*)tv.ptr : 0l, tv.format)); break; - case 13: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ullong*)tv.ptr: 0ull, tv.format)); break; - case 14: tv.widget->setText(numIntString(bitsValue(tv.ptr, tv.bitFrom, tv.bitCount), tv.format, tv.bitCount/8)); break; + case 0: tv.widget->setText((tv.ptr != 0 ? *(const QString *)tv.ptr : QString())); break; + case 1: tv.widget->setText((tv.ptr != 0 ? *(const bool *)tv.ptr : false) ? "true" : "false"); break; + case 2: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const int *)tv.ptr : 0, tv.format)); break; + case 3: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const long *)tv.ptr : 0l, tv.format)); break; + case 4: tv.widget->setText(QString(tv.ptr != 0 ? *(const char *)tv.ptr : char(0))); break; + case 5: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const float *)tv.ptr : 0.f, tv.format)); break; + case 6: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const double *)tv.ptr : 0., tv.format)); break; + case 7: tv.widget->setText(numFloatString(tv.ptr != 0 ? *(const short *)tv.ptr : short(0), tv.format)); break; + case 8: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const uint *)tv.ptr : 0u, tv.format)); break; + case 9: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ulong *)tv.ptr : 0ul, tv.format)); break; + case 10: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ushort *)tv.ptr : ushort(0), tv.format)); break; + case 11: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const uchar *)tv.ptr : uchar(0), tv.format)); break; + case 12: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const llong *)tv.ptr : 0l, tv.format)); break; + case 13: tv.widget->setText(numIntString(tv.ptr != 0 ? *(const ullong *)tv.ptr : 0ull, tv.format)); break; + case 14: + tv.widget->setText(numIntString(bitsValue(tv.ptr, tv.bitFrom, tv.bitCount), tv.format, tv.bitCount / 8)); + break; default: break; } } @@ -61,65 +63,149 @@ void QPIConsole::timerEvent(QTimerEvent * ) { } -#define ADD_VAR_BODY tv.name = name; if (!tv.name.isEmpty()) tv.name += ":"; tv.bitFrom = tv.bitCount = 0; tv.format = format; checkColumn(col); -#define ADD_VAR_SBODY tv.name = name; tv.bitFrom = tv.bitCount = 0; tv.format = format; checkColumn(col); +#define ADD_VAR_BODY \ + tv.name = name; \ + if (!tv.name.isEmpty()) tv.name += ":"; \ + tv.bitFrom = tv.bitCount = 0; \ + tv.format = format; \ + checkColumn(col); +#define ADD_VAR_SBODY \ + tv.name = name; \ + tv.bitFrom = tv.bitCount = 0; \ + tv.format = format; \ + checkColumn(col); -#define ADD_VAR_QT QLabel * lbl = new QLabel(name); QLabel * w = new QLabel(); \ - lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); \ - w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); \ - column(col).variables.back().label = lbl; column(col).variables.back().widget = w; \ - lbl->setAlignment(column(col).alignment); \ - applyFormat(lbl, format); applyFormat(w, format); \ - column(col).layout->addRow(lbl, w); +#define ADD_VAR_QT \ + QLabel * lbl = new QLabel(name); \ + QLabel * w = new QLabel(); \ + lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); \ + w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); \ + column(col).variables.back().label = lbl; \ + column(col).variables.back().widget = w; \ + lbl->setAlignment(column(col).alignment); \ + applyFormat(lbl, format); \ + applyFormat(w, format); \ + column(col).layout->addRow(lbl, w); void QPIConsole::addString(const QString & name, int col, Formats format) { - ADD_VAR_SBODY tv.type = -1; tv.ptr = 0; column(col).push_back(tv); + ADD_VAR_SBODY tv.type = -1; + tv.ptr = 0; + column(col).push_back(tv); QLabel * lbl = new QLabel(name); lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - column(col).variables.back().label = lbl; column(col).variables.back().widget = 0; + column(col).variables.back().label = lbl; + column(col).variables.back().widget = 0; lbl->setAlignment(column(col).alignment); applyFormat(lbl, format); column(col).layout->addRow(lbl); } -void QPIConsole::addVariable(const QString & name, const QString* ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 0; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} +void QPIConsole::addVariable(const QString & name, const QString * ptr, int col, Formats format) { + ADD_VAR_BODY tv.type = 0; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const bool * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 1; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 1; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const int * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 2; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 2; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const long * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 3; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 3; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const char * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 4; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 4; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const float * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 5; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 5; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const double * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 6; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 6; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const short * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 7; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 7; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const uint * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 8; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 8; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const ulong * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 9; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 9; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const ushort * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 10; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 10; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const uchar * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 11; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 11; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const llong * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 12; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 12; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addVariable(const QString & name, const ullong * ptr, int col, Formats format) { - ADD_VAR_BODY tv.type = 13; tv.ptr = ptr; column(col).push_back(tv); ADD_VAR_QT} + ADD_VAR_BODY tv.type = 13; + tv.ptr = ptr; + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addBitVariable(const QString & name, const void * ptr, int fromBit, int bitCount, int col, Formats format) { - tv.name = name; tv.bitFrom = fromBit; tv.bitCount = bitCount; tv.type = 14; tv.ptr = ptr; tv.format = format; - checkColumn(col); column(col).push_back(tv); ADD_VAR_QT} + tv.name = name; + tv.bitFrom = fromBit; + tv.bitCount = bitCount; + tv.type = 14; + tv.ptr = ptr; + tv.format = format; + checkColumn(col); + column(col).push_back(tv); + ADD_VAR_QT +} void QPIConsole::addEmptyLine(int col, uint count) { - tv.name = ""; tv.type = 0; tv.ptr = 0; tv.format = Normal; + tv.name = ""; + tv.type = 0; + tv.ptr = 0; + tv.format = Normal; for (uint i = 0; i < count; ++i) { checkColumn(col); column(col).push_back(tv); QLabel * lbl = new QLabel(); lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - column(col).variables.back().label = lbl; column(col).variables.back().widget = 0; + column(col).variables.back().label = lbl; + column(col).variables.back().widget = 0; lbl->setAlignment(column(col).alignment); applyFormat(lbl, tv.format); column(col).layout->addRow(lbl); @@ -128,10 +214,10 @@ void QPIConsole::addEmptyLine(int col, uint count) { int QPIConsole::addTab(const QString & name, char bind_key) { - QWidget * w = new QWidget(); - QVBoxLayout * lay = new QVBoxLayout(); + QWidget * w = new QWidget(); + QVBoxLayout * lay = new QVBoxLayout(); QHBoxLayout * clay = new QHBoxLayout(); - QLabel * lbl = new QLabel(); + QLabel * lbl = new QLabel(); lay->setContentsMargins(2, 2, 2, 2); clay->setContentsMargins(0, 0, 0, 0); lay->addLayout(clay); @@ -142,7 +228,7 @@ int QPIConsole::addTab(const QString & name, char bind_key) { tabs.push_back(Tab(name, bind_key)); tabs.back().layout = clay; tabs.back().widget = lbl; - cur_tab = tabs.size() - 1; + cur_tab = tabs.size() - 1; setCurrentIndex(cur_tab); return tabs.size(); } @@ -162,14 +248,14 @@ void QPIConsole::checkColumn(int col) { int QPIConsole::bitsValue(const void * src, int offset, int count) const { int ret = 0, stbyte = offset / 8, cbit = offset - stbyte * 8; - char cbyte = reinterpret_cast(src)[stbyte]; + char cbyte = reinterpret_cast(src)[stbyte]; for (int i = 0; i < count; i++) { ret |= ((cbyte >> cbit & 1) << i); cbit++; if (cbit == 8) { cbit = 0; stbyte++; - cbyte = reinterpret_cast(src)[stbyte]; + cbyte = reinterpret_cast(src)[stbyte]; } } return ret; @@ -181,7 +267,7 @@ const QString & QPIConsole::toBin(const void * d, int s) { uchar cc, b; for (int i = 0; i < s; ++i) { cc = ((const uchar *)d)[i]; - b = 1; + b = 1; for (int j = 0; j < 8; ++j) { binstr.prepend(cc & b ? "1" : "0"); b <<= 1; @@ -195,7 +281,7 @@ const QString & QPIConsole::toBin(const void * d, int s) { void QPIConsole::applyFormat(QLabel * l, QPIConsole::Formats f) { QColor fcol = Qt::black, bcol = QColor(0xFFFFFF); QFont fnt = font(); - + if (f.testFlag(QPIConsole::Bold)) fnt.setBold(true); if (f.testFlag(QPIConsole::Italic)) fnt.setItalic(true); if (f.testFlag(QPIConsole::Underline)) fnt.setUnderline(true); @@ -220,14 +306,14 @@ void QPIConsole::applyFormat(QLabel * l, QPIConsole::Formats f) { if (f.testFlag(QPIConsole::BackCyan)) bcol = Qt::cyan; if (f.testFlag(QPIConsole::BackWhite)) bcol = Qt::white; if (f.testFlag(QPIConsole::BackLighter)) bcol = bcol.lighter(150); - //if (f.testFlag(QPIConsole::BackDarker)) bcol = bcol.darker(150); - + // if (f.testFlag(QPIConsole::BackDarker)) bcol = bcol.darker(150); + if (f.testFlag(QPIConsole::Inverse)) { QColor tc = fcol; - fcol = bcol; - bcol = tc; + fcol = bcol; + bcol = tc; } - + l->setFont(fnt); QPalette pal = palette(); pal.setColor(QPalette::WindowText, fcol); diff --git a/libs/widgets/qpiconsole.h b/libs/widgets/qpiconsole.h index 9426421..6538479 100644 --- a/libs/widgets/qpiconsole.h +++ b/libs/widgets/qpiconsole.h @@ -1,33 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPICONSOLE_H #define QPICONSOLE_H -#include -#include -#include -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include +#include +#include +#include + typedef long long llong; typedef unsigned char uchar; @@ -40,44 +41,46 @@ typedef long double ldouble; class QAD_WIDGETS_EXPORT QPIConsole: public QTabWidget { Q_OBJECT + public: QPIConsole(QWidget * parent = 0); - - enum Format {Normal = 0x01, - Bold = 0x02, - Italic = 0x08, - Underline = 0x10, - Inverse = 0x40, - Black = 0x100, - Red = 0x200, - Green = 0x400, - Yellow = 0x800, - Blue = 0x1000, - Magenta = 0x2000, - Cyan = 0x4000, - White = 0x8000, - BackBlack = 0x10000, - BackRed = 0x20000, - BackGreen = 0x40000, - BackYellow = 0x80000, - BackBlue = 0x100000, - BackMagenta = 0x200000, - BackCyan = 0x400000, - BackWhite = 0x800000, - Dec = 0x1000000, - Hex = 0x2000000, - Oct = 0x4000000, - Bin = 0x8000000, - Scientific = 0x10000000, - Lighter = 0x20000000, - Darker = 0x40000000, - BackLighter = 0x80000000 - }; - + + enum Format { + Normal = 0x01, + Bold = 0x02, + Italic = 0x08, + Underline = 0x10, + Inverse = 0x40, + Black = 0x100, + Red = 0x200, + Green = 0x400, + Yellow = 0x800, + Blue = 0x1000, + Magenta = 0x2000, + Cyan = 0x4000, + White = 0x8000, + BackBlack = 0x10000, + BackRed = 0x20000, + BackGreen = 0x40000, + BackYellow = 0x80000, + BackBlue = 0x100000, + BackMagenta = 0x200000, + BackCyan = 0x400000, + BackWhite = 0x800000, + Dec = 0x1000000, + Hex = 0x2000000, + Oct = 0x4000000, + Bin = 0x8000000, + Scientific = 0x10000000, + Lighter = 0x20000000, + Darker = 0x40000000, + BackLighter = 0x80000000 + }; + Q_DECLARE_FLAGS(Formats, Format) Q_FLAGS(Formats) Q_ENUMS(Format) - + Q_PROPERTY(Qt::Alignment defaultAlignment READ defaultAlignment WRITE setDefaultAlignment) void addString(const QString & name, int column = 1, Formats format = QPIConsole::Normal); @@ -95,41 +98,58 @@ public: void addVariable(const QString & name, const ullong * ptr, int column = 1, Formats format = QPIConsole::Normal); void addVariable(const QString & name, const float * ptr, int column = 1, Formats format = QPIConsole::Normal); void addVariable(const QString & name, const double * ptr, int column = 1, Formats format = QPIConsole::Normal); - void addBitVariable(const QString & name, const void * ptr, int fromBit, int bitCount, int column = 1, Formats format = QPIConsole::Normal); + void + addBitVariable(const QString & name, const void * ptr, int fromBit, int bitCount, int column = 1, Formats format = QPIConsole::Normal); void addEmptyLine(int column = 1, uint count = 1); - uint tabsCount() const {return tabs.size();} - QString currentTab() const {return tabs[cur_tab].name;} + uint tabsCount() const { return tabs.size(); } + QString currentTab() const { return tabs[cur_tab].name; } int addTab(const QString & name, char bind_key = 0); bool removeTab(uint index); - bool removeTab(const QString & name) {return removeTab(tabIndex(name));} + bool removeTab(const QString & name) { return removeTab(tabIndex(name)); } bool renameTab(uint index, const QString & new_name); - bool renameTab(const QString & name, const QString & new_name) {return renameTab(tabIndex(name), new_name);} + bool renameTab(const QString & name, const QString & new_name) { return renameTab(tabIndex(name), new_name); } void setTabEnabled(int index, bool on); bool setTab(uint index); - bool setTab(const QString & name) {return setTab(tabIndex(name));} - //void clearTabs(bool clearScreen = true) {if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();} tabs.clear();} + bool setTab(const QString & name) { return setTab(tabIndex(name)); } + // void clearTabs(bool clearScreen = true) {if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();} tabs.clear();} - void addCustomStatus(const QString & str, Formats format = QPIConsole::Normal) {tabs[cur_tab].widget->setText(str); applyFormat(tabs[cur_tab].widget, format);} - void clearCustomStatus() {tabs[cur_tab].widget->clear();} - Qt::Alignment defaultAlignment() const {return def_align;} - void setDefaultAlignment(Qt::Alignment align) {def_align = align;} - void setColumnAlignment(int col, Qt::Alignment align) {if (col < 0 || col >= columns().size()) return; column(col).alignment = align;} - void setColumnAlignmentToAll(Qt::Alignment align) {for (int i = 0; i < tabs.size(); ++i) for (int j = 0; j < tabs[i].columns.size(); ++j) tabs[i].columns[j].alignment = align;/* fillLabels();*/} + void addCustomStatus(const QString & str, Formats format = QPIConsole::Normal) { + tabs[cur_tab].widget->setText(str); + applyFormat(tabs[cur_tab].widget, format); + } + void clearCustomStatus() { tabs[cur_tab].widget->clear(); } + Qt::Alignment defaultAlignment() const { return def_align; } + void setDefaultAlignment(Qt::Alignment align) { def_align = align; } + void setColumnAlignment(int col, Qt::Alignment align) { + if (col < 0 || col >= columns().size()) return; + column(col).alignment = align; + } + void setColumnAlignmentToAll(Qt::Alignment align) { + for (int i = 0; i < tabs.size(); ++i) + for (int j = 0; j < tabs[i].columns.size(); ++j) + tabs[i].columns[j].alignment = align; /* fillLabels();*/ + } - void clearVariables() {clearVariables(true);} - void clearVariables(bool clearScreen) {/*if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();}*/ columns().clear();} + void clearVariables() { clearVariables(true); } + void clearVariables(bool clearScreen) { /*if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();}*/ + columns().clear(); + } private: - void timerEvent(QTimerEvent * ); - QSize sizeHint() const {return QSize(100, 100);} + void timerEvent(QTimerEvent *); + QSize sizeHint() const { return QSize(100, 100); } void checkColumn(int col); void applyFormat(QLabel * l, Formats f); int bitsValue(const void * src, int offset, int count) const; - int tabIndex(const QString & n) const {for (int i = 0; i < tabs.size(); ++i) if (tabs[i].name == n) return i; return -1;} + int tabIndex(const QString & n) const { + for (int i = 0; i < tabs.size(); ++i) + if (tabs[i].name == n) return i; + return -1; + } const QString & toBin(const void * d, int s); - template + template QString numIntString(T v, Formats f, int bits = 0) { if (f.testFlag(QPIConsole::Hex)) return "0x" + QString::number(v, 16).toUpper(); if (f.testFlag(QPIConsole::Dec)) return QString::number(v); @@ -137,14 +157,14 @@ private: if (f.testFlag(QPIConsole::Bin)) return toBin(&v, bits); return QString::number(v); } - template + template QString numFloatString(T v, Formats f) { if (f.testFlag(QPIConsole::Scientific)) return QString::number(v, 'E', 5); return QString::number(v); } - + struct QAD_WIDGETS_EXPORT Variable { - Variable() {label = widget = 0;} + Variable() { label = widget = 0; } QString name; Formats format; int type; @@ -153,24 +173,40 @@ private: const void * ptr; QLabel * label; QLabel * widget; - void operator =(const Variable & src) {name = src.name; format = src.format; type = src.type; - bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr;} + void operator=(const Variable & src) { + name = src.name; + format = src.format; + type = src.type; + bitFrom = src.bitFrom; + bitCount = src.bitCount; + ptr = src.ptr; + } }; struct QAD_WIDGETS_EXPORT Column { - Column(Qt::Alignment align = Qt::AlignRight) {variables.reserve(16); alignment = align;} + Column(Qt::Alignment align = Qt::AlignRight) { + variables.reserve(16); + alignment = align; + } QVector variables; Qt::Alignment alignment; QFormLayout * layout; - int size() const {return variables.size();} - Variable & operator [](int index) {return variables[index];} - const Variable & operator [](int index) const {return variables[index];} - void push_back(const Variable & v) {variables.push_back(v);} - void operator =(const Column & src) {variables = src.variables; alignment = src.alignment;} + int size() const { return variables.size(); } + Variable & operator[](int index) { return variables[index]; } + const Variable & operator[](int index) const { return variables[index]; } + void push_back(const Variable & v) { variables.push_back(v); } + void operator=(const Column & src) { + variables = src.variables; + alignment = src.alignment; + } }; struct QAD_WIDGETS_EXPORT Tab { - Tab(QString n = "", char k = 0) {columns.reserve(16); name = n; key = k;} + Tab(QString n = "", char k = 0) { + columns.reserve(16); + name = n; + key = k; + } QVector columns; QString name; char key; @@ -178,22 +214,27 @@ private: QLabel * widget; }; - QVector & columns() {return tabs[cur_tab].columns;} - Column & column(int index) {return tabs[cur_tab].columns[index - 1];} + QVector & columns() { return tabs[cur_tab].columns; } + Column & column(int index) { return tabs[cur_tab].columns[index - 1]; } Qt::Alignment def_align; QVector tabs; QString binstr; Variable tv; int cur_tab, timer; - -private slots: - void tabChanged(int tab) {cur_tab = tab;} - -public slots: - void start(float freq = 40) {if (timer >= 0) killTimer(timer); timer = startTimer(freq > 0. ? 1000 / freq : 25);} - void stop() {if (timer >= 0) killTimer(timer); timer = -1;} +private slots: + void tabChanged(int tab) { cur_tab = tab; } + +public slots: + void start(float freq = 40) { + if (timer >= 0) killTimer(timer); + timer = startTimer(freq > 0. ? 1000 / freq : 25); + } + void stop() { + if (timer >= 0) killTimer(timer); + timer = -1; + } }; Q_DECLARE_OPERATORS_FOR_FLAGS(QPIConsole::Formats) diff --git a/libs/widgets/qpievaluator_p.cpp b/libs/widgets/qpievaluator_p.cpp index 84ac805..9eaa2c4 100644 --- a/libs/widgets/qpievaluator_p.cpp +++ b/libs/widgets/qpievaluator_p.cpp @@ -32,8 +32,8 @@ QPIEvaluatorContent::QPIEvaluatorContent() { addFunction("rad", 1); addFunction("deg", 1); clearCustomVariables(); - //addVariable("n", 0.); - //addVariable("x1", 123); + // addVariable("n", 0.); + // addVariable("x1", 123); } @@ -64,18 +64,18 @@ void QPIEvaluatorContent::clearCustomVariables() { void QPIEvaluatorContent::sortVariables() { var_index.clear(); -#if QT_VERSION < QT_VERSION_CHECK(5,13,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) qSort #else std::sort #endif - (variables.begin(), variables.end()); + (variables.begin(), variables.end()); for (int i = 0; i < variables.size(); i++) var_index[variables[i].name] = i; /* qDebug() << "---"; for (int i = 0; i < variables.size(); i++) { - qDebug() << variables[i].name; + qDebug() << variables[i].name; } */ } @@ -120,8 +120,10 @@ const QString & QPIEvaluator::prepare(const QString & string) { replaceOperators(); removeSpaces(); checkBrackets(); - while (fillElements()) checkBrackets(); - while (setSignes()) fillElements(); + while (fillElements()) + checkBrackets(); + while (setSignes()) + fillElements(); removeJunk(); findUnknownVariables(); return currentString; @@ -159,7 +161,8 @@ void QPIEvaluator::removeJunk() { elements.pop_back(); junk = true; break; - } else break; + } else + break; } } } @@ -189,7 +192,8 @@ void QPIEvaluator::findUnknownVariables() { QString cvar; unknownVars.clear(); for (int i = 0; i < currentString.length(); i++) { - if (elements[i].var_num == -666) cvar += currentString[i]; + if (elements[i].var_num == -666) + cvar += currentString[i]; else { if (cvar.length() == 0) continue; unknownVars << cvar; @@ -202,13 +206,8 @@ void QPIEvaluator::findUnknownVariables() { bool QPIEvaluator::isSign(const QChar & ch) { - return ch == '+' || ch == '-' || - ch == '*' || ch == '/' || - ch == '%' || ch == '^' || - ch == '=' || ch == ':' || - ch == '>' || ch == '<' || - ch == '}' || ch == '{' || - ch == '&' || ch == '|'; + return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '=' || ch == ':' || ch == '>' || ch == '<' || + ch == '}' || ch == '{' || ch == '&' || ch == '|'; } @@ -226,7 +225,8 @@ void QPIEvaluator::checkBrackets() { if (bcnt == 0) { currentString.insert(bpos + inserted, "("); inserted++; - } else bcnt--; + } else + bcnt--; } } if (bcnt > 0) currentString += QString(bcnt, ')'); @@ -234,9 +234,8 @@ void QPIEvaluator::checkBrackets() { for (int i = 0; i < tmps.length() - 1; i++) { fc = tmps[i].toLower(); sc = tmps[i + 1].toLower(); - if ((fc == ')' && sc == '(') || - (fc == ')' && sc >= '0' && sc <= '9') || - (fc == ')' && sc >= 'a' && sc <= 'z') ) tmps.insert(++i, '*'); + if ((fc == ')' && sc == '(') || (fc == ')' && sc >= '0' && sc <= '9') || (fc == ')' && sc >= 'a' && sc <= 'z')) + tmps.insert(++i, '*'); } currentString = tmps; } @@ -244,26 +243,26 @@ void QPIEvaluator::checkBrackets() { bool QPIEvaluator::fillElements() { int fstart, flen, cnum = 0, cpart = 0, cfunc; - QChar cc, nc, pc, fc = '!'; + QChar cc, nc, pc, fc = '!'; bool numFound = false; QString curfind, tmps = currentString; elements.resize(tmps.length()); for (int i = 0; i < elements.size(); i++) { - elements[i].type = QPIEvaluatorTypes::etVariable; + elements[i].type = QPIEvaluatorTypes::etVariable; elements[i].var_num = -666; } currentVariables.clear(); - //qDebug().nospace() << "search for functions ..."; + // qDebug().nospace() << "search for functions ..."; for (int i = 0; i < content.functionsCount(); i++) { curfind = content.function(i).identifier; - cfunc = i; //(int)content.function(i).type; - flen = curfind.length(); - fstart = 0; + cfunc = i; //(int)content.function(i).type; + flen = curfind.length(); + fstart = 0; while (fstart >= 0) { fstart = tmps.indexOf(curfind, fstart); if (fstart < 0) break; if (tmps[fstart + flen] != '(') { - //currentString.insert(fstart + flen, "("); + // currentString.insert(fstart + flen, "("); fstart++; continue; } @@ -275,11 +274,11 @@ bool QPIEvaluator::fillElements() { } } cnum = 0; - //qDebug().nospace() << "search for variables ..."; + // qDebug().nospace() << "search for variables ..."; for (int i = 0; i < content.variablesCount(); i++) { curfind = content.variable(i).name; - flen = curfind.length(); - fstart = 0; + flen = curfind.length(); + fstart = 0; while (fstart >= 0) { fstart = tmps.indexOf(curfind, fstart); if (fstart < 0) break; @@ -291,19 +290,19 @@ bool QPIEvaluator::fillElements() { } } curfind = ""; - cnum = 1; - //qDebug().nospace() << "search for numbers ..."; + cnum = 1; + // qDebug().nospace() << "search for numbers ..."; for (int i = 0; i < tmps.length(); i++) { cc = tmps[i]; /*if (cc == " " || cc == "(" || cc == ")") { - curfind = ""; - cpart = 0; - numFound = false; - continue; + curfind = ""; + cpart = 0; + numFound = false; + continue; }*/ switch (cpart) { case 0: - if ((cc >= '0' && cc <= '9')) {// || cc == '-' || cc == '+') { + if ((cc >= '0' && cc <= '9')) { // || cc == '-' || cc == '+') { curfind += cc; cpart = 1; continue; @@ -365,7 +364,7 @@ bool QPIEvaluator::fillElements() { break; } if (numFound) { - //qDebug().nospace() << "add " << cnum << ": " << curfind << " = " << curfind.toDouble(); + // qDebug().nospace() << "add " << cnum << ": " << curfind << " = " << curfind.toDouble(); currentVariables.push_back(QPIEvaluatorTypes::Variable("tmp" + QString::number(cnum), curfind.toDouble())); for (int j = i - curfind.length(); j < i; j++) { elements[j].set(QPIEvaluatorTypes::etNumber, cnum, -cnum); @@ -373,12 +372,12 @@ bool QPIEvaluator::fillElements() { } curfind = ""; cnum++; - cpart = 0; + cpart = 0; numFound = false; } } if (cpart > 0) { - //qDebug().nospace() << "add " << cnum << ": " << curfind << " = " << curfind.toDouble(); + // qDebug().nospace() << "add " << cnum << ": " << curfind << " = " << curfind.toDouble(); currentVariables.push_back(QPIEvaluatorTypes::Variable("tmp" + QString::number(cnum), curfind.toDouble())); for (int j = tmps.length() - curfind.length(); j < tmps.length(); j++) { elements[j].set(QPIEvaluatorTypes::etNumber, cnum, -cnum); @@ -386,30 +385,34 @@ bool QPIEvaluator::fillElements() { } } cc = nc = fc; - //qDebug().nospace() << "search for signes ..."; + // qDebug().nospace() << "search for signes ..."; for (int i = 0; i < tmps.length(); i++) { cc = tmps[i]; - if (i > 0) pc = tmps[i - 1]; - else pc = fc; - if (i < tmps.length() - 1) nc = tmps[i + 1]; - else nc = fc; + if (i > 0) + pc = tmps[i - 1]; + else + pc = fc; + if (i < tmps.length() - 1) + nc = tmps[i + 1]; + else + nc = fc; if (cc == '(' || cc == ')' || cc == ',') { elements[i].set(QPIEvaluatorTypes::etOperator, -1); continue; } if (cc == '-' || cc == '+') { elements[i].set(QPIEvaluatorTypes::etOperator, -1); - if (i < tmps.length() - 1) if (elements[i + 1].type == QPIEvaluatorTypes::etVariable || - elements[i + 1].type == QPIEvaluatorTypes::etFunction) continue; + if (i < tmps.length() - 1) + if (elements[i + 1].type == QPIEvaluatorTypes::etVariable || elements[i + 1].type == QPIEvaluatorTypes::etFunction) + continue; if ((pc == '(' || isSign(pc) || i == 0) && i < tmps.length() - 1) { if (elements[i + 1].type != QPIEvaluatorTypes::etOperator) { cnum = elements[i + 1].num; elements[i].set(QPIEvaluatorTypes::etNumber, cnum); tmps.replace(i, 1, fc); - ///cout << "found sign " << cc << " :" << cnum - 1 << endl; - if (cc == '-' && currentVariables.size() >= cnum) - currentVariables[cnum - 1].value = -currentVariables[cnum - 1].value; - //i++; + /// cout << "found sign " << cc << " :" << cnum - 1 << endl; + if (cc == '-' && currentVariables.size() >= cnum) currentVariables[cnum - 1].value = -currentVariables[cnum - 1].value; + // i++; continue; } } @@ -423,17 +426,17 @@ bool QPIEvaluator::fillElements() { qDebug().nospace() << tmps; cout << " "; for (int i = 0; i < elements.size(); i++) { - switch (elements[i].type) { - case etFunction: cout << "f"; break; - case etNumber: cout << "n"; break; - case etOperator: cout << "o"; break; - case etVariable: cout << "v"; break; - } + switch (elements[i].type) { + case etFunction: cout << "f"; break; + case etNumber: cout << "n"; break; + case etOperator: cout << "o"; break; + case etVariable: cout << "v"; break; + } } cout << endl; */ return false; - //for (int i = 0; i < currentVariables.size(); i++) qDebug() << "var " << i << ": " << currentVariables[i].value.real(); + // for (int i = 0; i < currentVariables.size(); i++) qDebug() << "var " << i << ": " << currentVariables[i].value.real(); } @@ -443,29 +446,45 @@ bool QPIEvaluator::setSignes() { QString tmps = currentString; for (int i = 0; i < tmps.length() - 1; i++) { needInsert = 0; - ni = i + 1; + ni = i + 1; if (i > 0) pi = i - 1; fc = tmps[i].toLower(); sc = tmps[ni].toLower(); pc = tmps[pi].toLower(); - //if (elements[i].type == etOperator || elements[ni].type == etVariable) continue; + // if (elements[i].type == etOperator || elements[ni].type == etVariable) continue; if (fc == ',' || sc == ',') continue; if (elements[i].type == QPIEvaluatorTypes::etOperator && elements[ni].type == QPIEvaluatorTypes::etOperator) continue; - if (fc == ')' && (elements[ni].type == QPIEvaluatorTypes::etNumber || elements[ni].type == QPIEvaluatorTypes::etVariable || elements[ni].type == QPIEvaluatorTypes::etFunction)) needInsert = 1; - if (sc == '(' && (elements[i].type == QPIEvaluatorTypes::etNumber || elements[i].type == QPIEvaluatorTypes::etVariable)) needInsert = 1; - if (elements[i].type == QPIEvaluatorTypes::etNumber && elements[ni].type == QPIEvaluatorTypes::etNumber && elements[i].num != elements[ni].num) needInsert = 1; - if (elements[i].type == QPIEvaluatorTypes::etVariable && elements[ni].type == QPIEvaluatorTypes::etVariable && elements[i].num != elements[ni].num) needInsert = 1; - if ((elements[i].type == QPIEvaluatorTypes::etNumber && elements[ni].type == QPIEvaluatorTypes::etVariable) || (elements[i].type == QPIEvaluatorTypes::etVariable && elements[ni].type == QPIEvaluatorTypes::etNumber)) needInsert = 1; - if ((elements[i].type == QPIEvaluatorTypes::etNumber || elements[i].type == QPIEvaluatorTypes::etVariable) && elements[ni].type == QPIEvaluatorTypes::etFunction) needInsert = 1; - if (elements[i].type == QPIEvaluatorTypes::etFunction && elements[ni].type == QPIEvaluatorTypes::etFunction && elements[i].num != elements[ni].num) needInsert = 2; - if (elements[i].type == QPIEvaluatorTypes::etFunction && elements[ni].type != QPIEvaluatorTypes::etFunction && sc != '(') needInsert = 2; - if (elements[pi].type == QPIEvaluatorTypes::etOperator && (elements[ni].type == QPIEvaluatorTypes::etFunction || elements[ni].type == QPIEvaluatorTypes::etVariable) && fc == '-') needInsert = 3; + if (fc == ')' && (elements[ni].type == QPIEvaluatorTypes::etNumber || elements[ni].type == QPIEvaluatorTypes::etVariable || + elements[ni].type == QPIEvaluatorTypes::etFunction)) + needInsert = 1; + if (sc == '(' && (elements[i].type == QPIEvaluatorTypes::etNumber || elements[i].type == QPIEvaluatorTypes::etVariable)) + needInsert = 1; + if (elements[i].type == QPIEvaluatorTypes::etNumber && elements[ni].type == QPIEvaluatorTypes::etNumber && + elements[i].num != elements[ni].num) + needInsert = 1; + if (elements[i].type == QPIEvaluatorTypes::etVariable && elements[ni].type == QPIEvaluatorTypes::etVariable && + elements[i].num != elements[ni].num) + needInsert = 1; + if ((elements[i].type == QPIEvaluatorTypes::etNumber && elements[ni].type == QPIEvaluatorTypes::etVariable) || + (elements[i].type == QPIEvaluatorTypes::etVariable && elements[ni].type == QPIEvaluatorTypes::etNumber)) + needInsert = 1; + if ((elements[i].type == QPIEvaluatorTypes::etNumber || elements[i].type == QPIEvaluatorTypes::etVariable) && + elements[ni].type == QPIEvaluatorTypes::etFunction) + needInsert = 1; + if (elements[i].type == QPIEvaluatorTypes::etFunction && elements[ni].type == QPIEvaluatorTypes::etFunction && + elements[i].num != elements[ni].num) + needInsert = 2; + if (elements[i].type == QPIEvaluatorTypes::etFunction && elements[ni].type != QPIEvaluatorTypes::etFunction && sc != '(') + needInsert = 2; + if (elements[pi].type == QPIEvaluatorTypes::etOperator && + (elements[ni].type == QPIEvaluatorTypes::etFunction || elements[ni].type == QPIEvaluatorTypes::etVariable) && fc == '-') + needInsert = 3; switch (needInsert) { case 1: currentString.insert(ni + inserted, "*"); elements.insert(ni + inserted, QPIEvaluatorTypes::Element(QPIEvaluatorTypes::etOperator, -1)); - //inserted++; - //i++; + // inserted++; + // i++; return true; /*case 2: currentString.insert(ni + inserted, ")"); @@ -478,17 +497,17 @@ bool QPIEvaluator::setSignes() { case 3: currentString.insert(ni + inserted, "1*"); elements.insert(ni + inserted, QPIEvaluatorTypes::Element(QPIEvaluatorTypes::etOperator, -1)); - //inserted; - //i++; + // inserted; + // i++; return true; } } /*if (elements[tmps.length() - 1].type == etFunction) { - currentString.insert(tmps.length() + inserted, ")"); - currentString.insert(tmps.length() + inserted, "("); - elements.insert(tmps.length() + inserted, Element(etOperator, -1)); - elements.insert(tmps.length() + inserted, Element(etOperator, -1)); - return true; + currentString.insert(tmps.length() + inserted, ")"); + currentString.insert(tmps.length() + inserted, "("); + elements.insert(tmps.length() + inserted, Element(etOperator, -1)); + elements.insert(tmps.length() + inserted, Element(etOperator, -1)); + return true; }*/ return false; } @@ -507,8 +526,9 @@ void QPIEvaluator::convert() { j++; } currentString.replace(i, j - i, " "); - for (int k = i + 1; k < j; k++) elements.remove(i); - //i++; + for (int k = i + 1; k < j; k++) + elements.remove(i); + // i++; } for (int i = 0; i < currentString.length(); i++) { pe = elements[i]; @@ -520,8 +540,9 @@ void QPIEvaluator::convert() { j++; } currentString.replace(i, j - i, " "); - for (int k = i + 1; k < j; k++) elements.remove(i); - //i++; + for (int k = i + 1; k < j; k++) + elements.remove(i); + // i++; } for (int i = 0; i < currentString.length(); i++) { pe = elements[i]; @@ -533,33 +554,33 @@ void QPIEvaluator::convert() { j++; } currentString.replace(i, j - i, " "); - for (int k = i + 1; k < j; k++) elements.remove(i); - //i++; + for (int k = i + 1; k < j; k++) + elements.remove(i); + // i++; } /*qDebug().nospace() << currentString; cout << " "; for (int i = 0; i < elements.size(); i++) { - switch (elements[i].type) { - case etFunction: cout << "f"; break; - case etNumber: cout << "n"; break; - case etOperator: cout << "o"; break; - case etVariable: cout << "v"; break; - } + switch (elements[i].type) { + case etFunction: cout << "f"; break; + case etNumber: cout << "n"; break; + case etOperator: cout << "o"; break; + case etVariable: cout << "v"; break; + } } cout << endl;*/ } - const QString & QPIEvaluator::preprocess(const QString & string) { static QString ret; int lind; ret = prepare(string); convert(); instructions.clear(); - //qDebug() << preproc->currentString; + // qDebug() << preproc->currentString; variables = currentVariables; - lind = parse(currentString); + lind = parse(currentString); if (instructions.size() == 0) { variables.push_back(QPIEvaluatorTypes::Variable()); instructions.push_back(QPIEvaluatorTypes::Instruction(QPIEvaluatorTypes::oNone, QVector(1, lind), -variables.size())); @@ -568,17 +589,17 @@ const QString & QPIEvaluator::preprocess(const QString & string) { /* cout << endl << "variables:" << endl; for (int i = 0; i < variables.size(); i++) - cout << i << " value = " << variables[i].value << endl; + cout << i << " value = " << variables[i].value << endl; cout << endl << "instructions:" << endl; for (int i = 0; i < instructions.size(); i++) { - cout << i << endl; - cout << " operation " << instructions[i].operation << endl; - cout << " operators: "; - for (int j = 0; j < instructions[i].operators.size(); j++) - cout << instructions[i].operators[j] << "; "; - cout << endl << " function " << instructions[i].function << endl; - cout << " out " << instructions[i].out << endl; + cout << i << endl; + cout << " operation " << instructions[i].operation << endl; + cout << " operators: "; + for (int j = 0; j < instructions[i].operators.size(); j++) + cout << instructions[i].operators[j] << "; "; + cout << endl << " function " << instructions[i].function << endl; + cout << " out " << instructions[i].out << endl; } */ makeOutput(ret); @@ -616,53 +637,51 @@ int QPIEvaluator::parse(const QString & string, int offset) { QVector args, atmp; QVector opers; - ///qDebug() << "to parse :" + string; - ///cout << " "; for (int i = 0; i < slen; i++) cout << preproc->elements[i + offset].type; cout << endl; + /// qDebug() << "to parse :" + string; + /// cout << " "; for (int i = 0; i < slen; i++) cout << preproc->elements[i + offset].type; cout << endl; for (int i = 0; i < slen; i++) { ce = elements[i + offset]; cc = string[i]; switch (ce.type) { - case QPIEvaluatorTypes::etNumber: - args.push_back(ce.var_num); - continue; - case QPIEvaluatorTypes::etVariable: - args.push_back(ce.var_num); - continue; + case QPIEvaluatorTypes::etNumber: args.push_back(ce.var_num); continue; + case QPIEvaluatorTypes::etVariable: args.push_back(ce.var_num); continue; case QPIEvaluatorTypes::etFunction: i++; cfunc = content.function(ce.var_num); - //facnt = cfunc.arguments; + // facnt = cfunc.arguments; atmp.clear(); bcnt = farg = 1; - ///qDebug() << "function: " + cfunc.identifier; - //for (int k = 0; k < facnt; k++) { - carg = ""; - k = i + 1; - //if (string.size() <= k || k < 0) return -666; + /// qDebug() << "function: " + cfunc.identifier; + // for (int k = 0; k < facnt; k++) { + carg = ""; + k = i + 1; + // if (string.size() <= k || k < 0) return -666; while (bcnt > 0) { - //if (k < facnt - 1) fcomma = string.indexOf(',', j); + // if (k < facnt - 1) fcomma = string.indexOf(',', j); cc = string[k]; switch (cc.toLatin1()) { case '(': bcnt++; break; case ')': bcnt--; if (bcnt == 0) { - ///qDebug() << "arument: " << carg; + /// qDebug() << "arument: " << carg; atmp.push_back(parse(carg, k + offset - carg.length())); k++; carg = ""; - if (atmp.size() > 0) if (atmp.back() < 0 && farg > 0) farg = atmp.back(); + if (atmp.size() > 0) + if (atmp.back() < 0 && farg > 0) farg = atmp.back(); continue; } break; case ',': if (bcnt == 1) { - ///qDebug() << "arument: " << carg; + /// qDebug() << "arument: " << carg; atmp.push_back(parse(carg, k + offset - carg.length())); k++; carg = ""; - if (atmp.size() > 0) if (atmp.back() < 0 && farg > 0) farg = atmp.back(); + if (atmp.size() > 0) + if (atmp.back() < 0 && farg > 0) farg = atmp.back(); continue; } break; @@ -677,31 +696,73 @@ int QPIEvaluator::parse(const QString & string, int offset) { } instructions.push_back(QPIEvaluatorTypes::Instruction(QPIEvaluatorTypes::oFunction, atmp, farg, ce.var_num)); args.push_back(farg); - //for (int i = 0; i < args.size(); i++) cout << preproc->currentVariables[-args[i]].value << endl; - //i = j + 1; + // for (int i = 0; i < args.size(); i++) cout << preproc->currentVariables[-args[i]].value << endl; + // i = j + 1; continue; case QPIEvaluatorTypes::etOperator: - //qDebug() << "operator: " << cc; + // qDebug() << "operator: " << cc; if (cc == '(') { sbrackets = inBrackets(string.right(slen - i)); args.push_back(parse(sbrackets, i + offset + 1)); i += sbrackets.length() + 1; continue; } - if (cc == '+') {opers.push_back(QPIEvaluatorTypes::oAdd); continue;} - if (cc == '-') {opers.push_back(QPIEvaluatorTypes::oSubtract); continue;} - if (cc == '*') {opers.push_back(QPIEvaluatorTypes::oMultiply); continue;} - if (cc == '/') {opers.push_back(QPIEvaluatorTypes::oDivide); continue;} - if (cc == '%') {opers.push_back(QPIEvaluatorTypes::oResidue); continue;} - if (cc == '^') {opers.push_back(QPIEvaluatorTypes::oPower); continue;} - if (cc == '=') {opers.push_back(QPIEvaluatorTypes::oEqual); continue;} - if (cc == ':') {opers.push_back(QPIEvaluatorTypes::oNotEqual); continue;} - if (cc == '}') {opers.push_back(QPIEvaluatorTypes::oGreaterEqual); continue;} - if (cc == '{') {opers.push_back(QPIEvaluatorTypes::oSmallerEqual); continue;} - if (cc == '>') {opers.push_back(QPIEvaluatorTypes::oGreater); continue;} - if (cc == '<') {opers.push_back(QPIEvaluatorTypes::oSmaller); continue;} - if (cc == '&') {opers.push_back(QPIEvaluatorTypes::oAnd); continue;} - if (cc == '|') {opers.push_back(QPIEvaluatorTypes::oOr); continue;} + if (cc == '+') { + opers.push_back(QPIEvaluatorTypes::oAdd); + continue; + } + if (cc == '-') { + opers.push_back(QPIEvaluatorTypes::oSubtract); + continue; + } + if (cc == '*') { + opers.push_back(QPIEvaluatorTypes::oMultiply); + continue; + } + if (cc == '/') { + opers.push_back(QPIEvaluatorTypes::oDivide); + continue; + } + if (cc == '%') { + opers.push_back(QPIEvaluatorTypes::oResidue); + continue; + } + if (cc == '^') { + opers.push_back(QPIEvaluatorTypes::oPower); + continue; + } + if (cc == '=') { + opers.push_back(QPIEvaluatorTypes::oEqual); + continue; + } + if (cc == ':') { + opers.push_back(QPIEvaluatorTypes::oNotEqual); + continue; + } + if (cc == '}') { + opers.push_back(QPIEvaluatorTypes::oGreaterEqual); + continue; + } + if (cc == '{') { + opers.push_back(QPIEvaluatorTypes::oSmallerEqual); + continue; + } + if (cc == '>') { + opers.push_back(QPIEvaluatorTypes::oGreater); + continue; + } + if (cc == '<') { + opers.push_back(QPIEvaluatorTypes::oSmaller); + continue; + } + if (cc == '&') { + opers.push_back(QPIEvaluatorTypes::oAnd); + continue; + } + if (cc == '|') { + opers.push_back(QPIEvaluatorTypes::oOr); + continue; + } } } /* @@ -711,25 +772,33 @@ int QPIEvaluator::parse(const QString & string, int offset) { for (int i = 0; i < opers.size(); i++) cout << opers[i] << ", "; */ if (opers.size() == 0) { - if (args.size() > 0) return args.back(); - else return -666; + if (args.size() > 0) + return args.back(); + else + return -666; } int oprior = -1; QVector opv; - while(1) { + while (1) { operationsByPriority(++oprior, opv); if (opv.isEmpty()) break; for (int j = 0; j < opers.size(); j++) { if (!opv.contains(opers[j])) continue; atmp.clear(); - if (j < args.size() && j >= 0) atmp.push_back(args[j]); - else atmp.push_back(-666); - if (j + 1 < args.size() && j >= -1) atmp.push_back(args[j + 1]); - else atmp.push_back(-666); + if (j < args.size() && j >= 0) + atmp.push_back(args[j]); + else + atmp.push_back(-666); + if (j + 1 < args.size() && j >= -1) + atmp.push_back(args[j + 1]); + else + atmp.push_back(-666); farg = 1; - if (atmp[0] < 0) farg = atmp[0]; + if (atmp[0] < 0) + farg = atmp[0]; else { - if (atmp[1] < 0) farg = atmp[1]; + if (atmp[1] < 0) + farg = atmp[1]; else { variables.push_back(QPIEvaluatorTypes::Variable()); farg = -variables.size(); @@ -745,7 +814,7 @@ int QPIEvaluator::parse(const QString & string, int offset) { } } return instructions.back().out; - ///cout << endl; + /// cout << endl; } @@ -758,7 +827,7 @@ bool QPIEvaluator::check() { } for (int i = 0; i < instructions.size(); i++) { error = false; - ci = instructions[i]; + ci = instructions[i]; switch (ci.operation) { case QPIEvaluatorTypes::oNone: break; case QPIEvaluatorTypes::oFunction: @@ -838,9 +907,10 @@ void QPIEvaluator::operationsByPriority(int p, QVector= 0. ? complexd_1 : -complexd_1; break; - case QPIEvaluatorTypes::bfRad: - tmpvars[oi].value = value(ci.operators[0]) * complexd(deg2rad_qpie, 0.); - break; - case QPIEvaluatorTypes::bfDeg: - tmpvars[oi].value = value(ci.operators[0]) * complexd(rad2deg_qpie, 0.); - break; + case QPIEvaluatorTypes::bfRad: tmpvars[oi].value = value(ci.operators[0]) * complexd(deg2rad_qpie, 0.); break; + case QPIEvaluatorTypes::bfDeg: tmpvars[oi].value = value(ci.operators[0]) * complexd(rad2deg_qpie, 0.); break; case QPIEvaluatorTypes::bfRandom: - tmp = static_cast(rand()) / RAND_MAX; - stmp = value(ci.operators[1]) - value(ci.operators[0]); + tmp = static_cast(rand()) / RAND_MAX; + stmp = value(ci.operators[1]) - value(ci.operators[0]); tmpvars[oi].value = value(ci.operators[0]) + tmp * stmp; break; default: break; @@ -969,75 +997,45 @@ inline bool QPIEvaluator::execInstructions() { int oi; complexd tmp; tmpvars = variables; - //cout << "var count " << tmpvars.size() << endl; + // cout << "var count " << tmpvars.size() << endl; for (int i = 0; i < instructions.size(); i++) { ci = instructions[i]; oi = -ci.out - 1; - //cout << value(ci.operators[0]) << operationChar(ci.operation) << value(ci.operators[1]) << ", " << oi << endl; + // cout << value(ci.operators[0]) << operationChar(ci.operation) << value(ci.operators[1]) << ", " << oi << endl; switch (ci.operation) { - case QPIEvaluatorTypes::oAdd: - tmpvars[oi].value = value(ci.operators[0]) + value(ci.operators[1]); - break; - case QPIEvaluatorTypes::oSubtract: - tmpvars[oi].value = value(ci.operators[0]) - value(ci.operators[1]); - break; - case QPIEvaluatorTypes::oMultiply: - tmpvars[oi].value = value(ci.operators[0]) * value(ci.operators[1]); - break; + case QPIEvaluatorTypes::oAdd: tmpvars[oi].value = value(ci.operators[0]) + value(ci.operators[1]); break; + case QPIEvaluatorTypes::oSubtract: tmpvars[oi].value = value(ci.operators[0]) - value(ci.operators[1]); break; + case QPIEvaluatorTypes::oMultiply: tmpvars[oi].value = value(ci.operators[0]) * value(ci.operators[1]); break; case QPIEvaluatorTypes::oDivide: tmp = value(ci.operators[1]); - if (tmp == complexd(0., 0.)) tmpvars[oi].value = 0.; - else tmpvars[oi].value = value(ci.operators[0]) / tmp; - break; - case QPIEvaluatorTypes::oResidue: - tmpvars[oi].value = residue(value(ci.operators[0]), value(ci.operators[1])); - break; - case QPIEvaluatorTypes::oPower: - tmpvars[oi].value = pow(value(ci.operators[0]), value(ci.operators[1])); - break; - case QPIEvaluatorTypes::oEqual: - tmpvars[oi].value = value(ci.operators[0]) == value(ci.operators[1]); - break; - case QPIEvaluatorTypes::oNotEqual: - tmpvars[oi].value = value(ci.operators[0]) != value(ci.operators[1]); - break; - case QPIEvaluatorTypes::oGreaterEqual: - tmpvars[oi].value = value(ci.operators[0]).real() >= value(ci.operators[1]).real(); - break; - case QPIEvaluatorTypes::oSmallerEqual: - tmpvars[oi].value = value(ci.operators[0]).real() <= value(ci.operators[1]).real(); - break; - case QPIEvaluatorTypes::oGreater: - tmpvars[oi].value = value(ci.operators[0]).real() > value(ci.operators[1]).real(); - break; - case QPIEvaluatorTypes::oSmaller: - tmpvars[oi].value = value(ci.operators[0]).real() < value(ci.operators[1]).real(); - break; - case QPIEvaluatorTypes::oAnd: - tmpvars[oi].value = value(ci.operators[0]).real() > 0. && value(ci.operators[1]).real() > 0.; - break; - case QPIEvaluatorTypes::oOr: - tmpvars[oi].value = value(ci.operators[0]).real() > 0. || value(ci.operators[1]).real() > 0.; - break; - case QPIEvaluatorTypes::oFunction: - execFunction(ci); - break; - case QPIEvaluatorTypes::oNone: - tmpvars[oi].value = value(ci.operators[0]); + if (tmp == complexd(0., 0.)) + tmpvars[oi].value = 0.; + else + tmpvars[oi].value = value(ci.operators[0]) / tmp; break; + case QPIEvaluatorTypes::oResidue: tmpvars[oi].value = residue(value(ci.operators[0]), value(ci.operators[1])); break; + case QPIEvaluatorTypes::oPower: tmpvars[oi].value = pow(value(ci.operators[0]), value(ci.operators[1])); break; + case QPIEvaluatorTypes::oEqual: tmpvars[oi].value = value(ci.operators[0]) == value(ci.operators[1]); break; + case QPIEvaluatorTypes::oNotEqual: tmpvars[oi].value = value(ci.operators[0]) != value(ci.operators[1]); break; + case QPIEvaluatorTypes::oGreaterEqual: tmpvars[oi].value = value(ci.operators[0]).real() >= value(ci.operators[1]).real(); break; + case QPIEvaluatorTypes::oSmallerEqual: tmpvars[oi].value = value(ci.operators[0]).real() <= value(ci.operators[1]).real(); break; + case QPIEvaluatorTypes::oGreater: tmpvars[oi].value = value(ci.operators[0]).real() > value(ci.operators[1]).real(); break; + case QPIEvaluatorTypes::oSmaller: tmpvars[oi].value = value(ci.operators[0]).real() < value(ci.operators[1]).real(); break; + case QPIEvaluatorTypes::oAnd: tmpvars[oi].value = value(ci.operators[0]).real() > 0. && value(ci.operators[1]).real() > 0.; break; + case QPIEvaluatorTypes::oOr: tmpvars[oi].value = value(ci.operators[0]).real() > 0. || value(ci.operators[1]).real() > 0.; break; + case QPIEvaluatorTypes::oFunction: execFunction(ci); break; + case QPIEvaluatorTypes::oNone: tmpvars[oi].value = value(ci.operators[0]); break; } } - if (!instructions.isEmpty()) - out = value(instructions.back().out); + if (!instructions.isEmpty()) out = value(instructions.back().out); return true; } bool QPIEvaluator::check(const QString & string) { currentString = preprocess(string); - correct = check(); - if (!correct) - return false; + correct = check(); + if (!correct) return false; lastError = "Correct"; return true; } diff --git a/libs/widgets/qpievaluator_p.h b/libs/widgets/qpievaluator_p.h index 91f3adb..1a9b6cb 100644 --- a/libs/widgets/qpievaluator_p.h +++ b/libs/widgets/qpievaluator_p.h @@ -1,35 +1,35 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPIEVALUATOR_P_H #define QPIEVALUATOR_P_H +#include +#include #include #include -#include -#include #include #include #ifndef PIP_MATH_COMPLEX -#define QPIEVALUATOR_COMPLEX +# define QPIEVALUATOR_COMPLEX typedef std::complex complexd; const complexd complexd_i(0., 1.); const complexd complexd_0(0.); @@ -38,100 +38,194 @@ const complexd complexd_1(1.); const double deg2rad_qpie = atan(1.) / 45.; const double rad2deg_qpie = 45. / atan(1.); -inline complexd round_qpie(const complexd & c) {return complexd(round(c.real()), round(c.imag()));} -inline complexd floor_qpie(const complexd & c) {return complexd(floor(c.real()), floor(c.imag()));} -inline complexd ceil_qpie(const complexd & c) {return complexd(ceil(c.real()), ceil(c.imag()));} +inline complexd round_qpie(const complexd & c) { + return complexd(round(c.real()), round(c.imag())); +} +inline complexd floor_qpie(const complexd & c) { + return complexd(floor(c.real()), floor(c.imag())); +} +inline complexd ceil_qpie(const complexd & c) { + return complexd(ceil(c.real()), ceil(c.imag())); +} #if (__cplusplus >= 201103L) // стандарт C++ 11 или выше # define acosc_qpie acos # define asinc_qpie asin # define atanc_qpie atan #else -inline complexd atanc_qpie(const complexd & c) {return complexd(0., 0.5) * log((complexd_1 - complexd_i * c) / (complexd_1 + complexd_i * c));} -inline complexd asinc_qpie(const complexd & c) {return -complexd_i * log(complexd_i * c + sqrt(complexd_1 - c * c));} -inline complexd acosc_qpie(const complexd & c) {return -complexd_i * log(c + complexd_i * sqrt(complexd_1 - c * c));} +inline complexd atanc_qpie(const complexd & c) { + return complexd(0., 0.5) * log((complexd_1 - complexd_i * c) / (complexd_1 + complexd_i * c)); +} +inline complexd asinc_qpie(const complexd & c) { + return -complexd_i * log(complexd_i * c + sqrt(complexd_1 - c * c)); +} +inline complexd acosc_qpie(const complexd & c) { + return -complexd_i * log(c + complexd_i * sqrt(complexd_1 - c * c)); +} #endif namespace QPIEvaluatorTypes { - static const int operationCount = 14; +static const int operationCount = 14; - enum eType {etNumber, etOperator, etVariable, etFunction}; - enum Operation {oNone, oAdd, oSubtract, oMultiply, oDivide, oResidue, oPower, - oEqual, oNotEqual, oGreater, oSmaller, oGreaterEqual, oSmallerEqual, - oAnd, oOr, oFunction}; - enum BaseFunctions {bfUnknown, bfSin, bfCos, bfTg, bfCtg, - bfArcsin, bfArccos, bfArctg, bfArcctg, - bfExp, bfRandom, bfSh, bfCh, bfTh, bfCth, - bfSqrt, bfSqr, bfPow, bfAbs, - bfLn, bfLg, bfLog, bfSign, - bfIm, bfRe, bfArg, bfLen, bfConj, - bfRad, bfDeg}; +enum eType { + etNumber, + etOperator, + etVariable, + etFunction +}; +enum Operation { + oNone, + oAdd, + oSubtract, + oMultiply, + oDivide, + oResidue, + oPower, + oEqual, + oNotEqual, + oGreater, + oSmaller, + oGreaterEqual, + oSmallerEqual, + oAnd, + oOr, + oFunction +}; +enum BaseFunctions { + bfUnknown, + bfSin, + bfCos, + bfTg, + bfCtg, + bfArcsin, + bfArccos, + bfArctg, + bfArcctg, + bfExp, + bfRandom, + bfSh, + bfCh, + bfTh, + bfCth, + bfSqrt, + bfSqr, + bfPow, + bfAbs, + bfLn, + bfLg, + bfLog, + bfSign, + bfIm, + bfRe, + bfArg, + bfLen, + bfConj, + bfRad, + bfDeg +}; - struct Instruction { - Instruction() {;} - Instruction(Operation oper, QVector opers, int out_ind, int func = -1) { - operation = oper; operators = opers; out = out_ind; function = func;} - Operation operation; - QVector operators; - int out; - int function;}; - struct Element { - Element() {;} - Element(eType new_type, int new_num, int new_var_num = -1) {set(new_type, new_num, new_var_num);} - void set(eType new_type, int new_num, int new_var_num = -1) {type = new_type; num = new_num; var_num = new_var_num;} - eType type; - int num; - int var_num;}; - struct Function { - Function() {arguments = 0; type = bfUnknown;} - Function(const QString & name, int args, BaseFunctions ftype) {identifier = name; arguments = args; type = ftype;} - QString identifier; - BaseFunctions type; - int arguments;}; - struct Variable { - Variable() {value = 0.;} - Variable(const QString & var_name, complexd val) {name = var_name; value = val;} - QString name; - complexd value;}; - inline bool operator <(const Variable & s1, const Variable & s2) { - if (s1.name.size() != s2.name.size()) - return s1.name.size() > s2.name.size(); - return s1.name > s2.name; +struct Instruction { + Instruction() { ; } + Instruction(Operation oper, QVector opers, int out_ind, int func = -1) { + operation = oper; + operators = opers; + out = out_ind; + function = func; } + Operation operation; + QVector operators; + int out; + int function; +}; +struct Element { + Element() { ; } + Element(eType new_type, int new_num, int new_var_num = -1) { set(new_type, new_num, new_var_num); } + void set(eType new_type, int new_num, int new_var_num = -1) { + type = new_type; + num = new_num; + var_num = new_var_num; + } + eType type; + int num; + int var_num; +}; +struct Function { + Function() { + arguments = 0; + type = bfUnknown; + } + Function(const QString & name, int args, BaseFunctions ftype) { + identifier = name; + arguments = args; + type = ftype; + } + QString identifier; + BaseFunctions type; + int arguments; +}; +struct Variable { + Variable() { value = 0.; } + Variable(const QString & var_name, complexd val) { + name = var_name; + value = val; + } + QString name; + complexd value; +}; +inline bool operator<(const Variable & s1, const Variable & s2) { + if (s1.name.size() != s2.name.size()) return s1.name.size() > s2.name.size(); + return s1.name > s2.name; } +} // namespace QPIEvaluatorTypes /* - ≠ : - ≥ } - ≤ { - ⋀ & - ⋁ | + ≠ : + ≥ } + ≤ { + ⋀ & + ⋁ | */ -class QPIEvaluatorContent -{ +class QPIEvaluatorContent { friend class QPIEvaluator; + public: QPIEvaluatorContent(); - ~QPIEvaluatorContent() {;} + ~QPIEvaluatorContent() { ; } - void addFunction(const QString & name, int args = 1) {functions.push_back(QPIEvaluatorTypes::Function(name, args, getBaseFunction(name)));} - void addVariable(const QString & name, const complexd & val = 0., bool sort = true) {variables.push_back(QPIEvaluatorTypes::Variable(name, val)); if (sort) sortVariables();} - int functionsCount() const {return functions.size();} - int variablesCount() const {return variables.size();} - int customVariablesCount() const {return variables.size() - cv_count;} - int findFunction(const QString & name) const {return func_index.value(name, -1);} - int findVariable(const QString & name) const {return var_index.value(name, -1);} - QPIEvaluatorTypes::Function function(int index) {if (index < 0 || index >= functions.size()) return QPIEvaluatorTypes::Function(); return functions[index];} - QPIEvaluatorTypes::Variable variable(int index) {if (index < 0 || index >= variables.size()) return QPIEvaluatorTypes::Variable(); return variables[index];} - QPIEvaluatorTypes::Function function(const QString & name) {return function(findFunction(name));} - QPIEvaluatorTypes::Variable variable(const QString & name) {return variable(findVariable(name));} - QPIEvaluatorTypes::Variable customVariable(int index) {if (index < cv_count || index >= variables.size() + cv_count) return QPIEvaluatorTypes::Variable(); return variables[index + cv_count];} + void addFunction(const QString & name, int args = 1) { + functions.push_back(QPIEvaluatorTypes::Function(name, args, getBaseFunction(name))); + } + void addVariable(const QString & name, const complexd & val = 0., bool sort = true) { + variables.push_back(QPIEvaluatorTypes::Variable(name, val)); + if (sort) sortVariables(); + } + int functionsCount() const { return functions.size(); } + int variablesCount() const { return variables.size(); } + int customVariablesCount() const { return variables.size() - cv_count; } + int findFunction(const QString & name) const { return func_index.value(name, -1); } + int findVariable(const QString & name) const { return var_index.value(name, -1); } + QPIEvaluatorTypes::Function function(int index) { + if (index < 0 || index >= functions.size()) return QPIEvaluatorTypes::Function(); + return functions[index]; + } + QPIEvaluatorTypes::Variable variable(int index) { + if (index < 0 || index >= variables.size()) return QPIEvaluatorTypes::Variable(); + return variables[index]; + } + QPIEvaluatorTypes::Function function(const QString & name) { return function(findFunction(name)); } + QPIEvaluatorTypes::Variable variable(const QString & name) { return variable(findVariable(name)); } + QPIEvaluatorTypes::Variable customVariable(int index) { + if (index < cv_count || index >= variables.size() + cv_count) return QPIEvaluatorTypes::Variable(); + return variables[index + cv_count]; + } bool setVariableValue(int index, complexd new_value); bool setVariableName(int index, const QString & new_name); - bool setVariableValue(const QString & var_name, const complexd & new_value) {return setVariableValue(findVariable(var_name), new_value);} - bool setVariableName(const QString & var_name, const QString & new_name) {return setVariableName(findVariable(var_name), new_name);} - void removeVariable(int index) {variables.remove(index);} - void removeVariable(const QString & var_name) {removeVariable(findVariable(var_name));} + bool setVariableValue(const QString & var_name, const complexd & new_value) { + return setVariableValue(findVariable(var_name), new_value); + } + bool setVariableName(const QString & var_name, const QString & new_name) { return setVariableName(findVariable(var_name), new_name); } + void removeVariable(int index) { variables.remove(index); } + void removeVariable(const QString & var_name) { removeVariable(findVariable(var_name)); } void clearCustomVariables(); void sortVariables(); QPIEvaluatorTypes::BaseFunctions getBaseFunction(const QString & name); @@ -141,29 +235,29 @@ private: QVector variables; QMap var_index, func_index; int cv_count; - }; -class QPIEvaluator -{ +class QPIEvaluator { public: - QPIEvaluator() {correct = false ;} - ~QPIEvaluator() {;} + QPIEvaluator() { correct = false; } + ~QPIEvaluator() { ; } bool check(const QString & string); - bool isCorrect() const {return correct;} + bool isCorrect() const { return correct; } int setVariable(const QString & name, complexd value = 0.); - void setVariable(int index, complexd value = 0.) {if (index >= 0 && index < content.variablesCount()) content.setVariableValue(index, value);} - void setCustomVariableValue(int index, complexd value = 0.) {content.variables[index + content.cv_count].value = value;} + void setVariable(int index, complexd value = 0.) { + if (index >= 0 && index < content.variablesCount()) content.setVariableValue(index, value); + } + void setCustomVariableValue(int index, complexd value = 0.) { content.variables[index + content.cv_count].value = value; } complexd evaluate(); - void removeVariable(const QString & name) {content.removeVariable(name);} - void clearCustomVariables() {content.clearCustomVariables();} - int variableIndex(const QString & name) const {return content.findVariable(name);} - const QStringList & unknownVariables() const {return unknownVars;} - const QString & expression() const {return currentString;} - const QString & error() const {return lastError;} - const complexd & lastResult() const {return out;} + void removeVariable(const QString & name) { content.removeVariable(name); } + void clearCustomVariables() { content.clearCustomVariables(); } + int variableIndex(const QString & name) const { return content.findVariable(name); } + const QStringList & unknownVariables() const { return unknownVars; } + const QString & expression() const { return currentString; } + const QString & error() const { return lastError; } + const complexd & lastResult() const { return out; } static QString inBrackets(const QString & string); QPIEvaluatorContent content; @@ -182,28 +276,42 @@ private: bool fillElements(); bool setSignes(); bool isSign(const QChar & ch); - QString inverse(const QString & string) {int len = string.length(); QString s; for (int i = 0; i < len; i++) s += string[len - i - 1]; return s;} + QString inverse(const QString & string) { + int len = string.length(); + QString s; + for (int i = 0; i < len; i++) + s += string[len - i - 1]; + return s; + } bool check(); bool execInstructions(); QString operationChar(const QPIEvaluatorTypes::Operation & operation); void operationsByPriority(int p, QVector & ret); QPIEvaluatorTypes::Operation operationInOrder(const int & index); - complexd value(const int & index) {if (index < 0) return tmpvars[-index - 1].value; else return kvars->at(index).value;} + complexd value(const int & index) { + if (index < 0) + return tmpvars[-index - 1].value; + else + return kvars->at(index).value; + } inline complexd residue(const complexd & f, const complexd & s); inline void execFunction(const QPIEvaluatorTypes::Instruction & ci); QVector elements; - QVector currentVariables, variables, tmpvars, * kvars; + QVector currentVariables, variables, tmpvars, *kvars; QVector instructions; QStringList unknownVars; QString currentString, lastError; complexd out; bool correct; - }; -inline bool operator ==(QPIEvaluatorTypes::Element e1, QPIEvaluatorTypes::Element e2) {return (e1.type == e2.type && e1.num == e2.num);} -inline bool operator !=(QPIEvaluatorTypes::Element e1, QPIEvaluatorTypes::Element e2) {return (e1.type != e2.type || e1.num != e2.num);} +inline bool operator==(QPIEvaluatorTypes::Element e1, QPIEvaluatorTypes::Element e2) { + return (e1.type == e2.type && e1.num == e2.num); +} +inline bool operator!=(QPIEvaluatorTypes::Element e1, QPIEvaluatorTypes::Element e2) { + return (e1.type != e2.type || e1.num != e2.num); +} #endif // QPIEVALUATOR_P_H diff --git a/libs/widgets/qpointedit.cpp b/libs/widgets/qpointedit.cpp index c70dc30..9475844 100644 --- a/libs/widgets/qpointedit.cpp +++ b/libs/widgets/qpointedit.cpp @@ -1,4 +1,5 @@ #include "qpointedit.h" + #include "float.h" diff --git a/libs/widgets/qpointedit.h b/libs/widgets/qpointedit.h index 1006257..9ce140f 100644 --- a/libs/widgets/qpointedit.h +++ b/libs/widgets/qpointedit.h @@ -1,62 +1,71 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QPOINTEDIT_H #define QPOINTEDIT_H -#include -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include +#include -class QAD_WIDGETS_EXPORT QPointEdit: public QWidget -{ + +class QAD_WIDGETS_EXPORT QPointEdit: public QWidget { Q_OBJECT Q_PROPERTY(QPointF value READ value WRITE setValue) Q_PROPERTY(int decimals READ decimals WRITE setDecimals) - + public: explicit QPointEdit(QWidget * parent = 0); - ~QPointEdit() {delete s_x; delete s_y; delete lbl;} - - QPointF value() const {return QPointF(s_x->value(), s_y->value());} - int decimals() const {return s_x->decimals();} - + ~QPointEdit() { + delete s_x; + delete s_y; + delete lbl; + } + + QPointF value() const { return QPointF(s_x->value(), s_y->value()); } + int decimals() const { return s_x->decimals(); } + public slots: - void setValue(QPointF v) {s_x->setValue(v.x()); s_y->setValue(v.y());} - void setDecimals(int d) {s_x->setDecimals(d); s_y->setDecimals(d);} - + void setValue(QPointF v) { + s_x->setValue(v.x()); + s_y->setValue(v.y()); + } + void setDecimals(int d) { + s_x->setDecimals(d); + s_y->setDecimals(d); + } + private: virtual void changeEvent(QEvent * e); - + QBoxLayout lay; - QDoubleSpinBox * s_x, * s_y; + QDoubleSpinBox *s_x, *s_y; QLabel * lbl; - + private slots: - void changed() {emit valueChanged(QPointF(s_x->value(), s_y->value()));} - + void changed() { emit valueChanged(QPointF(s_x->value(), s_y->value())); } + signals: void valueChanged(QPointF); - }; #endif // QPOINTEDIT_H diff --git a/libs/widgets/qrectedit.cpp b/libs/widgets/qrectedit.cpp index c823398..d242f59 100644 --- a/libs/widgets/qrectedit.cpp +++ b/libs/widgets/qrectedit.cpp @@ -1,4 +1,5 @@ #include "qrectedit.h" + #include "float.h" diff --git a/libs/widgets/qrectedit.h b/libs/widgets/qrectedit.h index 5fc0d33..9c242cd 100644 --- a/libs/widgets/qrectedit.h +++ b/libs/widgets/qrectedit.h @@ -1,34 +1,34 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QRECTEDIT_H #define QRECTEDIT_H -#include -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include +#include -class QAD_WIDGETS_EXPORT QRectEdit: public QWidget -{ + +class QAD_WIDGETS_EXPORT QRectEdit: public QWidget { Q_OBJECT Q_PROPERTY(QRectF value READ value WRITE setValue) Q_PROPERTY(int decimals READ decimals WRITE setDecimals) @@ -38,34 +38,66 @@ class QAD_WIDGETS_EXPORT QRectEdit: public QWidget public: explicit QRectEdit(QWidget * parent = 0); - ~QRectEdit() {delete s_x; delete s_y; delete s_w; delete s_h; delete lbl_0; delete lbl_1; delete lbl_2;} - - QRectF value() const {return QRectF(s_x->value(), s_y->value(), s_w->value(), s_h->value());} - int decimals() const {return s_x->decimals();} - double maximum() const {return s_x->maximum();} - double minimum() const {return s_x->minimum();} - double singleStep() const {return s_x->singleStep();} + ~QRectEdit() { + delete s_x; + delete s_y; + delete s_w; + delete s_h; + delete lbl_0; + delete lbl_1; + delete lbl_2; + } + + QRectF value() const { return QRectF(s_x->value(), s_y->value(), s_w->value(), s_h->value()); } + int decimals() const { return s_x->decimals(); } + double maximum() const { return s_x->maximum(); } + double minimum() const { return s_x->minimum(); } + double singleStep() const { return s_x->singleStep(); } public slots: - void setValue(QRectF v) {s_x->setValue(v.x()); s_y->setValue(v.y()); s_w->setValue(v.width()); s_h->setValue(v.height());} - void setDecimals(int d) {s_x->setDecimals(d); s_y->setDecimals(d); s_w->setDecimals(d); s_h->setDecimals(d);} - void setMaximum(double m) {s_x->setMaximum(m); s_y->setMaximum(m); s_w->setMaximum(m); s_h->setMaximum(m);} - void setMinimum(double m) {s_x->setMinimum(m); s_y->setMinimum(m); s_w->setMinimum(m); s_h->setMinimum(m);} - void setSingleStep(double m) {s_x->setSingleStep(m); s_y->setSingleStep(m); s_w->setSingleStep(m); s_h->setSingleStep(m);} + void setValue(QRectF v) { + s_x->setValue(v.x()); + s_y->setValue(v.y()); + s_w->setValue(v.width()); + s_h->setValue(v.height()); + } + void setDecimals(int d) { + s_x->setDecimals(d); + s_y->setDecimals(d); + s_w->setDecimals(d); + s_h->setDecimals(d); + } + void setMaximum(double m) { + s_x->setMaximum(m); + s_y->setMaximum(m); + s_w->setMaximum(m); + s_h->setMaximum(m); + } + void setMinimum(double m) { + s_x->setMinimum(m); + s_y->setMinimum(m); + s_w->setMinimum(m); + s_h->setMinimum(m); + } + void setSingleStep(double m) { + s_x->setSingleStep(m); + s_y->setSingleStep(m); + s_w->setSingleStep(m); + s_h->setSingleStep(m); + } private: virtual void changeEvent(QEvent * e); - + QBoxLayout lay; - QDoubleSpinBox * s_x, * s_y, * s_w, * s_h; - QLabel * lbl_0, * lbl_1, * lbl_2; - + QDoubleSpinBox *s_x, *s_y, *s_w, *s_h; + QLabel *lbl_0, *lbl_1, *lbl_2; + private slots: - void changed() {emit valueChanged(QRectF(s_x->value(), s_y->value(), s_w->value(), s_h->value()));} - + void changed() { emit valueChanged(QRectF(s_x->value(), s_y->value(), s_w->value(), s_h->value())); } + signals: void valueChanged(QRectF); - }; #endif // QRECTEDIT_H diff --git a/libs/widgets/qvariantedit.cpp b/libs/widgets/qvariantedit.cpp index 9842354..363979c 100644 --- a/libs/widgets/qvariantedit.cpp +++ b/libs/widgets/qvariantedit.cpp @@ -1,4 +1,5 @@ #include "qvariantedit.h" + #include #include #include @@ -6,7 +7,8 @@ QStringList StringListEdit::value() const { QStringList l; - for (int i = 0; i < combo->count(); ++i) l << combo->itemText(i); + for (int i = 0; i < combo->count(); ++i) + l << combo->itemText(i); return l; } @@ -46,14 +48,14 @@ void StringListEdit::clear() { StringListEdit::StringListEdit(QWidget * parent): QWidget(parent) { - lay = new QBoxLayout(QBoxLayout::LeftToRight); + lay = new QBoxLayout(QBoxLayout::LeftToRight); combo = new EComboBox(this); combo->setEditable(true); combo->setLineEdit(new CLineEdit); combo->setInsertPolicy(QComboBox::NoInsert); butt_apply = new QPushButton(this); - butt_add = new QPushButton(this); - butt_del = new QPushButton(this); + butt_add = new QPushButton(this); + butt_del = new QPushButton(this); butt_clear = new QPushButton(this); butt_apply->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); butt_add->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); @@ -80,8 +82,9 @@ StringListEdit::StringListEdit(QWidget * parent): QWidget(parent) { connect(butt_apply, SIGNAL(clicked(bool)), this, SLOT(editItem())); connect(butt_add, SIGNAL(clicked(bool)), this, SLOT(addItem())); connect(butt_del, SIGNAL(clicked(bool)), this, SLOT(delItem())); - connect(butt_clear, &QPushButton::clicked, [this](){ - if (QMessageBox::question(this, tr("Clear All"), tr("Clear All?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) clear(); + connect(butt_clear, &QPushButton::clicked, [this]() { + if (QMessageBox::question(this, tr("Clear All"), tr("Clear All?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) + clear(); }); } @@ -105,13 +108,11 @@ void StringListEdit::editItem() { } - - PathEdit::PathEdit(QWidget * parent): QWidget(parent), lay(QBoxLayout::LeftToRight, this) { is_dir = is_abs = is_save = false; - filter = tr("All files(*)"); - line = new CLineEdit(this); - butt_select = new QPushButton(this); + filter = tr("All files(*)"); + line = new CLineEdit(this); + butt_select = new QPushButton(this); butt_select->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); butt_select->setIcon(QIcon(":/icons/document-open.png")); butt_select->setToolTip(tr("Choose") + " ..."); @@ -134,7 +135,6 @@ void PathEdit::changeEvent(QEvent * e) { void PathEdit::resizeEvent(QResizeEvent *) { butt_select->setMaximumHeight(line->height()); - } @@ -149,7 +149,8 @@ void PathEdit::setValue(const QString & v) { void PathEdit::select() { QString ret; - if (is_dir) ret = QFileDialog::getExistingDirectory(this, tr("Select directory"), value()); + if (is_dir) + ret = QFileDialog::getExistingDirectory(this, tr("Select directory"), value()); else { if (is_save) ret = QFileDialog::getSaveFileName(this, tr("Select file"), value(), filter); @@ -157,31 +158,28 @@ void PathEdit::select() { ret = QFileDialog::getOpenFileName(this, tr("Select file"), value(), filter); } if (ret.isEmpty()) return; - if (!is_abs) - ret = QDir::current().relativeFilePath(ret); + if (!is_abs) ret = QDir::current().relativeFilePath(ret); line->setText(ret); emit valueChanged(); } - - QVariantEdit::QVariantEdit(QWidget * parent): QWidget(parent) { setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); layout()->setContentsMargins(0, 0, 0, 0); - _empty = 0; - _line = 0; - _check = 0; - _color = 0; - _list = 0; - _date = 0; - _spin = 0; - _espin = 0; - _rect = 0; - _point = 0; - _path = 0; - _enum = 0; - _custom =_cur_edit = 0; + _empty = 0; + _line = 0; + _check = 0; + _color = 0; + _list = 0; + _date = 0; + _spin = 0; + _espin = 0; + _rect = 0; + _point = 0; + _path = 0; + _enum = 0; + _custom = _cur_edit = 0; _recreate(QVariant()); } @@ -277,7 +275,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::Double: #endif - _espin = new EvalSpinBox(this); + _espin = new EvalSpinBox(this); _cur_edit = _espin; connect(_espin, SIGNAL(valueChanged(double)), this, SLOT(_changed())); break; @@ -296,7 +294,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::QString: #endif - _line = new CLineEdit(this); + _line = new CLineEdit(this); _cur_edit = _line; connect(_line, SIGNAL(textChanged(QString)), this, SLOT(_changed())); break; @@ -305,7 +303,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::QStringList: #endif - _list = new StringListEdit(this); + _list = new StringListEdit(this); _cur_edit = _list; connect(_list, SIGNAL(valueChanged()), this, SLOT(_changed())); break; @@ -354,7 +352,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::QDate: #endif - _date = new QDateEdit(this); + _date = new QDateEdit(this); _cur_edit = _date; connect(_date, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(_changed())); break; @@ -363,7 +361,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::QTime: #endif - _date = new QTimeEdit(this); + _date = new QTimeEdit(this); _cur_edit = _date; connect(_date, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(_changed())); break; @@ -372,7 +370,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { #else case QMetaType::QDateTime: #endif - _date = new QDateTimeEdit(this); + _date = new QDateTimeEdit(this); _cur_edit = _date; connect(_date, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(_changed())); break; @@ -403,7 +401,7 @@ void QVariantEdit::_recreate(const QVariant & new_value) { QWidget * fw = f->createEditor(); if (fw) { fw->setParent(this); - _custom = fw; + _custom = fw; _cur_edit = _custom; connect(_custom, SIGNAL(valueChanged()), this, SLOT(_changed())); } @@ -525,15 +523,15 @@ QVariant QVariantEdit::value() const { for (int i = 0; i < _enum->count(); ++i) ret.enum_list << QAD::Enumerator(_enum->itemData(i).toInt(), _enum->itemText(i)); ret.enum_name = _enum->property("enum_name").toString(); - ret.selected = _enum->currentText(); + ret.selected = _enum->currentText(); return QVariant::fromValue(ret); } if (_value.canConvert() && _path) { if (!_path->is_dir) { QAD::File ret; - ret.file = _path->value(); - ret.filter = _path->filter; - ret.is_abs = _path->is_abs; + ret.file = _path->value(); + ret.filter = _path->filter; + ret.is_abs = _path->is_abs; ret.is_save = _path->is_save; return QVariant::fromValue(ret); } @@ -541,7 +539,7 @@ QVariant QVariantEdit::value() const { if (_value.canConvert() && _path) { if (_path->is_dir) { QAD::Dir ret; - ret.dir = _path->value(); + ret.dir = _path->value(); ret.is_abs = _path->is_abs; return QVariant::fromValue(ret); } @@ -557,42 +555,66 @@ QVariant QVariantEdit::value() const { void QVariantEdit::setValue(const QVariant & v) { _recreate(v); if (_cur_edit) _cur_edit->blockSignals(true); - if (_line) {_line->setText(v.toString());} - if (_check) {_check->setChecked(v.toBool()); _check->setText(v.toBool() ? "true" : "false");} - if (_color) {_color->setColor(v.value());} - if (_list) {_list->setValue(v.toStringList());} - if (_date) {_date->setDateTime(v.toDateTime());} - if (_spin) {_spin->setValue(v.toDouble());} - if (_espin) {_espin->setValue(v.toDouble());} - if (_rect) {_rect->setValue(v.toRectF());} - if (_point) {_point->setValue(v.toPointF());} - if (_path) { - if (_path->is_dir) _setDir(v.value()); - else _setFile(v.value()); + if (_line) { + _line->setText(v.toString()); + } + if (_check) { + _check->setChecked(v.toBool()); + _check->setText(v.toBool() ? "true" : "false"); + } + if (_color) { + _color->setColor(v.value()); + } + if (_list) { + _list->setValue(v.toStringList()); + } + if (_date) { + _date->setDateTime(v.toDateTime()); + } + if (_spin) { + _spin->setValue(v.toDouble()); + } + if (_espin) { + _espin->setValue(v.toDouble()); + } + if (_rect) { + _rect->setValue(v.toRectF()); + } + if (_point) { + _point->setValue(v.toPointF()); + } + if (_path) { + if (_path->is_dir) + _setDir(v.value()); + else + _setFile(v.value()); + } + if (_enum) { + _setEnum(v.value()); + } + if (_custom) { + _setCustom(v); } - if (_enum) {_setEnum(v.value());} - if (_custom) {_setCustom(v);} if (_cur_edit) _cur_edit->blockSignals(false); } void QVariantEdit::_delete() { - if (_cur_edit) - delete _cur_edit; + if (_cur_edit) delete _cur_edit; _cur_edit = 0; - _custom = 0; - _empty = 0; - _line = 0; - _check = 0; - _color = 0; - _list = 0; - _date = 0; - _spin = 0; - _espin = 0; - _rect = 0; - _point = 0; - _path = 0; - _enum = 0; + _custom = 0; + _empty = 0; + _line = 0; + _check = 0; + _color = 0; + _list = 0; + _date = 0; + _spin = 0; + _espin = 0; + _rect = 0; + _point = 0; + _path = 0; + _enum = 0; } @@ -604,9 +626,9 @@ void QVariantEdit::_resize() { void QVariantEdit::_newPath() { _delete(); - _path = new PathEdit(this); + _path = new PathEdit(this); _cur_edit = _path; - _value = _value.toString(); + _value = _value.toString(); connect(_path, SIGNAL(valueChanged()), this, SLOT(_changed())); _resize(); } @@ -615,7 +637,7 @@ void QVariantEdit::_newPath() { void QVariantEdit::_setEnum(const QAD::Enum & v) { _enum->clear(); _enum->setProperty("enum_name", v.enum_name); - foreach (const QAD::Enumerator & e, v.enum_list) + foreach(const QAD::Enumerator & e, v.enum_list) _enum->addItem(e.name, QVariant(e.value)); int i(0); for (i = 0; i < _enum->count(); ++i) @@ -623,18 +645,16 @@ void QVariantEdit::_setEnum(const QAD::Enum & v) { _enum->setCurrentIndex(i); break; } - if (i == _enum->count()) - _enum->setCurrentIndex(-1); + if (i == _enum->count()) _enum->setCurrentIndex(-1); } void QVariantEdit::_setFile(const QAD::File & v) { - _path->is_dir = false; + _path->is_dir = false; _path->filter = v.filter; _path->is_abs = v.is_abs; _path->is_save = v.is_save; _path->setValue(v.file); - } @@ -654,4 +674,3 @@ void QVariantEdit::_changed() { if (_check) _check->setText(_check->isChecked() ? "true" : "false"); emit valueChanged(value()); } - diff --git a/libs/widgets/qvariantedit.h b/libs/widgets/qvariantedit.h index 434e1fb..ed3ea95 100644 --- a/libs/widgets/qvariantedit.h +++ b/libs/widgets/qvariantedit.h @@ -1,120 +1,117 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QVARIANTEDIT_H #define QVARIANTEDIT_H -#include -#include -#include -#include "qvariantedit_custom.h" -#include "qad_types.h" #include "clineedit.h" -#include "ecombobox.h" #include "colorbutton.h" -#include "qrectedit.h" -#include "qpointedit.h" +#include "ecombobox.h" #include "evalspinbox.h" +#include "qad_types.h" #include "qad_widgets_export.h" +#include "qpointedit.h" +#include "qrectedit.h" +#include "qvariantedit_custom.h" + +#include +#include +#include -class QAD_WIDGETS_EXPORT StringListEdit: public QWidget -{ +class QAD_WIDGETS_EXPORT StringListEdit: public QWidget { Q_OBJECT + public: StringListEdit(QWidget * parent = 0); - + QStringList value() const; - + private: virtual void changeEvent(QEvent * e); - + QBoxLayout * lay; EComboBox * combo; - QPushButton * butt_apply, * butt_add, * butt_del, * butt_clear; - + QPushButton *butt_apply, *butt_add, *butt_del, *butt_clear; + public slots: void setValue(const QStringList & v); - + private slots: void editItem(); void addItem(); void delItem(); void clear(); - + signals: void valueChanged(); - }; - - -class QAD_WIDGETS_EXPORT PathEdit: public QWidget -{ +class QAD_WIDGETS_EXPORT PathEdit: public QWidget { Q_OBJECT + public: PathEdit(QWidget * parent = 0); - ~PathEdit() {delete line; delete butt_select;} - - QString value() const {return line->text();} - + ~PathEdit() { + delete line; + delete butt_select; + } + + QString value() const { return line->text(); } + bool is_dir, is_abs, is_save; QString filter; private: virtual void changeEvent(QEvent * e); - virtual void resizeEvent(QResizeEvent * ); + virtual void resizeEvent(QResizeEvent *); QBoxLayout lay; CLineEdit * line; QPushButton * butt_select; - + public slots: void setValue(const QString & v); - + private slots: void select(); - + signals: void valueChanged(); - }; - - -class QAD_WIDGETS_EXPORT QVariantEdit: public QWidget -{ +class QAD_WIDGETS_EXPORT QVariantEdit: public QWidget { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue) - + public: explicit QVariantEdit(QWidget * parent = 0); ~QVariantEdit(); - + QVariant value() const; - //QSize sizeHint() const {if (_cur_edit) return _cur_edit->sizeHint(); return QWidget::sizeHint();} - //QSize minimumSizeHint() const {if (_cur_edit) return _cur_edit->minimumSizeHint(); return QWidget::minimumSizeHint();} - + // QSize sizeHint() const {if (_cur_edit) return _cur_edit->sizeHint(); return QWidget::sizeHint();} + // QSize minimumSizeHint() const {if (_cur_edit) return _cur_edit->minimumSizeHint(); return QWidget::minimumSizeHint();} + protected: - virtual void resizeEvent(QResizeEvent * ); + virtual void resizeEvent(QResizeEvent *); void _recreate(const QVariant & new_value); void _delete(); void _resize(); @@ -123,8 +120,8 @@ protected: void _setFile(const QAD::File & v); void _setDir(const QAD::Dir & v); void _setCustom(const QVariant & v); - - + + QLabel * _empty; CLineEdit * _line; QCheckBox * _check; @@ -137,18 +134,17 @@ protected: QPointEdit * _point; PathEdit * _path; EComboBox * _enum; - QWidget * _custom, * _cur_edit; + QWidget *_custom, *_cur_edit; QVariant _value; - + private slots: void _changed(); - + public slots: void setValue(const QVariant & v); - + signals: void valueChanged(QVariant); - }; #endif // QVARIANTEDIT_H diff --git a/libs/widgets/qvariantedit_custom.cpp b/libs/widgets/qvariantedit_custom.cpp index 29fecb5..c83fab6 100644 --- a/libs/widgets/qvariantedit_custom.cpp +++ b/libs/widgets/qvariantedit_custom.cpp @@ -1,9 +1,7 @@ #include "qvariantedit_custom.h" -QVariantEditorFactories::QVariantEditorFactories() { - -} +QVariantEditorFactories::QVariantEditorFactories() {} QVariantEditorFactories * QVariantEditorFactories::instance() { @@ -19,7 +17,7 @@ void QVariantEditorFactories::registerEditorFactory(int meta_id, QVariantEditorF return; } if (s->factories.contains(meta_id)) - ;//qDebug() << "[QVariantEditorFactories] Warning: factory for metaTypeID" << meta_id << "already registered, override"; + ; // qDebug() << "[QVariantEditorFactories] Warning: factory for metaTypeID" << meta_id << "already registered, override"; s->factories[meta_id] = f; } @@ -40,4 +38,3 @@ QVariantEditorFactoryBase * QVariantEditorFactories::editorFactory(int meta_id) QVariantEditorFactories * s = QVariantEditorFactories::instance(); return s->factories.value(meta_id, 0); } - diff --git a/libs/widgets/qvariantedit_custom.h b/libs/widgets/qvariantedit_custom.h index 912e325..815564e 100644 --- a/libs/widgets/qvariantedit_custom.h +++ b/libs/widgets/qvariantedit_custom.h @@ -1,42 +1,44 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef QVARIANTEDIT_CUSTOM_H #define QVARIANTEDIT_CUSTOM_H -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include + class QVariantEdit; class QAD_WIDGETS_EXPORT QVariantEditorFactoryBase { friend class QVariantEdit; + public: QVariantEditorFactoryBase() {} virtual ~QVariantEditorFactoryBase() {} virtual QWidget * createEditor() = 0; -private: +private: }; @@ -51,7 +53,7 @@ private: QVariantEditorFactories(); static QVariantEditorFactories * instance(); - QMap factories; + QMap factories; }; diff --git a/libs/widgets/rangeslider.cpp b/libs/widgets/rangeslider.cpp index 4bf9063..f25c947 100644 --- a/libs/widgets/rangeslider.cpp +++ b/libs/widgets/rangeslider.cpp @@ -1,49 +1,53 @@ #include "rangeslider.h" + #include "qad_types.h" + #include RangeSlider::RangeSlider(QWidget * parent) - : QWidget(parent), - m_minimum(0), - m_maximum(100), - m_lowerValue(0), - m_upperValue(100), - mFirstHandlePressed(false), - mSecondHandlePressed(false), - orientation(Qt::Horizontal), - m_mode(DoubleHandles) -{init();} + : QWidget(parent) + , m_minimum(0) + , m_maximum(100) + , m_lowerValue(0) + , m_upperValue(100) + , mFirstHandlePressed(false) + , mSecondHandlePressed(false) + , orientation(Qt::Horizontal) + , m_mode(DoubleHandles) { + init(); +} RangeSlider::RangeSlider(Qt::Orientation ori, Mode m, QWidget * parent) - : QWidget(parent), - m_minimum(0), - m_maximum(100), - m_lowerValue(0), - m_upperValue(100), - mFirstHandlePressed(false), - mSecondHandlePressed(false), - orientation(ori), - m_mode(m) -{init();} + : QWidget(parent) + , m_minimum(0) + , m_maximum(100) + , m_lowerValue(0) + , m_upperValue(100) + , mFirstHandlePressed(false) + , mSecondHandlePressed(false) + , orientation(ori) + , m_mode(m) { + init(); +} void RangeSlider::init() { setMouseTracking(true); - scHandleSideLength = 16*lineThickness(this); - scSliderBarHeight = 8*lineThickness(this); - scLeftRightMargin = 2*lineThickness(this); + scHandleSideLength = 16 * lineThickness(this); + scSliderBarHeight = 8 * lineThickness(this); + scLeftRightMargin = 2 * lineThickness(this); } void RangeSlider::paintEvent(QPaintEvent *) { QPainter painter(this); // Background QRectF backgroundRect; - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) backgroundRect = QRectF(scLeftRightMargin, (height() - scSliderBarHeight) / 2, width() - scLeftRightMargin * 2, scSliderBarHeight); else - backgroundRect = QRectF((width() - scSliderBarHeight) / 2, scLeftRightMargin, scSliderBarHeight, height() - scLeftRightMargin*2); + backgroundRect = QRectF((width() - scSliderBarHeight) / 2, scLeftRightMargin, scSliderBarHeight, height() - scLeftRightMargin * 2); QPen pen(palette().color(QPalette::Disabled, QPalette::Text)); painter.setPen(pen); @@ -59,18 +63,16 @@ void RangeSlider::paintEvent(QPaintEvent *) { painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(palette().color(QPalette::Active, QPalette::Button)); QRectF leftHandleRect = firstHandleRect(); - if(m_mode.testFlag(LeftHandle)) - painter.drawEllipse(leftHandleRect); + if (m_mode.testFlag(LeftHandle)) painter.drawEllipse(leftHandleRect); // Second value handle rect QRectF rightHandleRect = secondHandleRect(); - if(m_mode.testFlag(RightHandle)) - painter.drawEllipse(rightHandleRect); + if (m_mode.testFlag(RightHandle)) painter.drawEllipse(rightHandleRect); // Handles painter.setRenderHint(QPainter::Antialiasing, false); QRectF selectedRect(backgroundRect); - if(orientation == Qt::Horizontal) { + if (orientation == Qt::Horizontal) { selectedRect.setLeft((m_mode.testFlag(LeftHandle) ? leftHandleRect.right() : leftHandleRect.left()) + 0.5); selectedRect.setRight((m_mode.testFlag(RightHandle) ? rightHandleRect.left() : rightHandleRect.right()) - 0.5); } else { @@ -99,71 +101,73 @@ QRectF RangeSlider::secondHandleRect() const { QRectF RangeSlider::handleRect(int value) const { - if(orientation == Qt::Horizontal) - return QRect(value, (height()-scHandleSideLength) / 2, scHandleSideLength, scHandleSideLength); + if (orientation == Qt::Horizontal) + return QRect(value, (height() - scHandleSideLength) / 2, scHandleSideLength, scHandleSideLength); else - return QRect((width()-scHandleSideLength) / 2, value, scHandleSideLength, scHandleSideLength); + return QRect((width() - scHandleSideLength) / 2, value, scHandleSideLength, scHandleSideLength); } -void RangeSlider::mousePressEvent(QMouseEvent* e) { - if(e->buttons() & Qt::LeftButton) { +void RangeSlider::mousePressEvent(QMouseEvent * e) { + if (e->buttons() & Qt::LeftButton) { int posCheck, posMax, posValue, firstHandleRectPosValue, secondHandleRectPosValue; - posCheck = (orientation == Qt::Horizontal) ? e->pos().y() : e->pos().x(); - posMax = (orientation == Qt::Horizontal) ? height() : width(); - posValue = (orientation == Qt::Horizontal) ? e->pos().x() : e->pos().y(); - firstHandleRectPosValue = (orientation == Qt::Horizontal) ? firstHandleRect().x() : firstHandleRect().y(); + posCheck = (orientation == Qt::Horizontal) ? e->pos().y() : e->pos().x(); + posMax = (orientation == Qt::Horizontal) ? height() : width(); + posValue = (orientation == Qt::Horizontal) ? e->pos().x() : e->pos().y(); + firstHandleRectPosValue = (orientation == Qt::Horizontal) ? firstHandleRect().x() : firstHandleRect().y(); secondHandleRectPosValue = (orientation == Qt::Horizontal) ? secondHandleRect().x() : secondHandleRect().y(); - mSecondHandlePressed = secondHandleRect().contains(e->pos()); - mFirstHandlePressed = !mSecondHandlePressed && firstHandleRect().contains(e->pos()); - if(mFirstHandlePressed) { + mSecondHandlePressed = secondHandleRect().contains(e->pos()); + mFirstHandlePressed = !mSecondHandlePressed && firstHandleRect().contains(e->pos()); + if (mFirstHandlePressed) { mDelta = posValue - (firstHandleRectPosValue + scHandleSideLength / 2); - } else if(mSecondHandlePressed) { + } else if (mSecondHandlePressed) { mDelta = posValue - (secondHandleRectPosValue + scHandleSideLength / 2); } - if(posCheck >= 2 && posCheck <= posMax - 2) { + if (posCheck >= 2 && posCheck <= posMax - 2) { int step = interval() / 10 < 1 ? 1 : interval() / 10; - if(posValue < firstHandleRectPosValue) + if (posValue < firstHandleRectPosValue) setLowerValue(m_lowerValue - step); - else if(((posValue > firstHandleRectPosValue + scHandleSideLength) || !m_mode.testFlag(LeftHandle)) - && ((posValue < secondHandleRectPosValue) || !m_mode.testFlag(RightHandle))) - { - if(m_mode.testFlag(DoubleHandles)) { - if(posValue - (firstHandleRectPosValue + scHandleSideLength) < - (secondHandleRectPosValue - (firstHandleRectPosValue + scHandleSideLength)) / 2) { + else if (((posValue > firstHandleRectPosValue + scHandleSideLength) || !m_mode.testFlag(LeftHandle)) && + ((posValue < secondHandleRectPosValue) || !m_mode.testFlag(RightHandle))) { + if (m_mode.testFlag(DoubleHandles)) { + if (posValue - (firstHandleRectPosValue + scHandleSideLength) < + (secondHandleRectPosValue - (firstHandleRectPosValue + scHandleSideLength)) / 2) { setLowerValue((m_lowerValue + step < m_upperValue) ? m_lowerValue + step : m_upperValue); - } else { + } else { setUpperValue((m_upperValue - step > m_lowerValue) ? m_upperValue - step : m_lowerValue); } - } else if(m_mode.testFlag(LeftHandle)) { + } else if (m_mode.testFlag(LeftHandle)) { setLowerValue((m_lowerValue + step < m_upperValue) ? m_lowerValue + step : m_upperValue); - } else if(m_mode.testFlag(RightHandle)) { + } else if (m_mode.testFlag(RightHandle)) { setUpperValue((m_upperValue - step > m_lowerValue) ? m_upperValue - step : m_lowerValue); } - } - else if(posValue > secondHandleRectPosValue + scHandleSideLength) + } else if (posValue > secondHandleRectPosValue + scHandleSideLength) setUpperValue(m_upperValue + step); } } } -void RangeSlider::mouseMoveEvent(QMouseEvent* e) { - if(e->buttons() & Qt::LeftButton) { +void RangeSlider::mouseMoveEvent(QMouseEvent * e) { + if (e->buttons() & Qt::LeftButton) { int posValue, firstHandleRectPosValue, secondHandleRectPosValue; - posValue = (orientation == Qt::Horizontal) ? e->pos().x() : e->pos().y(); - firstHandleRectPosValue = (orientation == Qt::Horizontal) ? firstHandleRect().x() : firstHandleRect().y(); + posValue = (orientation == Qt::Horizontal) ? e->pos().x() : e->pos().y(); + firstHandleRectPosValue = (orientation == Qt::Horizontal) ? firstHandleRect().x() : firstHandleRect().y(); secondHandleRectPosValue = (orientation == Qt::Horizontal) ? secondHandleRect().x() : secondHandleRect().y(); - if(mFirstHandlePressed && m_mode.testFlag(LeftHandle)) { - if(posValue - mDelta + scHandleSideLength / 2 <= secondHandleRectPosValue) { - setLowerValue((posValue - mDelta - scLeftRightMargin - scHandleSideLength / 2) * 1.0 / validLength() * interval() + m_minimum); + if (mFirstHandlePressed && m_mode.testFlag(LeftHandle)) { + if (posValue - mDelta + scHandleSideLength / 2 <= secondHandleRectPosValue) { + setLowerValue((posValue - mDelta - scLeftRightMargin - scHandleSideLength / 2) * 1.0 / validLength() * interval() + + m_minimum); } else { setLowerValue(m_upperValue); } - } else if(mSecondHandlePressed && m_mode.testFlag(RightHandle)) { - if(firstHandleRectPosValue + scHandleSideLength * (m_mode.testFlag(DoubleHandles) ? 1.5 : 0.5) <= posValue - mDelta) { - setUpperValue((posValue - mDelta - scLeftRightMargin - scHandleSideLength / 2 - (m_mode.testFlag(DoubleHandles) ? scHandleSideLength : 0)) * 1.0 / validLength() * interval() + m_minimum); + } else if (mSecondHandlePressed && m_mode.testFlag(RightHandle)) { + if (firstHandleRectPosValue + scHandleSideLength * (m_mode.testFlag(DoubleHandles) ? 1.5 : 0.5) <= posValue - mDelta) { + setUpperValue((posValue - mDelta - scLeftRightMargin - scHandleSideLength / 2 - + (m_mode.testFlag(DoubleHandles) ? scHandleSideLength : 0)) * + 1.0 / validLength() * interval() + + m_minimum); } else { setUpperValue(m_lowerValue); } @@ -173,13 +177,13 @@ void RangeSlider::mouseMoveEvent(QMouseEvent* e) { void RangeSlider::mouseReleaseEvent(QMouseEvent *) { - mFirstHandlePressed = false; + mFirstHandlePressed = false; mSecondHandlePressed = false; } void RangeSlider::changeEvent(QEvent * e) { - if(e->type() == QEvent::EnabledChange) { + if (e->type() == QEvent::EnabledChange) { update(); } } @@ -191,8 +195,8 @@ QSize RangeSlider::minimumSizeHint() const { void RangeSlider::setLowerValue(int value) { - if(value > m_maximum) value = m_maximum; - if(value < m_minimum) value = m_minimum; + if (value > m_maximum) value = m_maximum; + if (value < m_minimum) value = m_minimum; m_lowerValue = value; emit lowerValueChanged(m_lowerValue); emit valueChanged(m_lowerValue, m_upperValue); @@ -201,8 +205,8 @@ void RangeSlider::setLowerValue(int value) { void RangeSlider::setUpperValue(int value) { - if(value > m_maximum) value = m_maximum; - if(value < m_minimum) value = m_minimum; + if (value > m_maximum) value = m_maximum; + if (value < m_minimum) value = m_minimum; m_upperValue = value; emit upperValueChanged(m_upperValue); emit valueChanged(m_lowerValue, m_upperValue); @@ -211,12 +215,12 @@ void RangeSlider::setUpperValue(int value) { void RangeSlider::setMinimum(int minimum) { - if(minimum <= m_maximum) { + if (minimum <= m_maximum) { m_minimum = minimum; } else { int oldMax = m_maximum; - m_minimum = oldMax; - m_maximum = minimum; + m_minimum = oldMax; + m_maximum = minimum; } update(); setLowerValue(m_minimum); @@ -227,12 +231,12 @@ void RangeSlider::setMinimum(int minimum) { void RangeSlider::setMaximum(int maximum) { - if(maximum >= m_minimum) { + if (maximum >= m_minimum) { m_maximum = maximum; } else { int oldMin = m_minimum; - m_maximum = oldMin; - m_minimum = maximum; + m_maximum = oldMin; + m_minimum = maximum; } update(); setLowerValue(m_minimum); diff --git a/libs/widgets/rangeslider.h b/libs/widgets/rangeslider.h index d25cf16..e18b9bd 100644 --- a/libs/widgets/rangeslider.h +++ b/libs/widgets/rangeslider.h @@ -1,14 +1,14 @@ #ifndef RANGESLIDER_H #define RANGESLIDER_H -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include -class QAD_WIDGETS_EXPORT RangeSlider : public QWidget -{ + +class QAD_WIDGETS_EXPORT RangeSlider: public QWidget { Q_OBJECT Q_FLAGS(Mode) Q_PROPERTY(int minimum READ minimum WRITE setMinimum NOTIFY minimumChanged) @@ -19,29 +19,29 @@ class QAD_WIDGETS_EXPORT RangeSlider : public QWidget public: enum ModeEnum { - NoHandle = 0x0, - LeftHandle = 0x1, - RightHandle = 0x2, + NoHandle = 0x0, + LeftHandle = 0x1, + RightHandle = 0x2, DoubleHandles = LeftHandle | RightHandle }; Q_DECLARE_FLAGS(Mode, ModeEnum) - RangeSlider(QWidget* parent = Q_NULLPTR); + RangeSlider(QWidget * parent = Q_NULLPTR); RangeSlider(Qt::Orientation ori, Mode m = DoubleHandles, QWidget * parent = Q_NULLPTR); - int minimum() const {return m_minimum;} - int maximum() const {return m_maximum;} - int lowerValue() const {return m_lowerValue;} - int upperValue() const {return m_upperValue;} - QPair value() const {return QPair(m_lowerValue, m_upperValue);} - Mode mode() const {return m_mode;} + int minimum() const { return m_minimum; } + int maximum() const { return m_maximum; } + int lowerValue() const { return m_lowerValue; } + int upperValue() const { return m_upperValue; } + QPair value() const { return QPair(m_lowerValue, m_upperValue); } + Mode mode() const { return m_mode; } protected: QSize minimumSizeHint() const override; void paintEvent(QPaintEvent *) override; void mousePressEvent(QMouseEvent * e) override; - void mouseMoveEvent(QMouseEvent* e) override; + void mouseMoveEvent(QMouseEvent * e) override; void mouseReleaseEvent(QMouseEvent *) override; void changeEvent(QEvent * e) override; @@ -89,4 +89,4 @@ private: Q_DECLARE_OPERATORS_FOR_FLAGS(RangeSlider::Mode) -#endif //RANGESLIDER_H +#endif // RANGESLIDER_H diff --git a/libs/widgets/scroll_spin_box.cpp b/libs/widgets/scroll_spin_box.cpp index faa1055..d4cfd04 100644 --- a/libs/widgets/scroll_spin_box.cpp +++ b/libs/widgets/scroll_spin_box.cpp @@ -13,18 +13,20 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License - along with this programap-> If not, see . + along with this programap-> If not, see . */ #include "scroll_spin_box.h" + #include "ui_scroll_spin_box.h" -#include -#include -#include + #include +#include #include #include -#include +#include +#include +#include ScrollSpinBox::ScrollSpinBox(QWidget * parent): QWidget(parent) { @@ -33,10 +35,10 @@ ScrollSpinBox::ScrollSpinBox(QWidget * parent): QWidget(parent) { ui->spin->setPrecision(3); ui->handle->installEventFilter(this); connect(ui->spin, SIGNAL(valueChanged(double)), this, SIGNAL(valueChanged(double))); - last_value = 0.; - sensivity_ = 0.2; + last_value = 0.; + sensivity_ = 0.2; scroll_scale = sensivity_ / 10; - canceled = false; + canceled = false; } @@ -53,11 +55,8 @@ double ScrollSpinBox::value() const { void ScrollSpinBox::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: ui->retranslateUi(this); break; + default: break; } } @@ -73,15 +72,9 @@ void ScrollSpinBox::resizeEvent(QResizeEvent * e) { bool ScrollSpinBox::eventFilter(QObject * o, QEvent * e) { switch (e->type()) { - case QEvent::MouseButtonPress: - mousePress((QMouseEvent*)e); - return true; - case QEvent::MouseButtonRelease: - mouseRelease((QMouseEvent*)e); - return true; - case QEvent::MouseMove: - mouseMove((QMouseEvent*)e); - return true; + case QEvent::MouseButtonPress: mousePress((QMouseEvent *)e); return true; + case QEvent::MouseButtonRelease: mouseRelease((QMouseEvent *)e); return true; + case QEvent::MouseMove: mouseMove((QMouseEvent *)e); return true; default: break; } return QWidget::eventFilter(o, e); @@ -95,8 +88,8 @@ void ScrollSpinBox::mousePress(QMouseEvent * e) { ui->spin->setExpression(last_text); } if (e->button() == Qt::LeftButton) { - down_pos = e->pos(); - last_text = ui->spin->expression(); + down_pos = e->pos(); + last_text = ui->spin->expression(); last_value = qAbs(ui->spin->value()); if (last_value == 0.) last_value = 1.; } diff --git a/libs/widgets/scroll_spin_box.h b/libs/widgets/scroll_spin_box.h index 266bbdc..13a3d99 100644 --- a/libs/widgets/scroll_spin_box.h +++ b/libs/widgets/scroll_spin_box.h @@ -1,48 +1,49 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SCROLL_SPIN_BOX_H #define SCROLL_SPIN_BOX_H -#include #include "qad_widgets_export.h" +#include + namespace Ui { - class ScrollSpinBox; +class ScrollSpinBox; } class EvalSpinBox; -class QAD_WIDGETS_EXPORT ScrollSpinBox: public QWidget -{ +class QAD_WIDGETS_EXPORT ScrollSpinBox: public QWidget { Q_OBJECT Q_PROPERTY(double sensivity READ sensivity WRITE setSensivity) Q_PROPERTY(double value READ value WRITE setValue) + public: explicit ScrollSpinBox(QWidget * parent = 0); EvalSpinBox * spin(); double value() const; - double sensivity() const {return sensivity_;} + double sensivity() const { return sensivity_; } protected: void changeEvent(QEvent * e); @@ -59,12 +60,11 @@ protected: bool canceled; public slots: - void setSensivity(double s) {sensivity_ = s;} + void setSensivity(double s) { sensivity_ = s; } void setValue(double v); signals: void valueChanged(double); - }; #endif // SCROLL_SPIN_BOX_H diff --git a/libs/widgets/session_manager.cpp b/libs/widgets/session_manager.cpp index 8c2008f..50069ad 100644 --- a/libs/widgets/session_manager.cpp +++ b/libs/widgets/session_manager.cpp @@ -7,9 +7,9 @@ #else # include #endif -#include "session_manager.h" #include "qad_locations.h" #include "qad_types.h" +#include "session_manager.h" SessionManager::SessionManager(QString file) { @@ -45,8 +45,8 @@ void SessionManager::removeMainWidget(QWidget * e) { void SessionManager::addEntry(const QString & name, QMainWindow * e) { - mwindows.push_back(QPair(name, e)); - mw_splitters[e] = e->findChildren(); + mwindows.push_back(QPair(name, e)); + mw_splitters[e] = e->findChildren(); } @@ -61,14 +61,18 @@ void SessionManager::save() { tsc << mwindows[i].second; sr.setValue(mwindows[i].first + " state", mwindows[i].second->saveState(), false); sr.setValue(mwindows[i].first + " window state", (int)mwindows[i].second->windowState(), false); - sr.setValue(mwindows[i].first + " geometry " + QString::number((int)mwindows[i].second->windowState()), mwindows[i].second->saveGeometry(), false); - QList spl = mw_splitters[mwindows[i].second]; - foreach (QSplitter * s, spl) + sr.setValue(mwindows[i].first + " geometry " + QString::number((int)mwindows[i].second->windowState()), + mwindows[i].second->saveGeometry(), + false); + QList spl = mw_splitters[mwindows[i].second]; + foreach(QSplitter * s, spl) sr.setValue(mwindows[i].first + " splitter " + s->objectName(), s->saveState(), false); } for (int i = 0; i < widgets.size(); ++i) { tsc << widgets[i].second; - sr.setValue(widgets[i].first + " geometry " + QString::number((int)widgets[i].second->windowState()), widgets[i].second->saveGeometry(), false); + sr.setValue(widgets[i].first + " geometry " + QString::number((int)widgets[i].second->windowState()), + widgets[i].second->saveGeometry(), + false); sr.setValue(widgets[i].first + " window state", (int)widgets[i].second->windowState(), false); } for (int i = 0; i < checks.size(); ++i) @@ -107,22 +111,22 @@ void SessionManager::save() { sr.setValue(ints[i].first, *ints[i].second, false); for (int i = 0; i < floats.size(); ++i) sr.setValue(floats[i].first, *floats[i].second, false); - QSet all_list; - foreach (QObject * c, tsc) { - all_list |= QList2QSet(c->findChildren()); + QSet all_list; + foreach(QObject * c, tsc) { + all_list |= QList2QSet(c->findChildren()); } - QMap funcs = metaFunctions(all_list, "sessionSave"); - //qDebug() << "check for save" << all_list.size(); - foreach (QObject * o, all_list) { + QMap funcs = metaFunctions(all_list, "sessionSave"); + // qDebug() << "check for save" << all_list.size(); + foreach(QObject * o, all_list) { const QMetaObject * mo = o->metaObject(); - QByteArray fn = funcs.value(mo); + QByteArray fn = funcs.value(mo); if (!mo || fn.isEmpty()) continue; QByteArray value; - //qDebug() << "save" << o->objectName(); - mo->invokeMethod(o, fn.constData(), Q_ARG(QByteArray*, &value)); + // qDebug() << "save" << o->objectName(); + mo->invokeMethod(o, fn.constData(), Q_ARG(QByteArray *, &value)); sr.setValue(o->objectName(), value, false); } - //qDebug() << mcl.size(); + // qDebug() << mcl.size(); emit saving(sr); sr.writeAll(); } @@ -133,7 +137,7 @@ void restoreWindowState(QWidget * w, QPIConfig & sr, QString name) { w->setWindowState(Qt::WindowNoState); w->restoreGeometry(sr.getValue(name + " geometry 0").toByteArray()); if (wstate == Qt::WindowMaximized) { - QTimer::singleShot(0, w, [w,wstate](){w->setWindowState((Qt::WindowState)wstate);}); + QTimer::singleShot(0, w, [w, wstate]() { w->setWindowState((Qt::WindowState)wstate); }); } bool wnd_ok = false; QRect srect; @@ -143,8 +147,8 @@ void restoreWindowState(QWidget * w, QPIConfig & sr, QString name) { srect = QApplication::desktop()->geometry(); } #else - QList sl = QApplication::screens(); - foreach (QScreen * s, sl) { + QList sl = QApplication::screens(); + foreach(QScreen * s, sl) { if (s->geometry().contains(w->geometry())) { wnd_ok = true; break; @@ -154,9 +158,10 @@ void restoreWindowState(QWidget * w, QPIConfig & sr, QString name) { #endif if (!wnd_ok) { w->setWindowState(Qt::WindowNoState); - w->setGeometry(srect.x() + (srect.width () - w->width ()) / 2, - srect.y() + (srect.height() - w->height()) / 2, - w->width(), w->height()); + w->setGeometry(srect.x() + (srect.width() - w->width()) / 2, + srect.y() + (srect.height() - w->height()) / 2, + w->width(), + w->height()); } } @@ -172,13 +177,11 @@ void SessionManager::load(bool onlyMainwindow) { QMainWindow * mw = mwindows[i].second; tsc << mw; QByteArray ba = sr.getValue(mwindows[i].first + " state").toByteArray(); - if (!ba.isEmpty()) - mw->restoreState(ba); - QList spl = mw_splitters[mw]; - foreach (QSplitter * s, spl) { + if (!ba.isEmpty()) mw->restoreState(ba); + QList spl = mw_splitters[mw]; + foreach(QSplitter * s, spl) { ba = sr.getValue(mwindows[i].first + " splitter " + s->objectName()).toByteArray(); - if (!ba.isEmpty()) - s->restoreState(ba); + if (!ba.isEmpty()) s->restoreState(ba); } restoreWindowState(mw, sr, mwindows[i].first); } @@ -194,9 +197,8 @@ void SessionManager::load(bool onlyMainwindow) { lines[i].second->setText(sr.getValue(lines[i].first, lines[i].second->text()).toString()); for (int i = 0; i < combos.size(); ++i) { QComboBox * c = combos[i].second; - int v = sr.getValue(combos[i].first, c->currentIndex()).toInt(); - if (v >= 0 && v < c->count()) - c->setCurrentIndex(v); + int v = sr.getValue(combos[i].first, c->currentIndex()).toInt(); + if (v >= 0 && v < c->count()) c->setCurrentIndex(v); } for (int i = 0; i < dspins.size(); ++i) dspins[i].second->setValue(sr.getValue(dspins[i].first, dspins[i].second->value()).toDouble()); @@ -208,16 +210,16 @@ void SessionManager::load(bool onlyMainwindow) { evals[i].second->setExpression(sr.getValue(evals[i].first, evals[i].second->expression()).toString()); for (int i = 0; i < tabs.size(); ++i) { QTabWidget * t = tabs[i].second; - int v = sr.getValue(tabs[i].first, t->currentIndex()).toDouble(); - if (v >= 0 && v < t->count()) - t->setCurrentIndex(v); + int v = sr.getValue(tabs[i].first, t->currentIndex()).toDouble(); + if (v >= 0 && v < t->count()) t->setCurrentIndex(v); } for (int i = 0; i < groups.size(); ++i) groups[i].second->setChecked(sr.getValue(groups[i].first, groups[i].second->isChecked()).toBool()); for (int i = 0; i < buttons.size(); ++i) buttons[i].second->setChecked(sr.getValue(buttons[i].first, buttons[i].second->isChecked()).toBool()); for (int i = 0; i < stacks.size(); ++i) - stacks[i].second->setCurrentIndex(qMin(sr.getValue(stacks[i].first, stacks[i].second->currentIndex()).toInt(), stacks[i].second->count())); + stacks[i].second->setCurrentIndex( + qMin(sr.getValue(stacks[i].first, stacks[i].second->currentIndex()).toInt(), stacks[i].second->count())); for (int i = 0; i < actions.size(); ++i) actions[i].second->setChecked(sr.getValue(actions[i].first, actions[i].second->isChecked()).toBool()); for (int i = 0; i < stringlists.size(); ++i) @@ -232,19 +234,19 @@ void SessionManager::load(bool onlyMainwindow) { *ints[i].second = sr.getValue(ints[i].first, *ints[i].second).toInt(); for (int i = 0; i < floats.size(); ++i) *floats[i].second = sr.getValue(floats[i].first, *floats[i].second).toFloat(); - QSet all_list; - foreach (QObject * c, tsc) { - all_list |= QList2QSet(c->findChildren()); + QSet all_list; + foreach(QObject * c, tsc) { + all_list |= QList2QSet(c->findChildren()); } - QMap funcs = metaFunctions(all_list, "sessionLoad"); - //qDebug() << "check for load" << all_list.size(); - foreach (QObject * o, all_list) { + QMap funcs = metaFunctions(all_list, "sessionLoad"); + // qDebug() << "check for load" << all_list.size(); + foreach(QObject * o, all_list) { const QMetaObject * mo = o->metaObject(); - QByteArray fn = funcs.value(mo); + QByteArray fn = funcs.value(mo); if (!mo || fn.isEmpty()) continue; QByteArray value = sr.getValue(o->objectName()).toByteArray(); - //qDebug() << "load" << o->objectName(); - mo->invokeMethod(o, fn.constData(), Q_ARG(QByteArray*, &value)); + // qDebug() << "load" << o->objectName(); + mo->invokeMethod(o, fn.constData(), Q_ARG(QByteArray *, &value)); } emit loading(sr); } @@ -276,8 +278,8 @@ void SessionManager::clear(bool with_filename) { QMap SessionManager::metaFunctions(const QSet & objects, QByteArray fname) { - QMap funcs; - foreach (QObject * o, objects) { + QMap funcs; + foreach(QObject * o, objects) { const QMetaObject * mo = o->metaObject(); if (!mo) continue; QByteArray fn; @@ -286,9 +288,9 @@ QMap SessionManager::metaFunctions(const QSetmethod(i); QByteArray mmn = #if QT_VERSION >= 0x050000 - mm.name(); + mm.name(); #else - mm.signature(); + mm.signature(); mmn = mmn.left(mmn.indexOf('(')); #endif @@ -301,7 +303,8 @@ QMap SessionManager::metaFunctions(const QSet. + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SESSION_MANAGER_H #define SESSION_MANAGER_H -#include -#include -#include -#include -#include +#include "evalspinbox.h" +#include "qad_widgets_export.h" +#include "qpiconfig.h" +#include "spinslider.h" + #include +#include #include -#include -#include +#include +#include +#include +#include +#include #include #include -#include -#include "spinslider.h" -#include "evalspinbox.h" -#include "qpiconfig.h" -#include "qad_widgets_export.h" +#include +#include /// for all children widgets of "QMainWindow"s and MainWidgets @@ -44,88 +45,87 @@ /// * void sessionLoad(QByteArray * data); -class QAD_WIDGETS_EXPORT SessionManager: public QObject -{ +class QAD_WIDGETS_EXPORT SessionManager: public QObject { Q_OBJECT + public: SessionManager(QString file = QString()); void setFile(const QString & file); - void addEntry(QMainWindow * e) {addEntry(e->objectName(), e);} - void addEntry(QCheckBox * e) {addEntry(e->objectName(), e);} - void addEntry(QLineEdit * e) {addEntry(e->objectName(), e);} - void addEntry(QComboBox * e) {addEntry(e->objectName(), e);} - void addEntry(QDoubleSpinBox * e) {addEntry(e->objectName(), e);} - void addEntry(QSpinBox * e) {addEntry(e->objectName(), e);} - void addEntry(SpinSlider * e) {addEntry(e->objectName(), e);} - void addEntry(EvalSpinBox * e) {addEntry(e->objectName(), e);} - void addEntry(QTabWidget * e) {addEntry(e->objectName(), e);} - void addEntry(QGroupBox * e) {addEntry(e->objectName(), e);} - void addEntry(QAction * e) {addEntry(e->objectName(), e);} - void addEntry(QAbstractButton * e) {addEntry(e->objectName(), e);} - void addEntry(QStackedWidget * e) {addEntry(e->objectName(), e);} - void addMainWidget(QWidget * e) {addMainWidget(e->objectName(), e);} + void addEntry(QMainWindow * e) { addEntry(e->objectName(), e); } + void addEntry(QCheckBox * e) { addEntry(e->objectName(), e); } + void addEntry(QLineEdit * e) { addEntry(e->objectName(), e); } + void addEntry(QComboBox * e) { addEntry(e->objectName(), e); } + void addEntry(QDoubleSpinBox * e) { addEntry(e->objectName(), e); } + void addEntry(QSpinBox * e) { addEntry(e->objectName(), e); } + void addEntry(SpinSlider * e) { addEntry(e->objectName(), e); } + void addEntry(EvalSpinBox * e) { addEntry(e->objectName(), e); } + void addEntry(QTabWidget * e) { addEntry(e->objectName(), e); } + void addEntry(QGroupBox * e) { addEntry(e->objectName(), e); } + void addEntry(QAction * e) { addEntry(e->objectName(), e); } + void addEntry(QAbstractButton * e) { addEntry(e->objectName(), e); } + void addEntry(QStackedWidget * e) { addEntry(e->objectName(), e); } + void addMainWidget(QWidget * e) { addMainWidget(e->objectName(), e); } void removeMainWidget(QWidget * e); - void addEntry(const QString & name, QMainWindow * e); - void addEntry(const QString & name, QCheckBox * e) {checks.push_back(QPair(name, e));} - void addEntry(const QString & name, QLineEdit * e) {lines.push_back(QPair(name, e));} - void addEntry(const QString & name, QComboBox * e) {combos.push_back(QPair(name, e));} - void addEntry(const QString & name, QDoubleSpinBox * e) {dspins.push_back(QPair(name, e));} - void addEntry(const QString & name, QSpinBox * e) {spins.push_back(QPair(name, e));} - void addEntry(const QString & name, SpinSlider * e) {spinsliders.push_back(QPair(name, e));} - void addEntry(const QString & name, EvalSpinBox * e) {evals.push_back(QPair(name, e));} - void addEntry(const QString & name, QTabWidget * e) {tabs.push_back(QPair(name, e));} - void addEntry(const QString & name, QGroupBox * e) {groups.push_back(QPair(name, e));} - void addEntry(const QString & name, QAbstractButton * e) {buttons.push_back(QPair(name, e));} - void addEntry(const QString & name, QStackedWidget * e) {stacks.push_back(QPair(name, e));} - void addEntry(const QString & name, QAction * e) {actions.push_back(QPair(name, e));} - void addEntry(const QString & name, QStringList * e) {stringlists.push_back(QPair(name, e));} - void addEntry(const QString & name, QString * e) {strings.push_back(QPair(name, e));} - void addEntry(const QString & name, QColor * e) {colors.push_back(QPair(name, e));} - void addEntry(const QString & name, bool * e) {bools.push_back(QPair(name, e));} - void addEntry(const QString & name, int * e) {ints.push_back(QPair(name, e));} - void addEntry(const QString & name, float * e) {floats.push_back(QPair(name, e));} - void addMainWidget(const QString & name, QWidget * e) {widgets.push_back(QPair(name, e));} + void addEntry(const QString & name, QMainWindow * e); + void addEntry(const QString & name, QCheckBox * e) { checks.push_back(QPair(name, e)); } + void addEntry(const QString & name, QLineEdit * e) { lines.push_back(QPair(name, e)); } + void addEntry(const QString & name, QComboBox * e) { combos.push_back(QPair(name, e)); } + void addEntry(const QString & name, QDoubleSpinBox * e) { dspins.push_back(QPair(name, e)); } + void addEntry(const QString & name, QSpinBox * e) { spins.push_back(QPair(name, e)); } + void addEntry(const QString & name, SpinSlider * e) { spinsliders.push_back(QPair(name, e)); } + void addEntry(const QString & name, EvalSpinBox * e) { evals.push_back(QPair(name, e)); } + void addEntry(const QString & name, QTabWidget * e) { tabs.push_back(QPair(name, e)); } + void addEntry(const QString & name, QGroupBox * e) { groups.push_back(QPair(name, e)); } + void addEntry(const QString & name, QAbstractButton * e) { buttons.push_back(QPair(name, e)); } + void addEntry(const QString & name, QStackedWidget * e) { stacks.push_back(QPair(name, e)); } + void addEntry(const QString & name, QAction * e) { actions.push_back(QPair(name, e)); } + void addEntry(const QString & name, QStringList * e) { stringlists.push_back(QPair(name, e)); } + void addEntry(const QString & name, QString * e) { strings.push_back(QPair(name, e)); } + void addEntry(const QString & name, QColor * e) { colors.push_back(QPair(name, e)); } + void addEntry(const QString & name, bool * e) { bools.push_back(QPair(name, e)); } + void addEntry(const QString & name, int * e) { ints.push_back(QPair(name, e)); } + void addEntry(const QString & name, float * e) { floats.push_back(QPair(name, e)); } + void addMainWidget(const QString & name, QWidget * e) { widgets.push_back(QPair(name, e)); } private: - QMap metaFunctions(const QSet & objects, QByteArray fname); + QMap metaFunctions(const QSet & objects, QByteArray fname); - QVector > mwindows; - QVector > widgets; - QVector > checks; - QVector > lines; - QVector > combos; - QVector > dspins; - QVector > spins; - QVector > spinsliders; - QVector > evals; - QVector > tabs; - QVector > groups; - QVector > buttons; - QVector > stacks; - QVector > actions; - QVector > stringlists; - QVector > strings; - QVector > colors; - QVector > bools; - QVector > ints; - QVector > floats; - QMap > mw_splitters; + QVector> mwindows; + QVector> widgets; + QVector> checks; + QVector> lines; + QVector> combos; + QVector> dspins; + QVector> spins; + QVector> spinsliders; + QVector> evals; + QVector> tabs; + QVector> groups; + QVector> buttons; + QVector> stacks; + QVector> actions; + QVector> stringlists; + QVector> strings; + QVector> colors; + QVector> bools; + QVector> ints; + QVector> floats; + QMap> mw_splitters; QString file_; public slots: void save(); void load(bool onlyMainwindow); - void load() {load(false);} + void load() { load(false); } void clear(bool with_filename); - void clear() {clear(true);} + void clear() { clear(true); } signals: - void loading(QPIConfig & ); - void saving(QPIConfig & ); - + void loading(QPIConfig &); + void saving(QPIConfig &); }; #endif // SESSION_MANAGER_H diff --git a/libs/widgets/shortcuts.cpp b/libs/widgets/shortcuts.cpp index 6b96141..c24b56d 100644 --- a/libs/widgets/shortcuts.cpp +++ b/libs/widgets/shortcuts.cpp @@ -1,19 +1,20 @@ #include "shortcuts.h" -#include + #include -#include #include +#include +#include #include +#include #include #include -#include -#include #include +#include /// ShortcutEdit -ShortcutEdit::ShortcutEdit(QWidget *parent) : CLineEdit(parent) { +ShortcutEdit::ShortcutEdit(QWidget * parent): CLineEdit(parent) { ti = nullptr; ca = nullptr; connect(this, &CLineEdit::textChanged, this, &ShortcutEdit::textChangedSlot); @@ -24,21 +25,20 @@ void ShortcutEdit::keyPressEvent(QKeyEvent * e) { Qt::KeyboardModifiers km = e->modifiers(); km &= ~Qt::KeypadModifier; km &= ~Qt::GroupSwitchModifier; - if (e->key() != Qt::Key_Control && e->key() != Qt::Key_Shift && - e->key() != Qt::Key_Alt && e->key() != Qt::Key_Meta) { - setText(QKeySequence(km | e->key()).toString()); + if (e->key() != Qt::Key_Control && e->key() != Qt::Key_Shift && e->key() != Qt::Key_Alt && e->key() != Qt::Key_Meta) { + setText(QKeySequence(km | e->key()).toString()); } } -void ShortcutEdit::assignAction(QAction *a) { +void ShortcutEdit::assignAction(QAction * a) { clear(); ca = a; reset(); } -QAction *ShortcutEdit::action() const { +QAction * ShortcutEdit::action() const { return ca; } @@ -81,7 +81,7 @@ Shortcuts::Shortcuts(QWidget * parent, bool on): QTreeWidget(parent) { p.eraseRect(ti.rect()); p.end(); empty_icon = QPixmap::fromImage(ti); - bfont = font(); + bfont = font(); bfont.setWeight(QFont::Bold); active = on; setColumnCount(2); @@ -103,7 +103,7 @@ Shortcuts::Shortcuts(QWidget * parent, bool on): QTreeWidget(parent) { Shortcuts::~Shortcuts() { - for (ShortcutEdit * i : edits) { + for (ShortcutEdit * i: edits) { delete i; } edits.clear(); @@ -125,28 +125,28 @@ void Shortcuts::assignWindow(QWidget * w) { if (!w) { return; } - while (!(qobject_cast(w)) && (w->parentWidget())) { + while (!(qobject_cast(w)) && (w->parentWidget())) { w = w->parentWidget(); } - aw = qobject_cast(w); + aw = qobject_cast(w); updateShortcuts(); } QStringList Shortcuts::actionTree(QAction * a) { QStringList tree; - QList aw = a->associatedWidgets(); + QList aw = a->associatedWidgets(); if (aw.size() == 0) { return tree; } - for (QWidget * i : aw) { - auto tm = qobject_cast(i); + for (QWidget * i: aw) { + auto tm = qobject_cast(i); if (!tm) { continue; } auto cw = i; while (cw) { - tm = qobject_cast(cw); + tm = qobject_cast(cw); if (tm) { if (!tm->title().isEmpty()) { tree.push_front(tm->title()); @@ -160,8 +160,8 @@ QStringList Shortcuts::actionTree(QAction * a) { return tree; } } - for (QWidget * i : aw) { - auto tt = qobject_cast(i); + for (QWidget * i: aw) { + auto tt = qobject_cast(i); if (!tt) { continue; } @@ -174,9 +174,9 @@ QStringList Shortcuts::actionTree(QAction * a) { } -QList > Shortcuts::shortcuts() { - QList > l; - for (const ShortcutEdit * i : edits) { +QList> Shortcuts::shortcuts() { + QList> l; + for (const ShortcutEdit * i: edits) { if (i->action()->objectName().isEmpty()) { continue; } @@ -187,12 +187,12 @@ QList > Shortcuts::shortcuts() { void Shortcuts::clear() { - foreach (ShortcutEdit * i, edits) + foreach(ShortcutEdit * i, edits) delete i; edits.clear(); hide(); - QList tl = findItems("", Qt::MatchContains); - foreach (QTreeWidgetItem * i, tl) + QList tl = findItems("", Qt::MatchContains); + foreach(QTreeWidgetItem * i, tl) delete i; show(); } @@ -208,7 +208,7 @@ bool Shortcuts::checkAction(QAction * a) { if (QString(a->metaObject()->className()) != "QAction") { return false; } - if (qobject_cast(a)) { + if (qobject_cast(a)) { return false; } return true; @@ -227,21 +227,21 @@ void Shortcuts::updateShortcuts() { #else header()->setSectionResizeMode(0, QHeaderView::Fixed); #endif - QList al = aw->findChildren(); - QTreeWidgetItem * pi, * ci; + QList al = aw->findChildren(); + QTreeWidgetItem *pi, *ci; QStringList tree; bool s = isSortingEnabled(), isFound; setSortingEnabled(false); - for (QAction * i : al) { + for (QAction * i: al) { if (!checkAction(i)) continue; edits.push_back(new ShortcutEdit()); tree = actionTree(i); - pi = invisibleRootItem(); - for (const QString & t : tree) { + pi = invisibleRootItem(); + for (const QString & t: tree) { isFound = false; for (int j = 0; j < pi->childCount(); ++j) { if (pi->child(j)->text(0) == t) { - pi = pi->child(j); + pi = pi->child(j); isFound = true; break; } @@ -264,7 +264,7 @@ void Shortcuts::updateShortcuts() { edits.back()->ti = ci; edits.back()->assignAction(i); pi->addChild(ci); - //qDebug() << "set widget" << edits.back(); + // qDebug() << "set widget" << edits.back(); setItemWidget(ci, 1, edits.back()); } setSortingEnabled(s); @@ -280,14 +280,14 @@ void Shortcuts::updateShortcuts() { void Shortcuts::commit() { - for (ShortcutEdit * i : edits) { + for (ShortcutEdit * i: edits) { i->commit(); } } void Shortcuts::resetShortcuts() { - for (ShortcutEdit * i : edits) { + for (ShortcutEdit * i: edits) { i->reset(); } updateShortcuts(); @@ -317,9 +317,8 @@ bool Shortcuts::filterTree(QTreeWidgetItem * ti, QString f) { isFound = true; } } - if (ti->text(0).indexOf(f, 0, Qt::CaseInsensitive) >= 0 || - ti->text(1).indexOf(f, 0, Qt::CaseInsensitive) >= 0) { - isFound = true; + if (ti->text(0).indexOf(f, 0, Qt::CaseInsensitive) >= 0 || ti->text(1).indexOf(f, 0, Qt::CaseInsensitive) >= 0) { + isFound = true; } ti->setHidden(!isFound); return isFound; @@ -327,8 +326,7 @@ bool Shortcuts::filterTree(QTreeWidgetItem * ti, QString f) { void Shortcuts::updateEditorGeometries() { - for (ShortcutEdit * i : edits) { + for (ShortcutEdit * i: edits) { i->setGeometry(visualRect(indexFromItem(i->ti, 1))); } } - diff --git a/libs/widgets/shortcuts.h b/libs/widgets/shortcuts.h index d07a295..3066230 100644 --- a/libs/widgets/shortcuts.h +++ b/libs/widgets/shortcuts.h @@ -1,27 +1,28 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SHORTCUTS_H #define SHORTCUTS_H -#include "qad_widgets_export.h" #include "clineedit.h" +#include "qad_widgets_export.h" + #include @@ -29,15 +30,15 @@ class QMainWindow; class ShortcutEdit; -class QAD_WIDGETS_EXPORT ShortcutEdit: public CLineEdit -{ +class QAD_WIDGETS_EXPORT ShortcutEdit: public CLineEdit { Q_OBJECT friend class Shortcuts; -public: - explicit ShortcutEdit(QWidget *parent = nullptr); - void assignAction(QAction *a); - QAction *action() const; +public: + explicit ShortcutEdit(QWidget * parent = nullptr); + + void assignAction(QAction * a); + QAction * action() const; bool isEmpty() const; void commit(); void reset(); @@ -53,18 +54,18 @@ private: }; -class QAD_WIDGETS_EXPORT Shortcuts: public QTreeWidget -{ +class QAD_WIDGETS_EXPORT Shortcuts: public QTreeWidget { Q_OBJECT + public: explicit Shortcuts(QWidget * parent = nullptr, bool on = true); ~Shortcuts() override; void assignWindow(QWidget * w); - void setActive(bool on) {active = on;} + void setActive(bool on) { active = on; } QStringList actionTree(QAction * a); static bool checkAction(QAction * a); - QList > shortcuts(); + QList> shortcuts(); public slots: void clear(); @@ -76,7 +77,7 @@ public slots: private: virtual void updateEditorGeometries() override; virtual void changeEvent(QEvent *) override; - bool filterTree(QTreeWidgetItem *ti, QString f); + bool filterTree(QTreeWidgetItem * ti, QString f); QMainWindow * aw; QVector edits; diff --git a/libs/widgets/spinslider.cpp b/libs/widgets/spinslider.cpp index bbe7d9f..fff0630 100644 --- a/libs/widgets/spinslider.cpp +++ b/libs/widgets/spinslider.cpp @@ -1,16 +1,17 @@ #include "spinslider.h" + #include SpinSlider::SpinSlider(QWidget * parent): QWidget(parent) { min_ = val_ = 0.; - max_ = 100.; - dec_ = 1; - page = 10.; - ticks_ = 1; - direc = LeftToRight; - square = false; - slider = new QSlider(); + max_ = 100.; + dec_ = 1; + page = 10.; + ticks_ = 1; + direc = LeftToRight; + square = false; + slider = new QSlider(); slider->setOrientation(Qt::Horizontal); slider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); spin = new QDoubleSpinBox(); @@ -51,23 +52,29 @@ bool SpinSlider::adaptiveStep() const { void SpinSlider::setAdaptiveStep(bool on) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) - if (on) spin->setStepType(QDoubleSpinBox::AdaptiveDecimalStepType); - else spin->setStepType(QDoubleSpinBox::DefaultStepType); + if (on) + spin->setStepType(QDoubleSpinBox::AdaptiveDecimalStepType); + else + spin->setStepType(QDoubleSpinBox::DefaultStepType); #endif } void SpinSlider::adjust() { adjusting = true; - delim = qPow(10, dec_); + delim = qPow(10, dec_); spin->setDecimals(dec_); spin->setRange(min_, max_); - if (square) slider->setRange(sqrt(min_ * delim), sqrt(max_ * delim)); - else slider->setRange(min_ * delim, max_ * delim); + if (square) + slider->setRange(sqrt(min_ * delim), sqrt(max_ * delim)); + else + slider->setRange(min_ * delim, max_ * delim); if (val_ < min_) val_ = min_; if (val_ > max_) val_ = max_; spin->setValue(val_); - if (square) slider->setValue(static_cast(sqrt(val_ * delim))); - else slider->setValue(static_cast(val_ * delim)); + if (square) + slider->setValue(static_cast(sqrt(val_ * delim))); + else + slider->setValue(static_cast(val_ * delim)); slider->setPageStep(qRound(page * delim)); slider->setTickInterval(qRound(ticks_ * delim)); emit valueChanged(val_); @@ -79,8 +86,10 @@ void SpinSlider::adjust() { void SpinSlider::sliderChanged(int value) { if (adjusting) return; adjusting = true; - if (square) spin->setValue(static_cast(sqr(value) / delim)); - else spin->setValue(static_cast(value) / delim); + if (square) + spin->setValue(static_cast(sqr(value) / delim)); + else + spin->setValue(static_cast(value) / delim); val_ = spin->value(); emit valueChanged(val_); emit valueChangedInt(qRound(val_)); @@ -91,9 +100,11 @@ void SpinSlider::sliderChanged(int value) { void SpinSlider::spinChanged(double value) { if (adjusting) return; adjusting = true; - val_ = value; - if (square) slider->setValue(static_cast(sqrt(value * delim))); - else slider->setValue(qRound(value * delim)); + val_ = value; + if (square) + slider->setValue(static_cast(sqrt(value * delim))); + else + slider->setValue(qRound(value * delim)); emit valueChanged(val_); emit valueChangedInt(qRound(val_)); adjusting = false; diff --git a/libs/widgets/spinslider.h b/libs/widgets/spinslider.h index fda4742..42da5ba 100644 --- a/libs/widgets/spinslider.h +++ b/libs/widgets/spinslider.h @@ -1,33 +1,33 @@ /* - QAD - Qt ADvanced + QAD - Qt ADvanced - Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru + Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ #ifndef SPINSLIDER_H #define SPINSLIDER_H -#include -#include -#include #include "qad_widgets_export.h" +#include +#include +#include -class QAD_WIDGETS_EXPORT SpinSlider: public QWidget -{ + +class QAD_WIDGETS_EXPORT SpinSlider: public QWidget { Q_OBJECT Q_ENUMS(Direction) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) @@ -52,50 +52,85 @@ public: explicit SpinSlider(QWidget * parent = 0); ~SpinSlider(); - enum Direction {LeftToRight, RightToLeft, TopToBottom, BottomToTop}; + enum Direction { + LeftToRight, + RightToLeft, + TopToBottom, + BottomToTop + }; - double minimum() const {return min_;} - double maximum() const {return max_;} - double spinMinimum() const {return spin->minimum();} - double spinMaximum() const {return spin->maximum();} - double value() const {return val_;} - int decimals() const {return dec_;} - double singleStep() const {return spin->singleStep();} + double minimum() const { return min_; } + double maximum() const { return max_; } + double spinMinimum() const { return spin->minimum(); } + double spinMaximum() const { return spin->maximum(); } + double value() const { return val_; } + int decimals() const { return dec_; } + double singleStep() const { return spin->singleStep(); } bool adaptiveStep() const; - double pageStep() const {return page;} - QString prefix() const {return spin->prefix();} - QString suffix() const {return spin->suffix();} - QSlider::TickPosition tickPosition() const {return slider->tickPosition();} - int tickInterval() const {return ticks_;} - Qt::Orientation orientation() const {return slider->orientation();} - Direction direction() const {return direc;} - bool invertedAppearance() const {return slider->invertedAppearance();} - bool squareScale() const {return square;} + double pageStep() const { return page; } + QString prefix() const { return spin->prefix(); } + QString suffix() const { return spin->suffix(); } + QSlider::TickPosition tickPosition() const { return slider->tickPosition(); } + int tickInterval() const { return ticks_; } + Qt::Orientation orientation() const { return slider->orientation(); } + Direction direction() const { return direc; } + bool invertedAppearance() const { return slider->invertedAppearance(); } + bool squareScale() const { return square; } - void setSingleStep(double step) {spin->setSingleStep(step); slider->setPageStep(qRound(step * delim));} + void setSingleStep(double step) { + spin->setSingleStep(step); + slider->setPageStep(qRound(step * delim)); + } void setAdaptiveStep(bool on); - void setPageStep(double step) {page = step; slider->setPageStep(qRound(page * delim));} - void setPrefix(QString prefix) {spin->setPrefix(prefix);} - void setSuffix(QString suffix) {spin->setSuffix(suffix);} - void setTickPosition(QSlider::TickPosition tp) {slider->setTickPosition(tp);} - void setTickInterval(int ti) {ticks_ = ti; slider->setTickInterval(qRound(ticks_ * delim));} + void setPageStep(double step) { + page = step; + slider->setPageStep(qRound(page * delim)); + } + void setPrefix(QString prefix) { spin->setPrefix(prefix); } + void setSuffix(QString suffix) { spin->setSuffix(suffix); } + void setTickPosition(QSlider::TickPosition tp) { slider->setTickPosition(tp); } + void setTickInterval(int ti) { + ticks_ = ti; + slider->setTickInterval(qRound(ticks_ * delim)); + } void setOrientation(Qt::Orientation orient); - void setDirection(Direction d) {direc = d; layout->setDirection((QBoxLayout::Direction)d);} - void setInvertedAppearance(bool yes) {slider->setInvertedAppearance(yes);} - void setSquareScale(bool yes) {square = yes; adjust();} + void setDirection(Direction d) { + direc = d; + layout->setDirection((QBoxLayout::Direction)d); + } + void setInvertedAppearance(bool yes) { slider->setInvertedAppearance(yes); } + void setSquareScale(bool yes) { + square = yes; + adjust(); + } public slots: - void setMinimum(double value) {min_ = value; adjust();} - void setMaximum(double value) {max_ = value; adjust();} - void setSpinMinimum(double value) {spin->setMinimum(value);} - void setSpinMaximum(double value) {spin->setMaximum(value);} - void setValue(double value) {val_ = value; spin->setValue(value);} - void setDecimals(int value) {dec_ = value; adjust();} - void reset() {val_ = 0.; spin->setValue(0.);} + void setMinimum(double value) { + min_ = value; + adjust(); + } + void setMaximum(double value) { + max_ = value; + adjust(); + } + void setSpinMinimum(double value) { spin->setMinimum(value); } + void setSpinMaximum(double value) { spin->setMaximum(value); } + void setValue(double value) { + val_ = value; + spin->setValue(value); + } + void setDecimals(int value) { + dec_ = value; + adjust(); + } + void reset() { + val_ = 0.; + spin->setValue(0.); + } private: void adjust(); - double sqr(const double & v) {return v * v;} + double sqr(const double & v) { return v * v; } double min_, max_, val_, delim, page; int dec_, ticks_; @@ -112,7 +147,6 @@ private slots: signals: void valueChanged(double); void valueChangedInt(int); - }; diff --git a/utils/blockeditor/blockeditor_main.cpp b/utils/blockeditor/blockeditor_main.cpp index e2f8e34..3bf3b37 100644 --- a/utils/blockeditor/blockeditor_main.cpp +++ b/utils/blockeditor/blockeditor_main.cpp @@ -1,14 +1,14 @@ -#include #include "blockeditor.h" +#include + int main(int argc, char * argv[]) { QApplication a(argc, argv); enableHighDPI(); a.setWindowIcon(QIcon(":/icons/blockview.png")); BlockEditor w; - if (a.arguments().size() > 1) - w.loadFile(a.arguments().back()); + if (a.arguments().size() > 1) w.loadFile(a.arguments().back()); w.show(); return a.exec(); } diff --git a/utils/piintrospector/containers_view.cpp b/utils/piintrospector/containers_view.cpp index f04a399..7d962be 100644 --- a/utils/piintrospector/containers_view.cpp +++ b/utils/piintrospector/containers_view.cpp @@ -1,8 +1,9 @@ #include "containers_view.h" -#include + #include -#include #include +#include +#include enum ColumnContainers { @@ -15,12 +16,10 @@ enum ColumnContainers { }; - - ContainersModel::ContainersModel() { mode_changes = false; - ls_column = 0; - ls_order = Qt::AscendingOrder; + ls_column = 0; + ls_order = Qt::AscendingOrder; all.resize(columnCount(), 0L); prev_all.resize(all.size(), 0L); } @@ -29,20 +28,20 @@ ContainersModel::ContainersModel() { void ContainersModel::update(const PIVector & t) { prev_data.clear(); all.fill(0U); - piForeachC (PIIntrospectionContainers::TypeInfo & i, cur_data) { + piForeachC(PIIntrospectionContainers::TypeInfo & i, cur_data) { prev_data[i.id] = i; } - piForeachC (PIIntrospectionContainers::TypeInfo & i, t) { - all[ccCount] += i.count; -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) + piForeachC(PIIntrospectionContainers::TypeInfo & i, t) { + all[ccCount] += i.count; +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) all[ccBytesAllocated] += i.allocated_bytes; - all[ccBytesUsed] += i.used_bytes; + all[ccBytesUsed] += i.used_bytes; #else all[ccBytesAllocated] += i.allocated; - all[ccBytesUsed] += i.used; + all[ccBytesUsed] += i.used; #endif } - int pts = cur_data.size_s(); + int pts = cur_data.size_s(); cur_data = t; if (t.size_s() > pts) { beginInsertRows(QModelIndex(), pts, t.size_s() - 1); @@ -96,11 +95,11 @@ QVariant ContainersModel::headerData(int section, Qt::Orientation orientation, i ret[i] -= prev_all[i]; } switch (section) { - case ccType : return tr("Type"); - case ccItemSize : return tr("Item size"); - case ccCount : return tr("Count (%1)").arg(ret[ccCount]); + case ccType: return tr("Type"); + case ccItemSize: return tr("Item size"); + case ccCount: return tr("Count (%1)").arg(ret[ccCount]); case ccBytesAllocated: return tr("Allocated (%1)").arg(PI2QString(PIString::readableSize(ret[ccBytesAllocated]))); - case ccBytesUsed : return tr("Used (%1)").arg(PI2QString(PIString::readableSize(ret[ccBytesUsed]))); + case ccBytesUsed: return tr("Used (%1)").arg(PI2QString(PIString::readableSize(ret[ccBytesUsed]))); default: break; } return QVariant(); @@ -108,16 +107,16 @@ QVariant ContainersModel::headerData(int section, Qt::Orientation orientation, i QVariant ContainersModel::data(const QModelIndex & index, int role) const { - if (role != Qt::DisplayRole && role != Qt::UserRole && role != (Qt::UserRole+1)) return QVariant(); + if (role != Qt::DisplayRole && role != Qt::UserRole && role != (Qt::UserRole + 1)) return QVariant(); uint id = uint(index.internalId()); const PIIntrospectionContainers::TypeInfo & t(cur_data[index.row()]); llong v = 0L; if (role == Qt::DisplayRole || role == Qt::UserRole) { switch (index.column()) { - case ccType: return PI2QString(t.name); + case ccType: return PI2QString(t.name); case ccItemSize: if (role == Qt::UserRole) return t.item_size; -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) return PI2QString(t.item_size_str); #else return PI2QString(PIString::readableSize(t.item_size)); @@ -128,7 +127,7 @@ QVariant ContainersModel::data(const QModelIndex & index, int role) const { switch (index.column()) { case ccCount: return int(t.count) - int(prev_data.value(id).count); case ccBytesAllocated: -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) v = t.allocated_bytes; v -= prev_data.value(id).allocated_bytes; #else @@ -138,7 +137,7 @@ QVariant ContainersModel::data(const QModelIndex & index, int role) const { if (role == Qt::UserRole) return piAbs(v); return PI2QString(PIString::readableSize(v)); case ccBytesUsed: -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) v = t.used_bytes; v -= prev_data.value(id).used_bytes; #else @@ -152,7 +151,7 @@ QVariant ContainersModel::data(const QModelIndex & index, int role) const { switch (index.column()) { case ccCount: return t.count; case ccBytesAllocated: -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) if (role == Qt::UserRole) return t.allocated_bytes; return PI2QString(t.allocated_str); case ccBytesUsed: @@ -163,12 +162,12 @@ QVariant ContainersModel::data(const QModelIndex & index, int role) const { return PI2QString(PIString::readableSize(t.allocated)); case ccBytesUsed: if (role == Qt::UserRole) return t.used; - return PI2QString(PIString::readableSize(t.used)); + return PI2QString(PIString::readableSize(t.used)); #endif } } } - if (role == (Qt::UserRole+1) && (index.column() == ccCount)) { + if (role == (Qt::UserRole + 1) && (index.column() == ccCount)) { return t.count; } return QVariant(); @@ -180,21 +179,21 @@ Qt::ItemFlags ContainersModel::flags(const QModelIndex & index) const { } -//bool cmp(const PIIntrospectionContainers::TypeInfo & a, const PIIntrospectionContainers::TypeInfo & b); -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +// bool cmp(const PIIntrospectionContainers::TypeInfo & a, const PIIntrospectionContainers::TypeInfo & b); +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) bool cmp_func_name_a(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { return QString::localeAwareCompare(PI2QString(t0.name), PI2QString(t1.name)) < 0; } bool cmp_func_name_d(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { return !cmp_func_name_a(t0, t1); } -# define CMP_FUNC(field) \ - bool cmp_func_##field##_a(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { \ - return t0.field < t1.field; \ - } \ - bool cmp_func_##field##_d(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { \ - return t0.field > t1.field; \ - } +# define CMP_FUNC(field) \ + bool cmp_func_##field##_a(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { \ + return t0.field < t1.field; \ + } \ + bool cmp_func_##field##_d(const PIIntrospectionContainers::TypeInfo & t0, const PIIntrospectionContainers::TypeInfo & t1) { \ + return t0.field > t1.field; \ + } #else int cmp_func_name_a(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { return QString::localeAwareCompare(PI2QString(t0->name), PI2QString(t1->name)); @@ -202,17 +201,17 @@ int cmp_func_name_a(const PIIntrospectionContainers::TypeInfo * t0, const PIIntr int cmp_func_name_d(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { return -cmp_func_name_a(t0, t1); } -# define CMP_FUNC(field) \ - int cmp_func_##field##_a(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { \ - return (t0->field) <= (t1->field) ? -1 : ((t0->field) == (t1->field) ? 0 : 1); \ - } \ - int cmp_func_##field##_d(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { \ - return -cmp_func_##field##_a(t0, t1); \ - } +# define CMP_FUNC(field) \ + int cmp_func_##field##_a(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { \ + return (t0->field) <= (t1->field) ? -1 : ((t0->field) == (t1->field) ? 0 : 1); \ + } \ + int cmp_func_##field##_d(const PIIntrospectionContainers::TypeInfo * t0, const PIIntrospectionContainers::TypeInfo * t1) { \ + return -cmp_func_##field##_a(t0, t1); \ + } #endif CMP_FUNC(item_size) CMP_FUNC(count) -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) CMP_FUNC(allocated_bytes) CMP_FUNC(used_bytes) #else @@ -222,30 +221,30 @@ CMP_FUNC(used) #undef CMP_FUNC void ContainersModel::sort(int column, Qt::SortOrder order) { ls_column = column; - ls_order = order; + ls_order = order; if (cur_data.isEmpty()) return; PIVector::CompareFunc cf = nullptr; -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) switch (column) { - case ccType : cf = order == Qt::AscendingOrder ? cmp_func_name_a : cmp_func_name_d ; break; - case ccItemSize : cf = order == Qt::AscendingOrder ? cmp_func_item_size_a : cmp_func_item_size_d ; break; - case ccCount : cf = order == Qt::AscendingOrder ? cmp_func_count_a : cmp_func_count_d ; break; + case ccType: cf = order == Qt::AscendingOrder ? cmp_func_name_a : cmp_func_name_d; break; + case ccItemSize: cf = order == Qt::AscendingOrder ? cmp_func_item_size_a : cmp_func_item_size_d; break; + case ccCount: cf = order == Qt::AscendingOrder ? cmp_func_count_a : cmp_func_count_d; break; case ccBytesAllocated: cf = order == Qt::AscendingOrder ? cmp_func_allocated_bytes_a : cmp_func_allocated_bytes_d; break; - case ccBytesUsed : cf = order == Qt::AscendingOrder ? cmp_func_used_bytes_a : cmp_func_used_bytes_d ; break; - default : break; + case ccBytesUsed: cf = order == Qt::AscendingOrder ? cmp_func_used_bytes_a : cmp_func_used_bytes_d; break; + default: break; } #else switch (column) { - case ccType : cf = order == Qt::AscendingOrder ? cmp_func_name_a : cmp_func_name_d ; break; - case ccItemSize : cf = order == Qt::AscendingOrder ? cmp_func_item_size_a : cmp_func_item_size_d; break; - case ccCount : cf = order == Qt::AscendingOrder ? cmp_func_count_a : cmp_func_count_d ; break; + case ccType: cf = order == Qt::AscendingOrder ? cmp_func_name_a : cmp_func_name_d; break; + case ccItemSize: cf = order == Qt::AscendingOrder ? cmp_func_item_size_a : cmp_func_item_size_d; break; + case ccCount: cf = order == Qt::AscendingOrder ? cmp_func_count_a : cmp_func_count_d; break; case ccBytesAllocated: cf = order == Qt::AscendingOrder ? cmp_func_allocated_a : cmp_func_allocated_d; break; - case ccBytesUsed : cf = order == Qt::AscendingOrder ? cmp_func_used_a : cmp_func_used_d ; break; - default : break; + case ccBytesUsed: cf = order == Qt::AscendingOrder ? cmp_func_used_a : cmp_func_used_d; break; + default: break; } #endif if (cf) cur_data.sort(cf); - //qDebug() << "sort" << column << order; + // qDebug() << "sort" << column << order; dataChanged(index(0, 0), index(cur_data.size_s() - 1, columnCount())); } @@ -258,14 +257,11 @@ void ContainersModel::setChangesMode(bool yes) { } - - void ContainersDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QStyledItemDelegate::paint(painter, option, index); - if (model->index(index.row(), ccCount).data(Qt::UserRole+1).toInt() == 0) { + if (model->index(index.row(), ccCount).data(Qt::UserRole + 1).toInt() == 0) { QColor col; - if (option.state == QStyle::State_Enabled || - option.state == QStyle::State_HasFocus) + if (option.state == QStyle::State_Enabled || option.state == QStyle::State_HasFocus) col = option.palette.color(QPalette::Active, QPalette::WindowText); else col = option.palette.color(QPalette::Disabled, QPalette::WindowText); @@ -277,8 +273,6 @@ void ContainersDelegate::paint(QPainter * painter, const QStyleOptionViewItem & } - - ContainersView::ContainersView(QWidget * parent): QWidget(parent) { setupUi(this); model = new ContainersModel(); @@ -292,18 +286,14 @@ ContainersView::ContainersView(QWidget * parent): QWidget(parent) { } -ContainersView::~ContainersView() { -} +ContainersView::~ContainersView() {} void ContainersView::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: retranslateUi(this); break; + default: break; } } diff --git a/utils/piintrospector/containers_view.h b/utils/piintrospector/containers_view.h index 13961a0..7e67e52 100644 --- a/utils/piintrospector/containers_view.h +++ b/utils/piintrospector/containers_view.h @@ -1,16 +1,18 @@ #ifndef CONTAINERS_VIEW_H #define CONTAINERS_VIEW_H -#include "ui_containers_view.h" -#include -#include -#include -#include -#include "piqt.h" #include "piintrospection_containers_p.h" +#include "piqt.h" +#include "ui_containers_view.h" + +#include +#include +#include +#include class ContainersModel: public QAbstractItemModel { Q_OBJECT + public: ContainersModel(); @@ -19,7 +21,7 @@ public: int rowCount(const QModelIndex & parent = QModelIndex()) const; int columnCount(const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex & child) const {return QModelIndex();} + QModelIndex parent(const QModelIndex & child) const { return QModelIndex(); } QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; bool hasChildren(const QModelIndex & parent = QModelIndex()) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; @@ -37,39 +39,40 @@ protected: public slots: void setChangesMode(bool yes); - }; class ContainersDelegate: public QStyledItemDelegate { Q_OBJECT + public: - ContainersDelegate(QAbstractItemModel * m) {model = m;} - void paint(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex &index) const; + ContainersDelegate(QAbstractItemModel * m) { model = m; } + void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const; QAbstractItemModel * model; }; - -class ContainersView: public QWidget, private Ui::ContainersView -{ +class ContainersView + : public QWidget + , private Ui::ContainersView { Q_OBJECT + public: ContainersView(QWidget * parent = 0); ~ContainersView(); void showContainers(const PIVector & t); void clear(); + protected: void changeEvent(QEvent * e); ContainersModel * model; private slots: - void sessionSave(QByteArray * data) {*data = treeContainers->header()->saveState();} - void sessionLoad(QByteArray * data) {treeContainers->header()->restoreState(*data);} + void sessionSave(QByteArray * data) { *data = treeContainers->header()->saveState(); } + void sessionLoad(QByteArray * data) { treeContainers->header()->restoreState(*data); } public slots: - }; diff --git a/utils/piintrospector/objects_view.cpp b/utils/piintrospector/objects_view.cpp index d1803e6..3ac98d1 100644 --- a/utils/piintrospector/objects_view.cpp +++ b/utils/piintrospector/objects_view.cpp @@ -1,4 +1,5 @@ #include "objects_view.h" + #include #include @@ -16,18 +17,14 @@ ObjectsView::ObjectsView(QWidget * parent): QWidget(parent) { } -ObjectsView::~ObjectsView() { -} +ObjectsView::~ObjectsView() {} void ObjectsView::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: retranslateUi(this); break; + default: break; } } @@ -37,7 +34,7 @@ void ObjectsView::showObjects(const PIVector & obje int vpos = treeObjects->verticalScrollBar()->value(); treeObjects->clear(); - piForeachC (PIIntrospection::ObjectInfo & i, objects) { + piForeachC(PIIntrospection::ObjectInfo & i, objects) { stat[PI2QString(i.classname)]++; QTreeWidgetItem * ti = new QTreeWidgetItem(); ti->setText(coClassName, PI2QString(i.classname)); diff --git a/utils/piintrospector/objects_view.h b/utils/piintrospector/objects_view.h index 7143291..e663fc4 100644 --- a/utils/piintrospector/objects_view.h +++ b/utils/piintrospector/objects_view.h @@ -1,28 +1,31 @@ #ifndef OBJECTS_VIEW_H #define OBJECTS_VIEW_H +#include "piintrospection_server_p.h" +#include "piqt.h" #include "ui_objects_view.h" + #include #include -#include "piqt.h" -#include "piintrospection_server_p.h" -class ObjectsView: public QWidget, private Ui::ObjectsView -{ +class ObjectsView + : public QWidget + , private Ui::ObjectsView { Q_OBJECT + public: ObjectsView(QWidget * parent = 0); ~ObjectsView(); void showObjects(const PIVector & objects); + protected: void changeEvent(QEvent * e); private slots: - void sessionSave(QByteArray * data) {*data = treeObjects->header()->saveState();} - void sessionLoad(QByteArray * data) {treeObjects->header()->restoreState(*data);} + void sessionSave(QByteArray * data) { *data = treeObjects->header()->saveState(); } + void sessionLoad(QByteArray * data) { treeObjects->header()->restoreState(*data); } public slots: - }; #endif // OBJECTS_VIEW_H diff --git a/utils/piintrospector/piintrospector.cpp b/utils/piintrospector/piintrospector.cpp index aac5f2d..31b8689 100644 --- a/utils/piintrospector/piintrospector.cpp +++ b/utils/piintrospector/piintrospector.cpp @@ -1,11 +1,13 @@ #include "piintrospector.h" -#include -#include + +#include "ccm_piintrospector.h" +#include "pichunkstream.h" +#include "pidir.h" #include "pifile.h" #include "pitime.h" -#include "pidir.h" -#include "pichunkstream.h" -#include "ccm_piintrospector.h" + +#include +#include QPIIntrospector::QPIIntrospector(QWidget * parent): EMainWindow(parent), peer("__introspection_client__") { @@ -13,22 +15,22 @@ QPIIntrospector::QPIIntrospector(QWidget * parent): EMainWindow(parent), peer("_ request_timer = 0; session.setFile("qpiintrospector_session.conf"); #if QT_VERSION >= 0x050000 - //treeContainers->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + // treeContainers->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else - //treeContainers->header()->setResizeMode(QHeaderView::ResizeToContents); + // treeContainers->header()->setResizeMode(QHeaderView::ResizeToContents); #endif CONNECTU_QUEUED(&peer, peerConnectedEvent, this, peersChanged, this); CONNECTU_QUEUED(&peer, peerDisconnectedEvent, this, peersChanged, this); CONNECTU_QUEUED(&peer, dataReceivedEvent, this, peerReceived, this); - //CONNECTU(&peer, peerConnectedEvent, this, reqProcPIEvents); - //CONNECTU(&peer, peerDisconnectedEvent, this, reqProcPIEvents); - //CONNECTU(&peer, dataReceivedEvent, this, reqProcPIEvents); + // CONNECTU(&peer, peerConnectedEvent, this, reqProcPIEvents); + // CONNECTU(&peer, peerDisconnectedEvent, this, reqProcPIEvents); + // CONNECTU(&peer, dataReceivedEvent, this, reqProcPIEvents); session.addEntry(this); session.addEntry(tabWidgetMain); PICodeInfo::EnumInfo * ei = PICodeInfo::enumsInfo->value("PIIntrospection::InfoTypes"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) { -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) { +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) QCheckBox * cb = new QCheckBox(PI2QString(e.name.mid(2).toString())); #else QCheckBox * cb = new QCheckBox(PI2QString(e.name.mid(2))); @@ -54,19 +56,15 @@ QPIIntrospector::~QPIIntrospector() { void QPIIntrospector::changeEvent(QEvent * e) { EMainWindow::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslateUi(this); - break; + case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void QPIIntrospector::timerEvent(QTimerEvent * e) { - if (e->timerId() == pip_timer) - callQueuedEvents(); - if (e->timerId() == request_timer) - buttonRequest->click(); + if (e->timerId() == pip_timer) callQueuedEvents(); + if (e->timerId() == request_timer) buttonRequest->click(); } @@ -86,9 +84,9 @@ void QPIIntrospector::buildTree(QByteArray d) { pd >> threads; treeContainers->clear(); piForeachC (PIIntrospectionThreads::ThreadInfo & t, threads) { - QTreeWidgetItem * ti = new QTreeWidgetItem(); - ti->setText(0, QString(PI2QString(t.name) + " (%1)").arg(t.id)); - treeContainers->addTopLevelItem(ti); + QTreeWidgetItem * ti = new QTreeWidgetItem(); + ti->setText(0, QString(PI2QString(t.name) + " (%1)").arg(t.id)); + treeContainers->addTopLevelItem(ti); }*/ } @@ -101,8 +99,7 @@ void QPIIntrospector::procRequestTimer() { } -void QPIIntrospector::buildDumpSection(QTreeWidgetItem * pi, PIString & str) { -} +void QPIIntrospector::buildDumpSection(QTreeWidgetItem * pi, PIString & str) {} void QPIIntrospector::showInfo() { @@ -141,15 +138,15 @@ QString QPIIntrospector::durationStr(PISystemTime t) { QString ret; double s = t.toSeconds(); int d, h, m; - d = piFloor(s / (24*60*60)); + d = piFloor(s / (24 * 60 * 60)); if (d > 0) { ret += QString::number(d) + " d "; - s -= d * (24*60*60); + s -= d * (24 * 60 * 60); } - h = piFloor(s / (60*60)); + h = piFloor(s / (60 * 60)); if (h > 0) { ret += QString::number(h) + " h "; - s -= h * (60*60); + s -= h * (60 * 60); } m = piFloor(s / 60); if (m > 0) { @@ -160,11 +157,11 @@ QString QPIIntrospector::durationStr(PISystemTime t) { return ret; } -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) void QPIIntrospector::prepareContainers(PIVector & data) { for (PIIntrospectionContainers::TypeInfo & i: data) { i.allocated_bytes = i.allocated * i.item_size; - i.used_bytes = i.used * i.item_size; + i.used_bytes = i.used * i.item_size; i.item_size_str.setReadableSize(i.item_size); i.allocated_str.setReadableSize(i.allocated_bytes); i.used_str.setReadableSize(i.used_bytes); @@ -174,56 +171,63 @@ void QPIIntrospector::prepareContainers(PIVectoritem(r)->data(Qt::UserRole).toString()); - if (cur_server != cs) - widgetContainers->clear(); + if (r < 0) + cs.clear(); + else + cs = Q2PIString(listApp->item(r)->data(Qt::UserRole).toString()); + if (cur_server != cs) widgetContainers->clear(); cur_server = cs; } void QPIIntrospector::peerReceived(const PIString & from, const PIByteArray & data) { if (from != cur_server) return; - //piCout << "rec" << data.size(); + // piCout << "rec" << data.size(); PIByteArray ba(data); if (ba.size_s() < 4) return; - uint sign(0); ba >> sign; + uint sign(0); + ba >> sign; if (sign != PIIntrospection::sign) return; PIChunkStream cs(ba); PIByteArray pba; while (!cs.atEnd()) { switch (cs.read()) { case PIIntrospection::itInfo: { - pba.clear(); cs.get(pba); + pba.clear(); + cs.get(pba); PIIntrospection::unpackInfo(pba, info); - } break; + } break; case PIIntrospection::itProcStat: { - pba.clear(); cs.get(pba); + pba.clear(); + cs.get(pba); PIIntrospection::unpackProcStat(pba, stat); widgetThreads->setStat(stat.threads); - //showInfo(info); - } break; + // showInfo(info); + } break; case PIIntrospection::itContainers: { - pba.clear(); cs.get(pba); + pba.clear(); + cs.get(pba); PIVector data; PIIntrospection::unpackContainers(pba, data); -#if PIP_VERSION >= PIP_MAKE_VERSION(2,35,0) +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 35, 0) prepareContainers(data); #endif widgetContainers->showContainers(data); - } break; + } break; case PIIntrospection::itObjects: { - pba.clear(); cs.get(pba); + pba.clear(); + cs.get(pba); PIVector objects; PIIntrospection::unpackObjects(pba, objects); widgetObjects->showObjects(objects); - } break; + } break; case PIIntrospection::itThreads: { - pba.clear(); cs.get(pba); + pba.clear(); + cs.get(pba); PIVector threads; PIIntrospection::unpackThreads(pba, threads); widgetThreads->showThreads(threads); - } break; + } break; default: break; } } @@ -237,14 +241,13 @@ void QPIIntrospector::peersChanged(const PIString & name) { QString cs = listApp->currentItem() ? listApp->currentItem()->text() : ""; listApp->clear(); peer.lock(); - piForeachC (PIPeer::PeerInfo & p, peer.allPeers()) { + piForeachC(PIPeer::PeerInfo & p, peer.allPeers()) { QString pn = PI2QString(p.name); if (!pn.contains(tag)) continue; QListWidgetItem * li = new QListWidgetItem(pn.left(pn.indexOf(tag))); li->setData(Qt::UserRole, pn); listApp->addItem(li); - if (pn == cs) - listApp->setCurrentRow(listApp->count() - 1); + if (pn == cs) listApp->setCurrentRow(listApp->count() - 1); } peer.unlock(); listApp->blockSignals(false); @@ -255,7 +258,7 @@ void QPIIntrospector::on_buttonRequest_clicked() { if (cur_server.isEmpty()) return; PIIntrospection::RequiredInfo info; for (int i = 0; i < layoutRequestFlags->count(); ++i) { - QCheckBox * cb = qobject_cast(layoutRequestFlags->itemAt(i)->widget()); + QCheckBox * cb = qobject_cast(layoutRequestFlags->itemAt(i)->widget()); if (!cb) continue; if (!cb->isChecked()) continue; info.types |= cb->property("__value__").toInt(); diff --git a/utils/piintrospector/piintrospector.h b/utils/piintrospector/piintrospector.h index b90c58e..3aa5503 100644 --- a/utils/piintrospector/piintrospector.h +++ b/utils/piintrospector/piintrospector.h @@ -1,26 +1,30 @@ #ifndef PIINTROSPECTOR_H #define PIINTROSPECTOR_H +#include "piintrospection_server_p.h" +#include "pipeer.h" +#include "piqt.h" #include "ui_piintrospector.h" + +#include #include #include -#include #include -#include "piqt.h" -#include "pipeer.h" -#include "piintrospection_server_p.h" -class QPIIntrospector: public EMainWindow, private Ui::QPIIntrospector, public PIObject -{ +class QPIIntrospector + : public EMainWindow + , private Ui::QPIIntrospector + , public PIObject { Q_OBJECT PIOBJECT(QPIIntrospector); + public: QPIIntrospector(QWidget * parent = 0); ~QPIIntrospector(); protected: void changeEvent(QEvent * e); - void timerEvent(QTimerEvent * ); + void timerEvent(QTimerEvent *); void savingSession(QPIConfig & conf); void loadingSession(QPIConfig & conf); @@ -37,7 +41,7 @@ protected: PIIntrospection::ProcessStat stat; PIPeer peer; int request_timer, pip_timer; - + private slots: void buildTree(QByteArray d); void procRequestTimer(); @@ -45,7 +49,6 @@ private slots: void on_buttonRequest_clicked(); public slots: - }; #endif // PIINTROSPECTOR_H diff --git a/utils/piintrospector/piintrospector_main.cpp b/utils/piintrospector/piintrospector_main.cpp index ed13494..2607876 100644 --- a/utils/piintrospector/piintrospector_main.cpp +++ b/utils/piintrospector/piintrospector_main.cpp @@ -1,9 +1,8 @@ +#include "piintrospector.h" +#include "qcodeedit.h" + #include #include -#include "piintrospector.h" - - -#include "qcodeedit.h" int main(int argc, char * argv[]) { QApplication a(argc, argv); enableHighDPI(); @@ -11,24 +10,24 @@ int main(int argc, char * argv[]) { /*QCodeEdit w; w.setEditorFont(QFont("dejavu sans mono", 10)); w.setText( - "Telegram.addCommand(\"Поискать 💰\", \"find_money\");\n" - "Telegram.addCommand(\"🔍Исследования\", \"research\");\n" - "Telegram.addCommand(\"📖Инфо/🌍Планета\", \"planet_info\");\n" - "Telegram.addCommand(\"📖Инфо/💻Дерево исследований\", \"research_map\");\n" - "Telegram.addCommand(\"📖Инфо/🌌Сканер планет\", \"map_info\");\n" - "Telegram.addCommand(\"🛠Строительство/📖Инфо\", \"planet_info\");\n" - "Telegram.addCommand(\"🛠Строительство/⛏Шахта\", \"info_plant\");\n" - "Telegram.addCommand(\"🛠Строительство/⛏Шахта/📖Инфо\", \"info_plant\");\n" - "Telegram.addCommand(\"🛠Строительство/⛏Шахта/🛠Cтроить ⛏Шахту\", \"build_plant\");\n" - "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция\", \"info_solar\");\n" - "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция/📖Инфо\", \"info_solar\");\n" - "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция/🛠Cтроить ⚡️Электростанцию\", \"build_solar\");\n" - "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор\", \"info_accum\");\n" - "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор/📖Инфо\", \"info_accum\");\n" - "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор/🛠Cтроить 🔋Аккумулятор\", \"build_accum\");\n" - "Telegram.addCommand(\"🛠Строительство/📦Хранилище\", \"info_storage\");\n" - "Telegram.addCommand(\"🛠Строительство/📦Хранилище/📖Инфо\", \"info_storage\");\n" - ); + "Telegram.addCommand(\"Поискать 💰\", \"find_money\");\n" + "Telegram.addCommand(\"🔍Исследования\", \"research\");\n" + "Telegram.addCommand(\"📖Инфо/🌍Планета\", \"planet_info\");\n" + "Telegram.addCommand(\"📖Инфо/💻Дерево исследований\", \"research_map\");\n" + "Telegram.addCommand(\"📖Инфо/🌌Сканер планет\", \"map_info\");\n" + "Telegram.addCommand(\"🛠Строительство/📖Инфо\", \"planet_info\");\n" + "Telegram.addCommand(\"🛠Строительство/⛏Шахта\", \"info_plant\");\n" + "Telegram.addCommand(\"🛠Строительство/⛏Шахта/📖Инфо\", \"info_plant\");\n" + "Telegram.addCommand(\"🛠Строительство/⛏Шахта/🛠Cтроить ⛏Шахту\", \"build_plant\");\n" + "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция\", \"info_solar\");\n" + "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция/📖Инфо\", \"info_solar\");\n" + "Telegram.addCommand(\"🛠Строительство/⚡️Электростанция/🛠Cтроить ⚡️Электростанцию\", \"build_solar\");\n" + "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор\", \"info_accum\");\n" + "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор/📖Инфо\", \"info_accum\");\n" + "Telegram.addCommand(\"🛠Строительство/🔋Аккумулятор/🛠Cтроить 🔋Аккумулятор\", \"build_accum\");\n" + "Telegram.addCommand(\"🛠Строительство/📦Хранилище\", \"info_storage\");\n" + "Telegram.addCommand(\"🛠Строительство/📦Хранилище/📖Инфо\", \"info_storage\");\n" + ); //w.textEdit()->setCursorWidth(1);*/ w.show(); return a.exec(); diff --git a/utils/piintrospector/threads_view.cpp b/utils/piintrospector/threads_view.cpp index 40c3f3a..9edee86 100644 --- a/utils/piintrospector/threads_view.cpp +++ b/utils/piintrospector/threads_view.cpp @@ -1,10 +1,12 @@ #include "threads_view.h" -#include -#include -#include -#include + #include "ccm_piintrospector.h" +#include +#include +#include +#include + enum ColumnThreads { ctClassname, @@ -19,13 +21,11 @@ enum ColumnThreads { }; - - ThreadsModel::ThreadsModel() { PICodeInfo::EnumInfo * ei = PICodeInfo::enumsInfo->value("PIIntrospectionThreads::ThreadState"); if (ei) { - piForeachC (PICodeInfo::EnumeratorInfo & e, ei->members) { -#if PIP_VERSION >= PIP_MAKE_VERSION(2,39,0) + piForeachC(PICodeInfo::EnumeratorInfo & e, ei->members) { +#if PIP_VERSION >= PIP_MAKE_VERSION(2, 39, 0) state_names[e.value] = PI2QString(e.name.mid(1).toString()); #else state_names[e.value] = PI2QString(e.name.mid(1)); @@ -51,7 +51,7 @@ void ThreadsModel::update(const PIVector & t endRemoveRows(); } dataChanged(index(0, 0), index(threads.size_s() - 1, columnCount())); - //emit headerDataChanged(Qt::Horizontal, ccCount, columnCount()); + // emit headerDataChanged(Qt::Horizontal, ccCount, columnCount()); } @@ -94,13 +94,13 @@ QVariant ThreadsModel::headerData(int section, Qt::Orientation orientation, int if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return QVariant(); switch (section) { case ctClassname: return tr("Classname"); - case ctName : return tr("Name"); - case ctID : return tr("pID (pri)"); - case ctDelay : return tr("Delay, ms"); - case ctState : return tr("State"); - case ctLoad : return tr("CPU, %"); - case ctRunCost : return tr("Run cost, avg"); - case ctRunCount : return tr("Run counts"); + case ctName: return tr("Name"); + case ctID: return tr("pID (pri)"); + case ctDelay: return tr("Delay, ms"); + case ctState: return tr("State"); + case ctLoad: return tr("CPU, %"); + case ctRunCost: return tr("Run cost, avg"); + case ctRunCount: return tr("Run counts"); default: break; } return QVariant(); @@ -113,26 +113,32 @@ QVariant ThreadsModel::data(const QModelIndex & index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case ctClassname: return PI2QString(ti.classname); - case ctName : return PI2QString(ti.name); - case ctID : return QString("%1 (%2)").arg(ti.id).arg(ti.priority); - case ctDelay : return QString::number(ti.delay); - case ctState : return state_names.value(ti.state); - case ctLoad : { - piForeachC (PISystemMonitor::ThreadStats & s, stat) { + case ctName: return PI2QString(ti.name); + case ctID: return QString("%1 (%2)").arg(ti.id).arg(ti.priority); + case ctDelay: return QString::number(ti.delay); + case ctState: return state_names.value(ti.state); + case ctLoad: { + piForeachC(PISystemMonitor::ThreadStats & s, stat) { if (s.id == llong(ti.id)) { return QString::number(s.cpu_load_kernel + s.cpu_load_user, 'f', 2) + " %"; } } return "-"; - } - case ctRunCost : { - double v = ti.run_us; + } + case ctRunCost: { + double v = ti.run_us; QByteArray suff = " us"; - if (v > 1000.) {v /= 1000.; suff = " ms";} - if (v > 1000.) {v /= 1000.; suff = " s";} - return QString::number(v, 'f', 1) + suff; + if (v > 1000.) { + v /= 1000.; + suff = " ms"; } - case ctRunCount : return QString::number(ti.run_count); + if (v > 1000.) { + v /= 1000.; + suff = " s"; + } + return QString::number(v, 'f', 1) + suff; + } + case ctRunCount: return QString::number(ti.run_count); } } if (index.column() == ctState) { @@ -152,43 +158,39 @@ Qt::ItemFlags ThreadsModel::flags(const QModelIndex & index) const { } - /* void ContainersDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { - QStyledItemDelegate::paint(painter, option, index); - if (model->index(index.row(), ccCount).data(Qt::UserRole+1).toInt() == 0) { - QColor col; - if (option.state == QStyle::State_Enabled || - option.state == QStyle::State_HasFocus) - col = option.palette.color(QPalette::Active, QPalette::WindowText); - else - col = option.palette.color(QPalette::Disabled, QPalette::WindowText); - col.setAlphaF(0.5); - int y = option.rect.center().y() + (option.fontMetrics.height() / 2.5) - option.fontMetrics.strikeOutPos(); - painter->setPen(QPen(col, lineThickness())); - painter->drawLine(QPoint(option.rect.left(), y), QPoint(option.rect.right(), y)); - } + QStyledItemDelegate::paint(painter, option, index); + if (model->index(index.row(), ccCount).data(Qt::UserRole+1).toInt() == 0) { + QColor col; + if (option.state == QStyle::State_Enabled || + option.state == QStyle::State_HasFocus) + col = option.palette.color(QPalette::Active, QPalette::WindowText); + else + col = option.palette.color(QPalette::Disabled, QPalette::WindowText); + col.setAlphaF(0.5); + int y = option.rect.center().y() + (option.fontMetrics.height() / 2.5) - option.fontMetrics.strikeOutPos(); + painter->setPen(QPen(col, lineThickness())); + painter->drawLine(QPoint(option.rect.left(), y), QPoint(option.rect.right(), y)); + } } */ - - ThreadsView::ThreadsView(QWidget * parent): QWidget(parent) { setupUi(this); - model = new ThreadsModel(); + model = new ThreadsModel(); QSortFilterProxyModel * proxy = new QSortFilterProxyModel(); proxy->setSourceModel(model); proxy->setSortRole(Qt::UserRole); proxy->setDynamicSortFilter(false); treeThreads->setModel(model); connect(checkHideStopped, SIGNAL(toggled(bool)), this, SLOT(updateHidden())); - //treeContainers->setItemDelegate(new ContainersDelegate(model)); + // treeContainers->setItemDelegate(new ContainersDelegate(model)); } -ThreadsView::~ThreadsView() { -} +ThreadsView::~ThreadsView() {} void ThreadsView::setStat(const PIVector & stat) { @@ -199,20 +201,18 @@ void ThreadsView::setStat(const PIVector & stat) { void ThreadsView::changeEvent(QEvent * e) { QWidget::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: retranslateUi(this); break; + default: break; } } void ThreadsView::updateHidden() { bool hide_stopped = checkHideStopped->isChecked(); - QModelIndex root = treeThreads->rootIndex(); + QModelIndex root = treeThreads->rootIndex(); for (int i = 0; i < model->rowCount(); ++i) { - if (!hide_stopped) treeThreads->setRowHidden(i, root, false); + if (!hide_stopped) + treeThreads->setRowHidden(i, root, false); else { if (model->index(i, ctState).data(Qt::UserRole).toInt() == PIIntrospectionThreads::sStopped) treeThreads->setRowHidden(i, root, true); diff --git a/utils/piintrospector/threads_view.h b/utils/piintrospector/threads_view.h index bd643b6..4e5a2ff 100644 --- a/utils/piintrospector/threads_view.h +++ b/utils/piintrospector/threads_view.h @@ -1,20 +1,22 @@ #ifndef THREADS_VIEW_H #define THREADS_VIEW_H -#include "ui_threads_view.h" -#include -#include -#include -#include -#include -#include +#include "piintrospection_threads_p.h" #include "piqt.h" #include "pisystemmonitor.h" -#include "piintrospection_threads_p.h" +#include "ui_threads_view.h" + +#include +#include +#include +#include +#include +#include class ThreadsModel: public QAbstractItemModel { Q_OBJECT + public: ThreadsModel(); @@ -24,7 +26,7 @@ public: int rowCount(const QModelIndex & parent = QModelIndex()) const; int columnCount(const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex & child) const {return QModelIndex();} + QModelIndex parent(const QModelIndex & child) const { return QModelIndex(); } QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; bool hasChildren(const QModelIndex & parent = QModelIndex()) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; @@ -36,25 +38,25 @@ protected: PIVector stat; QHash state_names; QHash state_colors; - }; - /* class ContainersDelegate: public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT public: - ContainersDelegate(QAbstractItemModel * m) {model = m;} - void paint(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex &index) const override; - QAbstractItemModel * model; + ContainersDelegate(QAbstractItemModel * m) {model = m;} + void paint(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex &index) const override; + QAbstractItemModel * model; }; */ -class ThreadsView: public QWidget, private Ui::ThreadsView -{ +class ThreadsView + : public QWidget + , private Ui::ThreadsView { Q_OBJECT + public: ThreadsView(QWidget * parent = 0); ~ThreadsView(); @@ -69,12 +71,11 @@ protected: ThreadsModel * model; private slots: - void sessionSave(QByteArray * data) {*data = treeThreads->header()->saveState();} - void sessionLoad(QByteArray * data) {treeThreads->header()->restoreState(*data);} + void sessionSave(QByteArray * data) { *data = treeThreads->header()->saveState(); } + void sessionLoad(QByteArray * data) { treeThreads->header()->restoreState(*data); } void updateHidden(); public slots: - };