From e1905d7de8b124701f041346819068df864b948f Mon Sep 17 00:00:00 2001 From: Darcy Shen Date: Sat, 2 Dec 2023 17:12:34 +0800 Subject: [PATCH] [16_8] bin/format on src/Plugins/Qt --- .github/workflows/clang-format-linter.yml | 6 +- bin/format | 10 +- src/Plugins/Qt/QTMApplication.hpp | 134 +- src/Plugins/Qt/QTMFileDialog.cpp | 162 +- src/Plugins/Qt/QTMFileDialog.hpp | 82 +- src/Plugins/Qt/QTMGuiHelper.cpp | 94 +- src/Plugins/Qt/QTMGuiHelper.hpp | 29 +- src/Plugins/Qt/QTMInteractiveInputHelper.hpp | 22 +- src/Plugins/Qt/QTMInteractivePrompt.cpp | 51 +- src/Plugins/Qt/QTMInteractivePrompt.hpp | 10 +- src/Plugins/Qt/QTMMenuHelper.cpp | 1142 ++++++------ src/Plugins/Qt/QTMMenuHelper.hpp | 313 ++-- src/Plugins/Qt/QTMPipeLink.cpp | 57 +- src/Plugins/Qt/QTMPipeLink.hpp | 30 +- src/Plugins/Qt/QTMPixmapOrImage.hpp | 62 +- src/Plugins/Qt/QTMPrintDialog.cpp | 255 +-- src/Plugins/Qt/QTMPrintDialog.hpp | 753 ++++---- src/Plugins/Qt/QTMPrinterSettings.cpp | 673 +++---- src/Plugins/Qt/QTMPrinterSettings.hpp | 193 +- src/Plugins/Qt/QTMScrollView.cpp | 376 ++-- src/Plugins/Qt/QTMScrollView.hpp | 58 +- src/Plugins/Qt/QTMSockets.cpp | 394 ++-- src/Plugins/Qt/QTMSockets.hpp | 113 +- src/Plugins/Qt/QTMStyle.cpp | 594 +++--- src/Plugins/Qt/QTMStyle.hpp | 152 +- src/Plugins/Qt/QTMTreeModel.cpp | 280 ++- src/Plugins/Qt/QTMTreeModel.hpp | 115 +- src/Plugins/Qt/QTMWidget.cpp | 987 +++++----- src/Plugins/Qt/QTMWidget.hpp | 68 +- src/Plugins/Qt/QTMWindow.cpp | 127 +- src/Plugins/Qt/QTMWindow.hpp | 54 +- src/Plugins/Qt/qt_chooser_widget.cpp | 355 ++-- src/Plugins/Qt/qt_chooser_widget.hpp | 32 +- src/Plugins/Qt/qt_color_picker_widget.cpp | 50 +- src/Plugins/Qt/qt_color_picker_widget.hpp | 25 +- src/Plugins/Qt/qt_dialogues.cpp | 365 ++-- src/Plugins/Qt/qt_dialogues.hpp | 91 +- src/Plugins/Qt/qt_font.cpp | 106 +- src/Plugins/Qt/qt_font.hpp | 40 +- src/Plugins/Qt/qt_gui.cpp | 1129 ++++++------ src/Plugins/Qt/qt_gui.hpp | 189 +- src/Plugins/Qt/qt_menu.cpp | 81 +- src/Plugins/Qt/qt_menu.hpp | 37 +- src/Plugins/Qt/qt_picture.cpp | 290 +-- src/Plugins/Qt/qt_picture.hpp | 48 +- src/Plugins/Qt/qt_pipe_link.cpp | 94 +- src/Plugins/Qt/qt_printer_widget.cpp | 86 +- src/Plugins/Qt/qt_printer_widget.hpp | 24 +- src/Plugins/Qt/qt_renderer.cpp | 695 +++---- src/Plugins/Qt/qt_renderer.hpp | 96 +- src/Plugins/Qt/qt_simple_widget.cpp | 745 ++++---- src/Plugins/Qt/qt_simple_widget.hpp | 122 +- src/Plugins/Qt/qt_sys_utils.cpp | 39 +- src/Plugins/Qt/qt_sys_utils.hpp | 17 +- src/Plugins/Qt/qt_tm_widget.cpp | 1452 +++++++-------- src/Plugins/Qt/qt_tm_widget.hpp | 92 +- src/Plugins/Qt/qt_ui_element.cpp | 1709 +++++++++--------- src/Plugins/Qt/qt_ui_element.hpp | 172 +- src/Plugins/Qt/qt_utilities.cpp | 811 +++++---- src/Plugins/Qt/qt_utilities.hpp | 122 +- src/Plugins/Qt/qt_widget.cpp | 565 +++--- src/Plugins/Qt/qt_widget.hpp | 274 +-- src/Plugins/Qt/qt_window_widget.cpp | 415 ++--- src/Plugins/Qt/qt_window_widget.hpp | 70 +- 64 files changed, 9019 insertions(+), 8815 deletions(-) diff --git a/.github/workflows/clang-format-linter.yml b/.github/workflows/clang-format-linter.yml index 473097bdbd..67f4969a92 100644 --- a/.github/workflows/clang-format-linter.yml +++ b/.github/workflows/clang-format-linter.yml @@ -15,14 +15,16 @@ on: - 'src/Graphics/Types/**.hpp' - 'src/Graphics/Types/**.cpp' - 'src/Typeset/Boxes/Graphics/**.cpp' - - 'src/Plugins/Pdf/**.cpp' - - 'src/Plugins/Pdf/**.hpp' - 'src/Plugins/Ghostscript/**.cpp' - 'src/Plugins/Ghostscript/**.hpp' - 'src/Plugins/Html/**.cpp' - 'src/Plugins/Html/**.hpp' - 'src/Plugins/Metafont/**.cpp' - 'src/Plugins/Metafont/**.hpp' + - 'src/Plugins/Pdf/**.cpp' + - 'src/Plugins/Pdf/**.hpp' + - 'src/Plugins/Qt/**.cpp' + - 'src/Plugins/Qt/**.hpp' - 'src/Plugins/Xml/**.cpp' - 'src/Plugins/Xml/**.hpp' - 'src/Data/Tree/**.cpp' diff --git a/bin/format b/bin/format index 1e3c6d54a9..98298c4fbd 100755 --- a/bin/format +++ b/bin/format @@ -28,16 +28,18 @@ clang-format -i src/Graphics/Fonts/**.hpp clang-format -i src/Graphics/Types/**.cpp clang-format -i src/Graphics/Types/**.hpp clang-format -i src/Typeset/Boxes/Graphics/**.cpp -clang-format -i src/Plugins/Pdf/**.cpp -clang-format -i src/Plugins/Pdf/**.hpp clang-format -i src/Plugins/Ghostscript/**.cpp clang-format -i src/Plugins/Ghostscript/**.hpp clang-format -i src/Plugins/Html/*.cpp clang-format -i src/Plugins/Html/*.hpp -clang-format -i src/Plugins/Xml/*.cpp -clang-format -i src/Plugins/Xml/*.hpp clang-format -i src/Plugins/Metafont/*.cpp clang-format -i src/Plugins/Metafont/*.hpp +clang-format -i src/Plugins/Pdf/**.cpp +clang-format -i src/Plugins/Pdf/**.hpp +clang-format -i src/Plugins/Qt/**.cpp +clang-format -i src/Plugins/Qt/**.hpp +clang-format -i src/Plugins/Xml/*.cpp +clang-format -i src/Plugins/Xml/*.hpp clang-format -i src/Mogan/**.cpp clang-format -i src/Mogan/**.hpp diff --git a/src/Plugins/Qt/QTMApplication.hpp b/src/Plugins/Qt/QTMApplication.hpp index ded43f583c..3f1607a66a 100644 --- a/src/Plugins/Qt/QTMApplication.hpp +++ b/src/Plugins/Qt/QTMApplication.hpp @@ -12,25 +12,24 @@ #ifndef QTMAPPLICATION_HPP #define QTMAPPLICATION_HPP -#include -#include -#include +#include "renderer.hpp" #include "string.hpp" #include "sys_utils.hpp" -#include "url.hpp" #include "tm_url.hpp" -#include "renderer.hpp" +#include "url.hpp" +#include +#include +#include #include #include - void init_palette (QApplication* app); void init_style_sheet (QApplication* app); -void set_standard_style_sheet (QWidget *w); +void set_standard_style_sheet (QWidget* w); #ifdef Q_OS_MAC -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include // On MacOS we have to register appropriate mime types for PDF files @@ -42,43 +41,43 @@ void set_standard_style_sheet (QWidget *w); // (mg) I'm not sure this is the right place to have this code, but well... -class QMacPasteboardMimePDF : public QMacPasteboardMime -{ +class QMacPasteboardMimePDF : public QMacPasteboardMime { public: QMacPasteboardMimePDF () - : QMacPasteboardMime (MIME_QT_CONVERTOR | MIME_ALL) - {} + : QMacPasteboardMime (MIME_QT_CONVERTOR | MIME_ALL) {} - QString convertorName() { return "PDF"; } + QString convertorName () { return "PDF"; } - QString flavorFor (QString const & mime) - { + QString flavorFor (QString const& mime) { if (mime == QLatin1String ("application/pdf")) return QLatin1String ("com.adobe.pdf"); - return QString(); + return QString (); } - QString mimeFor(QString flav) - { + QString mimeFor (QString flav) { if (flav == QLatin1String ("com.adobe.pdf")) return QLatin1String ("application/pdf"); return QString (); } - bool canConvert(QString const & mime, QString flav) - { return mimeFor (flav) == mime; } + bool canConvert (QString const& mime, QString flav) { + return mimeFor (flav) == mime; + } - QVariant convertToMime (QString const & mime, QList data, QString flav) - { - (void) flav; (void) mime; + QVariant convertToMime (QString const& mime, QList data, + QString flav) { + (void) flav; + (void) mime; if (data.count () > 1) - debug_qt << "QMacPasteboardMimePDF: Cannot handle multiple member data " << LF; + debug_qt << "QMacPasteboardMimePDF: Cannot handle multiple member data " + << LF; return data.first (); } - QList convertFromMime (QString const & mime, QVariant data, QString flav) - { - (void) flav; (void) mime; + QList convertFromMime (QString const& mime, QVariant data, + QString flav) { + (void) flav; + (void) mime; QList ret; ret.append (data.toByteArray ()); return ret; @@ -87,54 +86,53 @@ class QMacPasteboardMimePDF : public QMacPasteboardMime #endif #endif - /* FIXME: We would like to do the following - + #ifdef USE_EXCEPTIONS class QTMApplication... blah blah - + #else - + typedef QApplication QTMApplication; - + #endif - + But MOC has trouble with conditional compilation. */ /*! QTMApplication - + Reimplements notify() in order to catch exceptions thrown from event handlers and slots. - + NOTE: see http://qt-project.org/forums/viewthread/17731 for the reason why the constructor takes an int& */ -class QTMApplication: public QApplication { +class QTMApplication : public QApplication { Q_OBJECT - + #ifdef Q_OS_MAC -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QMacPasteboardMimePDF mac_pasteboard_mime_pdf; #endif #endif - + public: - QTMApplication (int& argc, char** argv) : - QApplication (argc, argv) { - init_palette (this); - init_style_sheet (this); -#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor); + QTMApplication (int& argc, char** argv) : QApplication (argc, argv) { + init_palette (this); + init_style_sheet (this); +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + QGuiApplication::setHighDpiScaleFactorRoundingPolicy ( + Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor); #endif #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (!retina_manual) { - qreal ratio = QApplication::primaryScreen ()->devicePixelRatio (); - retina_factor= qRound (ratio - 0.1); - } -#endif + if (!retina_manual) { + qreal ratio = QApplication::primaryScreen ()->devicePixelRatio (); + retina_factor= qRound (ratio - 0.1); } +#endif + } void set_window_icon (string icon_path) { url icon_url= url_system (get_env ("TEXMACS_PATH") * icon_path); @@ -143,7 +141,8 @@ class QTMApplication: public QApplication { setWindowIcon (QIcon ((const char*) _icon)); } else - std_warning << "Could not find TeXmacs icon file: " << as_string (icon_url) << LF; + std_warning << "Could not find TeXmacs icon file: " + << as_string (icon_url) << LF; } /* @@ -157,39 +156,32 @@ class QTMApplication: public QApplication { return QApplication::event(event); } */ - - virtual bool notify (QObject* receiver, QEvent* event) - { + + virtual bool notify (QObject* receiver, QEvent* event) { try { return QApplication::notify (receiver, event); - } - catch (string s) { - //c_string cs (s); - //tm_failure (cs); - //qt_error << "Thrown " << s << LF; + } catch (string s) { + // c_string cs (s); + // tm_failure (cs); + // qt_error << "Thrown " << s << LF; the_exception= s; } return false; } }; -class QTMCoreApplication: public QCoreApplication { +class QTMCoreApplication : public QCoreApplication { Q_OBJECT - + public: - QTMCoreApplication (int& argc, char** argv) : - QCoreApplication (argc, argv) {} + QTMCoreApplication (int& argc, char** argv) : QCoreApplication (argc, argv) {} - void set_window_icon (string icon_path) { - (void) icon_path; - } + void set_window_icon (string icon_path) { (void) icon_path; } - virtual bool notify (QObject* receiver, QEvent* event) - { + virtual bool notify (QObject* receiver, QEvent* event) { try { return QCoreApplication::notify (receiver, event); - } - catch (string s) { + } catch (string s) { qt_error << "Thrown " << s << LF; the_exception= s; } @@ -197,4 +189,4 @@ class QTMCoreApplication: public QCoreApplication { } }; -#endif // QTMAPPLICATION_HPP +#endif // QTMAPPLICATION_HPP diff --git a/src/Plugins/Qt/QTMFileDialog.cpp b/src/Plugins/Qt/QTMFileDialog.cpp index 93b0ffb1cc..24393c55ad 100644 --- a/src/Plugins/Qt/QTMFileDialog.cpp +++ b/src/Plugins/Qt/QTMFileDialog.cpp @@ -1,87 +1,86 @@ /****************************************************************************** -* MODULE : QTMFileDialog.cpp -* DESCRIPTION: QT file choosers -* COPYRIGHT : (C) 2009 David MICHEL -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMFileDialog.cpp + * DESCRIPTION: QT file choosers + * COPYRIGHT : (C) 2009 David MICHEL + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "QTMFileDialog.hpp" -#include -#include -#include -#include -#include +#include "analyze.hpp" +#include "dictionary.hpp" +#include "image_files.hpp" +#include "qt_gui.hpp" +#include "qt_utilities.hpp" +#include "sys_utils.hpp" +#include "tm_file.hpp" #include #include #include #include -#include "tm_file.hpp" -#include "sys_utils.hpp" -#include "qt_utilities.hpp" -#include "qt_gui.hpp" -#include "analyze.hpp" -#include "dictionary.hpp" -#include "image_files.hpp" +#include +#include +#include +#include +#include -QTMFileDialog::QTMFileDialog (QWidget * parent, const QString & caption, - const QString & directory, const QString & filter) - : QDialog (parent) -{ +QTMFileDialog::QTMFileDialog (QWidget* parent, const QString& caption, + const QString& directory, const QString& filter) + : QDialog (parent) { setWindowTitle (caption); hbox= new QHBoxLayout (this); hbox->setContentsMargins (0, 0, 0, 0); file= new QMyFileDialog (0, caption, directory, filter); - file->setOption(QFileDialog::DontUseNativeDialog, true); + file->setOption (QFileDialog::DontUseNativeDialog, true); hbox->addWidget (file); setLayout (hbox); - setAcceptDrops(true); - connect(file, SIGNAL(accepted()), this, SLOT(accept())); - connect(file, SIGNAL(finished(int)), this, SLOT(done(int))); - connect(file, SIGNAL(rejected()), this, SLOT(reject())); + setAcceptDrops (true); + connect (file, SIGNAL (accepted ()), this, SLOT (accept ())); + connect (file, SIGNAL (finished (int)), this, SLOT (done (int))); + connect (file, SIGNAL (rejected ()), this, SLOT (reject ())); } -void QTMFileDialog::dragEnterEvent(QDragEnterEvent *event) -{ - event->acceptProposedAction(); +void +QTMFileDialog::dragEnterEvent (QDragEnterEvent* event) { + event->acceptProposedAction (); } -void QTMFileDialog::dragMoveEvent(QDragMoveEvent *event) -{ - event->acceptProposedAction(); +void +QTMFileDialog::dragMoveEvent (QDragMoveEvent* event) { + event->acceptProposedAction (); } -void QTMFileDialog::dropEvent(QDropEvent *event) -{ - const QMimeData *mimeData = event->mimeData(); - - foreach (QString format, mimeData->formats()) { - if (format == "text/uri-list") { - file->selectFile(mimeData->urls().at(0).toLocalFile()); - break; - } - } - - event->acceptProposedAction(); -} +void +QTMFileDialog::dropEvent (QDropEvent* event) { + const QMimeData* mimeData= event->mimeData (); -void QTMFileDialog::dragLeaveEvent(QDragLeaveEvent *event) -{ - event->accept(); + foreach (QString format, mimeData->formats ()) { + if (format == "text/uri-list") { + file->selectFile (mimeData->urls ().at (0).toLocalFile ()); + break; + } + } + + event->acceptProposedAction (); } +void +QTMFileDialog::dragLeaveEvent (QDragLeaveEvent* event) { + event->accept (); +} static QWidget* simple_input (string s, QLineEdit* ledit, QWidget* parent= 0) { - QWidget* widget= new QWidget (parent); + QWidget* widget= new QWidget (parent); QHBoxLayout* layout= new QHBoxLayout (widget); layout->setContentsMargins (0, 0, 0, 0); -// string in_lan= get_input_language (); -// string out_lan= get_output_language (); -// QLabel* label= new QLabel (to_qstring (tm_var_encode (translate (s, in_lan, out_lan))), parent); + // string in_lan= get_input_language (); + // string out_lan= get_output_language (); + // QLabel* label= new QLabel (to_qstring (tm_var_encode (translate (s, + // in_lan, out_lan))), parent); QLabel* label= new QLabel (to_qstring (s), parent); layout->addWidget (label); layout->addWidget (ledit); @@ -89,8 +88,7 @@ simple_input (string s, QLineEdit* ledit, QWidget* parent= 0) { return widget; } -QTMImagePreview::QTMImagePreview (QWidget* parent) - : QWidget (parent) { +QTMImagePreview::QTMImagePreview (QWidget* parent) : QWidget (parent) { QVBoxLayout* vbox= new QVBoxLayout (this); vbox->addStretch (); image= new QLabel (this); @@ -114,9 +112,9 @@ QTMImagePreview::QTMImagePreview (QWidget* parent) setImage (0); } -void -QTMImagePreview::setImage (const QString& file) { //generate thumbnail -BEGIN_SLOT +void +QTMImagePreview::setImage (const QString& file) { // generate thumbnail + BEGIN_SLOT QImage img; wid->setText (""); hei->setText (""); @@ -124,21 +122,25 @@ BEGIN_SLOT yps->setText (""); string localname= from_qstring_utf8 (file); - url image_url= url_system (localname); - if (DEBUG_CONVERT) debug_convert<<"image preview :["<setText (QString::number (w_pt) + "pt"); hei->setText (QString::number (h_pt) + "pt"); if (w_pt > h_pt) { w= 98; - h= ceil (h_pt*98/w_pt); - } else { - w= ceil (w_pt*98/h_pt); + h= ceil (h_pt * 98 / w_pt); + } + else { + w= ceil (w_pt * 98 / h_pt); h= 98; } // generate thumbnail: @@ -148,8 +150,8 @@ BEGIN_SLOT } } - if (img.isNull()) { - QImage vide (100, 100, QImage::Format_RGB32); + if (img.isNull ()) { + QImage vide (100, 100, QImage::Format_RGB32); QPainter painter; painter.begin (&vide); painter.fillRect (0, 0, 100, 100, Qt::white); @@ -161,19 +163,21 @@ BEGIN_SLOT painter.drawLine (0, 99, 99, 0); painter.drawRect (0, 0, 99, 99); painter.end (); - image->setPixmap(QPixmap::fromImage(vide)); + image->setPixmap (QPixmap::fromImage (vide)); } else - image->setPixmap (QPixmap::fromImage (img.scaled (98, 98, Qt::KeepAspectRatio, Qt::FastTransformation))); -END_SLOT + image->setPixmap (QPixmap::fromImage ( + img.scaled (98, 98, Qt::KeepAspectRatio, Qt::FastTransformation))); + END_SLOT } -QTMImageDialog::QTMImageDialog (QWidget* parent, const QString& caption, const QString& directory, const QString& filter) - : QTMFileDialog (parent, caption, directory, filter) -{ +QTMImageDialog::QTMImageDialog (QWidget* parent, const QString& caption, + const QString& directory, const QString& filter) + : QTMFileDialog (parent, caption, directory, filter) { preview= new QTMImagePreview (this); - hbox->insertWidget(0, preview); - connect(file, SIGNAL(currentChanged (const QString&)), preview, SLOT(setImage(const QString&))); + hbox->insertWidget (0, preview); + connect (file, SIGNAL (currentChanged (const QString&)), preview, + SLOT (setImage (const QString&))); } string diff --git a/src/Plugins/Qt/QTMFileDialog.hpp b/src/Plugins/Qt/QTMFileDialog.hpp index b99ca20e5e..41ed1d3c4d 100644 --- a/src/Plugins/Qt/QTMFileDialog.hpp +++ b/src/Plugins/Qt/QTMFileDialog.hpp @@ -1,69 +1,72 @@ /****************************************************************************** -* MODULE : QTMFileDialog.hpp -* DESCRIPTION: QT file choosers -* COPYRIGHT : (C) 2009 David MICHEL -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMFileDialog.hpp + * DESCRIPTION: QT file choosers + * COPYRIGHT : (C) 2009 David MICHEL + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMFILEDIALOG_HPP #define QTMFILEDIALOG_HPP +#include "string.hpp" #include +#include #include #include -#include -#include "string.hpp" -class QMyFileDialog : public QFileDialog -{ +class QMyFileDialog : public QFileDialog { Q_OBJECT public: - QMyFileDialog (QWidget* parent= 0, - const QString & caption = QString(), - const QString & directory = QString(), - const QString & filter = QString()) - : QFileDialog(parent, caption, directory, filter) { } + QMyFileDialog (QWidget* parent= 0, const QString& caption= QString (), + const QString& directory= QString (), + const QString& filter = QString ()) + : QFileDialog (parent, caption, directory, filter) {} }; -class QTMFileDialog : public QDialog -{ +class QTMFileDialog : public QDialog { Q_OBJECT protected: QHBoxLayout* hbox; QFileDialog* file; - void dragEnterEvent(QDragEnterEvent* event); - void dragMoveEvent(QDragMoveEvent* event); - void dragLeaveEvent(QDragLeaveEvent* event); - void dropEvent(QDropEvent* event); + void dragEnterEvent (QDragEnterEvent* event); + void dragMoveEvent (QDragMoveEvent* event); + void dragLeaveEvent (QDragLeaveEvent* event); + void dropEvent (QDropEvent* event); public: - QTMFileDialog (QWidget* parent= 0, - const QString& caption = QString(), - const QString& directory = QString(), - const QString & filter = QString()); + QTMFileDialog (QWidget* parent= 0, const QString& caption= QString (), + const QString& directory= QString (), + const QString& filter = QString ()); QStringList selectedFiles () { return file->selectedFiles (); }; #if defined(Q_OS_MAC) void setOptions (QFileDialog::Options opts) { file->setOptions (opts); }; #endif - void setAcceptMode (QFileDialog::AcceptMode mode) { file->setAcceptMode(mode); } + void setAcceptMode (QFileDialog::AcceptMode mode) { + file->setAcceptMode (mode); + } void setViewMode (QFileDialog::ViewMode mode) { file->setViewMode (mode); } void setFileMode (QFileDialog::FileMode mode) { file->setFileMode (mode); } void setNameFilter (const QString& filter) { file->setNameFilter (filter); } - void setNameFilters (const QStringList& filters) { file->setNameFilters (filters); } - void setDefaultSuffix (const QString& suffix) { file->setDefaultSuffix (suffix); } - void setLabelText (QFileDialog::DialogLabel label, const QString& text) { file->setLabelText (label, text); } + void setNameFilters (const QStringList& filters) { + file->setNameFilters (filters); + } + void setDefaultSuffix (const QString& suffix) { + file->setDefaultSuffix (suffix); + } + void setLabelText (QFileDialog::DialogLabel label, const QString& text) { + file->setLabelText (label, text); + } }; -class QTMImagePreview : public QWidget -{ +class QTMImagePreview : public QWidget { Q_OBJECT - QLabel *image; + QLabel* image; public: QLineEdit* wid; @@ -78,19 +81,16 @@ public slots: QTMImagePreview (QWidget* parent= 0); }; -class QTMImageDialog : public QTMFileDialog -{ +class QTMImageDialog : public QTMFileDialog { Q_OBJECT QTMImagePreview* preview; public: - QTMImageDialog (QWidget* parent= 0, - const QString& caption = QString (), - const QString& directory = QString (), - const QString& filter = QString ()); + QTMImageDialog (QWidget* parent= 0, const QString& caption= QString (), + const QString& directory= QString (), + const QString& filter = QString ()); string getParamsAsString (); }; #endif // defined QTMFILEDIALOG_HPP - diff --git a/src/Plugins/Qt/QTMGuiHelper.cpp b/src/Plugins/Qt/QTMGuiHelper.cpp index f1b46af0e2..b353a79eaf 100644 --- a/src/Plugins/Qt/QTMGuiHelper.cpp +++ b/src/Plugins/Qt/QTMGuiHelper.cpp @@ -1,92 +1,92 @@ /****************************************************************************** -* MODULE : QTMGuiHelper.cpp -* DESCRIPTION: QT Gui helper class. -* Infrastructure for delayed menu installation -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMGuiHelper.cpp + * DESCRIPTION: QT Gui helper class. + * Infrastructure for delayed menu installation + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "QTMGuiHelper.hpp" +#include "iterator.hpp" #include "qt_tm_widget.hpp" #include "qt_utilities.hpp" #include "scheme.hpp" -#include "iterator.hpp" #include void QTMGuiHelper::doUpdate () { -BEGIN_SLOT + BEGIN_SLOT // cout << "UPDATE " << texmacs_time () << LF; - gui->update(); -END_SLOT + gui->update (); + END_SLOT } void QTMGuiHelper::doRefresh () { -BEGIN_SLOT - emit refresh(); -END_SLOT + BEGIN_SLOT + emit refresh (); + END_SLOT } bool -QTMGuiHelper::eventFilter (QObject *obj, QEvent *event) { - if (event->type() == QEvent::FileOpen) { - static bool new_window_flag= false; - QFileOpenEvent* openEvent = static_cast(event); - string s= from_qstring(openEvent->file().toUtf8()); +QTMGuiHelper::eventFilter (QObject* obj, QEvent* event) { + if (event->type () == QEvent::FileOpen) { + static bool new_window_flag= false; + QFileOpenEvent* openEvent = static_cast (event); + string s= from_qstring (openEvent->file ().toUtf8 ()); if (!is_empty (s)) { - //qDebug ("File Open Event %s", s); - const char *win= new_window_flag? ":new-window": ":current-window"; - exec_delayed (scheme_cmd (list_object (symbol_object ("load-buffer"), - object (url_system (s)), eval (win)))); + // qDebug ("File Open Event %s", s); + const char* win= new_window_flag ? ":new-window" : ":current-window"; + exec_delayed (scheme_cmd (list_object ( + symbol_object ("load-buffer"), object (url_system (s)), eval (win)))); } new_window_flag= true; return true; - } else { - // standard event processing + } + else { + // standard event processing return QObject::eventFilter (obj, event); } } void -QTMGuiHelper::aboutToShowMainMenu() { -BEGIN_SLOT - //cout << "Show :" << menu_count << LF; +QTMGuiHelper::aboutToShowMainMenu () { + BEGIN_SLOT + // cout << "Show :" << menu_count << LF; menu_count++; -END_SLOT + END_SLOT } -void -QTMGuiHelper::aboutToHideMainMenu() { -BEGIN_SLOT +void +QTMGuiHelper::aboutToHideMainMenu () { + BEGIN_SLOT menu_count--; - //cout << "Hide :" << menu_count << " " << N(waiting_widgets) << LF; + // cout << "Hide :" << menu_count << " " << N(waiting_widgets) << LF; if (menu_count <= 0) { - menu_count = 0; + menu_count= 0; QTimer::singleShot (0, the_gui->gui_helper, SLOT (doPopWaitingWidgets ())); } -END_SLOT + END_SLOT } -void -QTMGuiHelper::doPopWaitingWidgets() { -BEGIN_SLOT +void +QTMGuiHelper::doPopWaitingWidgets () { + BEGIN_SLOT if (!is_nil (waiting_widgets)) { - if (DEBUG_QT) - debug_qt << "Installing postponed menu" << LF; - waiting_widgets->item->install_main_menu(); - waiting_widgets = waiting_widgets->next; + if (DEBUG_QT) debug_qt << "Installing postponed menu" << LF; + waiting_widgets->item->install_main_menu (); + waiting_widgets= waiting_widgets->next; } -END_SLOT + END_SLOT } void QTMGuiHelper::emitTmSlotRefresh (string kind) { -BEGIN_SLOT + BEGIN_SLOT emit tmSlotRefresh (kind); -END_SLOT + END_SLOT } diff --git a/src/Plugins/Qt/QTMGuiHelper.hpp b/src/Plugins/Qt/QTMGuiHelper.hpp index 013b2c022f..53347c2202 100644 --- a/src/Plugins/Qt/QTMGuiHelper.hpp +++ b/src/Plugins/Qt/QTMGuiHelper.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : QTMGuiHelper.hpp -* DESCRIPTION: QT Gui helper class. Infrastructure for delayed menu installation -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMGuiHelper.hpp + * DESCRIPTION: QT Gui helper class. Infrastructure for delayed menu + *installation COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMGUIHELPER_HPP #define QTMGUIHELPER_HPP @@ -22,24 +22,25 @@ class QTMGuiHelper : public QObject { qt_gui_rep* gui; public: - inline QTMGuiHelper (qt_gui_rep *_gui) : QObject (), gui (_gui) {} + inline QTMGuiHelper (qt_gui_rep* _gui) : QObject (), gui (_gui) {} protected: - bool eventFilter (QObject *obj, QEvent *event); - + bool eventFilter (QObject* obj, QEvent* event); + public slots: void doUpdate (); void doRefresh (); - + void aboutToShowMainMenu (); void aboutToHideMainMenu (); void doPopWaitingWidgets (); - + void emitTmSlotRefresh (string kind); signals: void refresh (); - void tmSlotRefresh (string); //!< qt_widgets which need to refresh connect here. + void tmSlotRefresh ( + string); //!< qt_widgets which need to refresh connect here. }; #endif // QTMGUIHELPER_HPP diff --git a/src/Plugins/Qt/QTMInteractiveInputHelper.hpp b/src/Plugins/Qt/QTMInteractiveInputHelper.hpp index 98917820b4..9d6aed4a25 100644 --- a/src/Plugins/Qt/QTMInteractiveInputHelper.hpp +++ b/src/Plugins/Qt/QTMInteractiveInputHelper.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : QTMInteractiveInputHelper.hpp -* DESCRIPTION: QT Interactive Input Helper class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMInteractiveInputHelper.hpp + * DESCRIPTION: QT Interactive Input Helper class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMINTERACTIVEINPUTHELPER_HPP #define QTMINTERACTIVEINPUTHELPER_HPP @@ -21,11 +21,11 @@ class QTMInteractiveInputHelper : public QObject { qt_tm_widget_rep* wid; public: - inline QTMInteractiveInputHelper (qt_tm_widget_rep* _wid): - QObject(), wid(_wid) {} + inline QTMInteractiveInputHelper (qt_tm_widget_rep* _wid) + : QObject (), wid (_wid) {} public slots: - void commit(int result); + void commit (int result); }; #endif // QTMINTERACTIVEINPUTHELPER_HPP diff --git a/src/Plugins/Qt/QTMInteractivePrompt.cpp b/src/Plugins/Qt/QTMInteractivePrompt.cpp index bfdd2a3d68..33d703e116 100644 --- a/src/Plugins/Qt/QTMInteractivePrompt.cpp +++ b/src/Plugins/Qt/QTMInteractivePrompt.cpp @@ -8,8 +8,8 @@ * in the root directory or . ******************************************************************************/ -#include "scheme.hpp" #include "gui.hpp" +#include "scheme.hpp" #include "QTMInteractivePrompt.hpp" #include "QTMStyle.hpp" @@ -18,49 +18,48 @@ #include #include -QTMInteractivePrompt::QTMInteractivePrompt(qt_widget int_prompt, - qt_widget int_input, - QWidget* parent) -: QWidget (parent), active (false) -{ - QLayoutItem* li = int_prompt->as_qlayoutitem (); - QLayoutItem* li2 = int_input->as_qlayoutitem (); - QHBoxLayout* _hl = new QHBoxLayout (); - +QTMInteractivePrompt::QTMInteractivePrompt (qt_widget int_prompt, + qt_widget int_input, + QWidget* parent) + : QWidget (parent), active (false) { + QLayoutItem* li = int_prompt->as_qlayoutitem (); + QLayoutItem* li2= int_input->as_qlayoutitem (); + QHBoxLayout* _hl= new QHBoxLayout (); + setStyle (qtmstyle ()); setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed); - - if (QLabel *_la = qobject_cast (li->widget ())) + + if (QLabel* _la= qobject_cast (li->widget ())) _la->setBuddy (li2->widget ()); - if (QWidget *w = qobject_cast (li2->widget ())) - w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + if (QWidget* w= qobject_cast (li2->widget ())) + w->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed); _hl->addSpacing (6); _hl->addItem (li); _hl->addSpacing (6); _hl->addItem (li2); - _hl->setContentsMargins (3,0,0,0); + _hl->setContentsMargins (3, 0, 0, 0); setLayout (_hl); if (tm_style_sheet == "" && use_mini_bars) { QFont f = font (); - int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); + int fs= as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); f.setPointSize (qt_zoom (fs > 0 ? fs : QTM_MINI_FONTSIZE)); - li->widget()->setFont (f); - li2->widget()->setFont (f); + li->widget ()->setFont (f); + li2->widget ()->setFont (f); } } - -void QTMInteractivePrompt::start() { - QWidget *_le = findChild(); +void +QTMInteractivePrompt::start () { + QWidget* _le= findChild (); if (_le) { - active = true; + active= true; _le->show (); - _le->setFocus (Qt::OtherFocusReason); + _le->setFocus (Qt::OtherFocusReason); } } -void QTMInteractivePrompt::end() { - active = false; +void +QTMInteractivePrompt::end () { + active= false; } - diff --git a/src/Plugins/Qt/QTMInteractivePrompt.hpp b/src/Plugins/Qt/QTMInteractivePrompt.hpp index dd28463b68..2f59cbbd59 100644 --- a/src/Plugins/Qt/QTMInteractivePrompt.hpp +++ b/src/Plugins/Qt/QTMInteractivePrompt.hpp @@ -15,19 +15,17 @@ class qt_widget; -class QTMInteractivePrompt : public QWidget -{ +class QTMInteractivePrompt : public QWidget { Q_OBJECT bool active; - + public: - QTMInteractivePrompt (qt_widget, qt_widget, QWidget* p=0); - + QTMInteractivePrompt (qt_widget, qt_widget, QWidget* p= 0); + void start (); void end (); bool isActive () { return active; } }; #endif // QTMINTERACTIVEPROMPT_HPP - diff --git a/src/Plugins/Qt/QTMMenuHelper.cpp b/src/Plugins/Qt/QTMMenuHelper.cpp index 9786afdc2c..309c52a794 100644 --- a/src/Plugins/Qt/QTMMenuHelper.cpp +++ b/src/Plugins/Qt/QTMMenuHelper.cpp @@ -1,42 +1,42 @@ /****************************************************************************** -* MODULE : QTMMenuHelper.cpp -* DESCRIPTION: QT Texmacs menu helper classes -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMMenuHelper.cpp + * DESCRIPTION: QT Texmacs menu helper classes + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "analyze.hpp" -#include "preferences.hpp" #include "object_l5.hpp" +#include "preferences.hpp" -#include "qt_gui.hpp" -#include "qt_utilities.hpp" -#include "qt_window_widget.hpp" -#include "qt_ui_element.hpp" // qt_choice_command_rep -#include "qt_picture.hpp" // xpm_image -#include "qt_tm_widget.hpp" // tweak_iconbar_size -#include "QTMMenuHelper.hpp" #include "QTMGuiHelper.hpp" +#include "QTMMenuHelper.hpp" #include "QTMStyle.hpp" #include "QTMTreeModel.hpp" +#include "qt_gui.hpp" +#include "qt_picture.hpp" // xpm_image +#include "qt_tm_widget.hpp" // tweak_iconbar_size +#include "qt_ui_element.hpp" // qt_choice_command_rep +#include "qt_utilities.hpp" +#include "qt_window_widget.hpp" -#include +#include #include #include -#include +#include /****************************************************************************** * QTMCommand ******************************************************************************/ /*! Queues the object's command into the main queue. */ -void -QTMCommand::apply() { -BEGIN_SLOT +void +QTMCommand::apply () { + BEGIN_SLOT if (!is_nil (cmd)) { the_gui->process_command (cmd); if (DEBUG_QT) { @@ -47,22 +47,21 @@ BEGIN_SLOT */ } } -END_SLOT + END_SLOT } /****************************************************************************** * QTMAction ******************************************************************************/ -QTMAction::QTMAction (QObject *parent) : QAction (parent) { - QObject::connect (the_gui->gui_helper, SIGNAL (refresh()), - this, SLOT (doRefresh())); - _timer = new QTimer (this); - QObject::connect (_timer, SIGNAL (timeout()), - this, SLOT (doShowToolTip())); +QTMAction::QTMAction (QObject* parent) : QAction (parent) { + QObject::connect (the_gui->gui_helper, SIGNAL (refresh ()), this, + SLOT (doRefresh ())); + _timer= new QTimer (this); + QObject::connect (_timer, SIGNAL (timeout ()), this, SLOT (doShowToolTip ())); if (tm_style_sheet == "" && !use_mini_bars) { int sz= 14; - //int sz= (int) floor (14 * retina_scale + 0.5); + // int sz= (int) floor (14 * retina_scale + 0.5); #ifdef Q_OS_MAC QFont fn ("Lucida Grande", sz); #else @@ -73,36 +72,35 @@ QTMAction::QTMAction (QObject *parent) : QAction (parent) { } } -QTMAction::~QTMAction() { - if (menu() && !menu()->parent()) delete menu(); +QTMAction::~QTMAction () { + if (menu () && !menu ()->parent ()) delete menu (); } void QTMAction::set_text (string s) { - if (N(s)) { - // FIXME: this will only work if the system language is English! - if (s == "Help" || s == "Edit" || s == "View" || - s == "Preferences...") - s = s * " "; - s= replace (s, "&", "&&"); - str = s; + if (N (s)) { + // FIXME: this will only work if the system language is English! + if (s == "Help" || s == "Edit" || s == "View" || s == "Preferences...") + s= s * " "; + s = replace (s, "&", "&&"); + str= s; setText (to_qstring (s)); } } -void -QTMAction::doRefresh() { -BEGIN_SLOT +void +QTMAction::doRefresh () { + BEGIN_SLOT set_text (str); -END_SLOT + END_SLOT } void -QTMAction::showToolTip() { -BEGIN_SLOT - _timer->start (500); // Restarts the timer if already running - _pos = QCursor::pos(); -END_SLOT +QTMAction::showToolTip () { + BEGIN_SLOT + _timer->start (500); // Restarts the timer if already running + _pos= QCursor::pos (); + END_SLOT } /* @@ -112,99 +110,94 @@ END_SLOT cursor is this particular one, so in order to avoid displaying outdated toolTips (because the user moved fast over items) we compute distances. This is obviously wrong, and will behave weirdly under certain resolutions, - for given menu item sizes, etc. Also, one typically moves for a while + for given menu item sizes, etc. Also, one typically moves for a while horizontally over the first item in an extensible menu, so once the user stops, the distance is bigger than the given constant and no tooltip is displayed. */ void -QTMAction::doShowToolTip() { -BEGIN_SLOT - static int step = QApplication::font().pointSize(); - _timer->stop(); - if ((QCursor::pos() - _pos).manhattanLength() < step) // Hideous HACK - QToolTip::showText (QCursor::pos(), toolTip()); - else - QToolTip::hideText(); -END_SLOT +QTMAction::doShowToolTip () { + BEGIN_SLOT + static int step= QApplication::font ().pointSize (); + _timer->stop (); + if ((QCursor::pos () - _pos).manhattanLength () < step) // Hideous HACK + QToolTip::showText (QCursor::pos (), toolTip ()); + else QToolTip::hideText (); + END_SLOT } /****************************************************************************** * QTMWidgetAction ******************************************************************************/ - -QTMWidgetAction::QTMWidgetAction (widget _wid, QObject *parent) -: QWidgetAction (parent), wid (_wid) { - QObject::connect (the_gui->gui_helper, SIGNAL (refresh()), - this, SLOT (doRefresh())); +QTMWidgetAction::QTMWidgetAction (widget _wid, QObject* parent) + : QWidgetAction (parent), wid (_wid) { + QObject::connect (the_gui->gui_helper, SIGNAL (refresh ()), this, + SLOT (doRefresh ())); } -QWidget * -QTMWidgetAction::createWidget (QWidget * parent) { - QWidget* qw = concrete (wid)->as_qwidget(); +QWidget* +QTMWidgetAction::createWidget (QWidget* parent) { + QWidget* qw= concrete (wid)->as_qwidget (); qw->setParent (parent); return qw; } - /****************************************************************************** * QTMTileAction ******************************************************************************/ QTMTileAction::QTMTileAction (array& arr, int _cols, QObject* parent) -: QWidgetAction (parent), cols (_cols) { + : QWidgetAction (parent), cols (_cols) { actions.reserve (N (arr)); - for (int i = 0; i < N (arr); i++) { + for (int i= 0; i < N (arr); i++) { if (is_nil (arr[i])) break; - QAction* act = concrete (arr[i])->as_qaction(); + QAction* act= concrete (arr[i])->as_qaction (); act->setParent (this); actions.append (act); }; } QWidget* -QTMTileAction::createWidget (QWidget* parent) -{ - if (DEBUG_QT_WIDGETS) - debug_widgets << "QTMTileAction::createWidget\n"; - QWidget* wid= new QTMMenuWidget (parent); - QGridLayout* l= new QGridLayout (wid); - // wid->setAutoFillBackground (true); - // wid->setBackgroundRole (QPalette::Base); +QTMTileAction::createWidget (QWidget* parent) { + if (DEBUG_QT_WIDGETS) debug_widgets << "QTMTileAction::createWidget\n"; + QWidget* wid= new QTMMenuWidget (parent); + QGridLayout* l = new QGridLayout (wid); + // wid->setAutoFillBackground (true); + // wid->setBackgroundRole (QPalette::Base); wid->setLayout (l); l->setSizeConstraint (QLayout::SetFixedSize); l->setHorizontalSpacing (2); l->setVerticalSpacing (2); l->setContentsMargins (4, 0, 4, 0); - int row = 0, col = 0; - for (int i = 0; i < actions.count(); i++) { - QAction* sa = actions[i]; + int row= 0, col= 0; + for (int i= 0; i < actions.count (); i++) { + QAction* sa= actions[i]; QToolButton* tb= new QTMMenuButton (wid); tb->setDefaultAction (sa); - QObject::connect (tb, SIGNAL (released()), this, SLOT (trigger())); - if (tm_style_sheet == "") - tb->setStyle (qtmstyle ()); + QObject::connect (tb, SIGNAL (released ()), this, SLOT (trigger ())); + if (tm_style_sheet == "") tb->setStyle (qtmstyle ()); l->addWidget (tb, row, col); col++; - if (col >= cols) { col = 0; row++; } + if (col >= cols) { + col= 0; + row++; + } } return wid; } - /****************************************************************************** * QTMMinibarAction ******************************************************************************/ QTMMinibarAction::QTMMinibarAction (array& arr, QObject* parent) -: QWidgetAction (parent) -{ + : QWidgetAction (parent) { actions.reserve (N (arr)); - for (int i = 0; i < N (arr); i++) { + for (int i= 0; i < N (arr); i++) { if (is_nil (arr[i])) break; - QAction* act = concrete (arr[i])->as_qaction(); + QAction* act= concrete (arr[i])->as_qaction (); act->setParent (this); actions.append (act); }; @@ -212,43 +205,46 @@ QTMMinibarAction::QTMMinibarAction (array& arr, QObject* parent) QWidget* QTMMinibarAction::createWidget (QWidget* parent) { - static QImage* pxm = xpm_image ("tm_add.xpm"); // See qt_tm_widget.cpp - QSize sz = pxm ? pxm->size() : QSize (16, 16); + static QImage* pxm= xpm_image ("tm_add.xpm"); // See qt_tm_widget.cpp + QSize sz = pxm ? pxm->size () : QSize (16, 16); qt_tm_widget_rep::tweak_iconbar_size (sz); - + if (DEBUG_QT_WIDGETS) debug_widgets << "QTMMinibarAction::createWidget\n"; - QWidget* wid= new QWidget (parent); - QBoxLayout* l= new QBoxLayout (QBoxLayout::LeftToRight, wid); + QWidget* wid= new QWidget (parent); + QBoxLayout* l = new QBoxLayout (QBoxLayout::LeftToRight, wid); wid->setLayout (l); - // l->setSizeConstraint (QLayout::SetFixedSize); + // l->setSizeConstraint (QLayout::SetFixedSize); l->setContentsMargins (0, 0, 0, 0); l->setSpacing (0); - for (int i=0; i < actions.count(); i++) { + for (int i= 0; i < actions.count (); i++) { QAction* sa= actions[i]; - if (QWidgetAction * wa = qobject_cast (sa)) { - QWidget *w = wa->requestWidget (wid); - l->addWidget(w); - } else if (sa->text().isNull() && sa->icon().isNull()) { - l->addSpacing(8); - } else { - QToolButton *tb = new QToolButton (wid); - - //HACK: texmacs does not use the checked state of the action - // if the action is checkable then it means that it should be checked - sa->setChecked (sa->isCheckable()); - + if (QWidgetAction* wa= qobject_cast (sa)) { + QWidget* w= wa->requestWidget (wid); + l->addWidget (w); + } + else if (sa->text ().isNull () && sa->icon ().isNull ()) { + l->addSpacing (8); + } + else { + QToolButton* tb= new QToolButton (wid); + + // HACK: texmacs does not use the checked state of the action + // if the action is checkable then it means that it should be checked + sa->setChecked (sa->isCheckable ()); + tb->setDefaultAction (sa); tb->setAutoRaise (true); tb->setPopupMode (QToolButton::InstantPopup); if (tm_style_sheet == "") { - tb->setStyle (qtmstyle()); + tb->setStyle (qtmstyle ()); tb->setIconSize (sz); } if (use_mini_bars) { - QFont f = tb->font(); - int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); + QFont f= tb->font (); + int fs= + as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); f.setPointSize (qt_zoom (fs > 0 ? fs : QTM_MINI_FONTSIZE)); - tb->setFont(f); + tb->setFont (f); } l->addWidget (tb); } @@ -266,57 +262,56 @@ QTMMenuButton::QTMMenuButton (QWidget* parent) : QToolButton (parent) { void QTMMenuButton::mousePressEvent (QMouseEvent* e) { - // this one triggers the action and toggles the button + // this one triggers the action and toggles the button QToolButton::mousePressEvent (e); - // this one forwards the event to the parent - // (which eventually is the menu) + // this one forwards the event to the parent + // (which eventually is the menu) QWidget::mousePressEvent (e); } void QTMMenuButton::mouseReleaseEvent (QMouseEvent* e) { - // this one triggers the action and untoggles the button + // this one triggers the action and untoggles the button QToolButton::mouseReleaseEvent (e); - // this one forwards the event to the parent - // (which eventually is the menu which then closes itself) + // this one forwards the event to the parent + // (which eventually is the menu which then closes itself) QWidget::mouseReleaseEvent (e); } void QTMMenuButton::paintEvent (QPaintEvent* e) { (void) e; - - // initialize the options + + // initialize the options QStyleOptionToolButton opt; initStyleOption (&opt); - QPainter p (this); + QPainter p (this); QStyleOptionToolButton option; - QRect r = rect(); - option.rect = r; - option.state = QStyle::State_Enabled | (opt.state & QStyle::State_MouseOver - ? QStyle::State_Selected - : QStyle::State_None); - // draw the control background as a menu item - style()->drawControl (QStyle::CE_MenuItem, &option, &p, this); - // draw the icon with a bit of inset. + QRect r= rect (); + option.rect = r; + option.state = QStyle::State_Enabled | + (opt.state & QStyle::State_MouseOver ? QStyle::State_Selected + : QStyle::State_None); + // draw the control background as a menu item + style ()->drawControl (QStyle::CE_MenuItem, &option, &p, this); + // draw the icon with a bit of inset. r.adjust (2, 2, -2, -2); - defaultAction()->icon().paint (&p, r); + defaultAction ()->icon ().paint (&p, r); } /****************************************************************************** * QTMMenuWidget ******************************************************************************/ -QTMMenuWidget::QTMMenuWidget (QWidget* parent) : QWidget (parent) { -} +QTMMenuWidget::QTMMenuWidget (QWidget* parent) : QWidget (parent) {} void -QTMMenuWidget::paintEvent(QPaintEvent* e) { - QPainter p (this); +QTMMenuWidget::paintEvent (QPaintEvent* e) { + QPainter p (this); QStyleOptionMenuItem option; - option.rect = rect(); - style()->drawControl (QStyle::CE_MenuEmptyArea, &option, &p, this); + option.rect= rect (); + style ()->drawControl (QStyle::CE_MenuEmptyArea, &option, &p, this); QWidget::paintEvent (e); } @@ -325,17 +320,16 @@ QTMMenuWidget::paintEvent(QPaintEvent* e) { ******************************************************************************/ QTMLazyMenu::QTMLazyMenu (promise _pm, QWidget* p, bool right) -: QMenu (p), promise_widget (_pm), show_right (right) { + : QMenu (p), promise_widget (_pm), show_right (right) { QObject::connect (this, SIGNAL (aboutToShow ()), this, SLOT (force ())); } void -QTMLazyMenu::showEvent (QShowEvent* e) -{ - if (show_right && parentWidget()) { - QPoint p = pos(); - p.rx() += parentWidget()->width(); - p.ry() -= parentWidget()->height(); +QTMLazyMenu::showEvent (QShowEvent* e) { + if (show_right && parentWidget ()) { + QPoint p= pos (); + p.rx ()+= parentWidget ()->width (); + p.ry ()-= parentWidget ()->height (); move (p); } QMenu::showEvent (e); @@ -345,71 +339,71 @@ QTMLazyMenu::showEvent (QShowEvent* e) depend on that of the latter. */ void QTMLazyMenu::attachTo (QAction* a) { - QObject::connect (a, SIGNAL (destroyed (QObject*)), - this, SLOT (destroy (QObject*))); + QObject::connect (a, SIGNAL (destroyed (QObject*)), this, + SLOT (destroy (QObject*))); a->setMenu (this); } void QTMLazyMenu::transferActions (QList* from) { if (from == NULL) return; - QList list = actions(); - while (!list.isEmpty()) { - QAction* a = list.takeFirst(); + QList list= actions (); + while (!list.isEmpty ()) { + QAction* a= list.takeFirst (); removeAction (a); } - while (!from->isEmpty()) { - QAction* a = from->takeFirst(); + while (!from->isEmpty ()) { + QAction* a= from->takeFirst (); addAction (a); } } void QTMLazyMenu::force () { -BEGIN_SLOT - QList* list = concrete (promise_widget())->get_qactionlist(); + BEGIN_SLOT + QList* list= concrete (promise_widget ())->get_qactionlist (); transferActions (list); -END_SLOT + END_SLOT } void QTMLazyMenu::destroy (QObject* obj) { -BEGIN_SLOT - (void) obj; - deleteLater(); -END_SLOT + BEGIN_SLOT (void) obj; + deleteLater (); + END_SLOT } /****************************************************************************** * QTMInputTextWidgetHelper ******************************************************************************/ -QTMInputTextWidgetHelper::QTMInputTextWidgetHelper (qt_widget _wid, bool _cac): QObject (), p_wid (_wid), can_autocommit (_cac) { - QTMLineEdit* le = qobject_cast(wid()->qwid); - setParent(le); +QTMInputTextWidgetHelper::QTMInputTextWidgetHelper (qt_widget _wid, bool _cac) + : QObject (), p_wid (_wid), can_autocommit (_cac) { + QTMLineEdit* le= qobject_cast (wid ()->qwid); + setParent (le); ASSERT (le != NULL, "QTMInputTextWidgetHelper: expecting valid QTMLineEdit"); QObject::connect (le, SIGNAL (returnPressed ()), this, SLOT (commit ())); - QObject::connect (le, SIGNAL (focusOut (Qt::FocusReason)), - this, SLOT (leave (Qt::FocusReason))); + QObject::connect (le, SIGNAL (focusOut (Qt::FocusReason)), this, + SLOT (leave (Qt::FocusReason))); } /*! Executed when the enter key is pressed. */ void QTMInputTextWidgetHelper::commit () { -BEGIN_SLOT - if (sender() != wid()->qwid) return; - wid()->commit(true); -END_SLOT + BEGIN_SLOT + if (sender () != wid ()->qwid) return; + wid ()->commit (true); + END_SLOT } /*! Executed after commit of the input field (enter) and when losing focus */ void QTMInputTextWidgetHelper::leave (Qt::FocusReason reason) { -BEGIN_SLOT - if (sender() != wid()->qwid) return; - wid()->commit((reason != Qt::OtherFocusReason && can_autocommit && - get_preference ("gui:line-input:autocommit") == "on")); -END_SLOT + BEGIN_SLOT + if (sender () != wid ()->qwid) return; + wid ()->commit ((reason != Qt::OtherFocusReason && can_autocommit && + get_preference ("gui:line-input:autocommit") == "on")); + END_SLOT } /****************************************************************************** @@ -417,50 +411,49 @@ END_SLOT ******************************************************************************/ QTMFieldWidgetHelper::QTMFieldWidgetHelper (qt_widget _wid, QComboBox* cb) -: QObject (cb), wid (_wid), done (false) { + : QObject (cb), wid (_wid), done (false) { ASSERT (cb != NULL, "QTMFieldWidgetHelper: expecting valid QComboBox"); - QObject::connect (cb, SIGNAL (editTextChanged (const QString&)), - this, SLOT (commit (const QString&))); + QObject::connect (cb, SIGNAL (editTextChanged (const QString&)), this, + SLOT (commit (const QString&))); } QTMFieldWidgetHelper::QTMFieldWidgetHelper (qt_widget _wid, QLineEdit* cb) -: QObject (cb), wid (_wid), done (false) { + : QObject (cb), wid (_wid), done (false) { ASSERT (cb != NULL, "QTMFieldWidgetHelper: expecting valid QLineEdit"); - QObject::connect (cb, SIGNAL (textChanged (const QString&)), - this, SLOT (commit (const QString&))); + QObject::connect (cb, SIGNAL (textChanged (const QString&)), this, + SLOT (commit (const QString&))); } void QTMFieldWidgetHelper::commit (const QString& qst) { -BEGIN_SLOT - static_cast (wid.rep)->input = + BEGIN_SLOT + static_cast (wid.rep)->input= scm_quote (from_qstring (qst)); -END_SLOT + END_SLOT } /****************************************************************************** * QTMLineEdit ******************************************************************************/ -QTMLineEdit::QTMLineEdit (QWidget* parent, string _type, string _ww, - int style, command _cmd) - : QLineEdit (parent), completing (false), - type ("default"), name ("default"), serial ("default"), - ww (_ww), cmd (_cmd), last_key (0) { +QTMLineEdit::QTMLineEdit (QWidget* parent, string _type, string _ww, int style, + command _cmd) + : QLineEdit (parent), completing (false), type ("default"), + name ("default"), serial ("default"), ww (_ww), cmd (_cmd), last_key (0) { set_type (_type); - if (type == "password") setEchoMode(QLineEdit::Password); + if (type == "password") setEchoMode (QLineEdit::Password); if (style & WIDGET_STYLE_MINI) { if (tm_style_sheet == "") { - setStyle (qtmstyle()); + setStyle (qtmstyle ()); // FIXME: we should remove this and let the scheme code decide. #ifdef OS_MACOS - QPalette pal (palette()); + QPalette pal (palette ()); pal.setColor (QPalette::Base, QColor (252, 252, 248)); pal.setColor (QPalette::WindowText, Qt::black); setPalette (pal); #endif } } - + // just to be sure we don't capture the wrong keys in keyPressEvent setCompleter (0); @@ -475,11 +468,11 @@ void QTMLineEdit::set_type (string t) { int i= search_forwards (":", 0, t); if (i >= 0) { - type= t (i+1, N(t)); - name= t (0, i); + type = t (i + 1, N (t)); + name = t (0, i); int j= search_forwards ("#", 0, name); if (j >= 0) { - serial= name (j+1, N(name)); + serial= name (j + 1, N (name)); name = name (0, j); } } @@ -488,11 +481,8 @@ QTMLineEdit::set_type (string t) { bool QTMLineEdit::continuous () { - return - starts (type, "search") || - starts (type, "replace-") || - starts (type, "spell") || - starts (serial, "form-"); + return starts (type, "search") || starts (type, "replace-") || + starts (type, "spell") || starts (serial, "form-"); } /* @@ -501,221 +491,224 @@ QTMLineEdit::continuous () { */ bool QTMLineEdit::event (QEvent* ev) { - if (ev->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent= static_cast (ev); + if (ev->type () == QEvent::KeyPress) { + QKeyEvent* keyEvent= static_cast (ev); keyPressEvent (keyEvent); return true; } return QLineEdit::event (ev); } -extern hashmap qtkeymap; -void initkeymap (); +extern hashmap qtkeymap; +void initkeymap (); /* FIXME: This is a hideous mess... */ void -QTMLineEdit::keyPressEvent (QKeyEvent* ev) -{ - QCompleter* c = completer(); - - last_key = (ev->key() == Qt::Key_Tab && ev->modifiers() & Qt::ShiftModifier) - ? Qt::Key_Backtab - : ev->key(); +QTMLineEdit::keyPressEvent (QKeyEvent* ev) { + QCompleter* c= completer (); + + last_key= (ev->key () == Qt::Key_Tab && ev->modifiers () & Qt::ShiftModifier) + ? Qt::Key_Backtab + : ev->key (); if (continuous ()) { initkeymap (); if ((last_key != Qt::Key_Tab || type == "replace-what") && (last_key != Qt::Key_Backtab || type == "replace-by") && - last_key != Qt::Key_Down && - last_key != Qt::Key_Up && - last_key != Qt::Key_Enter && - last_key != Qt::Key_Return && + last_key != Qt::Key_Down && last_key != Qt::Key_Up && + last_key != Qt::Key_Enter && last_key != Qt::Key_Return && last_key != Qt::Key_Escape && (!starts (type, "spell") || last_key < 49 || last_key >= 58) && (!starts (type, "spell") || last_key != 43) && - (ev->modifiers() & Qt::ControlModifier) == 0 && - (ev->modifiers() & Qt::MetaModifier) == 0) + (ev->modifiers () & Qt::ControlModifier) == 0 && + (ev->modifiers () & Qt::MetaModifier) == 0) QLineEdit::keyPressEvent (ev); string key= "none"; - string s = from_qstring (text()); + string s = from_qstring (text ()); if (last_key >= 32 && last_key <= 126) { key= string ((char) last_key); if (is_upcase (key[0])) - if ((ev->modifiers() & Qt::ShiftModifier) == 0) + if ((ev->modifiers () & Qt::ShiftModifier) == 0) key[0]= (int) (key[0] + ((int) 'a') - ((int) 'A')); } if (qtkeymap->contains (last_key)) key= qtkeymap[last_key]; - if ((ev->modifiers() & Qt::ShiftModifier) && N(key) > 1) key= "S-" * key; + if ((ev->modifiers () & Qt::ShiftModifier) && N (key) > 1) key= "S-" * key; #ifdef Q_OS_MAC - if (ev->modifiers() & Qt::ControlModifier) key= "C-" * key; - if (ev->modifiers() & Qt::AltModifier) key= "none"; - if (ev->modifiers() & Qt::MetaModifier) key= "M-" * key; + if (ev->modifiers () & Qt::ControlModifier) key= "C-" * key; + if (ev->modifiers () & Qt::AltModifier) key= "none"; + if (ev->modifiers () & Qt::MetaModifier) key= "M-" * key; #else - if (ev->modifiers() & Qt::ControlModifier) key= "M-" * key; - if (ev->modifiers() & Qt::AltModifier) key= "A-" * key; - if (ev->modifiers() & Qt::MetaModifier) key= "C-" * key; + if (ev->modifiers () & Qt::ControlModifier) key= "M-" * key; + if (ev->modifiers () & Qt::AltModifier) key= "A-" * key; + if (ev->modifiers () & Qt::MetaModifier) key= "C-" * key; #endif cmd (list_object (list_object (object (s), object (key)))); return; } else if (c) { - int row = 0; + int row= 0; switch (last_key) { - case Qt::Key_Down: - completing = true; - setCursorPosition (0); - c->complete(); - case Qt::Key_Tab: - { -// cout << "Completing= " << completing << LF; -// cout << "hasSelectedText= " << hasSelectedText() << LF; -// cout << "CursorPosition= " << cursorPosition() << LF; -// cout << "SelectionStart= " << selectionStart() << LF; - - if (completing) { -// cout << "CompletionCount= " << c->completionCount() << LF; - if (c->completionCount() > 1) { - if (! c->setCurrentRow (c->currentRow() + 1)) - c->setCurrentRow (0); // cycle - } else { - completing = false; - setCursorPosition (text().length()); - c->setCompletionPrefix (""); - //c->popup()->hide(); + case Qt::Key_Down: + completing= true; + setCursorPosition (0); + c->complete (); + case Qt::Key_Tab: { + // cout << "Completing= " << completing << LF; + // cout << "hasSelectedText= " << hasSelectedText() << LF; + // cout << "CursorPosition= " << cursorPosition() << LF; + // cout << "SelectionStart= " << selectionStart() << LF; + + if (completing) { + // cout << "CompletionCount= " << c->completionCount() << LF; + if (c->completionCount () > 1) { + if (!c->setCurrentRow (c->currentRow () + 1)) + c->setCurrentRow (0); // cycle + } + else { + completing= false; + setCursorPosition (text ().length ()); + c->setCompletionPrefix (""); + // c->popup()->hide(); + } + if (hasSelectedText ()) setCursorPosition (selectionStart ()); + if (c->currentCompletion () != "") { + int pos= cursorPosition (); + setText (c->currentCompletion ()); + setSelection (pos, text ().length ()); + } + else { + completing= false; + setSelection (0, text ().length ()); + c->setCompletionPrefix (""); + } + } + else { + QString prefix; + if (hasSelectedText ()) prefix= text ().left (selectionStart ()); + else prefix= text ().left (cursorPosition ()); + c->setCompletionPrefix (prefix); + // cout << "prefix= " << from_qstring (prefix) << LF; + // cout << "CompletionCount= " << c->completionCount() << LF; + + // If there are no completions, go to the end of the line or + // send the key up for tab navigation + if (c->completionCount () == 0 || + (c->completionCount () == 1 && + c->currentCompletion () == text ())) { + if (c->popup () && c->popup ()->isVisible ()) { + setCursorPosition (text ().length ()); + c->popup ()->hide (); } - if (hasSelectedText()) - setCursorPosition (selectionStart()); - if (c->currentCompletion() != "") { - int pos = cursorPosition(); - setText (c->currentCompletion ()); - setSelection (pos, text().length()); - } else { - completing = false; - setSelection (0, text(). length()); - c->setCompletionPrefix (""); + else if (cursorPosition () == text ().length ()) { + QLineEdit::keyPressEvent (ev); } - } else { - QString prefix; - if (hasSelectedText()) - prefix = text().left (selectionStart()); - else - prefix = text().left (cursorPosition()); - c->setCompletionPrefix (prefix); -// cout << "prefix= " << from_qstring (prefix) << LF; -// cout << "CompletionCount= " << c->completionCount() << LF; - - // If there are no completions, go to the end of the line or - // send the key up for tab navigation - if (c->completionCount() == 0 || - (c->completionCount() == 1 && c->currentCompletion() == text())) { - if (c->popup() && c->popup()->isVisible()) { - setCursorPosition (text().length()); - c->popup()->hide(); - } else if (cursorPosition() == text().length()) { - QLineEdit::keyPressEvent (ev); - } else { - setCursorPosition (text().length()); - } - return; + else { + setCursorPosition (text ().length ()); } + return; + } - completing = true; - // hack: advance one completion (needed after tab navigation) - if (c->currentCompletion() == text()) { - clear(); - if (! c->setCurrentRow (c->currentRow() + 1)) - c->setCurrentRow (0); // cycle - } - c->complete(); + completing= true; + // hack: advance one completion (needed after tab navigation) + if (c->currentCompletion () == text ()) { + clear (); + if (!c->setCurrentRow (c->currentRow () + 1)) + c->setCurrentRow (0); // cycle } - ev->accept(); + c->complete (); } - return; - // This is different on purpose: when "back-completing" suggested text - // we want to display the previous entry to the one suggested - case Qt::Key_Up: - completing = true; - setCursorPosition (0); - c->complete(); - case Qt::Key_Backtab: - { - if (!completing) { - if (hasSelectedText()) - c->setCompletionPrefix (text().left (selectionStart())); - else - c->setCompletionPrefix (text().left (cursorPosition())); - // If there are no completions, go to the end of the line or - // send the key up for tab navigation - if (c->completionCount() == 0 || - (c->completionCount() == 1 && c->currentCompletion() == text())) { - if (c->popup() && c->popup()->isVisible()) { - setCursorPosition (text().length()); - c->popup()->hide(); - } else if (cursorPosition() == text().length()) { - QLineEdit::keyPressEvent (ev); - } else { - setCursorPosition (text().length()); - } - return; + ev->accept (); + } + return; + // This is different on purpose: when "back-completing" suggested text + // we want to display the previous entry to the one suggested + case Qt::Key_Up: + completing= true; + setCursorPosition (0); + c->complete (); + case Qt::Key_Backtab: { + if (!completing) { + if (hasSelectedText ()) + c->setCompletionPrefix (text ().left (selectionStart ())); + else c->setCompletionPrefix (text ().left (cursorPosition ())); + // If there are no completions, go to the end of the line or + // send the key up for tab navigation + if (c->completionCount () == 0 || + (c->completionCount () == 1 && + c->currentCompletion () == text ())) { + if (c->popup () && c->popup ()->isVisible ()) { + setCursorPosition (text ().length ()); + c->popup ()->hide (); } - completing = true; - c->complete(); - } else { - row = c->currentRow(); - if (! c->setCurrentRow (row - 1)) - c->setCurrentRow (c->completionCount() - 1); // cycle - if (c->currentCompletion() != "") { - int pos; - if (hasSelectedText()) - pos = selectionStart(); - else - pos = cursorPosition(); - setText (c->currentCompletion ()); - setSelection (pos, text().length()); + else if (cursorPosition () == text ().length ()) { + QLineEdit::keyPressEvent (ev); + } + else { + setCursorPosition (text ().length ()); } - } - ev->accept(); - } - return; - case Qt::Key_Enter: - case Qt::Key_Return: - if (c->popup() && c->popup()->isVisible()) { - setCursorPosition (text().length()); - c->popup()->hide(); - } else if (completing) { - completing = false; - setText (c->currentCompletion()); - setCursorPosition (text().length()); - c->setCompletionPrefix (""); - } else { - completing = false; - c->setCompletionPrefix (""); - QLineEdit::keyPressEvent (ev); return; } - ev->accept(); - return; - case Qt::Key_Escape: - if (completing && c->completionMode() == QCompleter::PopupCompletion) { - if (c->popup()) c->popup()->hide(); - completing = false; - } else { - emit editingFinished(); - ev->accept(); - if (parentWidget()) // HACK to return focus to the main editor widget - parentWidget()->setFocus (); + completing= true; + c->complete (); + } + else { + row= c->currentRow (); + if (!c->setCurrentRow (row - 1)) + c->setCurrentRow (c->completionCount () - 1); // cycle + if (c->currentCompletion () != "") { + int pos; + if (hasSelectedText ()) pos= selectionStart (); + else pos= cursorPosition (); + setText (c->currentCompletion ()); + setSelection (pos, text ().length ()); } + } + ev->accept (); + } + return; + case Qt::Key_Enter: + case Qt::Key_Return: + if (c->popup () && c->popup ()->isVisible ()) { + setCursorPosition (text ().length ()); + c->popup ()->hide (); + } + else if (completing) { + completing= false; + setText (c->currentCompletion ()); + setCursorPosition (text ().length ()); c->setCompletionPrefix (""); - return; - default: - completing = false; + } + else { + completing= false; c->setCompletionPrefix (""); QLineEdit::keyPressEvent (ev); return; + } + ev->accept (); + return; + case Qt::Key_Escape: + if (completing && c->completionMode () == QCompleter::PopupCompletion) { + if (c->popup ()) c->popup ()->hide (); + completing= false; + } + else { + emit editingFinished (); + ev->accept (); + if (parentWidget ()) // HACK to return focus to the main editor widget + parentWidget ()->setFocus (); + } + c->setCompletionPrefix (""); + return; + default: + completing= false; + c->setCompletionPrefix (""); + QLineEdit::keyPressEvent (ev); + return; } - } else { + } + else { QLineEdit::keyPressEvent (ev); } } @@ -724,120 +717,117 @@ void QTMLineEdit::inputMethodEvent (QInputMethodEvent* ev) { QLineEdit::inputMethodEvent (ev); - if (!ev->commitString().isEmpty() && - ev->preeditString().isEmpty() && - continuous()) { - string str= from_qstring(ev->commitString()); + if (!ev->commitString ().isEmpty () && ev->preeditString ().isEmpty () && + continuous ()) { + string str= from_qstring (ev->commitString ()); cmd (list_object (list_object (object (str), object (str)))); } } QSize QTMLineEdit::sizeHint () const { - return qt_decode_length (ww, "", QLineEdit::sizeHint(), fontMetrics()); + return qt_decode_length (ww, "", QLineEdit::sizeHint (), fontMetrics ()); } -void -QTMLineEdit::focusInEvent (QFocusEvent* ev) -{ - setCursorPosition (text().size()); - // selectAll (); +void +QTMLineEdit::focusInEvent (QFocusEvent* ev) { + setCursorPosition (text ().size ()); + // selectAll (); QLineEdit::focusInEvent (ev); } void -QTMLineEdit::focusOutEvent (QFocusEvent* ev) -{ +QTMLineEdit::focusOutEvent (QFocusEvent* ev) { if (!continuous ()) { - Qt::FocusReason reason = - (last_key != Qt::Key_Escape) ? ev->reason() : Qt::OtherFocusReason; + Qt::FocusReason reason= + (last_key != Qt::Key_Escape) ? ev->reason () : Qt::OtherFocusReason; emit focusOut (reason); } QLineEdit::focusOutEvent (ev); } - /****************************************************************************** * QTMTabWidget ******************************************************************************/ -QTMTabWidget::QTMTabWidget (QWidget *p) : QTabWidget(p) { - QObject::connect (this, SIGNAL (currentChanged (int)), this, SLOT (resizeOthers (int))); +QTMTabWidget::QTMTabWidget (QWidget* p) : QTabWidget (p) { + QObject::connect (this, SIGNAL (currentChanged (int)), this, + SLOT (resizeOthers (int))); } /*! Resizes the widget to the size of the tab given by the index. - + In particular, we must tell all parent widgets to adjustSize() as well as possibly resize the window: qt_window_widget_rep's constructor sets a fixed - size for windows which do not contain variable size resize_widgets. In this + size for windows which do not contain variable size resize_widgets. In this case we must update the fixed size to reflect the change of tab. */ void QTMTabWidget::resizeOthers (int current) { -BEGIN_SLOT - for (int i = 0; i < count(); ++i) { + BEGIN_SLOT + for (int i= 0; i < count (); ++i) { if (i != current) - widget(i)->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); - else - widget(i)->setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum); + widget (i)->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); + else widget (i)->setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum); } - - // FIXME? this could loop indefinitely if parents are cyclic. - QWidget* p = this; - while (p != window()) { - p->adjustSize(); - p = p->parentWidget(); + + // FIXME? this could loop indefinitely if parents are cyclic. + QWidget* p= this; + while (p != window ()) { + p->adjustSize (); + p= p->parentWidget (); } - p->adjustSize(); + p->adjustSize (); - if (window()->minimumSize()!=QSize (0,0) && - window()->maximumSize() != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) - window()->setFixedSize (window()->sizeHint()); -END_SLOT + if (window ()->minimumSize () != QSize (0, 0) && + window ()->maximumSize () != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) + window ()->setFixedSize (window ()->sizeHint ()); + END_SLOT } /****************************************************************************** * QTMRefreshWidget ******************************************************************************/ -widget make_menu_widget (object wid); +widget make_menu_widget (object wid); extern bool menu_caching; -QTMRefreshWidget::QTMRefreshWidget (qt_widget _tmwid, string _strwid, string _kind) -: QWidget (), strwid (_strwid), kind (_kind), - curobj (false), cur (), tmwid (_tmwid), qwid (NULL), cache (widget ()) -{ - QObject::connect (the_gui->gui_helper, SIGNAL (tmSlotRefresh (string)), - this, SLOT (doRefresh (string))); - QVBoxLayout* l = new QVBoxLayout (this); +QTMRefreshWidget::QTMRefreshWidget (qt_widget _tmwid, string _strwid, + string _kind) + : QWidget (), strwid (_strwid), kind (_kind), curobj (false), cur (), + tmwid (_tmwid), qwid (NULL), cache (widget ()) { + QObject::connect (the_gui->gui_helper, SIGNAL (tmSlotRefresh (string)), this, + SLOT (doRefresh (string))); + QVBoxLayout* l= new QVBoxLayout (this); l->setContentsMargins (0, 0, 0, 0); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // https://doc.qt.io/qt-5/qlayout-obsolete.html#setMargin l->setMargin (0); #endif setLayout (l); - + doRefresh ("init"); } bool QTMRefreshWidget::recompute (string what) { if (what != "init" && kind != "any" && kind != what) return false; - string s = "'(vertical (link " * strwid * "))"; + string s= "'(vertical (link " * strwid * "))"; eval ("(lazy-initialize-force)"); - object xwid = call ("menu-expand", eval (s)); - + object xwid= call ("menu-expand", eval (s)); + if (cache->contains (xwid)) { if (curobj == xwid) return false; - curobj = xwid; - cur = cache [xwid]; + curobj= xwid; + cur = cache[xwid]; return true; - } else { - curobj = xwid; - object uwid = eval (s); - cur = make_menu_widget (uwid); + } + else { + curobj = xwid; + object uwid= eval (s); + cur = make_menu_widget (uwid); tmwid->add_child (cur); // FIXME?! Is this ok? what when we refresh? - if (menu_caching) cache (xwid) = cur; + if (menu_caching) cache (xwid)= cur; return true; } } @@ -868,45 +858,44 @@ QTMRefreshWidget::deleteLayout (QLayout* l) { void QTMRefreshWidget::doRefresh (string kind) { -BEGIN_SLOT + BEGIN_SLOT if (recompute (kind)) { if (qwid) qwid->setParent (NULL); delete qwid; - qwid = concrete (cur)->as_qwidget(); + qwid= concrete (cur)->as_qwidget (); qwid->setParent (this); - delete layout()->takeAt(0); - layout()->addWidget (qwid); - update(); - - // Tell the window to fix its size to the new one if we had it fixed to - // begin with (this is indicated by minimum and maximum sizes set to - // values other than the default) - if (window()->minimumSize() != QSize (0,0) && - window()->maximumSize() != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) - window()->setFixedSize (window()->sizeHint()); + delete layout ()->takeAt (0); + layout ()->addWidget (qwid); + update (); + + // Tell the window to fix its size to the new one if we had it fixed to + // begin with (this is indicated by minimum and maximum sizes set to + // values other than the default) + if (window ()->minimumSize () != QSize (0, 0) && + window ()->maximumSize () != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) + window ()->setFixedSize (window ()->sizeHint ()); } -END_SLOT + END_SLOT } - /****************************************************************************** * QTMRefreshableWidget ******************************************************************************/ -QTMRefreshableWidget::QTMRefreshableWidget (qt_widget _tmwid, object _prom, string _kind) -: QWidget (), prom (_prom), kind (_kind), - curobj (false), cur (), tmwid (_tmwid), qwid (NULL) -{ - QObject::connect (the_gui->gui_helper, SIGNAL (tmSlotRefresh (string)), - this, SLOT (doRefresh (string))); - QVBoxLayout* l = new QVBoxLayout (this); +QTMRefreshableWidget::QTMRefreshableWidget (qt_widget _tmwid, object _prom, + string _kind) + : QWidget (), prom (_prom), kind (_kind), curobj (false), cur (), + tmwid (_tmwid), qwid (NULL) { + QObject::connect (the_gui->gui_helper, SIGNAL (tmSlotRefresh (string)), this, + SLOT (doRefresh (string))); + QVBoxLayout* l= new QVBoxLayout (this); l->setContentsMargins (0, 0, 0, 0); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) l->setMargin (0); #endif setLayout (l); - + doRefresh ("init"); } @@ -914,11 +903,11 @@ bool QTMRefreshableWidget::recompute (string what) { if (what != "init" && kind != "any" && kind != what) return false; eval ("(lazy-initialize-force)"); - object xwid = call (prom); + object xwid= call (prom); if (curobj == xwid) return false; if (!is_widget (xwid)) return false; curobj= xwid; - cur= as_widget (xwid); + cur = as_widget (xwid); tmwid->add_child (cur); // FIXME?! Is this ok? what when we refresh? return true; } @@ -949,85 +938,85 @@ QTMRefreshableWidget::deleteLayout (QLayout* l) { void QTMRefreshableWidget::doRefresh (string kind) { -BEGIN_SLOT + BEGIN_SLOT if (recompute (kind)) { if (qwid) qwid->setParent (NULL); delete qwid; - qwid = concrete (cur)->as_qwidget(); + qwid= concrete (cur)->as_qwidget (); qwid->setParent (this); - delete layout()->takeAt(0); - layout()->addWidget (qwid); - update(); - - // Tell the window to fix its size to the new one if we had it fixed to - // begin with (this is indicated by minimum and maximum sizes set to - // values other than the default) - if (window()->minimumSize() != QSize (0,0) && - window()->maximumSize() != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) - window()->setFixedSize (window()->sizeHint()); + delete layout ()->takeAt (0); + layout ()->addWidget (qwid); + update (); + + // Tell the window to fix its size to the new one if we had it fixed to + // begin with (this is indicated by minimum and maximum sizes set to + // values other than the default) + if (window ()->minimumSize () != QSize (0, 0) && + window ()->maximumSize () != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) + window ()->setFixedSize (window ()->sizeHint ()); } -END_SLOT + END_SLOT } - /****************************************************************************** * QTMComboBox ******************************************************************************/ QTMComboBox::QTMComboBox (QWidget* parent) : QComboBox (parent) { - ///// Obtain the minimum vertical size + ///// Obtain the minimum vertical size QComboBox cb; cb.setSizeAdjustPolicy (AdjustToContents); cb.addItem (""); - minSize = cb.sizeHint(); // we'll just keep the height - - ///// Add width of the arrow button + minSize= cb.sizeHint (); // we'll just keep the height + + ///// Add width of the arrow button QStyleOptionComboBox opt; opt.initFrom (&cb); - opt.activeSubControls = QStyle::SC_ComboBoxArrow; - QRect r = style()->subControlRect (QStyle::CC_ComboBox, &opt, - QStyle::SC_ComboBoxArrow, &cb); - int max_w= (int) floor (40 * retina_scale); - minSize.setWidth (min (r.width(), max_w)); + opt.activeSubControls= QStyle::SC_ComboBoxArrow; + QRect r = style ()->subControlRect (QStyle::CC_ComboBox, &opt, + QStyle::SC_ComboBoxArrow, &cb); + int max_w = (int) floor (40 * retina_scale); + minSize.setWidth (min (r.width (), max_w)); } /*! Add items and fix the ComboBox size using texmacs length units. - + Relative sizes are set based on the minimum bounding box in which any item of - the list fits. Absolute sizes are set independently of the size of items in + the list fits. Absolute sizes are set independently of the size of items in the list. - + The QComboBox' minimum height is the original minimumSizeHint(). */ void -QTMComboBox::addItemsAndResize (const QStringList& texts, string ww, string hh) { +QTMComboBox::addItemsAndResize (const QStringList& texts, string ww, + string hh) { QComboBox::addItems (texts); - - ///// Calculate the minimal contents size: -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - calcSize = QApplication::globalStrut (); + + ///// Calculate the minimal contents size: +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + calcSize= QApplication::globalStrut (); #else // see https://doc.qt.io/qt-5/qapplication-obsolete.html#globalStrut-prop // no replacement of QApplication::globalStrut #endif - const QFontMetrics& fm = fontMetrics (); - - for (int i = 0; i < count(); ++i) { - QRect br = fm.boundingRect (itemText(i)); - calcSize.setWidth (qMax (calcSize.width(), br.width())); - calcSize.setHeight (qMax (calcSize.height(), br.height())); + const QFontMetrics& fm= fontMetrics (); + + for (int i= 0; i < count (); ++i) { + QRect br= fm.boundingRect (itemText (i)); + calcSize.setWidth (qMax (calcSize.width (), br.width ())); + calcSize.setHeight (qMax (calcSize.height (), br.height ())); } - calcSize = qt_decode_length (ww, hh, calcSize, fm); - //if (ends (ww, "em") && (parent () == NULL)) - // calcSize.rwidth ()= (int) floor (retina_scale * calcSize.width () + 0.5); - //if (ends (hh, "em") && (parent () == NULL)) - // calcSize.rheight()= (int) floor (retina_scale * calcSize.height() + 0.5); - - ///// Add minimum constraints and fix size - calcSize.setHeight (qMax (calcSize.height(), minSize.height())); - calcSize.rwidth() += minSize.width(); - + calcSize= qt_decode_length (ww, hh, calcSize, fm); + // if (ends (ww, "em") && (parent () == NULL)) + // calcSize.rwidth ()= (int) floor (retina_scale * calcSize.width () + 0.5); + // if (ends (hh, "em") && (parent () == NULL)) + // calcSize.rheight()= (int) floor (retina_scale * calcSize.height() + 0.5); + + ///// Add minimum constraints and fix size + calcSize.setHeight (qMax (calcSize.height (), minSize.height ())); + calcSize.rwidth ()+= minSize.width (); + setFixedSize (calcSize); } @@ -1038,25 +1027,23 @@ QTMComboBox::addItemsAndResize (const QStringList& texts, string ww, string hh) bool QTMComboBox::event (QEvent* ev) { bool ret= true; - if (ev->type() == QEvent::KeyPress && isEditable()) { // Handle ALL keys - QKeyEvent* k = static_cast (ev); - if (k->key() == Qt::Key_Up || k->key() == Qt::Key_Down) - showPopup(); - else if (k->key() != Qt::Key_Escape) // HACK: QTMLineEdit won't need this - lineEdit()->event (ev); // but we do. + if (ev->type () == QEvent::KeyPress && isEditable ()) { // Handle ALL keys + QKeyEvent* k= static_cast (ev); + if (k->key () == Qt::Key_Up || k->key () == Qt::Key_Down) showPopup (); + else if (k->key () != Qt::Key_Escape) // HACK: QTMLineEdit won't need this + lineEdit ()->event (ev); // but we do. } else ret= QComboBox::event (ev); return ret; } - /****************************************************************************** * QTMScrollArea ******************************************************************************/ /*! Sets the widget for the scrollarea and looks for QListViews. - + This is needed to correctly update the scrollbars when the user navigates with the keys through items in a QListView contained in the QTMScrollArea. It also scrolls the viewport to the position of selected items in QListWidgets. @@ -1064,44 +1051,43 @@ QTMComboBox::event (QEvent* ev) { void QTMScrollArea::setWidgetAndConnect (QWidget* w) { setWidget (w); - - listViews = w->findChildren(); - for (ListViewsIterator it = listViews.begin(); it != listViews.end(); ++it) { - if (! (*it)->isScrollable()) + + listViews= w->findChildren (); + for (ListViewsIterator it= listViews.begin (); it != listViews.end (); ++it) { + if (!(*it)->isScrollable ()) QObject::connect (*it, SIGNAL (selectionChanged (const QItemSelection&)), - this, SLOT (scrollToSelection (const QItemSelection&))); + this, SLOT (scrollToSelection (const QItemSelection&))); } } /*! Scrolls the area to a given index in a QTMListView. */ void QTMScrollArea::scrollToSelection (const QItemSelection& sel) { -BEGIN_SLOT - if (sel.isEmpty()) - return; + BEGIN_SLOT + if (sel.isEmpty ()) return; - QTMListView* lw = qobject_cast (sender()); + QTMListView* lw= qobject_cast (sender ()); if (lw) { - QRect r = lw->visualRect (sel.indexes().last()); - QRect g = lw->geometry(); - int x = r.x() + g.x(); - int y = r.y() + g.y(); - - if (! viewport()->geometry().contains (x, y)) - ensureVisible (x, y, r.width(), r.height()); + QRect r= lw->visualRect (sel.indexes ().last ()); + QRect g= lw->geometry (); + int x= r.x () + g.x (); + int y= r.y () + g.y (); + + if (!viewport ()->geometry ().contains (x, y)) + ensureVisible (x, y, r.width (), r.height ()); } -END_SLOT + END_SLOT } /*! Work around a problem with scrolling before the widget is shown. - + Calling ensureVisible() before the widget is shown scrolls the viewport by an insufficient amount. See the comments to QTMScrollArea. */ void QTMScrollArea::showEvent (QShowEvent* ev) { - for (ListViewsIterator it = listViews.begin(); it != listViews.end(); ++it) { - QItemSelection sel = (*it)->selectionModel()->selection(); + for (ListViewsIterator it= listViews.begin (); it != listViews.end (); ++it) { + QItemSelection sel= (*it)->selectionModel ()->selection (); (*it)->selectionChanged (sel, sel); } QScrollArea::showEvent (ev); @@ -1111,42 +1097,38 @@ QTMScrollArea::showEvent (QShowEvent* ev) { * QTMListView ******************************************************************************/ -QTMListView::QTMListView (const command& cmd, - const QStringList& strings, - const QStringList& selections, - bool multiple, - bool scroll, - bool filtered, - QWidget* parent) -: QListView (parent) { - - stringModel = new QStringListModel (strings, this); - filterModel = new QSortFilterProxyModel (this); - +QTMListView::QTMListView (const command& cmd, const QStringList& strings, + const QStringList& selections, bool multiple, + bool scroll, bool filtered, QWidget* parent) + : QListView (parent) { + + stringModel= new QStringListModel (strings, this); + filterModel= new QSortFilterProxyModel (this); + filterModel->setSourceModel (stringModel); - //filterModel->setDynamicSortFilter (true); + // filterModel->setDynamicSortFilter (true); filterModel->setFilterCaseSensitivity (Qt::CaseSensitive); - + setModel (filterModel); - + setSelectionMode (multiple ? ExtendedSelection : SingleSelection); setEditTriggers (NoEditTriggers); - // NOTE: using selectionModel()->select(item, QItemSelection::SelectCurrent) - // doesn't update the selection but overwrites it, so we explicitly define - // our QItemSelection and use merge() + // NOTE: using selectionModel()->select(item, QItemSelection::SelectCurrent) + // doesn't update the selection but overwrites it, so we explicitly define + // our QItemSelection and use merge() QItemSelection sel; - for (int i = 0; i < model()->rowCount(); ++i) { - QModelIndex item = model()->index (i, 0); - if (selections.contains (model()->data (item, Qt::DisplayRole).toString(), + for (int i= 0; i < model ()->rowCount (); ++i) { + QModelIndex item= model ()->index (i, 0); + if (selections.contains (model ()->data (item, Qt::DisplayRole).toString (), Qt::CaseSensitive)) - sel.merge (QItemSelection(item, item), QItemSelectionModel::Select); + sel.merge (QItemSelection (item, item), QItemSelectionModel::Select); } - selectionModel()->select (sel, QItemSelectionModel::Select); - + selectionModel ()->select (sel, QItemSelectionModel::Select); + if (!scroll) { - setMinimumWidth (sizeHintForColumn(0)); - setMinimumHeight (sizeHintForRow(0) * model()->rowCount()); + setMinimumWidth (sizeHintForColumn (0)); + setMinimumHeight (sizeHintForRow (0) * model ()->rowCount ()); setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); setFrameStyle (QFrame::NoFrame); @@ -1155,25 +1137,26 @@ QTMListView::QTMListView (const command& cmd, setUniformItemSizes (true); setSizePolicy (QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - command ecmd = tm_new (this, cmd, multiple, filtered); - QTMCommand* qcmd = new QTMCommand (this, ecmd); - QObject::connect (selectionModel(), - SIGNAL (selectionChanged (const QItemSelection&, const QItemSelection&)), - qcmd, - SLOT (apply())); + command ecmd= tm_new (this, cmd, multiple, filtered); + QTMCommand* qcmd= new QTMCommand (this, ecmd); + QObject::connect ( + selectionModel (), + SIGNAL (selectionChanged (const QItemSelection&, const QItemSelection&)), + qcmd, SLOT (apply ())); } /*! Reimplemented from QListView. - - We simply emit another signal, mainly to notify QTMScrollArea that we have a new - selection for those cases were we don't have our own scrollbars. + + We simply emit another signal, mainly to notify QTMScrollArea that we have a + new selection for those cases were we don't have our own scrollbars. */ void -QTMListView::selectionChanged (const QItemSelection& c, const QItemSelection& p) { -BEGIN_SLOT +QTMListView::selectionChanged (const QItemSelection& c, + const QItemSelection& p) { + BEGIN_SLOT QListView::selectionChanged (c, p); emit selectionChanged (c); -END_SLOT + END_SLOT } /****************************************************************************** @@ -1181,46 +1164,43 @@ END_SLOT ******************************************************************************/ QTMTreeView::QTMTreeView (command cmd, tree data, const tree& roles, QWidget* p) -: QTreeView (p), _t (data), _cmd (cmd) { + : QTreeView (p), _t (data), _cmd (cmd) { setModel (QTMTreeModel::instance (_t, roles)); - setUniformRowHeights (true); // assuming we display only text. - setHeaderHidden (true); // for now... - QObject::connect (this, SIGNAL (pressed (const QModelIndex&)), - this, SLOT (callOnChange (const QModelIndex&))); + setUniformRowHeights (true); // assuming we display only text. + setHeaderHidden (true); // for now... + QObject::connect (this, SIGNAL (pressed (const QModelIndex&)), this, + SLOT (callOnChange (const QModelIndex&))); } void QTMTreeView::currentChanged (const QModelIndex& curr, const QModelIndex& prev) { (void) prev; - if (selectedIndexes().contains(curr)) - callOnChange (curr, false); + if (selectedIndexes ().contains (curr)) callOnChange (curr, false); } void QTMTreeView::callOnChange (const QModelIndex& index, bool mouse) { -BEGIN_SLOT - object arguments = mouse ? list_object ((int)QApplication::mouseButtons()) - : list_object (-1); - - // docs state the index is valid, no need to check - QVariant d = tmModel()->data (index, QTMTreeModel::CommandRole); - // If there's no CommandRole, we return the subtree by default - if (!d.isValid() || !d.canConvert (QVariant::String)) - arguments = cons (tmModel()->item_from_index (index), arguments); - else - arguments = cons (from_qstring (d.toString()), arguments); - int cnt = QTMTreeModel::TMUserRole; - d = tmModel()->data (index, cnt); - while (d.isValid() && d.canConvert (QVariant::String)) { - arguments = cons (from_qstring (d.toString()), arguments); - d = tmModel()->data (index, ++cnt); + BEGIN_SLOT + object arguments= mouse ? list_object ((int) QApplication::mouseButtons ()) + : list_object (-1); + + // docs state the index is valid, no need to check + QVariant d= tmModel ()->data (index, QTMTreeModel::CommandRole); + // If there's no CommandRole, we return the subtree by default + if (!d.isValid () || !d.canConvert (QVariant::String)) + arguments= cons (tmModel ()->item_from_index (index), arguments); + else arguments= cons (from_qstring (d.toString ()), arguments); + int cnt= QTMTreeModel::TMUserRole; + d = tmModel ()->data (index, cnt); + while (d.isValid () && d.canConvert (QVariant::String)) { + arguments= cons (from_qstring (d.toString ()), arguments); + d = tmModel ()->data (index, ++cnt); } _cmd (arguments); -END_SLOT + END_SLOT } inline QTMTreeModel* -QTMTreeView::tmModel() const { - return static_cast (model()); +QTMTreeView::tmModel () const { + return static_cast (model ()); } - diff --git a/src/Plugins/Qt/QTMMenuHelper.hpp b/src/Plugins/Qt/QTMMenuHelper.hpp index 6d505ac8ce..52dd98c0f8 100644 --- a/src/Plugins/Qt/QTMMenuHelper.hpp +++ b/src/Plugins/Qt/QTMMenuHelper.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : QTMMenuHelper.hpp -* DESCRIPTION: QT Texmacs menu helper classes -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMMenuHelper.hpp + * DESCRIPTION: QT Texmacs menu helper classes + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMMENUHELPER_HPP #define QTMMENUHELPER_HPP @@ -16,23 +16,23 @@ #include "promise.hpp" #include "scheme.hpp" -#include "qt_gui.hpp" #include "qt_dialogues.hpp" +#include "qt_gui.hpp" -#include -#include -#include -#include -#include #include -#include -#include #include +#include #include -#include +#include +#include #include +#include +#include #include +#include #include +#include +#include /*! Handles TeXmacs commands in the QT way. @@ -45,54 +45,54 @@ To use this class, one typically takes some given command "cmd" and does the following: - + QTMCommand* qtmcmd = new QTMCommand (theQWidget, cmd); - QObject::connect(theQWidget, SIGNAL (somethingHappened()), qtmcmd, SLOT (apply())); - + QObject::connect(theQWidget, SIGNAL (somethingHappened()), qtmcmd, SLOT + (apply())); + Since the slot in this class accepts no arguments, commands which require access to the QWidget must be subclassed from command_rep to accept the particular QWidget as a parameter. Then their invocation (which apply() will call) must access it. An alternative would be to subclass QTMCommand to add slots accepting arguments - but making sure that the underlying command_rep is properly sent to the mentioned - queue. + but making sure that the underlying command_rep is properly sent to the + mentioned queue. */ -class QTMCommand: public QObject { +class QTMCommand : public QObject { Q_OBJECT protected: command cmd; public: - QTMCommand (QObject* parent, command _cmd): QObject(parent), cmd (_cmd) {} + QTMCommand (QObject* parent, command _cmd) : QObject (parent), cmd (_cmd) {} public slots: void apply (); }; - /*! A QMenu which builds its entries just before show()ing. - + The menu entries are given as a texmacs widget in form of a promise which is evaluated each time we force(). No caching internal to this object should be performed lest we break dynamic menus. - + If this is intended as a submenu of a QAction, we must attachTo() it: then, when the action is about to be destroyed() we are notified and remove ourselves - + If this is used as a menu for a button, then it suffices to set the parent accordingly in the constructor. */ -class QTMLazyMenu: public QMenu { +class QTMLazyMenu : public QMenu { Q_OBJECT - + promise promise_widget; - bool show_right; + bool show_right; public: - QTMLazyMenu (promise _pm, QWidget* p = NULL, bool right = false); - void attachTo (QAction* a); + QTMLazyMenu (promise _pm, QWidget* p= NULL, bool right= false); + void attachTo (QAction* a); virtual void showEvent (QShowEvent* event); public slots: @@ -102,12 +102,11 @@ public slots: void transferActions (QList* src); protected slots: - void destroy (QObject* obj=0); + void destroy (QObject* obj= 0); }; - /*! The basic action for items in TeXmacs' menus. - + This custom action frees its menu if it does not already have an owner: this is part of the memory policy explained in qt_menu_rep. @@ -119,127 +118,122 @@ protected slots: */ class QTMAction : public QAction { Q_OBJECT - + QTimer* _timer; - QPoint _pos; - string str; - + QPoint _pos; + string str; + public: - QTMAction (QObject *parent = NULL); - ~QTMAction(); + QTMAction (QObject* parent= NULL); + ~QTMAction (); void set_text (string s); - + public slots: - void doRefresh(); - void showToolTip(); // actions; - int cols; - + QVector actions; + int cols; + public: - QTMTileAction (array& arr, int _cols, QObject* parent=NULL); + QTMTileAction (array& arr, int _cols, QObject* parent= NULL); virtual QWidget* createWidget (QWidget* parent); }; - /*! */ class QTMMinibarAction : public QWidgetAction { Q_OBJECT - QVector actions; + QVector actions; public: - QTMMinibarAction (array& arr, QObject* parent=NULL); + QTMMinibarAction (array& arr, QObject* parent= NULL); virtual QWidget* createWidget (QWidget* parent); }; - /*! QTMMenuButton is a custom button appropriate for menus. - + We need to subclass QToolButton for two reasons: 1) Custom appearance 2) If used in QWidgetAction the menu does not disappear upon triggering the button. See QTBUG-10427 and TeXmacs bug #37719. */ -class QTMMenuButton: public QToolButton { +class QTMMenuButton : public QToolButton { Q_OBJECT public: - QTMMenuButton (QWidget* parent = NULL); - + QTMMenuButton (QWidget* parent= NULL); + void mouseReleaseEvent (QMouseEvent* e); void mousePressEvent (QMouseEvent* e); void paintEvent (QPaintEvent* e); }; - /*! */ -class QTMMenuWidget: public QWidget { +class QTMMenuWidget : public QWidget { Q_OBJECT public: - QTMMenuWidget (QWidget* parent = NULL); - void paintEvent(QPaintEvent *event); + QTMMenuWidget (QWidget* parent= NULL); + void paintEvent (QPaintEvent* event); }; - /*! A customized QLineEdit with special keyboard handling and styling. */ class QTMLineEdit : public QLineEdit { Q_OBJECT - bool completing; - string type; // type of input field - string name; // optional name of input field - string serial; // optional serial number of input field - string ww; // width of the parsed widget - command cmd; - int last_key; + bool completing; + string type; // type of input field + string name; // optional name of input field + string serial; // optional serial number of input field + string ww; // width of the parsed widget + command cmd; + int last_key; + public: - QTMLineEdit (QWidget *parent, string _type, string _ww, - int style=0, command _cmd= command ()); - void set_type (string t); - bool continuous (); - virtual QSize sizeHint () const ; - virtual bool event (QEvent* ev); + QTMLineEdit (QWidget* parent, string _type, string _ww, int style= 0, + command _cmd= command ()); + void set_type (string t); + bool continuous (); + virtual QSize sizeHint () const; + virtual bool event (QEvent* ev); signals: void focusOut (Qt::FocusReason reason); - + protected: virtual void keyPressEvent (QKeyEvent* ev); virtual void inputMethodEvent (QInputMethodEvent* ev); @@ -247,57 +241,56 @@ class QTMLineEdit : public QLineEdit { virtual void focusOutEvent (QFocusEvent* ev); }; - /*! A class to keep a QTMLineEdit and a qt_input_text_widget_rep in sync. - - After certain events we store state information about the QLineEdit into the + + After certain events we store state information about the QLineEdit into the qt_input_text_widget_rep: - + - When the user has finished editing (i.e. has pressed enter) we save the text from the QWidget in the texmacs widget and set a "modified" flag. - When the user leaves the QWidget we restore the text from the texmacs widget and in case there was a modification we execute the scheme command. - + Additionally and depending on user configuration we may always store the text when leaving or apply the command when pressing enter. - + @note On memory management: the QTMInputTextWidgetHelper is owned by the QTMLineEdit it is helping with. */ class QTMInputTextWidgetHelper : public QObject { Q_OBJECT - - qt_widget p_wid; //!< A pointer to a qt_input_text_widget_rep - bool can_autocommit; - + + qt_widget p_wid; //!< A pointer to a qt_input_text_widget_rep + bool can_autocommit; + public: QTMInputTextWidgetHelper (qt_widget _wid, bool _cac); - + protected: qt_input_text_widget_rep* wid () { // useful cast - return static_cast (p_wid.rep); } + return static_cast (p_wid.rep); + } public slots: void commit (); void leave (Qt::FocusReason reason); }; - /*! A class to keep a QComboBox and a qt_field_widget_rep in sync. - - After certain events we store state information about the QComboBox into the + + After certain events we store state information about the QComboBox into the qt_input_text_widget_rep: when the user has finished editing (i.e. has pressed enter), or has left the QComboBox for instance. - + @note On memory management: the QTMFieldWidgetHelper is owned by the QComboBox it is helping with. */ class QTMFieldWidgetHelper : public QObject { Q_OBJECT - + qt_widget wid; - bool done; - + bool done; + public: QTMFieldWidgetHelper (qt_widget _wid, QComboBox* parent); QTMFieldWidgetHelper (qt_widget _wid, QLineEdit* parent); @@ -306,74 +299,70 @@ public slots: void commit (const QString& qst); }; - /*! A QTabWidget which resizes itself to the currently displayed page. */ class QTMTabWidget : public QTabWidget { Q_OBJECT public: - QTMTabWidget (QWidget* p = NULL); + QTMTabWidget (QWidget* p= NULL); public slots: - void resizeOthers(int index); + void resizeOthers (int index); }; - /*! A container widget which redraws the widgets it owns. */ class QTMRefreshWidget : public QWidget { Q_OBJECT - - string strwid; - string kind; - object curobj; - widget cur; - qt_widget tmwid; - QWidget* qwid; - hashmap cache; - + + string strwid; + string kind; + object curobj; + widget cur; + qt_widget tmwid; + QWidget* qwid; + hashmap cache; + public: QTMRefreshWidget (qt_widget _tmwid, string _strwid, string _kind); bool recompute (string what); - //static void deleteLayout (QLayout*); + // static void deleteLayout (QLayout*); public slots: void doRefresh (string kind); }; - /*! A container widget which redraws the widgets it owns. */ class QTMRefreshableWidget : public QWidget { Q_OBJECT - - object prom; - string kind; - object curobj; - widget cur; + + object prom; + string kind; + object curobj; + widget cur; qt_widget tmwid; - QWidget* qwid; - + QWidget* qwid; + public: QTMRefreshableWidget (qt_widget _tmwid, object _prom, string _kind); bool recompute (string what); - //static void deleteLayout (QLayout*); + // static void deleteLayout (QLayout*); public slots: void doRefresh (string kind); }; - /*! A mutilated QComboBox which fixes its size using texmacs lengths. - + To use just create the QWidget and call addItemsAndResize(). */ class QTMComboBox : public QComboBox { Q_OBJECT - - QSize calcSize; - QSize minSize; - + + QSize calcSize; + QSize minSize; + public: QTMComboBox (QWidget* parent); @@ -381,7 +370,6 @@ class QTMComboBox : public QComboBox { bool event (QEvent* ev); }; - /*! A QListView with a sorting proxy model. */ class QTMListView : public QListView { Q_OBJECT @@ -393,62 +381,61 @@ class QTMListView : public QListView { public: QTMListView (const command& cmd, const QStringList& vals, const QStringList&, - bool multiple, bool scroll = false, bool filtered = false, - QWidget* parent = NULL); - - QSortFilterProxyModel* filter() const { return filterModel; } - bool isScrollable() const { - return (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff) && - (horizontalScrollBarPolicy() != Qt::ScrollBarAlwaysOff); + bool multiple, bool scroll= false, bool filtered= false, + QWidget* parent= NULL); + + QSortFilterProxyModel* filter () const { return filterModel; } + bool isScrollable () const { + return (verticalScrollBarPolicy () != Qt::ScrollBarAlwaysOff) && + (horizontalScrollBarPolicy () != Qt::ScrollBarAlwaysOff); } signals: void selectionChanged (const QItemSelection& c); protected slots: - virtual void selectionChanged (const QItemSelection& c, const QItemSelection& p); + virtual void selectionChanged (const QItemSelection& c, + const QItemSelection& p); }; - class QTMTreeModel; /*! A simple wrapper around a QTreeView. - + This class keeps a pointer to the tree it's displaying, in order to keep it - alive. It also instantiates (if necessary) the QTMTreeModel it needs to sync + alive. It also instantiates (if necessary) the QTMTreeModel it needs to sync with the data. This model is property of a qt_tree_observer, which will delete it when the tree is. */ class QTMTreeView : public QTreeView { Q_OBJECT - tree _t; + tree _t; command _cmd; - + QTMTreeView (const QTMTreeView&); QTMTreeView& operator= (const QTMTreeView&); - + public: - QTMTreeView (command cmd, tree data, const tree& roles, QWidget* parent=0); - QTMTreeModel* tmModel() const; - + QTMTreeView (command cmd, tree data, const tree& roles, QWidget* parent= 0); + QTMTreeModel* tmModel () const; + protected: virtual void currentChanged (const QModelIndex& cur, const QModelIndex& pre); - + private slots: - void callOnChange (const QModelIndex& index, bool mouse=true); + void callOnChange (const QModelIndex& index, bool mouse= true); }; - /*! A QScrollArea which automatically scrolls to selected items in QListWidgets. - + This is needed because of our implementation of choice_widget which disables the default scrollbars in QListWidget. Instead we add an explicit QScrollArea - which then has to be scrolled manually, for instance when the user navigates - with the cursor keys. To this end we use the slot scrollToSelection(), + which then has to be scrolled manually, for instance when the user navigates + with the cursor keys. To this end we use the slot scrollToSelection(), connected to the signal currentIndexChanged() of each QListWidget contained in the QScrollArea. - + Furthermore, we must implement showEvent() because scrolling at the time of widget compilation in qt_ui_element_rep::as_qwidget() before the widget is shown results in an unsufficient scroll performed (by an amount roughly the @@ -456,13 +443,13 @@ private slots: */ class QTMScrollArea : public QScrollArea { Q_OBJECT - + QList listViews; - + typedef QList::iterator ListViewsIterator; public: - QTMScrollArea (QWidget* p = NULL) : QScrollArea(p) { }; + QTMScrollArea (QWidget* p= NULL) : QScrollArea (p){}; void setWidgetAndConnect (QWidget* w); protected: diff --git a/src/Plugins/Qt/QTMPipeLink.cpp b/src/Plugins/Qt/QTMPipeLink.cpp index 946b019825..3133162f03 100644 --- a/src/Plugins/Qt/QTMPipeLink.cpp +++ b/src/Plugins/Qt/QTMPipeLink.cpp @@ -1,25 +1,25 @@ /****************************************************************************** -* MODULE : qt_pipe_link.cpp -* DESCRIPTION: QT TeXmacs links -* COPYRIGHT : (C) 2009 David MICHEL -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_pipe_link.cpp + * DESCRIPTION: QT TeXmacs links + * COPYRIGHT : (C) 2009 David MICHEL + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ -#include "tm_link.hpp" -#include "qt_utilities.hpp" -#include "qt_gui.hpp" #include "QTMPipeLink.hpp" +#include "qt_gui.hpp" +#include "qt_utilities.hpp" +#include "tm_link.hpp" #include static string debug_io_string (QByteArray s) { - int i, n= s.size (); + int i, n= s.size (); string r; - for (i=0; i. -******************************************************************************/ + * MODULE : QTMPipeLink.hpp + * DESCRIPTION: QT TeXmacs links - header file + * COPYRIGHT : (C) 2009 David MICHEL + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTM_PIPE_LINK_H #define QTM_PIPE_LINK_H -#include "string.hpp" #include "command.hpp" +#include "string.hpp" #include class QTMPipeLink : public QProcess { @@ -23,17 +23,17 @@ public slots: void readErrOut (); public: - string cmd; - string outbuf; - string errbuf; + string cmd; + string outbuf; + string errbuf; command* feed_cmd; QTMPipeLink (string); ~QTMPipeLink (); - inline void setOutbuf(string out) { outbuf= out; } - inline void setErrbuf (string err) { errbuf= err; } - inline string& getOutbuf() { return outbuf; } + inline void setOutbuf (string out) { outbuf= out; } + inline void setErrbuf (string err) { errbuf= err; } + inline string& getOutbuf () { return outbuf; } inline string& getErrbuf () { return errbuf; } bool launchCmd (); diff --git a/src/Plugins/Qt/QTMPixmapOrImage.hpp b/src/Plugins/Qt/QTMPixmapOrImage.hpp index 3a507338cd..4b2f02f7fa 100644 --- a/src/Plugins/Qt/QTMPixmapOrImage.hpp +++ b/src/Plugins/Qt/QTMPixmapOrImage.hpp @@ -1,20 +1,20 @@ /****************************************************************************** -* MODULE : QTMPixmapOrImage.hpp -* DESCRIPTION: Union of QPixmap and QImage for headless mode -* COPYRIGHT : (C) 2022 Gregoire Lecerf -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMPixmapOrImage.hpp + * DESCRIPTION: Union of QPixmap and QImage for headless mode + * COPYRIGHT : (C) 2022 Gregoire Lecerf + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMPIXMAPORIMAGE_HPP #define QTMPIXMAPORIMAGE_HPP #include "boot.hpp" -#include #include +#include // if QTMPIXMAPS is defined we use QPixmap for characters // otherwise we use QImage (which supports alpha also under X11) @@ -36,42 +36,32 @@ struct QTMPixmapOrImage { else delete (QPixmap*) rep; } QTMPixmapOrImage (int w, int h) { - if (headless_mode) - rep= (void*) new QImage (w, h, QImage::Format_ARGB32); - else - rep= (void*) new QPixmap (w, h); + if (headless_mode) rep= (void*) new QImage (w, h, QImage::Format_ARGB32); + else rep= (void*) new QPixmap (w, h); } QTMPixmapOrImage (QSize s) { - if (headless_mode) - rep= (void*) new QImage (s, QImage::Format_ARGB32); - else - rep= (void*) new QPixmap (s); + if (headless_mode) rep= (void*) new QImage (s, QImage::Format_ARGB32); + else rep= (void*) new QPixmap (s); } - QTMPixmapOrImage (const QPixmap& px): rep ((void*) new QPixmap (px)) {} - QTMPixmapOrImage (const QImage& im): rep ((void*) new QImage (im)) {} + QTMPixmapOrImage (const QPixmap& px) : rep ((void*) new QPixmap (px)) {} + QTMPixmapOrImage (const QImage& im) : rep ((void*) new QImage (im)) {} QTMPixmapOrImage (const QTMPixmapOrImage& pxim) { if (headless_mode) rep= (void*) new QImage (); else rep= (void*) new QPixmap (); - if (headless_mode) - *((QImage*) rep)= *((QImage*) pxim.rep); - else - *((QPixmap*) rep)= *((QPixmap*) pxim.rep); + if (headless_mode) *((QImage*) rep)= *((QImage*) pxim.rep); + else *((QPixmap*) rep)= *((QPixmap*) pxim.rep); } - QTMPixmapOrImage& operator=(const QTMPixmapOrImage& pxim) { - if (headless_mode) - *((QImage*) rep)= *((QImage*) pxim.rep); - else - *((QPixmap*) rep)= *((QPixmap*) pxim.rep); + QTMPixmapOrImage& operator= (const QTMPixmapOrImage& pxim) { + if (headless_mode) *((QImage*) rep)= *((QImage*) pxim.rep); + else *((QPixmap*) rep)= *((QPixmap*) pxim.rep); } void fill (const QColor& c) { - if (headless_mode) - ((QImage*) rep)->fill (c); - else - ((QPixmap*) rep)->fill (c); + if (headless_mode) ((QImage*) rep)->fill (c); + else ((QPixmap*) rep)->fill (c); } bool isNull () { - return headless_mode ? - ((QImage*) rep)->isNull () : ((QPixmap*) rep)->isNull (); + return headless_mode ? ((QImage*) rep)->isNull () + : ((QPixmap*) rep)->isNull (); } QImage* QImage_ptr () { ASSERT (headless_mode, "internal bug in QTMPixmapOrImage::QImage_ptr"); @@ -81,9 +71,7 @@ struct QTMPixmapOrImage { ASSERT (!headless_mode, "internal bug in QTMPixmapOrImage::QPixmap_ptr"); return (QPixmap*) rep; } - void* void_ptr () { - return rep; - } + void* void_ptr () { return rep; } }; #ifdef QTMPIXMAPS diff --git a/src/Plugins/Qt/QTMPrintDialog.cpp b/src/Plugins/Qt/QTMPrintDialog.cpp index 58b06ee22c..e02de14428 100644 --- a/src/Plugins/Qt/QTMPrintDialog.cpp +++ b/src/Plugins/Qt/QTMPrintDialog.cpp @@ -1,6 +1,6 @@ /****************************************************************************** * MODULE : QTMPrintDialog.cpp - * DESCRIPTION: + * DESCRIPTION: * COPYRIGHT : (C) 2010 Miguel de Benito Delgado ******************************************************************************* * This software falls under the GNU general public license version 3 or later. @@ -11,29 +11,27 @@ #include "QTMPrintDialog.hpp" /*! - * Constructs a QTMPrintDialog and sets up the connections that allow for + * Constructs a QTMPrintDialog and sets up the connections that allow for * asynchronous loading of printer configuration: - * QTMPrinterSettings will emit QTMPrinterSettings::doneReading() after a call to - * QTMPrinterSettings::readFromSystemConfig() terminates, that is, after the + * QTMPrinterSettings will emit QTMPrinterSettings::doneReading() after a call + * to QTMPrinterSettings::readFromSystemConfig() terminates, that is, after the * command executed is done. * - * @see QTMPrinterSettings + * @see QTMPrinterSettings * * @todo Read the current printer settings from TeXmacs. */ -QTMPrintDialog::QTMPrintDialog(QTMPrinterSettings* s, QDialog* parent) - : QDialog(parent), _settings(s) { - - setupUi(this); - - QObject::connect(_settings, SIGNAL(doneReading()), - this, SLOT(updatePrinterCapabilities())); - QObject::connect(printerCombo, SIGNAL(currentIndexChanged(const QString)), - _settings, SLOT(startReadingSystemConfig(const QString&))); - +QTMPrintDialog::QTMPrintDialog (QTMPrinterSettings* s, QDialog* parent) + : QDialog (parent), _settings (s) { -} + setupUi (this); + QObject::connect (_settings, SIGNAL (doneReading ()), this, + SLOT (updatePrinterCapabilities ())); + QObject::connect (printerCombo, SIGNAL (currentIndexChanged (const QString)), + _settings, + SLOT (startReadingSystemConfig (const QString&))); +} /*! * Updates the controls which depend on the capabilities of the selected @@ -43,30 +41,33 @@ QTMPrintDialog::QTMPrintDialog(QTMPrinterSettings* s, QDialog* parent) * @fixme How can we translate the output from the system config? Must we? */ void -QTMPrintDialog::updatePrinterCapabilities() { - int idx = 0; - - paperSizeCombo->clear(); - paperSizeCombo->addItems(_settings->getChoices(QTMPrinterSettings::PageSize, idx)); - paperSizeCombo->setCurrentIndex(idx); - paperSizeLabel->setEnabled(paperSizeCombo->count() > 1); - paperSizeCombo->setEnabled(paperSizeCombo->count() > 1); - - resolutionCombo->clear(); - resolutionCombo->addItems(_settings->getChoices(QTMPrinterSettings::Resolution, idx)); - resolutionCombo->setCurrentIndex(idx); - resolutionLabel->setEnabled(resolutionCombo->count() > 1); - resolutionCombo->setEnabled(resolutionCombo->count() > 1); - - if (_settings->getChoices(QTMPrinterSettings::Duplex, idx).size() > 1) { - duplexCheck->setEnabled(true); - } else { - duplexCheck->setEnabled(false); - duplexCheck->setChecked(false); +QTMPrintDialog::updatePrinterCapabilities () { + int idx= 0; + + paperSizeCombo->clear (); + paperSizeCombo->addItems ( + _settings->getChoices (QTMPrinterSettings::PageSize, idx)); + paperSizeCombo->setCurrentIndex (idx); + paperSizeLabel->setEnabled (paperSizeCombo->count () > 1); + paperSizeCombo->setEnabled (paperSizeCombo->count () > 1); + + resolutionCombo->clear (); + resolutionCombo->addItems ( + _settings->getChoices (QTMPrinterSettings::Resolution, idx)); + resolutionCombo->setCurrentIndex (idx); + resolutionLabel->setEnabled (resolutionCombo->count () > 1); + resolutionCombo->setEnabled (resolutionCombo->count () > 1); + + if (_settings->getChoices (QTMPrinterSettings::Duplex, idx).size () > 1) { + duplexCheck->setEnabled (true); + } + else { + duplexCheck->setEnabled (false); + duplexCheck->setChecked (false); } - - blackWhiteCheck->setEnabled(_settings->getChoices(QTMPrinterSettings::ColorModel, - idx).size() > 1); + + blackWhiteCheck->setEnabled ( + _settings->getChoices (QTMPrinterSettings::ColorModel, idx).size () > 1); } /*! @@ -75,134 +76,144 @@ QTMPrintDialog::updatePrinterCapabilities() { * the printer names, which are useless to print with lpr. */ void -QTMPrintDialog::setupUi(QDialog *dia) { +QTMPrintDialog::setupUi (QDialog* dia) { - Ui::QTMPrintDialog::setupUi(dia); + Ui::QTMPrintDialog::setupUi (dia); typedef QPair printerPair; - foreach (printerPair printer, _settings->availablePrinters()) - printerCombo->addItem(printer.first, printer.second); - - if(printerCombo->count() == 0) - printerCombo->addItem("No printers available"); // TODO hide everything else + foreach (printerPair printer, _settings->availablePrinters ()) + printerCombo->addItem (printer.first, printer.second); + + if (printerCombo->count () == 0) + printerCombo->addItem ( + "No printers available"); // TODO hide everything else // We use the QVariant field to retrieve the correct value later. - orientationCombo->addItem("Portrait", QTMPrinterSettings::Portrait); - orientationCombo->addItem("Landscape", QTMPrinterSettings::Landscape); - orientationCombo->addItem("Reverse portrait", QTMPrinterSettings::ReversePortrait); - orientationCombo->addItem("Reverse landscape", QTMPrinterSettings::ReverseLandscape); - + orientationCombo->addItem ("Portrait", QTMPrinterSettings::Portrait); + orientationCombo->addItem ("Landscape", QTMPrinterSettings::Landscape); + orientationCombo->addItem ("Reverse portrait", + QTMPrinterSettings::ReversePortrait); + orientationCombo->addItem ("Reverse landscape", + QTMPrinterSettings::ReverseLandscape); + // We use the QVariant field to retrieve the correct value later. - orderPagesCombo->addItem("Left-Right, Top-Bottom", QTMPrinterSettings::LR_TB); - orderPagesCombo->addItem("Right-Left, Top-Bottom", QTMPrinterSettings::RL_TB); - orderPagesCombo->addItem("Top-Bottom, Left-Right", QTMPrinterSettings::TB_LR); - orderPagesCombo->addItem("Top-Bottom, Right-Left", QTMPrinterSettings::TB_RL); - orderPagesCombo->addItem("Left-Right, Bottom-Top", QTMPrinterSettings::LR_BT); - orderPagesCombo->addItem("Right-Left, Bottom-Top", QTMPrinterSettings::RL_BT); - orderPagesCombo->addItem("Bottom-Top, Left-Right", QTMPrinterSettings::BT_LR); - orderPagesCombo->addItem("Bottom-Top, Right-Left", QTMPrinterSettings::BT_RL); - - // Force reading the printer settings for the first printer in the list. - _settings->startReadingSystemConfig(printerCombo->currentText()); + orderPagesCombo->addItem ("Left-Right, Top-Bottom", + QTMPrinterSettings::LR_TB); + orderPagesCombo->addItem ("Right-Left, Top-Bottom", + QTMPrinterSettings::RL_TB); + orderPagesCombo->addItem ("Top-Bottom, Left-Right", + QTMPrinterSettings::TB_LR); + orderPagesCombo->addItem ("Top-Bottom, Right-Left", + QTMPrinterSettings::TB_RL); + orderPagesCombo->addItem ("Left-Right, Bottom-Top", + QTMPrinterSettings::LR_BT); + orderPagesCombo->addItem ("Right-Left, Bottom-Top", + QTMPrinterSettings::RL_BT); + orderPagesCombo->addItem ("Bottom-Top, Left-Right", + QTMPrinterSettings::BT_LR); + orderPagesCombo->addItem ("Bottom-Top, Right-Left", + QTMPrinterSettings::BT_RL); + + // Force reading the printer settings for the first printer in the list. + _settings->startReadingSystemConfig (printerCombo->currentText ()); } - /*! - * Stores the values from the dialog into the QTMPrinterSettings object after the - * user presses the "Accept" button. + * Stores the values from the dialog into the QTMPrinterSettings object after + * the user presses the "Accept" button. */ -void -QTMPrintDialog::accept() { - - _settings->printerName = printerCombo->currentText(); - _settings->copyCount = copiesInput->text().toInt(); - _settings->collateCopies = collatedCheck->isChecked(); - - if (allPagesRadio->isChecked()) - _settings->firstPage = _settings->lastPage = 0; +void +QTMPrintDialog::accept () { + + _settings->printerName = printerCombo->currentText (); + _settings->copyCount = copiesInput->text ().toInt (); + _settings->collateCopies= collatedCheck->isChecked (); + + if (allPagesRadio->isChecked ()) _settings->firstPage= _settings->lastPage= 0; else { - _settings->firstPage = fromPageInput->text().toInt(); - _settings->lastPage = toPageInput->text().toInt(); + _settings->firstPage= fromPageInput->text ().toInt (); + _settings->lastPage = toPageInput->text ().toInt (); } - _settings->printOddPages = oddPagesCheck->isChecked(); - _settings->printEvenPages = evenPagesCheck->isChecked(); - _settings->paperSize = paperSizeCombo->currentText(); - _settings->orientation = (QTMPrinterSettings::PageOrientation) - orientationCombo->itemData(orderPagesCombo->currentIndex()).toInt(); - _settings->duplex = duplexCheck->isChecked(); - _settings->blackWhite = blackWhiteCheck->isChecked(); - _settings->pagesPerSide = pagesPerSideCombo->currentText().toInt(); - _settings->pagesOrder = (QTMPrinterSettings::PagePrintingOrder) - orderPagesCombo->itemData(orderPagesCombo->currentIndex()).toInt(); - _settings->fitToPage = fitToPageCheck->isChecked(); - _settings->blackWhite = blackWhiteCheck->isChecked(); - - QDialog::accept(); + _settings->printOddPages = oddPagesCheck->isChecked (); + _settings->printEvenPages= evenPagesCheck->isChecked (); + _settings->paperSize = paperSizeCombo->currentText (); + _settings->orientation= (QTMPrinterSettings::PageOrientation) orientationCombo + ->itemData (orderPagesCombo->currentIndex ()) + .toInt (); + _settings->duplex = duplexCheck->isChecked (); + _settings->blackWhite = blackWhiteCheck->isChecked (); + _settings->pagesPerSide= pagesPerSideCombo->currentText ().toInt (); + _settings->pagesOrder= (QTMPrinterSettings::PagePrintingOrder) orderPagesCombo + ->itemData (orderPagesCombo->currentIndex ()) + .toInt (); + _settings->fitToPage = fitToPageCheck->isChecked (); + _settings->blackWhite= blackWhiteCheck->isChecked (); + + QDialog::accept (); } /*! * */ -void QTMPrintDialog::reject() -{ - QDialog::reject(); +void +QTMPrintDialog::reject () { + QDialog::reject (); } - /////////////////// Some cosmetic stuff follows /////////////////// - /*! * Disable the From: and To: fields in the dialog. * * @note We use this signal because toggled() would be fired by our call to * setChecked inside on_*PageInput_textChanged() */ -void QTMPrintDialog::on_allPagesRadio_clicked(bool on) -{ - if(on) { - fromPageInput->setText(""); - toPageInput->setText(""); +void +QTMPrintDialog::on_allPagesRadio_clicked (bool on) { + if (on) { + fromPageInput->setText (""); + toPageInput->setText (""); } - allPagesRadio->setChecked(on); + allPagesRadio->setChecked (on); } /*! * Enable the From: and To: fields in the dialog. */ -void QTMPrintDialog::on_rangePagesRadio_clicked(bool on) -{ +void +QTMPrintDialog::on_rangePagesRadio_clicked (bool on) { if (on) { - int f = (_settings->firstPage < 1) ? 1 : _settings->firstPage; - int l = (_settings->lastPage < 1) ? 1 : _settings->lastPage; - fromPageInput->setText(QString("%1").arg(f)); - toPageInput->setText(QString("%1").arg(l)); + int f= (_settings->firstPage < 1) ? 1 : _settings->firstPage; + int l= (_settings->lastPage < 1) ? 1 : _settings->lastPage; + fromPageInput->setText (QString ("%1").arg (f)); + toPageInput->setText (QString ("%1").arg (l)); } - rangePagesRadio->setChecked(on); + rangePagesRadio->setChecked (on); } -void QTMPrintDialog::on_copiesInput_textChanged(const QString& text) -{ +void +QTMPrintDialog::on_copiesInput_textChanged (const QString& text) { (void) text; - collatedCheck->setEnabled(text.toInt() > 1); + collatedCheck->setEnabled (text.toInt () > 1); } -void QTMPrintDialog::on_fromPageInput_textChanged(const QString& text) -{ +void +QTMPrintDialog::on_fromPageInput_textChanged (const QString& text) { (void) text; - if (allPagesRadio->isChecked()) - rangePagesRadio->setChecked(true); + if (allPagesRadio->isChecked ()) rangePagesRadio->setChecked (true); } -void QTMPrintDialog::on_toPageInput_textChanged(const QString& text) { +void +QTMPrintDialog::on_toPageInput_textChanged (const QString& text) { (void) text; - if (allPagesRadio->isChecked()) - rangePagesRadio->setChecked(true); + if (allPagesRadio->isChecked ()) rangePagesRadio->setChecked (true); } -void QTMPrintDialog::on_oddPagesCheck_stateChanged(int state) { - evenPagesCheck->setEnabled(state == Qt::Checked); +void +QTMPrintDialog::on_oddPagesCheck_stateChanged (int state) { + evenPagesCheck->setEnabled (state == Qt::Checked); } -void QTMPrintDialog::on_evenPagesCheck_stateChanged(int state) { - oddPagesCheck->setEnabled(state == Qt::Checked); +void +QTMPrintDialog::on_evenPagesCheck_stateChanged (int state) { + oddPagesCheck->setEnabled (state == Qt::Checked); } diff --git a/src/Plugins/Qt/QTMPrintDialog.hpp b/src/Plugins/Qt/QTMPrintDialog.hpp index c50800d9cb..77c76a5659 100644 --- a/src/Plugins/Qt/QTMPrintDialog.hpp +++ b/src/Plugins/Qt/QTMPrintDialog.hpp @@ -1,6 +1,6 @@ /****************************************************************************** * MODULE : QTMPrintDialog.hpp - * DESCRIPTION: + * DESCRIPTION: * COPYRIGHT : (C) 2010 Miguel de Benito Delgado ******************************************************************************* * This software falls under the GNU general public license version 3 or later. @@ -16,16 +16,17 @@ ** Created: Sat Dec 18 20:23:41 2010 ** by: Qt User Interface Compiler version 4.7.1 ** - ** WARNING! All changes made in this file will be lost when recompiling UI file! + ** WARNING! All changes made in this file will be lost when recompiling UI + *file! ********************************************************************************/ #ifndef UI_QTMPRINTDIALOG_H #define UI_QTMPRINTDIALOG_H -#include +#include #include #include -#include +#include #include #include #include @@ -44,373 +45,386 @@ QT_BEGIN_NAMESPACE -class Ui_QTMPrintDialog -{ +class Ui_QTMPrintDialog { public: - QVBoxLayout *verticalLayout; - QGridLayout *gridLayout_3; - QComboBox *printerCombo; - QLabel *label_3; - QLineEdit *copiesInput; - QCheckBox *collatedCheck; - QHBoxLayout *horizontalLayout_2; - QGridLayout *gridLayout_2; - QLabel *label_7; - QRadioButton *allPagesRadio; - QRadioButton *rangePagesRadio; - QLineEdit *fromPageInput; - QLabel *label_4; - QLineEdit *toPageInput; - QCheckBox *evenPagesCheck; - QCheckBox *oddPagesCheck; - QFrame *line; - QHBoxLayout *horizontalLayout; - QSpacerItem *horizontalSpacer_2; - QGridLayout *gridLayout; - QLabel *paperSizeLabel; - QComboBox *paperSizeCombo; - QLabel *label_2; - QComboBox *orientationCombo; - QLabel *resolutionLabel; - QComboBox *resolutionCombo; - QSpacerItem *horizontalSpacer; - QHBoxLayout *horizontalLayout_3; - QSpacerItem *horizontalSpacer_3; - QCheckBox *duplexCheck; - QSpacerItem *horizontalSpacer_5; - QCheckBox *fitToPageCheck; - QSpacerItem *horizontalSpacer_4; - QGridLayout *gridLayout_4; - QLabel *label_5; - QComboBox *pagesPerSideCombo; - QLabel *label_6; - QComboBox *orderPagesCombo; - QFrame *line_2; - QCheckBox *blackWhiteCheck; - QDialogButtonBox *buttonBox; - - void setupUi(QDialog *QTMPrintDialog) - { - if (QTMPrintDialog->objectName().isEmpty()) - QTMPrintDialog->setObjectName(QString::fromUtf8("QTMPrintDialog")); - QTMPrintDialog->setWindowModality(Qt::WindowModal); - QTMPrintDialog->resize(527, 475); - QTMPrintDialog->setMinimumSize(QSize(527, 475)); - QTMPrintDialog->setWindowOpacity(1); - QTMPrintDialog->setLocale(QLocale(QLocale::English, QLocale::UnitedStates)); - QTMPrintDialog->setSizeGripEnabled(true); - QTMPrintDialog->setModal(true); - verticalLayout = new QVBoxLayout(QTMPrintDialog); - verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); - gridLayout_3 = new QGridLayout(); - gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3")); - printerCombo = new QComboBox(QTMPrintDialog); - printerCombo->setObjectName(QString::fromUtf8("printerCombo")); - printerCombo->setMinimumSize(QSize(331, 26)); - - gridLayout_3->addWidget(printerCombo, 0, 0, 1, 3); - - label_3 = new QLabel(QTMPrintDialog); - label_3->setObjectName(QString::fromUtf8("label_3")); - - gridLayout_3->addWidget(label_3, 1, 0, 1, 1); - - copiesInput = new QLineEdit(QTMPrintDialog); - copiesInput->setObjectName(QString::fromUtf8("copiesInput")); - copiesInput->setMaximumSize(QSize(81, 16777215)); - - gridLayout_3->addWidget(copiesInput, 1, 1, 1, 1); - - collatedCheck = new QCheckBox(QTMPrintDialog); - collatedCheck->setObjectName(QString::fromUtf8("collatedCheck")); - collatedCheck->setEnabled(false); - collatedCheck->setChecked(true); - - gridLayout_3->addWidget(collatedCheck, 1, 2, 1, 1); - - - verticalLayout->addLayout(gridLayout_3); - - horizontalLayout_2 = new QHBoxLayout(); - horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); - gridLayout_2 = new QGridLayout(); - gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")); - label_7 = new QLabel(QTMPrintDialog); - label_7->setObjectName(QString::fromUtf8("label_7")); - - gridLayout_2->addWidget(label_7, 0, 0, 1, 1); - - allPagesRadio = new QRadioButton(QTMPrintDialog); - allPagesRadio->setObjectName(QString::fromUtf8("allPagesRadio")); - allPagesRadio->setChecked(true); - - gridLayout_2->addWidget(allPagesRadio, 0, 1, 1, 1); - - rangePagesRadio = new QRadioButton(QTMPrintDialog); - rangePagesRadio->setObjectName(QString::fromUtf8("rangePagesRadio")); - - gridLayout_2->addWidget(rangePagesRadio, 1, 1, 1, 1); - - fromPageInput = new QLineEdit(QTMPrintDialog); - fromPageInput->setObjectName(QString::fromUtf8("fromPageInput")); - QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(fromPageInput->sizePolicy().hasHeightForWidth()); - fromPageInput->setSizePolicy(sizePolicy); - fromPageInput->setMaximumSize(QSize(81, 22)); - - gridLayout_2->addWidget(fromPageInput, 1, 2, 1, 1); - - label_4 = new QLabel(QTMPrintDialog); - label_4->setObjectName(QString::fromUtf8("label_4")); - - gridLayout_2->addWidget(label_4, 1, 3, 1, 1); - - toPageInput = new QLineEdit(QTMPrintDialog); - toPageInput->setObjectName(QString::fromUtf8("toPageInput")); - toPageInput->setMaximumSize(QSize(81, 22)); - - gridLayout_2->addWidget(toPageInput, 1, 4, 1, 1); - - evenPagesCheck = new QCheckBox(QTMPrintDialog); - evenPagesCheck->setObjectName(QString::fromUtf8("evenPagesCheck")); - evenPagesCheck->setChecked(true); - - gridLayout_2->addWidget(evenPagesCheck, 0, 2, 1, 1); - - oddPagesCheck = new QCheckBox(QTMPrintDialog); - oddPagesCheck->setObjectName(QString::fromUtf8("oddPagesCheck")); - oddPagesCheck->setChecked(true); - - gridLayout_2->addWidget(oddPagesCheck, 0, 4, 1, 1); - - - horizontalLayout_2->addLayout(gridLayout_2); - - - verticalLayout->addLayout(horizontalLayout_2); - - line = new QFrame(QTMPrintDialog); - line->setObjectName(QString::fromUtf8("line")); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - - verticalLayout->addWidget(line); - - horizontalLayout = new QHBoxLayout(); - horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); - horizontalSpacer_2 = new QSpacerItem(30, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout->addItem(horizontalSpacer_2); - - gridLayout = new QGridLayout(); - gridLayout->setObjectName(QString::fromUtf8("gridLayout")); - paperSizeLabel = new QLabel(QTMPrintDialog); - paperSizeLabel->setObjectName(QString::fromUtf8("paperSizeLabel")); - - gridLayout->addWidget(paperSizeLabel, 0, 0, 1, 1); - - paperSizeCombo = new QComboBox(QTMPrintDialog); - paperSizeCombo->setObjectName(QString::fromUtf8("paperSizeCombo")); - paperSizeCombo->setMinimumSize(QSize(200, 26)); - - gridLayout->addWidget(paperSizeCombo, 0, 1, 1, 1); - - label_2 = new QLabel(QTMPrintDialog); - label_2->setObjectName(QString::fromUtf8("label_2")); - - gridLayout->addWidget(label_2, 1, 0, 1, 1); - - orientationCombo = new QComboBox(QTMPrintDialog); - orientationCombo->setObjectName(QString::fromUtf8("orientationCombo")); - orientationCombo->setMinimumSize(QSize(200, 26)); - - gridLayout->addWidget(orientationCombo, 1, 1, 1, 1); - - resolutionLabel = new QLabel(QTMPrintDialog); - resolutionLabel->setObjectName(QString::fromUtf8("resolutionLabel")); - - gridLayout->addWidget(resolutionLabel, 2, 0, 1, 1); - - resolutionCombo = new QComboBox(QTMPrintDialog); - resolutionCombo->setObjectName(QString::fromUtf8("resolutionCombo")); - resolutionCombo->setMinimumSize(QSize(200, 26)); - - gridLayout->addWidget(resolutionCombo, 2, 1, 1, 1); - - - horizontalLayout->addLayout(gridLayout); - - horizontalSpacer = new QSpacerItem(30, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout->addItem(horizontalSpacer); - - - verticalLayout->addLayout(horizontalLayout); - - horizontalLayout_3 = new QHBoxLayout(); - horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); - horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_3->addItem(horizontalSpacer_3); - - duplexCheck = new QCheckBox(QTMPrintDialog); - duplexCheck->setObjectName(QString::fromUtf8("duplexCheck")); - duplexCheck->setEnabled(false); - duplexCheck->setMinimumSize(QSize(0, 31)); - duplexCheck->setLocale(QLocale(QLocale::English, QLocale::UnitedStates)); - - horizontalLayout_3->addWidget(duplexCheck); - - horizontalSpacer_5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_3->addItem(horizontalSpacer_5); - - fitToPageCheck = new QCheckBox(QTMPrintDialog); - fitToPageCheck->setObjectName(QString::fromUtf8("fitToPageCheck")); - fitToPageCheck->setChecked(true); - - horizontalLayout_3->addWidget(fitToPageCheck); - - horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_3->addItem(horizontalSpacer_4); - - - verticalLayout->addLayout(horizontalLayout_3); - - gridLayout_4 = new QGridLayout(); - gridLayout_4->setObjectName(QString::fromUtf8("gridLayout_4")); - label_5 = new QLabel(QTMPrintDialog); - label_5->setObjectName(QString::fromUtf8("label_5")); - - gridLayout_4->addWidget(label_5, 0, 0, 1, 1); - - pagesPerSideCombo = new QComboBox(QTMPrintDialog); - pagesPerSideCombo->setObjectName(QString::fromUtf8("pagesPerSideCombo")); - - gridLayout_4->addWidget(pagesPerSideCombo, 0, 1, 1, 1); - - label_6 = new QLabel(QTMPrintDialog); - label_6->setObjectName(QString::fromUtf8("label_6")); - - gridLayout_4->addWidget(label_6, 1, 0, 1, 1); - - orderPagesCombo = new QComboBox(QTMPrintDialog); - orderPagesCombo->setObjectName(QString::fromUtf8("orderPagesCombo")); - orderPagesCombo->setMinimumSize(QSize(211, 26)); - - gridLayout_4->addWidget(orderPagesCombo, 1, 1, 1, 1); - - - verticalLayout->addLayout(gridLayout_4); - - line_2 = new QFrame(QTMPrintDialog); - line_2->setObjectName(QString::fromUtf8("line_2")); - line_2->setFrameShape(QFrame::HLine); - line_2->setFrameShadow(QFrame::Sunken); - - verticalLayout->addWidget(line_2); - - blackWhiteCheck = new QCheckBox(QTMPrintDialog); - blackWhiteCheck->setObjectName(QString::fromUtf8("blackWhiteCheck")); - blackWhiteCheck->setEnabled(false); - blackWhiteCheck->setChecked(true); - - verticalLayout->addWidget(blackWhiteCheck); - - buttonBox = new QDialogButtonBox(QTMPrintDialog); - buttonBox->setObjectName(QString::fromUtf8("buttonBox")); - buttonBox->setOrientation(Qt::Horizontal); - buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); - - verticalLayout->addWidget(buttonBox); - + QVBoxLayout* verticalLayout; + QGridLayout* gridLayout_3; + QComboBox* printerCombo; + QLabel* label_3; + QLineEdit* copiesInput; + QCheckBox* collatedCheck; + QHBoxLayout* horizontalLayout_2; + QGridLayout* gridLayout_2; + QLabel* label_7; + QRadioButton* allPagesRadio; + QRadioButton* rangePagesRadio; + QLineEdit* fromPageInput; + QLabel* label_4; + QLineEdit* toPageInput; + QCheckBox* evenPagesCheck; + QCheckBox* oddPagesCheck; + QFrame* line; + QHBoxLayout* horizontalLayout; + QSpacerItem* horizontalSpacer_2; + QGridLayout* gridLayout; + QLabel* paperSizeLabel; + QComboBox* paperSizeCombo; + QLabel* label_2; + QComboBox* orientationCombo; + QLabel* resolutionLabel; + QComboBox* resolutionCombo; + QSpacerItem* horizontalSpacer; + QHBoxLayout* horizontalLayout_3; + QSpacerItem* horizontalSpacer_3; + QCheckBox* duplexCheck; + QSpacerItem* horizontalSpacer_5; + QCheckBox* fitToPageCheck; + QSpacerItem* horizontalSpacer_4; + QGridLayout* gridLayout_4; + QLabel* label_5; + QComboBox* pagesPerSideCombo; + QLabel* label_6; + QComboBox* orderPagesCombo; + QFrame* line_2; + QCheckBox* blackWhiteCheck; + QDialogButtonBox* buttonBox; + + void setupUi (QDialog* QTMPrintDialog) { + if (QTMPrintDialog->objectName ().isEmpty ()) + QTMPrintDialog->setObjectName (QString::fromUtf8 ("QTMPrintDialog")); + QTMPrintDialog->setWindowModality (Qt::WindowModal); + QTMPrintDialog->resize (527, 475); + QTMPrintDialog->setMinimumSize (QSize (527, 475)); + QTMPrintDialog->setWindowOpacity (1); + QTMPrintDialog->setLocale ( + QLocale (QLocale::English, QLocale::UnitedStates)); + QTMPrintDialog->setSizeGripEnabled (true); + QTMPrintDialog->setModal (true); + verticalLayout= new QVBoxLayout (QTMPrintDialog); + verticalLayout->setObjectName (QString::fromUtf8 ("verticalLayout")); + gridLayout_3= new QGridLayout (); + gridLayout_3->setObjectName (QString::fromUtf8 ("gridLayout_3")); + printerCombo= new QComboBox (QTMPrintDialog); + printerCombo->setObjectName (QString::fromUtf8 ("printerCombo")); + printerCombo->setMinimumSize (QSize (331, 26)); + + gridLayout_3->addWidget (printerCombo, 0, 0, 1, 3); + + label_3= new QLabel (QTMPrintDialog); + label_3->setObjectName (QString::fromUtf8 ("label_3")); + + gridLayout_3->addWidget (label_3, 1, 0, 1, 1); + + copiesInput= new QLineEdit (QTMPrintDialog); + copiesInput->setObjectName (QString::fromUtf8 ("copiesInput")); + copiesInput->setMaximumSize (QSize (81, 16777215)); + + gridLayout_3->addWidget (copiesInput, 1, 1, 1, 1); + + collatedCheck= new QCheckBox (QTMPrintDialog); + collatedCheck->setObjectName (QString::fromUtf8 ("collatedCheck")); + collatedCheck->setEnabled (false); + collatedCheck->setChecked (true); + + gridLayout_3->addWidget (collatedCheck, 1, 2, 1, 1); + + verticalLayout->addLayout (gridLayout_3); + + horizontalLayout_2= new QHBoxLayout (); + horizontalLayout_2->setObjectName ( + QString::fromUtf8 ("horizontalLayout_2")); + gridLayout_2= new QGridLayout (); + gridLayout_2->setObjectName (QString::fromUtf8 ("gridLayout_2")); + label_7= new QLabel (QTMPrintDialog); + label_7->setObjectName (QString::fromUtf8 ("label_7")); + + gridLayout_2->addWidget (label_7, 0, 0, 1, 1); + + allPagesRadio= new QRadioButton (QTMPrintDialog); + allPagesRadio->setObjectName (QString::fromUtf8 ("allPagesRadio")); + allPagesRadio->setChecked (true); + + gridLayout_2->addWidget (allPagesRadio, 0, 1, 1, 1); + + rangePagesRadio= new QRadioButton (QTMPrintDialog); + rangePagesRadio->setObjectName (QString::fromUtf8 ("rangePagesRadio")); + + gridLayout_2->addWidget (rangePagesRadio, 1, 1, 1, 1); + + fromPageInput= new QLineEdit (QTMPrintDialog); + fromPageInput->setObjectName (QString::fromUtf8 ("fromPageInput")); + QSizePolicy sizePolicy (QSizePolicy::Preferred, QSizePolicy::Fixed); + sizePolicy.setHorizontalStretch (0); + sizePolicy.setVerticalStretch (0); + sizePolicy.setHeightForWidth ( + fromPageInput->sizePolicy ().hasHeightForWidth ()); + fromPageInput->setSizePolicy (sizePolicy); + fromPageInput->setMaximumSize (QSize (81, 22)); + + gridLayout_2->addWidget (fromPageInput, 1, 2, 1, 1); + + label_4= new QLabel (QTMPrintDialog); + label_4->setObjectName (QString::fromUtf8 ("label_4")); + + gridLayout_2->addWidget (label_4, 1, 3, 1, 1); + + toPageInput= new QLineEdit (QTMPrintDialog); + toPageInput->setObjectName (QString::fromUtf8 ("toPageInput")); + toPageInput->setMaximumSize (QSize (81, 22)); + + gridLayout_2->addWidget (toPageInput, 1, 4, 1, 1); + + evenPagesCheck= new QCheckBox (QTMPrintDialog); + evenPagesCheck->setObjectName (QString::fromUtf8 ("evenPagesCheck")); + evenPagesCheck->setChecked (true); + + gridLayout_2->addWidget (evenPagesCheck, 0, 2, 1, 1); + + oddPagesCheck= new QCheckBox (QTMPrintDialog); + oddPagesCheck->setObjectName (QString::fromUtf8 ("oddPagesCheck")); + oddPagesCheck->setChecked (true); + + gridLayout_2->addWidget (oddPagesCheck, 0, 4, 1, 1); + + horizontalLayout_2->addLayout (gridLayout_2); + + verticalLayout->addLayout (horizontalLayout_2); + + line= new QFrame (QTMPrintDialog); + line->setObjectName (QString::fromUtf8 ("line")); + line->setFrameShape (QFrame::HLine); + line->setFrameShadow (QFrame::Sunken); + + verticalLayout->addWidget (line); + + horizontalLayout= new QHBoxLayout (); + horizontalLayout->setObjectName (QString::fromUtf8 ("horizontalLayout")); + horizontalSpacer_2= + new QSpacerItem (30, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + + horizontalLayout->addItem (horizontalSpacer_2); + + gridLayout= new QGridLayout (); + gridLayout->setObjectName (QString::fromUtf8 ("gridLayout")); + paperSizeLabel= new QLabel (QTMPrintDialog); + paperSizeLabel->setObjectName (QString::fromUtf8 ("paperSizeLabel")); + + gridLayout->addWidget (paperSizeLabel, 0, 0, 1, 1); + + paperSizeCombo= new QComboBox (QTMPrintDialog); + paperSizeCombo->setObjectName (QString::fromUtf8 ("paperSizeCombo")); + paperSizeCombo->setMinimumSize (QSize (200, 26)); + + gridLayout->addWidget (paperSizeCombo, 0, 1, 1, 1); + + label_2= new QLabel (QTMPrintDialog); + label_2->setObjectName (QString::fromUtf8 ("label_2")); + + gridLayout->addWidget (label_2, 1, 0, 1, 1); + + orientationCombo= new QComboBox (QTMPrintDialog); + orientationCombo->setObjectName (QString::fromUtf8 ("orientationCombo")); + orientationCombo->setMinimumSize (QSize (200, 26)); + + gridLayout->addWidget (orientationCombo, 1, 1, 1, 1); + + resolutionLabel= new QLabel (QTMPrintDialog); + resolutionLabel->setObjectName (QString::fromUtf8 ("resolutionLabel")); + + gridLayout->addWidget (resolutionLabel, 2, 0, 1, 1); + + resolutionCombo= new QComboBox (QTMPrintDialog); + resolutionCombo->setObjectName (QString::fromUtf8 ("resolutionCombo")); + resolutionCombo->setMinimumSize (QSize (200, 26)); + + gridLayout->addWidget (resolutionCombo, 2, 1, 1, 1); + + horizontalLayout->addLayout (gridLayout); + + horizontalSpacer= + new QSpacerItem (30, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + + horizontalLayout->addItem (horizontalSpacer); + + verticalLayout->addLayout (horizontalLayout); + + horizontalLayout_3= new QHBoxLayout (); + horizontalLayout_3->setObjectName ( + QString::fromUtf8 ("horizontalLayout_3")); + horizontalSpacer_3= + new QSpacerItem (40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + + horizontalLayout_3->addItem (horizontalSpacer_3); + + duplexCheck= new QCheckBox (QTMPrintDialog); + duplexCheck->setObjectName (QString::fromUtf8 ("duplexCheck")); + duplexCheck->setEnabled (false); + duplexCheck->setMinimumSize (QSize (0, 31)); + duplexCheck->setLocale (QLocale (QLocale::English, QLocale::UnitedStates)); + + horizontalLayout_3->addWidget (duplexCheck); + + horizontalSpacer_5= + new QSpacerItem (40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + + horizontalLayout_3->addItem (horizontalSpacer_5); + + fitToPageCheck= new QCheckBox (QTMPrintDialog); + fitToPageCheck->setObjectName (QString::fromUtf8 ("fitToPageCheck")); + fitToPageCheck->setChecked (true); + + horizontalLayout_3->addWidget (fitToPageCheck); + + horizontalSpacer_4= + new QSpacerItem (40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + + horizontalLayout_3->addItem (horizontalSpacer_4); + + verticalLayout->addLayout (horizontalLayout_3); + + gridLayout_4= new QGridLayout (); + gridLayout_4->setObjectName (QString::fromUtf8 ("gridLayout_4")); + label_5= new QLabel (QTMPrintDialog); + label_5->setObjectName (QString::fromUtf8 ("label_5")); + + gridLayout_4->addWidget (label_5, 0, 0, 1, 1); + + pagesPerSideCombo= new QComboBox (QTMPrintDialog); + pagesPerSideCombo->setObjectName (QString::fromUtf8 ("pagesPerSideCombo")); + + gridLayout_4->addWidget (pagesPerSideCombo, 0, 1, 1, 1); + + label_6= new QLabel (QTMPrintDialog); + label_6->setObjectName (QString::fromUtf8 ("label_6")); + + gridLayout_4->addWidget (label_6, 1, 0, 1, 1); + + orderPagesCombo= new QComboBox (QTMPrintDialog); + orderPagesCombo->setObjectName (QString::fromUtf8 ("orderPagesCombo")); + orderPagesCombo->setMinimumSize (QSize (211, 26)); + + gridLayout_4->addWidget (orderPagesCombo, 1, 1, 1, 1); + + verticalLayout->addLayout (gridLayout_4); + + line_2= new QFrame (QTMPrintDialog); + line_2->setObjectName (QString::fromUtf8 ("line_2")); + line_2->setFrameShape (QFrame::HLine); + line_2->setFrameShadow (QFrame::Sunken); + + verticalLayout->addWidget (line_2); + + blackWhiteCheck= new QCheckBox (QTMPrintDialog); + blackWhiteCheck->setObjectName (QString::fromUtf8 ("blackWhiteCheck")); + blackWhiteCheck->setEnabled (false); + blackWhiteCheck->setChecked (true); + + verticalLayout->addWidget (blackWhiteCheck); + + buttonBox= new QDialogButtonBox (QTMPrintDialog); + buttonBox->setObjectName (QString::fromUtf8 ("buttonBox")); + buttonBox->setOrientation (Qt::Horizontal); + buttonBox->setStandardButtons (QDialogButtonBox::Cancel | + QDialogButtonBox::Ok); + + verticalLayout->addWidget (buttonBox); + #ifndef QT_NO_SHORTCUT - label_3->setBuddy(copiesInput); - label_7->setBuddy(allPagesRadio); - label_4->setBuddy(toPageInput); - paperSizeLabel->setBuddy(paperSizeCombo); - label_2->setBuddy(orientationCombo); - resolutionLabel->setBuddy(resolutionCombo); - label_5->setBuddy(pagesPerSideCombo); - label_6->setBuddy(orderPagesCombo); + label_3->setBuddy (copiesInput); + label_7->setBuddy (allPagesRadio); + label_4->setBuddy (toPageInput); + paperSizeLabel->setBuddy (paperSizeCombo); + label_2->setBuddy (orientationCombo); + resolutionLabel->setBuddy (resolutionCombo); + label_5->setBuddy (pagesPerSideCombo); + label_6->setBuddy (orderPagesCombo); #endif // QT_NO_SHORTCUT - QWidget::setTabOrder(printerCombo, copiesInput); - QWidget::setTabOrder(copiesInput, allPagesRadio); - QWidget::setTabOrder(allPagesRadio, rangePagesRadio); - QWidget::setTabOrder(rangePagesRadio, fromPageInput); - QWidget::setTabOrder(fromPageInput, toPageInput); - QWidget::setTabOrder(toPageInput, evenPagesCheck); - QWidget::setTabOrder(evenPagesCheck, oddPagesCheck); - QWidget::setTabOrder(oddPagesCheck, collatedCheck); - QWidget::setTabOrder(collatedCheck, paperSizeCombo); - QWidget::setTabOrder(paperSizeCombo, orientationCombo); - QWidget::setTabOrder(orientationCombo, resolutionCombo); - QWidget::setTabOrder(resolutionCombo, duplexCheck); - QWidget::setTabOrder(duplexCheck, fitToPageCheck); - QWidget::setTabOrder(fitToPageCheck, pagesPerSideCombo); - QWidget::setTabOrder(pagesPerSideCombo, orderPagesCombo); - QWidget::setTabOrder(orderPagesCombo, blackWhiteCheck); - QWidget::setTabOrder(blackWhiteCheck, buttonBox); - - retranslateUi(QTMPrintDialog); - QObject::connect(buttonBox, SIGNAL(accepted()), QTMPrintDialog, SLOT(accept())); - QObject::connect(buttonBox, SIGNAL(rejected()), QTMPrintDialog, SLOT(reject())); - - QMetaObject::connectSlotsByName(QTMPrintDialog); + QWidget::setTabOrder (printerCombo, copiesInput); + QWidget::setTabOrder (copiesInput, allPagesRadio); + QWidget::setTabOrder (allPagesRadio, rangePagesRadio); + QWidget::setTabOrder (rangePagesRadio, fromPageInput); + QWidget::setTabOrder (fromPageInput, toPageInput); + QWidget::setTabOrder (toPageInput, evenPagesCheck); + QWidget::setTabOrder (evenPagesCheck, oddPagesCheck); + QWidget::setTabOrder (oddPagesCheck, collatedCheck); + QWidget::setTabOrder (collatedCheck, paperSizeCombo); + QWidget::setTabOrder (paperSizeCombo, orientationCombo); + QWidget::setTabOrder (orientationCombo, resolutionCombo); + QWidget::setTabOrder (resolutionCombo, duplexCheck); + QWidget::setTabOrder (duplexCheck, fitToPageCheck); + QWidget::setTabOrder (fitToPageCheck, pagesPerSideCombo); + QWidget::setTabOrder (pagesPerSideCombo, orderPagesCombo); + QWidget::setTabOrder (orderPagesCombo, blackWhiteCheck); + QWidget::setTabOrder (blackWhiteCheck, buttonBox); + + retranslateUi (QTMPrintDialog); + QObject::connect (buttonBox, SIGNAL (accepted ()), QTMPrintDialog, + SLOT (accept ())); + QObject::connect (buttonBox, SIGNAL (rejected ()), QTMPrintDialog, + SLOT (reject ())); + + QMetaObject::connectSlotsByName (QTMPrintDialog); } // setupUi - - void retranslateUi(QDialog *QTMPrintDialog) - { - QTMPrintDialog->setWindowTitle(QApplication::translate("QTMPrintDialog", "Print", 0)); - label_3->setText(QApplication::translate("QTMPrintDialog", "Copies:", 0)); - copiesInput->setText(QApplication::translate("QTMPrintDialog", "1", 0)); - collatedCheck->setText(QApplication::translate("QTMPrintDialog", "Collated", 0)); - label_7->setText(QApplication::translate("QTMPrintDialog", "Pages:", 0)); - allPagesRadio->setText(QApplication::translate("QTMPrintDialog", "All", 0)); - rangePagesRadio->setText(QApplication::translate("QTMPrintDialog", "From:", 0)); - fromPageInput->setText(QApplication::translate("QTMPrintDialog", "1", 0)); - label_4->setText(QApplication::translate("QTMPrintDialog", "To:", 0)); - toPageInput->setText(QApplication::translate("QTMPrintDialog", "1", 0)); - evenPagesCheck->setText(QApplication::translate("QTMPrintDialog", "Even", 0)); - oddPagesCheck->setText(QApplication::translate("QTMPrintDialog", "Odd", 0)); - paperSizeLabel->setText(QApplication::translate("QTMPrintDialog", "Paper size:", 0)); - label_2->setText(QApplication::translate("QTMPrintDialog", "Orientation:", 0)); - resolutionLabel->setText(QApplication::translate("QTMPrintDialog", "Resolution:", 0)); - duplexCheck->setText(QApplication::translate("QTMPrintDialog", "Print on both sides", 0)); - fitToPageCheck->setText(QApplication::translate("QTMPrintDialog", "Fit to page", 0)); - label_5->setText(QApplication::translate("QTMPrintDialog", "Pages per side:", 0)); - pagesPerSideCombo->clear(); - pagesPerSideCombo->insertItems(0, QStringList() - << QApplication::translate("QTMPrintDialog", "1", 0) - << QApplication::translate("QTMPrintDialog", "2", 0) - << QApplication::translate("QTMPrintDialog", "4", 0) - << QApplication::translate("QTMPrintDialog", "6", 0) - << QApplication::translate("QTMPrintDialog", "9", 0) - << QApplication::translate("QTMPrintDialog", "16", 0) - ); - label_6->setText(QApplication::translate("QTMPrintDialog", "Order:", 0)); - blackWhiteCheck->setText(QApplication::translate("QTMPrintDialog", "Print in black and white", 0)); + + void retranslateUi (QDialog* QTMPrintDialog) { + QTMPrintDialog->setWindowTitle ( + QApplication::translate ("QTMPrintDialog", "Print", 0)); + label_3->setText (QApplication::translate ("QTMPrintDialog", "Copies:", 0)); + copiesInput->setText (QApplication::translate ("QTMPrintDialog", "1", 0)); + collatedCheck->setText ( + QApplication::translate ("QTMPrintDialog", "Collated", 0)); + label_7->setText (QApplication::translate ("QTMPrintDialog", "Pages:", 0)); + allPagesRadio->setText ( + QApplication::translate ("QTMPrintDialog", "All", 0)); + rangePagesRadio->setText ( + QApplication::translate ("QTMPrintDialog", "From:", 0)); + fromPageInput->setText (QApplication::translate ("QTMPrintDialog", "1", 0)); + label_4->setText (QApplication::translate ("QTMPrintDialog", "To:", 0)); + toPageInput->setText (QApplication::translate ("QTMPrintDialog", "1", 0)); + evenPagesCheck->setText ( + QApplication::translate ("QTMPrintDialog", "Even", 0)); + oddPagesCheck->setText ( + QApplication::translate ("QTMPrintDialog", "Odd", 0)); + paperSizeLabel->setText ( + QApplication::translate ("QTMPrintDialog", "Paper size:", 0)); + label_2->setText ( + QApplication::translate ("QTMPrintDialog", "Orientation:", 0)); + resolutionLabel->setText ( + QApplication::translate ("QTMPrintDialog", "Resolution:", 0)); + duplexCheck->setText ( + QApplication::translate ("QTMPrintDialog", "Print on both sides", 0)); + fitToPageCheck->setText ( + QApplication::translate ("QTMPrintDialog", "Fit to page", 0)); + label_5->setText ( + QApplication::translate ("QTMPrintDialog", "Pages per side:", 0)); + pagesPerSideCombo->clear (); + pagesPerSideCombo->insertItems ( + 0, + QStringList () << QApplication::translate ("QTMPrintDialog", "1", 0) + << QApplication::translate ("QTMPrintDialog", "2", 0) + << QApplication::translate ("QTMPrintDialog", "4", 0) + << QApplication::translate ("QTMPrintDialog", "6", 0) + << QApplication::translate ("QTMPrintDialog", "9", 0) + << QApplication::translate ("QTMPrintDialog", "16", 0)); + label_6->setText (QApplication::translate ("QTMPrintDialog", "Order:", 0)); + blackWhiteCheck->setText (QApplication::translate ( + "QTMPrintDialog", "Print in black and white", 0)); } // retranslateUi - }; namespace Ui { - class QTMPrintDialog: public Ui_QTMPrintDialog {}; +class QTMPrintDialog : public Ui_QTMPrintDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_QTMPRINTDIALOG_H - #ifndef QTMPRINTDIALOG_HPP #define QTMPRINTDIALOG_HPP #include -//#include "ui_QTMPrintdialog.h" // life's sad without uic... +// #include "ui_QTMPrintdialog.h" // life's sad without uic... #include "QTMPrinterSettings.hpp" class QPrinter; @@ -422,29 +436,28 @@ class QPrinter; * native print dialogs are not configurable and expect features we cannot * implement: how to know if under MacOS the user selected "send per email"? */ -class QTMPrintDialog : public QDialog, protected Ui::QTMPrintDialog -{ +class QTMPrintDialog : public QDialog, protected Ui::QTMPrintDialog { Q_OBJECT - + public: - QTMPrintDialog(QTMPrinterSettings* s, QDialog* parent=0); - void setupUi(QDialog *dia); + QTMPrintDialog (QTMPrinterSettings* s, QDialog* parent= 0); + void setupUi (QDialog* dia); public slots: - void accept(); - void reject(); - + void accept (); + void reject (); + protected slots: - void updatePrinterCapabilities(); + void updatePrinterCapabilities (); // Auto connections: - void on_allPagesRadio_clicked(bool); - void on_rangePagesRadio_clicked(bool); - void on_copiesInput_textChanged(const QString& ); - void on_fromPageInput_textChanged(const QString& ); - void on_toPageInput_textChanged(const QString& ); - void on_oddPagesCheck_stateChanged(int state); - void on_evenPagesCheck_stateChanged(int state); - + void on_allPagesRadio_clicked (bool); + void on_rangePagesRadio_clicked (bool); + void on_copiesInput_textChanged (const QString&); + void on_fromPageInput_textChanged (const QString&); + void on_toPageInput_textChanged (const QString&); + void on_oddPagesCheck_stateChanged (int state); + void on_evenPagesCheck_stateChanged (int state); + protected: QTMPrinterSettings* _settings; }; diff --git a/src/Plugins/Qt/QTMPrinterSettings.cpp b/src/Plugins/Qt/QTMPrinterSettings.cpp index 09d3126c7f..bf960e7a60 100644 --- a/src/Plugins/Qt/QTMPrinterSettings.cpp +++ b/src/Plugins/Qt/QTMPrinterSettings.cpp @@ -16,7 +16,7 @@ #include #include #include -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include #else #include @@ -24,17 +24,18 @@ /*! * */ -QTMPrinterSettings::QTMPrinterSettings() -: collateCopies(true), blackWhite(true), printerName(""), fileName(""), - paperSize("A4"), dpi(600), firstPage(0), lastPage(0), printOddPages(true), - printEvenPages(true), fitToPage(true), copyCount(1), duplex(false), - pagesPerSide(1), pagesOrder(LR_TB), orientation(Portrait) -{ - configProgram = new QProcess(this); +QTMPrinterSettings::QTMPrinterSettings () + : collateCopies (true), blackWhite (true), printerName (""), fileName (""), + paperSize ("A4"), dpi (600), firstPage (0), lastPage (0), + printOddPages (true), printEvenPages (true), fitToPage (true), + copyCount (1), duplex (false), pagesPerSide (1), pagesOrder (LR_TB), + orientation (Portrait) { + configProgram= new QProcess (this); // See the class documentation for an explanation of the connected signal - QObject::connect(configProgram, SIGNAL(finished(int, QProcess::ExitStatus)), - this, SLOT(systemCommandFinished(int, QProcess::ExitStatus))); + QObject::connect (configProgram, + SIGNAL (finished (int, QProcess::ExitStatus)), this, + SLOT (systemCommandFinished (int, QProcess::ExitStatus))); } /*! @@ -42,26 +43,27 @@ QTMPrinterSettings::QTMPrinterSettings() * @todo Check this sets all the available parameters. */ void -QTMPrinterSettings::getFromQPrinter(const QPrinter& from) { - printerName = from.printerName (); - fileName = from.outputFileName (); - -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - orientation = (from.orientation() == QPrinter::Landscape) - ? Landscape : Portrait; - paperSize = qtPaperSizeToQString(from.paperSize()); +QTMPrinterSettings::getFromQPrinter (const QPrinter& from) { + printerName= from.printerName (); + fileName = from.outputFileName (); + +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + orientation= + (from.orientation () == QPrinter::Landscape) ? Landscape : Portrait; + paperSize= qtPaperSizeToQString (from.paperSize ()); #else - orientation = (from.pageLayout().orientation() == QPageLayout::Landscape) - ? Landscape : Portrait; - paperSize = qtPaperSizeToQString(from.pageLayout().pageSize().id()); + orientation= (from.pageLayout ().orientation () == QPageLayout::Landscape) + ? Landscape + : Portrait; + paperSize = qtPaperSizeToQString (from.pageLayout ().pageSize ().id ()); #endif - dpi = from.resolution (); - firstPage = from.fromPage (); - lastPage = from.toPage (); - copyCount = from.copyCount (); - collateCopies = from.collateCopies(); - blackWhite = (from.colorMode () == QPrinter::Color); - printProgram = from.printProgram(); + dpi = from.resolution (); + firstPage = from.fromPage (); + lastPage = from.toPage (); + copyCount = from.copyCount (); + collateCopies= from.collateCopies (); + blackWhite = (from.colorMode () == QPrinter::Color); + printProgram = from.printProgram (); } /*! @@ -69,45 +71,68 @@ QTMPrinterSettings::getFromQPrinter(const QPrinter& from) { * @todo Check this sets all the available parameters. */ void -QTMPrinterSettings::setToQPrinter(QPrinter& to) const { - to.setResolution(dpi); - to.setFromTo(firstPage, lastPage); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - to.setOrientation((orientation == Landscape) ? - QPrinter::Landscape : QPrinter::Portrait); - to.setPaperSize(qStringToQtPaperSize(paperSize)); +QTMPrinterSettings::setToQPrinter (QPrinter& to) const { + to.setResolution (dpi); + to.setFromTo (firstPage, lastPage); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + to.setOrientation ((orientation == Landscape) ? QPrinter::Landscape + : QPrinter::Portrait); + to.setPaperSize (qStringToQtPaperSize (paperSize)); #else - QPageLayout pageLayout= to.pageLayout(); - pageLayout.setOrientation((orientation == Landscape) ? - QPageLayout::Landscape : QPageLayout::Portrait); - pageLayout.setPageSize(qStringToQtPaperSize(paperSize)); - to.setPageLayout(pageLayout); + QPageLayout pageLayout= to.pageLayout (); + pageLayout.setOrientation ((orientation == Landscape) + ? QPageLayout::Landscape + : QPageLayout::Portrait); + pageLayout.setPageSize (qStringToQtPaperSize (paperSize)); + to.setPageLayout (pageLayout); #endif - to.setOutputFileName(fileName); - to.setCopyCount(copyCount); - to.setCollateCopies(collateCopies); - to.setColorMode(blackWhite ? QPrinter::Color : QPrinter::GrayScale); + to.setOutputFileName (fileName); + to.setCopyCount (copyCount); + to.setCollateCopies (collateCopies); + to.setColorMode (blackWhite ? QPrinter::Color : QPrinter::GrayScale); } /*! - * Just for internal use, converts QPrinter::PaperSize to a string + * Just for internal use, converts QPrinter::PaperSize to a string * representation. Massimiliano's code. */ QString -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) -QTMPrinterSettings::qtPaperSizeToQString(const QPrinter::PaperSize _size) { -#define PAPER(fmt) case QPrinter::fmt : return "fmt" +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +QTMPrinterSettings::qtPaperSizeToQString (const QPrinter::PaperSize _size) { +#define PAPER(fmt) \ + case QPrinter::fmt: \ + return "fmt" #else -QTMPrinterSettings::qtPaperSizeToQString(const QPageSize::PageSizeId _size) { -#define PAPER(fmt) case QPageSize::fmt : return "fmt" +QTMPrinterSettings::qtPaperSizeToQString (const QPageSize::PageSizeId _size) { +#define PAPER(fmt) \ + case QPageSize::fmt: \ + return "fmt" #endif switch (_size) { - PAPER (A0) ; PAPER (A1) ; PAPER (A2) ; PAPER (A3) ; PAPER (A4) ; - PAPER (A5) ; PAPER (A6) ; PAPER (A7) ; PAPER (A8) ; PAPER (A9) ; - PAPER (B0) ; PAPER (B1) ; PAPER (B2) ; PAPER (B3) ; PAPER (B4) ; - PAPER (B5) ; PAPER (B6) ; PAPER (B7) ; PAPER (B8) ; PAPER (B9) ; - PAPER (B10) ; PAPER (Letter) ; - default: return "A4"; + PAPER (A0); + PAPER (A1); + PAPER (A2); + PAPER (A3); + PAPER (A4); + PAPER (A5); + PAPER (A6); + PAPER (A7); + PAPER (A8); + PAPER (A9); + PAPER (B0); + PAPER (B1); + PAPER (B2); + PAPER (B3); + PAPER (B4); + PAPER (B5); + PAPER (B6); + PAPER (B7); + PAPER (B8); + PAPER (B9); + PAPER (B10); + PAPER (Letter); + default: + return "A4"; } #undef PAPER } @@ -115,106 +140,121 @@ QTMPrinterSettings::qtPaperSizeToQString(const QPageSize::PageSizeId _size) { /*! * Just for internal use, converts a string to QPrinter::PaperSize. */ -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QPrinter::PaperSize #else QPageSize::PageSizeId #endif -QTMPrinterSettings::qStringToQtPaperSize(const QString& _size) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) -#define PAPER(fmt) if(_size == "fmt") return QPrinter::fmt +QTMPrinterSettings::qStringToQtPaperSize (const QString& _size) { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#define PAPER(fmt) \ + if (_size == "fmt") return QPrinter::fmt #else -#define PAPER(fmt) if(_size == "fmt") return QPageSize::PageSizeId::fmt +#define PAPER(fmt) \ + if (_size == "fmt") return QPageSize::PageSizeId::fmt #endif - PAPER (A0) ; PAPER (A1) ; PAPER (A2) ; PAPER (A3) ; PAPER (A4) ; - PAPER (A5) ; PAPER (A6) ; PAPER (A7) ; PAPER (A8) ; PAPER (A9) ; - PAPER (B0) ; PAPER (B1) ; PAPER (B2) ; PAPER (B3) ; PAPER (B4) ; - PAPER (B5) ; PAPER (B6) ; PAPER (B7) ; PAPER (B8) ; PAPER (B9) ; - PAPER (B10) ; PAPER (Letter) ; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - return QPrinter::A4; // Default + PAPER (A0); + PAPER (A1); + PAPER (A2); + PAPER (A3); + PAPER (A4); + PAPER (A5); + PAPER (A6); + PAPER (A7); + PAPER (A8); + PAPER (A9); + PAPER (B0); + PAPER (B1); + PAPER (B2); + PAPER (B3); + PAPER (B4); + PAPER (B5); + PAPER (B6); + PAPER (B7); + PAPER (B8); + PAPER (B9); + PAPER (B10); + PAPER (Letter); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + return QPrinter::A4; // Default #else - return QPageSize::PageSizeId::A4; // Default + return QPageSize::PageSizeId::A4; // Default #endif #undef PAPER } - /*! * Returns a QStringList with all the available choices reported by the - * printer driver for the setting specified. + * printer driver for the setting specified. * * @param _which Specifies which driver option to query. - * @param _default Will hold the index number (in the returned list) of the + * @param _default Will hold the index number (in the returned list) of the * currently selected value, as reported by the printer driver. */ QStringList -QTMPrinterSettings::getChoices(DriverChoices _which, int& _default) { +QTMPrinterSettings::getChoices (DriverChoices _which, int& _default) { QStringList _ret; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QString::SplitBehavior behavior = QString::SkipEmptyParts; +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QString::SplitBehavior behavior= QString::SkipEmptyParts; #else - Qt::SplitBehavior behavior = Qt::SkipEmptyParts; + Qt::SplitBehavior behavior= Qt::SkipEmptyParts; #endif switch (_which) { - case PageSize: - _ret = printerOptions["PageSize"].split(" ", behavior); - break; - case Resolution: - _ret = printerOptions["Resolution"].split(" ", behavior); - break; - case Duplex: - _ret = printerOptions["Duplex"].split(" ", behavior); - break; - case ColorModel: - _ret = printerOptions["ColorModel"].split(" ", behavior); - break; - case Collate: - _ret = printerOptions["Collate"].split(" ", behavior); - break; + case PageSize: + _ret= printerOptions["PageSize"].split (" ", behavior); + break; + case Resolution: + _ret= printerOptions["Resolution"].split (" ", behavior); + break; + case Duplex: + _ret= printerOptions["Duplex"].split (" ", behavior); + break; + case ColorModel: + _ret= printerOptions["ColorModel"].split (" ", behavior); + break; + case Collate: + _ret= printerOptions["Collate"].split (" ", behavior); + break; } - + // FIXME: this is CUPS specific (marking the default option with an asterisk) - for (int i=0; i<_ret.size(); ++i) - if (_ret[i].trimmed().startsWith("*")) { - _ret[i] = _ret[i].trimmed().remove(0,1); - _default = i; + for (int i= 0; i < _ret.size (); ++i) + if (_ret[i].trimmed ().startsWith ("*")) { + _ret[i] = _ret[i].trimmed ().remove (0, 1); + _default= i; } return _ret; } - #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) /*! * @todo Read the printing program from some configuration file/preference? */ -CupsQTMPrinterSettings::CupsQTMPrinterSettings() : QTMPrinterSettings() { - printProgram = "lp "; +CupsQTMPrinterSettings::CupsQTMPrinterSettings () : QTMPrinterSettings () { + printProgram= "lp "; } /*! - * Runs the lpoptions program and returns. + * Runs the lpoptions program and returns. */ bool -CupsQTMPrinterSettings::fromSystemConfig(const QString& printer) { - if (configProgram->state() != QProcess::NotRunning) - return false; - +CupsQTMPrinterSettings::fromSystemConfig (const QString& printer) { + if (configProgram->state () != QProcess::NotRunning) return false; + // Watch out! the order of the options is relevant! - configProgram->start(QString("lpoptions -p \"%1\" -l").arg(printer)); - //, + configProgram->start (QString ("lpoptions -p \"%1\" -l").arg (printer)); + //, // QStringList() << QString("-p \"%1\"").arg(printer) // << "-l"); - - - printerName = printer; + + printerName= printer; return true; } /*! - * Parses the output of the lpoptions program once it finishes. This + * Parses the output of the lpoptions program once it finishes. This * asynchronous calling of lpoptions is needed because it performs network * calls. The available configuration choices are available as QStringLists * via QTMQTMPrinterSettings::getChoices(). @@ -223,48 +263,48 @@ CupsQTMPrinterSettings::fromSystemConfig(const QString& printer) { * found on CUPS 1.4.5 (systemv/lpoptions.c) A sample of the output * follows: * Resolution/Printer Resolution: *3600x3600dpi 1200x600dpi - * PageSize/Page Size: Letter Legal Executive HalfLetter 4x6 5x7 5x8 *A4 A5 A6 + * PageSize/Page Size: Letter Legal Executive HalfLetter 4x6 5x7 5x8 *A4 A5 A6 * InputSlot/Paper Source: Auto Tray1 Tray2 Tray3 Tray1_Man * Duplex/2-Sided Printing: *None DuplexNoTumble DuplexTumble * Collate/Collate: True *False * ColorModel/Print Color as Gray: Gray *CMYK */ void -CupsQTMPrinterSettings::systemCommandFinished(int exitCode, - QProcess::ExitStatus exitStatus) { +CupsQTMPrinterSettings::systemCommandFinished ( + int exitCode, QProcess::ExitStatus exitStatus) { (void) exitCode; - - printerOptions.clear(); + + printerOptions.clear (); if (exitStatus != QProcess::NormalExit) { - emit doneReading(); + emit doneReading (); return; } -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QRegExp rx("^(\\w+)/(.+):(.*)$"); // Param/Param desc: val1 val2 *default val4 - rx.setMinimal(true); // Non-greedy matching +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QRegExp rx ( + "^(\\w+)/(.+):(.*)$"); // Param/Param desc: val1 val2 *default val4 + rx.setMinimal (true); // Non-greedy matching #else QRegularExpression rx ("^(\\w+)/(.+):(.*)$"); rx.setPatternOptions (QRegularExpression::InvertedGreedinessOption); #endif - QList _lines = configProgram->readAllStandardOutput().split('\n'); + QList _lines= + configProgram->readAllStandardOutput ().split ('\n'); foreach (QString _line, _lines) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - if(rx.indexIn(_line) == -1) // No matches? +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + if (rx.indexIn (_line) == -1) // No matches? continue; // Store for further parsing later, see QTMPrinterSettings::getChoices() - printerOptions[rx.cap(1)] = rx.cap(3); + printerOptions[rx.cap (1)]= rx.cap (3); #else - QRegularExpressionMatch match = rx.match (_line); - if (!match.hasMatch ()) - continue; - printerOptions[match.captured(1)] = match.captured(3); + QRegularExpressionMatch match= rx.match (_line); + if (!match.hasMatch ()) continue; + printerOptions[match.captured (1)]= match.captured (3); #endif } - emit doneReading(); + emit doneReading (); } - /*! * Returns a command string to be run on the shell. It is assumed that CUPS is * available in the machine. Please see @@ -272,106 +312,123 @@ CupsQTMPrinterSettings::systemCommandFinished(int exitCode, * for the list of all CUPS options. */ QString -CupsQTMPrinterSettings::toSystemCommand() const { +CupsQTMPrinterSettings::toSystemCommand () const { QString _cmd; if (from_qstring (printProgram) == "lp ") - _cmd += to_qstring (get_printing_cmd ()) + " "; - - else if (! printProgram.isEmpty()) - _cmd += printProgram; - - if (! printerName.isEmpty()) - _cmd += QString(" -d \"%1\"").arg(printerName); - - _cmd += QString(" -o orientation-requested=%1").arg(orientation); - - if (duplex && (orientation==Landscape || orientation == ReverseLandscape)) - _cmd += " -o sides=two-sided-short-edge"; - else if (duplex && (orientation==Portrait || orientation == ReversePortrait)) - _cmd += " -o sides=two-sided-long-edge"; - - if (fitToPage) - _cmd += " -o fitplot"; + _cmd+= to_qstring (get_printing_cmd ()) + " "; + + else if (!printProgram.isEmpty ()) _cmd+= printProgram; + + if (!printerName.isEmpty ()) _cmd+= QString (" -d \"%1\"").arg (printerName); + + _cmd+= QString (" -o orientation-requested=%1").arg (orientation); + + if (duplex && (orientation == Landscape || orientation == ReverseLandscape)) + _cmd+= " -o sides=two-sided-short-edge"; + else if (duplex && + (orientation == Portrait || orientation == ReversePortrait)) + _cmd+= " -o sides=two-sided-long-edge"; + + if (fitToPage) _cmd+= " -o fitplot"; if (pagesPerSide > 1) { - _cmd += QString(" -o number-up=%1").arg(pagesPerSide); + _cmd+= QString (" -o number-up=%1").arg (pagesPerSide); // -o number-up-layout=string - // specifies the n-up image order in any of eight permutations from btlr + // specifies the n-up image order in any of eight permutations from btlr // (bottom, top, left, right) to tbrl. - _cmd += " -o number-up-layout="; + _cmd+= " -o number-up-layout="; switch (pagesOrder) { - case LR_TB: _cmd += "lrtb"; break; case RL_TB: _cmd += "rltb"; break; - case TB_LR: _cmd += "tblr"; break; case TB_RL: _cmd += "tbrl"; break; - case LR_BT: _cmd += "lrbt"; break; case RL_BT: _cmd += "rlbt"; break; - case BT_LR: _cmd += "btlr"; break; case BT_RL: _cmd += "btrl"; break; - default: _cmd += "lrtb"; break; + case LR_TB: + _cmd+= "lrtb"; + break; + case RL_TB: + _cmd+= "rltb"; + break; + case TB_LR: + _cmd+= "tblr"; + break; + case TB_RL: + _cmd+= "tbrl"; + break; + case LR_BT: + _cmd+= "lrbt"; + break; + case RL_BT: + _cmd+= "rlbt"; + break; + case BT_LR: + _cmd+= "btlr"; + break; + case BT_RL: + _cmd+= "btrl"; + break; + default: + _cmd+= "lrtb"; + break; } } - + // Specifies which pages to print in the document. The list can contain a list // of numbers and ranges (#-#) separated by commas (e.g. 1,3-5,16). // The page numbers refer to the output pages and not the document's original // pages - options like "number-up" can affect the numbering of the pages. if (firstPage != 0 || lastPage != 0) { - int f = (int)floor(firstPage / pagesPerSide); f = (f==0) ? 1 : f; - int l = (int)ceil (lastPage / pagesPerSide); l = (l==0) ? 1 : l; - if (firstPage > lastPage ) - _cmd += " -o outputorder=reverse"; - - _cmd += QString(" -o page-ranges=%1-%2").arg(f).arg(l); + int f= (int) floor (firstPage / pagesPerSide); + f = (f == 0) ? 1 : f; + int l= (int) ceil (lastPage / pagesPerSide); + l = (l == 0) ? 1 : l; + if (firstPage > lastPage) _cmd+= " -o outputorder=reverse"; + + _cmd+= QString (" -o page-ranges=%1-%2").arg (f).arg (l); } - + if (copyCount > 1) { - _cmd += QString(" -o Collate=") + (collateCopies ? "True" : "False"); - _cmd += QString(" -n %1").arg(copyCount); + _cmd+= QString (" -o Collate=") + (collateCopies ? "True" : "False"); + _cmd+= QString (" -n %1").arg (copyCount); } - - if (! printOddPages) - _cmd += " -o page-set=even"; - else if(! printEvenPages) - _cmd += " -o page-set=odd"; - - _cmd += " -- "; // Marks the end of options; use this to print a file whose - // name begins with a dash (-). - _cmd += '"' + fileName + '"'; - + + if (!printOddPages) _cmd+= " -o page-set=even"; + else if (!printEvenPages) _cmd+= " -o page-set=odd"; + + _cmd+= " -- "; // Marks the end of options; use this to print a file whose + // name begins with a dash (-). + _cmd+= '"' + fileName + '"'; + return _cmd; } - /*! * This is a temporary workaround the problem with the names returned for the * printers by QPrinterInfo::availablePrinters(). * @see QTMPrinterSettings::availablePrinters() * @todo Use asynchronous querying. */ -QList > -CupsQTMPrinterSettings::availablePrinters() { - QList > _ret; - QProcess stat(this); - stat.start("lpstat -a"); - if(! stat.waitForFinished(2000)) // 2 sec. +QList> +CupsQTMPrinterSettings::availablePrinters () { + QList> _ret; + QProcess stat (this); + stat.start ("lpstat -a"); + if (!stat.waitForFinished (2000)) // 2 sec. return _ret; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QRegExp rx("^(\\S+) +.*$"); - rx.setMinimal(true); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QRegExp rx ("^(\\S+) +.*$"); + rx.setMinimal (true); #else - QRegularExpression rx("^(\\S+) +.*$"); - rx.setPatternOptions(QRegularExpression::InvertedGreedinessOption); + QRegularExpression rx ("^(\\S+) +.*$"); + rx.setPatternOptions (QRegularExpression::InvertedGreedinessOption); #endif - QList _lines = stat.readAllStandardOutput().split('\n'); + QList _lines= stat.readAllStandardOutput ().split ('\n'); foreach (QString _line, _lines) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - if(rx.indexIn(_line) == -1) // No matches? +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + if (rx.indexIn (_line) == -1) // No matches? continue; - _ret << QPair(rx.cap(1),rx.cap(1)); + _ret << QPair (rx.cap (1), rx.cap (1)); #else - QRegularExpressionMatch match = rx.match (_line); - if (!match.hasMatch ()) - continue; - _ret << QPair(match.captured(1), match.captured(1)); + QRegularExpressionMatch match= rx.match (_line); + if (!match.hasMatch ()) continue; + _ret << QPair (match.captured (1), match.captured (1)); #endif } return _ret; @@ -379,41 +436,41 @@ CupsQTMPrinterSettings::availablePrinters() { #endif -#ifdef Q_OS_WIN +#ifdef Q_OS_WIN /*! - * + * * @todo Read the printing program from some configuration file/preference? */ -WinQTMPrinterSettings::WinQTMPrinterSettings() : QTMPrinterSettings() { +WinQTMPrinterSettings::WinQTMPrinterSettings () : QTMPrinterSettings () { // -sDEVICE=mswinpr2 // Selects the MS Windows printer device. - // + // // -dNoCancel - // Hides the progress dialog, which shows the percent of the document page + // Hides the progress dialog, which shows the percent of the document page // already processed and also provides a cancel button. - //printProgram = "gs -sDEVICE=mswinpr2"; - printProgram = "gsprint"; + // printProgram = "gs -sDEVICE=mswinpr2"; + printProgram= "gsprint"; } /*! * Uses Winprinfo ( @link http://unixwiz.net/tools/winprinfo.html @link ) to * read configuration parameters from the printer. */ -bool -WinQTMPrinterSettings::fromSystemConfig(const QString& printer) { - if (configProgram->state() != QProcess::NotRunning) - return false; +bool +WinQTMPrinterSettings::fromSystemConfig (const QString& printer) { + if (configProgram->state () != QProcess::NotRunning) return false; /* This (untested) alternative uses (wrong) postscript to read printer options - configProgram->start(QString("gs"), QStringList() + configProgram->start(QString("gs"), QStringList() << "-sDEVICE=mswinpr2" << QString("-sOutputFile=\"\\\\spool\\%1\"").arg(printer) << "-c \"currentpagedevice /Duplex get ==\""); */ - + // See the docs for QProcess::start() for the reason behind the triple \" - configProgram->start(QString("winprinfo --printer=\"\"\"%1\"\"\"").arg(printer)); - printerName = printer; + configProgram->start ( + QString ("winprinfo --printer=\"\"\"%1\"\"\"").arg (printer)); + printerName= printer; return true; } @@ -425,63 +482,62 @@ WinQTMPrinterSettings::fromSystemConfig(const QString& printer) { * monochrome/grey */ QString -WinQTMPrinterSettings::toSystemCommand() const { +WinQTMPrinterSettings::toSystemCommand () const { QString _cmd; - - if (! printProgram.isEmpty()) - _cmd += printProgram; - - /* + + if (!printProgram.isEmpty ()) _cmd+= printProgram; + + /* // This (untested) code is for use with the mswinpr2 driver: _cmd += QString(" -sOutputFile=\"\\\\spool\\%1\" ").arg(printerName); _cmd += QString(" -c << /Duplex %1 /Tumble %2 >> setpagedevice"). arg(duplex ? "true" : "false"). - arg((orientation == Landscape || orientation == ReverseLandscape) + arg((orientation == Landscape || orientation == ReverseLandscape) ? "true" : "false"); - + // -f Interprets following non-switch arguments as file names to be executed - // using the normal run command. Since this is the default behavior, + // using the normal run command. Since this is the default behavior, // -f is useful only for terminating the list of tokens for the -c switch. _cmd += QString(" -f \"%1\"").arg(fileName); */ - - _cmd += " -noquery"; // Don't show printer setup dialog. - if (! printerName.isEmpty()) - _cmd += QString(" -printer \"%1\"").arg(printerName); - + _cmd+= " -noquery"; // Don't show printer setup dialog. + + if (!printerName.isEmpty ()) + _cmd+= QString (" -printer \"%1\"").arg (printerName); + if (duplex) - _cmd += QString(" -duplex_%1"). - arg((orientation == Portrait || orientation == ReversePortrait) - ? "vertical" : "horizontal"); + _cmd+= QString (" -duplex_%1") + .arg ((orientation == Portrait || orientation == ReversePortrait) + ? "vertical" + : "horizontal"); else - _cmd += (orientation == Portrait || orientation == ReversePortrait) - ? " -portrait" : " -landscape"; - - if (pagesPerSide > 1) - _cmd += QString(" -copies %1").arg(pagesPerSide); - + _cmd+= (orientation == Portrait || orientation == ReversePortrait) + ? " -portrait" + : " -landscape"; + + if (pagesPerSide > 1) _cmd+= QString (" -copies %1").arg (pagesPerSide); + // Specifies which pages to print in the document. The list can contain a list // of numbers and ranges (#-#) separated by commas (e.g. 1,3-5,16). // The page numbers refer to the output pages and not the document's original // pages - options like "number-up" can affect the numbering of the pages. if (firstPage != 0 || lastPage != 0) { - int f = (int)floor(firstPage / pagesPerSide); f = (f==0) ? 1 : f; - int l = (int)ceil (lastPage / pagesPerSide); l = (l==0) ? 1 : l; + int f= (int) floor (firstPage / pagesPerSide); + f = (f == 0) ? 1 : f; + int l= (int) ceil (lastPage / pagesPerSide); + l = (l == 0) ? 1 : l; // FIXME: what happens if f > l? - _cmd += QString(" -from %1 -to %2").arg(f).arg(l); + _cmd+= QString (" -from %1 -to %2").arg (f).arg (l); } - - if (copyCount > 1) - _cmd += QString(" -copies %1").arg(pagesPerSide); - - if (! printOddPages) - _cmd += " -even"; - else if(! printEvenPages) - _cmd += " -odd"; - - _cmd += '"' + fileName + '"'; - + + if (copyCount > 1) _cmd+= QString (" -copies %1").arg (pagesPerSide); + + if (!printOddPages) _cmd+= " -even"; + else if (!printEvenPages) _cmd+= " -odd"; + + _cmd+= '"' + fileName + '"'; + return _cmd; } @@ -489,114 +545,117 @@ WinQTMPrinterSettings::toSystemCommand() const { * Parses winprinfo output. This is really UGLY. */ void -WinQTMPrinterSettings::systemCommandFinished(int exitCode, - QProcess::ExitStatus exitStatus) { +WinQTMPrinterSettings::systemCommandFinished (int exitCode, + QProcess::ExitStatus exitStatus) { (void) exitCode; - - printerOptions.clear(); - + + printerOptions.clear (); + if (exitStatus != QProcess::NormalExit) { - emit doneReading(); + emit doneReading (); return; } - - int resolutionsCounter = 0; - bool readingSizes = false; - QList _lines = configProgram->readAllStandardOutput().split('\n'); + + int resolutionsCounter= 0; + bool readingSizes = false; + QList _lines= + configProgram->readAllStandardOutput ().split ('\n'); foreach (QString _line, _lines) { // Parse special lines after the DC_ENUMRESOLUTIONS : (see below) if (resolutionsCounter > 0) { --resolutionsCounter; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QRegExp rx2("^.*x=(\\d)+.*y=(\\d)+.*$"); - rx2.setMinimal(true); - if (rx2.indexIn(_line) > -1) - printerOptions["Resolution"] += QString("%1x%2dpi "). - arg(rx2.cap(1)).arg(rx2.cap(2)); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QRegExp rx2 ("^.*x=(\\d)+.*y=(\\d)+.*$"); + rx2.setMinimal (true); + if (rx2.indexIn (_line) > -1) + printerOptions["Resolution"]+= + QString ("%1x%2dpi ").arg (rx2.cap (1)).arg (rx2.cap (2)); #else QRegularExpression rx2 ("^.*x=(\\d)+.*y=(\\d)+.*$"); rx2.setPatternOptions (QRegularExpression::InvertedGreedinessOption); - QRegularExpressionMatch match = rx2.match (_line); - if (match.hasMatch ()){ - printerOptions["Resolution"] += QString("%1x%2dpi "). - arg(match.captured(1)).arg(match.captured(2)); + QRegularExpressionMatch match= rx2.match (_line); + if (match.hasMatch ()) { + printerOptions["Resolution"]+= QString ("%1x%2dpi ") + .arg (match.captured (1)) + .arg (match.captured (2)); } #endif continue; } - if (_line.contains("PAPER SIZES FROM THE DEVMODE")) { - readingSizes = true; - //printerOptions["PaperSize"] = QString(); + if (_line.contains ("PAPER SIZES FROM THE DEVMODE")) { + readingSizes= true; + // printerOptions["PaperSize"] = QString(); continue; } - - // Parse special lines after PAPER SIZES FROM THE DEVMODE : + + // Parse special lines after PAPER SIZES FROM THE DEVMODE : if (readingSizes) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QRegExp rx2("^.*mm *(\\w)+.*$"); // [ 0] 215.90 279.40 mm Letter - rx2.setMinimal(true); - if (rx2.indexIn(_line) > -1) - printerOptions["PaperSize"] += rx2.cap(1); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QRegExp rx2 ("^.*mm *(\\w)+.*$"); // [ 0] 215.90 279.40 mm Letter + rx2.setMinimal (true); + if (rx2.indexIn (_line) > -1) printerOptions["PaperSize"]+= rx2.cap (1); continue; #else QRegularExpression rx2 ("^.*mm *(\\w)+.*$"); rx2.setPatternOptions (QRegularExpression::InvertedGreedinessOption); - QRegularExpressionMatch match = rx2.match (_line); - if (match.hasMatch()) { - printerOptions["PaperSize"] += match.captured(1); + QRegularExpressionMatch match= rx2.match (_line); + if (match.hasMatch ()) { + printerOptions["PaperSize"]+= match.captured (1); } continue; #endif } -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QRegExp rx("^ *DC_(\\w+) *(\\w+) *$"); // DC_SOMETHING - rx.setMinimal(true); // Non-greedy matching - if(rx.indexIn(_line) == -1) // No matches? +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QRegExp rx ("^ *DC_(\\w+) *(\\w+) *$"); // DC_SOMETHING + rx.setMinimal (true); // Non-greedy matching + if (rx.indexIn (_line) == -1) // No matches? continue; - QStringList capt = rx.capturedTexts(); + QStringList capt= rx.capturedTexts (); #else QRegularExpression rx2 ("^ *DC_(\\w+) *(\\w+) *$"); rx2.setPatternOptions (QRegularExpression::InvertedGreedinessOption); - QRegularExpressionMatch match = rx2.match (_line); - if (!match.hasMatch()) { + QRegularExpressionMatch match= rx2.match (_line); + if (!match.hasMatch ()) { continue; } - QStringList capt = match.capturedTexts(); + QStringList capt= match.capturedTexts (); #endif - if (capt.size() != 3) // We are only interested in some options. + if (capt.size () != 3) // We are only interested in some options. continue; - - if (capt[1] == "DUPLEX" && capt[2].toInt() > 0) - printerOptions["Duplex"] = "Yes No"; - if (capt[1] == "COLORDEVICE" && capt[2].toInt() > 0) - printerOptions["ColorModel"] = "Monochrome Gray Color"; + + if (capt[1] == "DUPLEX" && capt[2].toInt () > 0) + printerOptions["Duplex"]= "Yes No"; + if (capt[1] == "COLORDEVICE" && capt[2].toInt () > 0) + printerOptions["ColorModel"]= "Monochrome Gray Color"; if (capt[1] == "COLLATE") { - if (capt[2].toInt() > 0) { - printerOptions["Collate"] = "No *Yes"; - } else { - printerOptions["Collate"] = "*No Yes"; + if (capt[2].toInt () > 0) { + printerOptions["Collate"]= "No *Yes"; + } + else { + printerOptions["Collate"]= "*No Yes"; } } if (capt[1] == "ENUMRESOLUTIONS") { - resolutionsCounter = capt[2].toInt(); // The next iterations are special - //printerOptions["Resolution"] = QString(); + resolutionsCounter= capt[2].toInt (); // The next iterations are special + // printerOptions["Resolution"] = QString(); } } - - emit doneReading(); + + emit doneReading (); } /*! * @see QTMPrinterSettings::availablePrinters() * @todo Check whether the list returned by QPrinterInfo is ok. */ -QList > -WinQTMPrinterSettings::availablePrinters() { - QList > _ret; - foreach(QPrinterInfo printer, QPrinterInfo::availablePrinters()) - _ret << QPair(printer.printerName(), printer.printerName()); +QList> +WinQTMPrinterSettings::availablePrinters () { + QList> _ret; + foreach (QPrinterInfo printer, QPrinterInfo::availablePrinters ()) + _ret << QPair (printer.printerName (), + printer.printerName ()); return _ret; } diff --git a/src/Plugins/Qt/QTMPrinterSettings.hpp b/src/Plugins/Qt/QTMPrinterSettings.hpp index b407d6a40b..12177e0c0a 100644 --- a/src/Plugins/Qt/QTMPrinterSettings.hpp +++ b/src/Plugins/Qt/QTMPrinterSettings.hpp @@ -1,7 +1,7 @@ /****************************************************************************** * MODULE : QTMPrinterSettings.hpp - * DESCRIPTION: + * DESCRIPTION: * COPYRIGHT : (C) 2010 Miguel de Benito Delgado ******************************************************************************* * This software falls under the GNU general public license version 3 or later. @@ -14,116 +14,130 @@ #include -#include // Provides QPrinter::PaperSize -#include #include +#include // Provides QPrinter::PaperSize +#include /* Mock Interface of the Asynchronous command stuff class QTMAsynchronousCommand { public: QTMAsynchronousCommand(); - + virtual bool slotStart() = 0; virtual void signalDone() = 0; protected: virtual void signalFinished() = 0; }; */ - + /*! * This class holds the printing options that we are able to manage or - * heed, as well as list of available ones relevant to those. For instance, - * it can query the printing system as to the available paper sizes for a given - * printer. - * - * This class provides one signal, doneReading(), which will be emmitted after the - * system command used to read the configuration variables finishes. Why bother? - * Because lpoptions uses cupsGetDests() from the CUPS API, which in turn opens - * a connection to the server (using cupsGetDests2(), see cups/dest.c in CUPS - * source code, v1.4.5). If it takes too long to reply, we are going to freeze - * the interface. + * heed, as well as list of available ones relevant to those. For instance, + * it can query the printing system as to the available paper sizes for a given + * printer. + * + * This class provides one signal, doneReading(), which will be emmitted after + * the system command used to read the configuration variables finishes. Why + * bother? Because lpoptions uses cupsGetDests() from the CUPS API, which in + * turn opens a connection to the server (using cupsGetDests2(), see cups/dest.c + * in CUPS source code, v1.4.5). If it takes too long to reply, we are going to + * freeze the interface. */ class QTMPrinterSettings : public QObject { Q_OBJECT - + public: //! Left-Right_Top-Bottom, Right-Left_Top-Bottom, etc. - enum PagePrintingOrder { LR_TB, RL_TB, TB_LR, TB_RL, - LR_BT, RL_BT, BT_LR, BT_RL}; - + enum PagePrintingOrder { + LR_TB, + RL_TB, + TB_LR, + TB_RL, + LR_BT, + RL_BT, + BT_LR, + BT_RL + }; + //! Arguments to the "-o orientation-requested=" CUPS option - enum PageOrientation { Portrait = 3, Landscape = 4, - ReversePortrait = 5, ReverseLandscape = 6 }; - - /*! The different settings, for which we can read available choices from the + enum PageOrientation { + Portrait = 3, + Landscape = 4, + ReversePortrait = 5, + ReverseLandscape= 6 + }; + + /*! The different settings, for which we can read available choices from the * driver. See getChoices(). */ enum DriverChoices { PageSize, Resolution, Duplex, ColorModel, Collate }; - + //! TODO: Use this. - enum ColorMode { Monochrome, Gray8Bit, Color}; - - bool collateCopies; - bool blackWhite; //! Force black & white printing even on color printers - QString printerName; - QString fileName; - QString paperSize; - QString printProgram; - int dpi; - int firstPage; //! If firstPage == lastPage == 0, print everything - int lastPage; - bool printOddPages; - bool printEvenPages; - bool fitToPage; - int copyCount; - bool duplex; //! Print on both sides of the paper - int pagesPerSide; //! Can be one of 1,2,4,6,9,16 + enum ColorMode { Monochrome, Gray8Bit, Color }; + + bool collateCopies; + bool blackWhite; //! Force black & white printing even on color printers + QString printerName; + QString fileName; + QString paperSize; + QString printProgram; + int dpi; + int firstPage; //! If firstPage == lastPage == 0, print everything + int lastPage; + bool printOddPages; + bool printEvenPages; + bool fitToPage; + int copyCount; + bool duplex; //! Print on both sides of the paper + int pagesPerSide; //! Can be one of 1,2,4,6,9,16 PagePrintingOrder pagesOrder; - PageOrientation orientation; - + PageOrientation orientation; + public: - QTMPrinterSettings(); - - void getFromQPrinter(const QPrinter&); - void setToQPrinter(QPrinter&) const; - - QStringList getChoices(DriverChoices _which, int& _default); - + QTMPrinterSettings (); + + void getFromQPrinter (const QPrinter&); + void setToQPrinter (QPrinter&) const; + + QStringList getChoices (DriverChoices _which, int& _default); + /*! Implemented by one of CupsQTMPrinterSettings, WinQTMPrinterSettings */ - virtual QString toSystemCommand() const = 0; - - /*! - * Implemented by one of CupsQTMPrinterSettings, WinQTMPrinterSettings + virtual QString toSystemCommand () const= 0; + + /*! + * Implemented by one of CupsQTMPrinterSettings, WinQTMPrinterSettings * Must return a list of pairs of strings. The first item in each pair being * the printer's display name (i.e. the one to be shown to the user), the * second the queue name. */ - virtual QList > availablePrinters() = 0; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - static QString qtPaperSizeToQString(const QPrinter::PaperSize); - static QPrinter::PaperSize qStringToQtPaperSize(const QString&); + virtual QList> availablePrinters ()= 0; +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + static QString qtPaperSizeToQString (const QPrinter::PaperSize); + static QPrinter::PaperSize qStringToQtPaperSize (const QString&); #else - static QString qtPaperSizeToQString(const QPageSize::PageSizeId); - static QPageSize::PageSizeId qStringToQtPaperSize(const QString&); + static QString qtPaperSizeToQString (const QPageSize::PageSizeId); + static QPageSize::PageSizeId qStringToQtPaperSize (const QString&); #endif signals: - void doneReading(); + void doneReading (); public slots: - void startReadingSystemConfig(const QString& pname) { fromSystemConfig(pname); } + void startReadingSystemConfig (const QString& pname) { + fromSystemConfig (pname); + } protected slots: - virtual void systemCommandFinished(int exitCode, - QProcess::ExitStatus exitStatus) = 0; - + virtual void systemCommandFinished (int exitCode, + QProcess::ExitStatus exitStatus)= 0; + protected: /*! Implemented by one of CupsQTMPrinterSettings, WinQTMPrinterSettings */ - virtual bool fromSystemConfig(const QString& printer) = 0; - - QProcess* configProgram; + virtual bool fromSystemConfig (const QString& printer)= 0; + + QProcess* configProgram; QHash printerOptions; }; -#if defined(Q_OS_MAC) || defined (Q_OS_LINUX) +#if defined(Q_OS_MAC) || defined(Q_OS_LINUX) /*! * Implementation specific to the CUPS driver under MacOS and Linux. This @@ -133,47 +147,50 @@ protected slots: */ class CupsQTMPrinterSettings : public QTMPrinterSettings { // Q_OBJECT - // MOC does not support conditional compilation + // MOC does not support conditional compilation public: - CupsQTMPrinterSettings(); - QString toSystemCommand() const; - QList > availablePrinters(); + CupsQTMPrinterSettings (); + QString toSystemCommand () const; + QList> availablePrinters (); + protected: - bool fromSystemConfig(const QString& printer); - void systemCommandFinished(int exitCode, QProcess::ExitStatus exitStatus); - }; + bool fromSystemConfig (const QString& printer); + void systemCommandFinished (int exitCode, QProcess::ExitStatus exitStatus); +}; -#endif // defined(Q_WS_MAC) || defined (Q_WS_X11) +#endif // defined(Q_WS_MAC) || defined (Q_WS_X11) #ifdef Q_OS_WIN /*! - * A WinQTMPrinterSettings object sets the the default print command to be either + * A WinQTMPrinterSettings object sets the the default print command to be + either * Ghostscript's mswinpr2 driver or the tool gsprint. * * The GPL Ghostscript docs state - * that "The mswinpr2 device uses MS Windows printer drivers, and thus should + * that "The mswinpr2 device uses MS Windows printer drivers, and thus should * work with any printer with device-independent bitmap (DIB) raster * capabilities". See: * @link http://pages.cs.wisc.edu/~ghost/doc/svn/Devices.htm#Win @endlink * * However, the author of that driver has written another tool which should - * perform better on colour printers. See + * perform better on colour printers. See * @link http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm @endlink - + */ class WinQTMPrinterSettings : public QTMPrinterSettings { // Q_OBJECT - // MOC does not support conditional compilation + // MOC does not support conditional compilation public: - WinQTMPrinterSettings(); - QString toSystemCommand() const; - QList > availablePrinters(); + WinQTMPrinterSettings (); + QString toSystemCommand () const; + QList> availablePrinters (); + protected: - bool fromSystemConfig(const QString& printer); - void systemCommandFinished(int exitCode, QProcess::ExitStatus exitStatus); + bool fromSystemConfig (const QString& printer); + void systemCommandFinished (int exitCode, QProcess::ExitStatus exitStatus); }; #endif // Q_WS_WIN -#endif // QTMPRINTERSETTINGS_HPP +#endif // QTMPRINTERSETTINGS_HPP diff --git a/src/Plugins/Qt/QTMScrollView.cpp b/src/Plugins/Qt/QTMScrollView.cpp index fe9b4e8c4a..de5a3c18ac 100644 --- a/src/Plugins/Qt/QTMScrollView.cpp +++ b/src/Plugins/Qt/QTMScrollView.cpp @@ -13,261 +13,263 @@ #include "QTMScrollView.hpp" -#include -#include +#include #include #include +#include +#include #include -#include - /*! Provide automatic centering of the working area inside the viewport. - + The only purpose of this widget is to provide this centering. To support this we "un-wired" the event redirection built-in in QAbstractScrollArea (from the viewport widget to the QAbstractScrollArea) and re-wired event redirection from the surface to the QTMScrollView (see event()) - + All relevant events like resize, I/O events and the like which are sent to the surface are resent QTMScrollView::surfaceEvent() for handling. This allows to concentrate all the logic in only one object. */ class QTMSurface : public QWidget { - - QTMScrollView* sv; + + QTMScrollView* sv; + public: - QTMSurface(QWidget* p, QTMScrollView* _sv) : QWidget (p), sv (_sv) { } - + QTMSurface (QWidget* p, QTMScrollView* _sv) : QWidget (p), sv (_sv) {} + protected: - virtual bool event(QEvent *event) { - return sv->surfaceEvent(event) ? true : QWidget::event(event); - } + virtual bool event (QEvent* event) { + return sv->surfaceEvent (event) ? true : QWidget::event (event); + } }; /*! Constructor. - + NOTE: - We tell the p_surface to use all available space by default (this is needed by + We tell the p_surface to use all available space by default (this is needed by embedded widgets) by setting the SizePolicy to (Expanding, Expanding). In order to draw the vertical margins around the working area use a horizontal policy of Fixedl, as in qt_tm_widget_rep (see SLOT_SCROLLABLE there) - + NOTE: - Don't try to disable double buffering even if we do our own: the flag + Don't try to disable double buffering even if we do our own: the flag Qt::WA_PaintOnScreen is only supported on X11 and anyway makes things slower */ -QTMScrollView::QTMScrollView (QWidget *_parent): - QAbstractScrollArea (_parent), - editor_flag (false), - p_extents (QRect(0,0,0,0)) -{ - QWidget *_viewport = QAbstractScrollArea::viewport(); - _viewport->setBackgroundRole(QPalette::Mid); - _viewport->setAutoFillBackground(true); - setFrameShape(QFrame::NoFrame); - - p_surface = new QTMSurface (_viewport, this); - p_surface->setAttribute(Qt::WA_NoSystemBackground); - p_surface->setAttribute(Qt::WA_StaticContents); - p_surface->setAutoFillBackground(false); - p_surface->setBackgroundRole(QPalette::NoRole); - p_surface->setAttribute(Qt::WA_OpaquePaintEvent); - p_surface->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - QHBoxLayout *layout = new QHBoxLayout(); - layout->addWidget(p_surface, 0, Qt::AlignHCenter | Qt::AlignVCenter); - layout->setContentsMargins(0,0,0,0); - _viewport->setLayout(layout); +QTMScrollView::QTMScrollView (QWidget* _parent) + : QAbstractScrollArea (_parent), editor_flag (false), + p_extents (QRect (0, 0, 0, 0)) { + QWidget* _viewport= QAbstractScrollArea::viewport (); + _viewport->setBackgroundRole (QPalette::Mid); + _viewport->setAutoFillBackground (true); + setFrameShape (QFrame::NoFrame); + + p_surface= new QTMSurface (_viewport, this); + p_surface->setAttribute (Qt::WA_NoSystemBackground); + p_surface->setAttribute (Qt::WA_StaticContents); + p_surface->setAutoFillBackground (false); + p_surface->setBackgroundRole (QPalette::NoRole); + p_surface->setAttribute (Qt::WA_OpaquePaintEvent); + p_surface->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); + + QHBoxLayout* layout= new QHBoxLayout (); + layout->addWidget (p_surface, 0, Qt::AlignHCenter | Qt::AlignVCenter); + layout->setContentsMargins (0, 0, 0, 0); + _viewport->setLayout (layout); } -void -QTMScrollView::setOrigin ( QPoint newOrigin ) { - if (newOrigin.x() != p_origin.x()) - QAbstractScrollArea::horizontalScrollBar()->setSliderPosition(newOrigin.x()); - if (newOrigin.y() != p_origin.y()) - QAbstractScrollArea::verticalScrollBar()->setSliderPosition(newOrigin.y()); +void +QTMScrollView::setOrigin (QPoint newOrigin) { + if (newOrigin.x () != p_origin.x ()) + QAbstractScrollArea::horizontalScrollBar ()->setSliderPosition ( + newOrigin.x ()); + if (newOrigin.y () != p_origin.y ()) + QAbstractScrollArea::verticalScrollBar ()->setSliderPosition ( + newOrigin.y ()); } -void -QTMScrollView::setExtents ( QRect newExtents ) { - //QWidget *_viewport = QAbstractScrollArea::viewport(); - //cout << "Inside " << _viewport->width() << ", " << _viewport->height() << "\n"; - //cout << "Extents " << newExtents.width() << ", " << newExtents.height() << "\n"; - if (newExtents.width() < 0) newExtents.setWidth (0); - if (newExtents.height() < 0) newExtents.setHeight(0); +void +QTMScrollView::setExtents (QRect newExtents) { + // QWidget *_viewport = QAbstractScrollArea::viewport(); + // cout << "Inside " << _viewport->width() << ", " << _viewport->height() << + // "\n"; cout << "Extents " << newExtents.width() << ", " << + // newExtents.height() << "\n"; + if (newExtents.width () < 0) newExtents.setWidth (0); + if (newExtents.height () < 0) newExtents.setHeight (0); if (p_extents != newExtents) { - p_extents = newExtents; - updateScrollBars(); + p_extents= newExtents; + updateScrollBars (); } } /*! Scrolls contents so that the given point is visible. */ -void -QTMScrollView::ensureVisible ( int cx, int cy, int mx, int my ) { - QWidget *_viewport = QAbstractScrollArea::viewport(); - int w = _viewport->width(); - int h = _viewport->height(); - - int dx = - p_origin.x(); - int dy = - p_origin.y(); - int cw = p_extents.width(); - int ch = p_extents.height(); - - if (w < mx * 2) mx = w / 2; - if (h < my * 2) my = h / 2; - - if (cw <= w) { mx = 0; dx = 0; } - - if (ch <= h) { my = 0; dy = 0; } - - if (cx < mx - dx) dx = mx - cx; - else if (cx >= w - mx - dx) dx = w - mx - cx; - - if (cy < my - dy) dy = my - cy; - else if (cy >= h - my - dy) dy = h - my - cy; - - if (dx > 0) dx = 0; - else if (dx < w - cw && cw > w) dx = w - cw; - - if (dy > 0) dy = 0; - else if (dy < h - ch && ch > h) dy = h - ch; - - setOrigin (QPoint(-dx, -dy)); +void +QTMScrollView::ensureVisible (int cx, int cy, int mx, int my) { + QWidget* _viewport= QAbstractScrollArea::viewport (); + int w = _viewport->width (); + int h = _viewport->height (); + + int dx= -p_origin.x (); + int dy= -p_origin.y (); + int cw= p_extents.width (); + int ch= p_extents.height (); + + if (w < mx * 2) mx= w / 2; + if (h < my * 2) my= h / 2; + + if (cw <= w) { + mx= 0; + dx= 0; + } + + if (ch <= h) { + my= 0; + dy= 0; + } + + if (cx < mx - dx) dx= mx - cx; + else if (cx >= w - mx - dx) dx= w - mx - cx; + + if (cy < my - dy) dy= my - cy; + else if (cy >= h - my - dy) dy= h - my - cy; + + if (dx > 0) dx= 0; + else if (dx < w - cw && cw > w) dx= w - cw; + + if (dy > 0) dy= 0; + else if (dy < h - ch && ch > h) dy= h - ch; + + setOrigin (QPoint (-dx, -dy)); } /*! Scrollbar stabilization */ -void +void QTMScrollView::updateScrollBars (void) { - QWidget *_viewport = QAbstractScrollArea::viewport(); - QScrollBar *_hScrollBar = QAbstractScrollArea::horizontalScrollBar(); - QScrollBar *_vScrollBar = QAbstractScrollArea::verticalScrollBar(); - - int xw = p_extents.width(); - int xh = p_extents.height(); - int w = _viewport->width() ; // -2 - int h = _viewport->height(); // -2 - int sbw= qApp->style()->pixelMetric (QStyle::PM_ScrollBarExtent); - if (_hScrollBar->maximum() > _hScrollBar->minimum()) h += sbw; - if (_vScrollBar->maximum() > _vScrollBar->minimum()) w += sbw; - if (xw > w) h -= sbw; - if (xh > h) w -= sbw; + QWidget* _viewport = QAbstractScrollArea::viewport (); + QScrollBar* _hScrollBar= QAbstractScrollArea::horizontalScrollBar (); + QScrollBar* _vScrollBar= QAbstractScrollArea::verticalScrollBar (); + + int xw = p_extents.width (); + int xh = p_extents.height (); + int w = _viewport->width (); // -2 + int h = _viewport->height (); // -2 + int sbw= qApp->style ()->pixelMetric (QStyle::PM_ScrollBarExtent); + if (_hScrollBar->maximum () > _hScrollBar->minimum ()) h+= sbw; + if (_vScrollBar->maximum () > _vScrollBar->minimum ()) w+= sbw; + if (xw > w) h-= sbw; + if (xh > h) w-= sbw; if (!editor_flag) { if (xw < w) xw= w; if (xh < h) xh= h; } - int cw = (xw > w ? xw - w : 0); - if (_hScrollBar->sliderPosition() > cw) - _hScrollBar->setSliderPosition(cw); - _hScrollBar->setRange(0, cw); - _hScrollBar->setSingleStep((w >> 4) + 1); - _hScrollBar->setPageStep(w); - - int ch = (xh > h ? xh - h : 0); - if (_vScrollBar->sliderPosition() > ch) - _vScrollBar->setSliderPosition(ch); - _vScrollBar->setRange(0, ch); - _vScrollBar->setSingleStep((h >> 4) + 1); - _vScrollBar->setPageStep(h); - - surface()->setMinimumWidth (w < xw? w: xw); - surface()->setMinimumHeight(h < xh? h: xh); - + int cw= (xw > w ? xw - w : 0); + if (_hScrollBar->sliderPosition () > cw) _hScrollBar->setSliderPosition (cw); + _hScrollBar->setRange (0, cw); + _hScrollBar->setSingleStep ((w >> 4) + 1); + _hScrollBar->setPageStep (w); + + int ch= (xh > h ? xh - h : 0); + if (_vScrollBar->sliderPosition () > ch) _vScrollBar->setSliderPosition (ch); + _vScrollBar->setRange (0, ch); + _vScrollBar->setSingleStep ((h >> 4) + 1); + _vScrollBar->setPageStep (h); + + surface ()->setMinimumWidth (w < xw ? w : xw); + surface ()->setMinimumHeight (h < xh ? h : xh); + // we may need a relayout if the surface width is changed - updateGeometry(); + updateGeometry (); } /*! Scroll area updater */ void -QTMScrollView::scrollContentsBy ( int dx, int dy ) { - if (dx) p_origin.setX(p_origin.x() - dx); - if (dy) p_origin.setY(p_origin.y() - dy); +QTMScrollView::scrollContentsBy (int dx, int dy) { + if (dx) p_origin.setX (p_origin.x () - dx); + if (dy) p_origin.setY (p_origin.y () - dy); } -bool -QTMScrollView::viewportEvent(QEvent *e) -{ - switch (e->type()) { - case QEvent::Resize: - case QEvent::Paint: - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonDblClick: - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::MouseMove: - case QEvent::ContextMenu: - case QEvent::Wheel: - case QEvent::Drop: - case QEvent::DragEnter: - case QEvent::DragMove: - case QEvent::DragLeave: - // return QFrame::event(e); - return false; // let the viewport widget handle the event - case QEvent::LayoutRequest: +bool +QTMScrollView::viewportEvent (QEvent* e) { + switch (e->type ()) { + case QEvent::Resize: + case QEvent::Paint: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + case QEvent::MouseMove: + case QEvent::ContextMenu: + case QEvent::Wheel: + case QEvent::Drop: + case QEvent::DragEnter: + case QEvent::DragMove: + case QEvent::DragLeave: + // return QFrame::event(e); + return false; // let the viewport widget handle the event + case QEvent::LayoutRequest: #ifndef QT_NO_GESTURES - case QEvent::Gesture: - case QEvent::GestureOverride: - return event(e); + case QEvent::Gesture: + case QEvent::GestureOverride: + return event (e); #endif - default: - break; + default: + break; } return false; // let the viewport widget handle the event } -bool -QTMScrollView::surfaceEvent(QEvent *e) -{ - switch (e->type()) { - case QEvent::Resize: - case QEvent::Paint: - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonDblClick: - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::MouseMove: - case QEvent::ContextMenu: - case QEvent::Wheel: - case QEvent::Drop: - case QEvent::DragEnter: - case QEvent::DragMove: - case QEvent::DragLeave: - return QFrame::event(e); - case QEvent::LayoutRequest: +bool +QTMScrollView::surfaceEvent (QEvent* e) { + switch (e->type ()) { + case QEvent::Resize: + case QEvent::Paint: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + case QEvent::MouseMove: + case QEvent::ContextMenu: + case QEvent::Wheel: + case QEvent::Drop: + case QEvent::DragEnter: + case QEvent::DragMove: + case QEvent::DragLeave: + return QFrame::event (e); + case QEvent::LayoutRequest: #ifndef QT_NO_GESTURES - case QEvent::Gesture: - case QEvent::GestureOverride: - return event(e); + case QEvent::Gesture: + case QEvent::GestureOverride: + return event (e); #endif - default: - break; + default: + break; } return false; // let the surface widget handle the event } bool -QTMScrollView::event (QEvent *event) { - switch (event->type()) { - case QEvent::Resize: - { - bool res = QAbstractScrollArea::event(event); - QResizeEvent *re = static_cast (event); - updateScrollBars(); - resizeEventBis (re); - return res; - } - default: - break; +QTMScrollView::event (QEvent* event) { + switch (event->type ()) { + case QEvent::Resize: { + bool res= QAbstractScrollArea::event (event); + QResizeEvent* re = static_cast (event); + updateScrollBars (); + resizeEventBis (re); + return res; + } + default: + break; } - return QAbstractScrollArea::event(event); + return QAbstractScrollArea::event (event); } void -QTMScrollView::resizeEventBis (QResizeEvent *event) { +QTMScrollView::resizeEventBis (QResizeEvent* event) { (void) event; } diff --git a/src/Plugins/Qt/QTMScrollView.hpp b/src/Plugins/Qt/QTMScrollView.hpp index c9e766c12f..0b04b15b7b 100644 --- a/src/Plugins/Qt/QTMScrollView.hpp +++ b/src/Plugins/Qt/QTMScrollView.hpp @@ -20,55 +20,53 @@ class QPaintEvent; /*! Scroll view widget. - The current structure of the central texmacs widget (the canvas) is the + The current structure of the central texmacs widget (the canvas) is the following: the canvas is a derived class of QTMScrollView which being a QAbstractScrollArea owns a central widget called the "viewport". QAbstractScrollArea coordinates the viewport with the scrollbars and maintains - informations like the real extent of the working surface and the current - origin which can be acted upon via the scrollbars. This setup has been - augmented via another widget child of the scrollview which we call the - "surface", with the purpose of centering the working area. See the + informations like the real extent of the working surface and the current + origin which can be acted upon via the scrollbars. This setup has been + augmented via another widget child of the scrollview which we call the + "surface", with the purpose of centering the working area. See the documentation for QTMSurface for more info on this. */ class QTMScrollView : public QAbstractScrollArea { Q_OBJECT - bool editor_flag; // Set to true for editor widgets - QRect p_extents; // The size of the virtual area where things are drawn. - QPoint p_origin; // The offset into that area - QWidget* p_surface; // Actual drawing area, centered (or not) in the scrollarea - + bool editor_flag; // Set to true for editor widgets + QRect p_extents; // The size of the virtual area where things are drawn. + QPoint p_origin; // The offset into that area + QWidget* + p_surface; // Actual drawing area, centered (or not) in the scrollarea + public: - - QTMScrollView (QWidget *_parent = NULL); + QTMScrollView (QWidget* _parent= NULL); + + QPoint origin () { return p_origin; } + void setOrigin (QPoint newOrigin); - QPoint origin () { return p_origin; } - void setOrigin (QPoint newOrigin); - - QRect extents () { return p_extents; } - void setExtents (QRect newExtents); + QRect extents () { return p_extents; } + void setExtents (QRect newExtents); QWidget* surface () const { return p_surface; } - - void ensureVisible (int cx, int cy, int mx = 50, int my = 50); - - // Viewport/contents position converters. + + void ensureVisible (int cx, int cy, int mx= 50, int my= 50); + + // Viewport/contents position converters. QPoint viewportToContents (QPoint const& pos) const { return pos + p_origin; } QPoint contentsToViewport (QPoint const& pos) const { return pos - p_origin; } - + protected: - - void updateScrollBars(); + void updateScrollBars (); void scrollContentsBy (int dx, int dy); - - virtual void resizeEventBis (QResizeEvent *e); - virtual bool viewportEvent (QEvent *e); - virtual bool surfaceEvent (QEvent *e); - virtual bool event (QEvent *e); + + virtual void resizeEventBis (QResizeEvent* e); + virtual bool viewportEvent (QEvent* e); + virtual bool surfaceEvent (QEvent* e); + virtual bool event (QEvent* e); friend class QTMSurface; friend class qt_simple_widget_rep; }; - #endif // QTMSCROLLVIEW_HPP diff --git a/src/Plugins/Qt/QTMSockets.cpp b/src/Plugins/Qt/QTMSockets.cpp index 7691ba69c9..c599b83596 100644 --- a/src/Plugins/Qt/QTMSockets.cpp +++ b/src/Plugins/Qt/QTMSockets.cpp @@ -1,36 +1,36 @@ /****************************************************************************** -* MODULE : QTMsockets.cpp -* DESCRIPTION: QT TeXmacs sockets manager -* COPYRIGHT : (C) 2015 Denis RAUX -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMsockets.cpp + * DESCRIPTION: QT TeXmacs sockets manager + * COPYRIGHT : (C) 2015 Denis RAUX + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "QTMSockets.hpp" -#include "scheme.hpp" -#include "iterator.hpp" #include "analyze.hpp" +#include "iterator.hpp" +#include "scheme.hpp" #if !defined(OS_MINGW) && !defined(OS_WIN) +#include #include -#include -#include -#include -#include +#include #include +#include #include -#include -#include +#include +#include +#include #define CONNECT ::connect -#define CLOSE(a) close(a) -#define WRITE(a, b, c) ::write(a, b, c) +#define CLOSE(a) close (a) +#define WRITE(a, b, c) ::write (a, b, c) #define ERRNO errno -#define ERRSOC(a) a +#define ERRSOC(a) a #define GETADDRINFO getaddrinfo #define FREEADDRINFO freeaddrinfo #define ADDRINFO addrinfo @@ -45,11 +45,11 @@ #else #define CONNECT wsoc::connect -#define CLOSE(a) wsoc::closesocket(a) -#define WRITE(a, b, c) wsoc::send(a, b, c, 0) -#define ERRNO wsoc::WSAGetLastError() -#define ERRSOC(a) WSA##a -#define GETADDRINFO wsoc::getaddrinfo +#define CLOSE(a) wsoc::closesocket (a) +#define WRITE(a, b, c) wsoc::send (a, b, c, 0) +#define ERRNO wsoc::WSAGetLastError () +#define ERRSOC(a) WSA##a +#define GETADDRINFO wsoc::getaddrinfo #define FREEADDRINFO wsoc::freeaddrinfo #define ADDRINFO wsoc::addrinfo #define SOCKET wsoc::socket @@ -77,16 +77,16 @@ string_from_socket_address (SOCKADDR_STORAGE* sock) { #if defined(OS_MINGW) || defined(OS_WIN) return wsoc::inet_ntoa (((SOCKADDR_IN*) sock)->sin_addr); #else - if (inet_ntop (AF_INET, &(((sockaddr_in*) sock)->sin_addr), - tmp, sizeof(tmp)) == NULL) + if (inet_ntop (AF_INET, &(((sockaddr_in*) sock)->sin_addr), tmp, + sizeof (tmp)) == NULL) return ""; return tmp; #endif } if (sock->ss_family == AF_INET6) { #if !defined(OS_MINGW) && !defined(OS_WIN) || (_WIN32_WINNT >= 0x0600) - if (INET_NTOP (AF_INET6, &(((SOCKADDR_IN6*) sock)->sin6_addr), - tmp, sizeof(tmp)) == NULL) + if (INET_NTOP (AF_INET6, &(((SOCKADDR_IN6*) sock)->sin6_addr), tmp, + sizeof (tmp)) == NULL) return ""; #else return ""; @@ -96,12 +96,15 @@ string_from_socket_address (SOCKADDR_STORAGE* sock) { return ""; } -socket_basic::socket_basic (): st (ST_VOID) { +socket_basic::socket_basic () : st (ST_VOID) { #if defined(OS_MINGW) || defined(OS_WIN) if (!count) { using namespace wsoc; - err= WSAStartup (MAKEWORD (2,0), &wsadata); - if (err) {st= ST_WSA; return;} + err= WSAStartup (MAKEWORD (2, 0), &wsadata); + if (err) { + st= ST_WSA; + return; + } } #endif count++; @@ -115,98 +118,149 @@ socket_basic::~socket_basic () { }; socket_link::socket_link (int s, SOCKADDR_STORAGE* addr) { - id++; sock= s; qsnr= NULL; qsnw= NULL; + id++; + sock= s; + qsnr= NULL; + qsnw= NULL; if (st != ST_VOID) return; - memcpy (&add, addr, sizeof(add)); + memcpy (&add, addr, sizeof (add)); qsnr= tm_new (s, QSocketNotifier::Read); qsnw= tm_new (s, QSocketNotifier::Write); - if (!qsnr || !qsnw) { err= ERRNO; st= ST_NOTIF; return; } - QObject::connect (qsnr, SIGNAL(activated(int)), - this, SLOT(data_set_ready(int))); - QObject::connect (qsnw, SIGNAL(activated(int)), - this, SLOT(ready_to_send(int))); + if (!qsnr || !qsnw) { + err= ERRNO; + st = ST_NOTIF; + return; + } + QObject::connect (qsnr, SIGNAL (activated (int)), this, + SLOT (data_set_ready (int))); + QObject::connect (qsnw, SIGNAL (activated (int)), this, + SLOT (ready_to_send (int))); DBG_IO ("Socket created with fd= " << sock); st= ST_OK; } socket_link::socket_link (string host, unsigned short port) { - ++id; qsnr= NULL; qsnw= NULL; + ++id; + qsnr= NULL; + qsnw= NULL; if (st != ST_VOID) return; string host_tmp= host; - if (starts (host, "[") && ends (host, "]")) - host_tmp = host(1, N(host)-1); - c_string _host (host_tmp); - c_string _port (as_string (port)); - struct ADDRINFO hints; + if (starts (host, "[") && ends (host, "]")) host_tmp= host (1, N (host) - 1); + c_string _host (host_tmp); + c_string _port (as_string (port)); + struct ADDRINFO hints; struct ADDRINFO *result, *rp; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; + memset (&hints, 0, sizeof (hints)); + hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_PASSIVE; + hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; - hints.ai_canonname = NULL; - hints.ai_addr = NULL; - hints.ai_next = NULL; - int x = GETADDRINFO (_host, _port, &hints, &result); - if (x != 0) { err= ERRNO; st= ST_GETHOST; return; }; - for (rp = result; rp != NULL; rp = rp->ai_next) { - sock= SOCKET (rp->ai_family, rp->ai_socktype, - rp->ai_protocol); - if (sock < 0) - continue; - if (CONNECT (sock, rp->ai_addr, rp->ai_addrlen) != -1) - break; + hints.ai_canonname= NULL; + hints.ai_addr = NULL; + hints.ai_next = NULL; + int x = GETADDRINFO (_host, _port, &hints, &result); + if (x != 0) { + err= ERRNO; + st = ST_GETHOST; + return; + }; + for (rp= result; rp != NULL; rp= rp->ai_next) { + sock= SOCKET (rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (sock < 0) continue; + if (CONNECT (sock, rp->ai_addr, rp->ai_addrlen) != -1) break; CLOSE (sock); } - if (rp == NULL) { err= ERRNO; st= ST_CONNECTION; return; } + if (rp == NULL) { + err= ERRNO; + st = ST_CONNECTION; + return; + } FREEADDRINFO (result); #if !defined(OS_MINGW) && !defined(OS_WIN) if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) { - err= errno; st= ST_FCNTL; return; } + err= errno; + st = ST_FCNTL; + return; + } #else { using namespace wsoc; - u_long flags = -1; + u_long flags= -1; if (ioctlsocket (sock, FIONBIO, &flags) == SOCKET_ERROR) { - err= ERRNO; st= ST_FCNTL; return; } + err= ERRNO; + st = ST_FCNTL; + return; + } } #endif qsnr= tm_new (sock, QSocketNotifier::Read); qsnw= tm_new (sock, QSocketNotifier::Write); - if (!qsnr || !qsnw) { err= ERRNO; st= ST_NOTIF; return; } - QObject::connect (qsnr, SIGNAL (activated(int)), - this, SLOT (data_set_ready(int))); + if (!qsnr || !qsnw) { + err= ERRNO; + st = ST_NOTIF; + return; + } + QObject::connect (qsnr, SIGNAL (activated (int)), this, + SLOT (data_set_ready (int))); qsnw->setEnabled (false); - QObject::connect (qsnw, SIGNAL (activated(int)), - this, SLOT (ready_to_send(int))); + QObject::connect (qsnw, SIGNAL (activated (int)), this, + SLOT (ready_to_send (int))); DBG_IO ("Socket created with fd= " << sock); st= ST_OK; } -socket_link::~socket_link() { +socket_link::~socket_link () { DBG_IO ("Closing socket for fd= " << sock); - if (qsnr) { qsnr->disconnect (SIGNAL(activated(int))); tm_delete (qsnr); } - if (qsnw) { qsnw->disconnect (SIGNAL(activated(int))); tm_delete (qsnw); } - if (sock != -1) { CLOSE (sock); sock=-1;} + if (qsnr) { + qsnr->disconnect (SIGNAL (activated (int))); + tm_delete (qsnr); + } + if (qsnw) { + qsnw->disconnect (SIGNAL (activated (int))); + tm_delete (qsnw); + } + if (sock != -1) { + CLOSE (sock); + sock= -1; + } st= ST_CLOSED; } string socket_link::start () { string ret; - switch(st) { - case ST_OK: return ""; break; - case ST_VOID: ret= "Socket not initialised"; break; - case ST_SOCKET: ret= "Error in opening socket"; break; - case ST_FCNTL: ret= "Error in setting blocking mode"; break; - case ST_BIND: ret= "Error during bind"; break; - case ST_LISTEN: ret= "Error during listen"; break; - case ST_CONNECTION: ret= "Error during connect"; break; - case ST_GETHOST: ret= "Error in getting host"; break; - case ST_NOTIF: ret= "Error in setting notifier"; break; - default: ret= "No error message"; + switch (st) { + case ST_OK: + return ""; + break; + case ST_VOID: + ret= "Socket not initialised"; + break; + case ST_SOCKET: + ret= "Error in opening socket"; + break; + case ST_FCNTL: + ret= "Error in setting blocking mode"; + break; + case ST_BIND: + ret= "Error during bind"; + break; + case ST_LISTEN: + ret= "Error during listen"; + break; + case ST_CONNECTION: + ret= "Error during connect"; + break; + case ST_GETHOST: + ret= "Error in getting host"; + break; + case ST_NOTIF: + ret= "Error in setting notifier"; + break; + default: + ret= "No error message"; } - return ret * " errno: " * strerror(err); + return ret * " errno: " * strerror (err); } string& @@ -218,10 +272,10 @@ socket_link::watch (int channel) { string socket_link::read (int channel) { - DBG_IO ("Socket read size= " << N(inbuf)); - if (channel == LINK_OUT && N(inbuf)) { + DBG_IO ("Socket read size= " << N (inbuf)); + if (channel == LINK_OUT && N (inbuf)) { string r= inbuf; - inbuf= ""; + inbuf = ""; return r; } else return ""; @@ -237,18 +291,21 @@ void socket_link::data_set_ready (int s) { char data[2048]; qsnr->setEnabled (false); - int lgdata= RECV(s, data, sizeof(data), 0); + int lgdata= RECV (s, data, sizeof (data), 0); DBG_IO ("Socket incoming code= " << lgdata); if (lgdata == 0) { - DBG_IO ("Client disconnected"); + DBG_IO ("Client disconnected"); stop (); } else if (lgdata == -1) { switch (ERRNO) { - case ERRSOC(EWOULDBLOCK): - case ERRSOC(ECONNRESET): - case ERRSOC(ECONNABORTED): DBG_IO("Client disconnected"); break; - default: DBG_IO("Receiving error: " << ERRNO); + case ERRSOC (EWOULDBLOCK): + case ERRSOC (ECONNRESET): + case ERRSOC (ECONNABORTED): + DBG_IO ("Client disconnected"); + break; + default: + DBG_IO ("Receiving error: " << ERRNO); } stop (); } @@ -256,13 +313,17 @@ socket_link::data_set_ready (int s) { inbuf << string (data, lgdata); if (DEBUG_IO) { string s (data, lgdata); - bool ok= true; - for (int i= 0; i < N(s); i++) + bool ok= true; + for (int i= 0; i < N (s); i++) if (((int) (unsigned char) s[i]) >= 128 || - (((int) (unsigned char) s[i]) < 32 && - s[i] != '\n' && s[i] != '\t')) ok= false; - if (ok) { DBG_IO("Data received: " << s); } - else { DBG_IO("Binary data received size= " << N(s)); } + (((int) (unsigned char) s[i]) < 32 && s[i] != '\n' && s[i] != '\t')) + ok= false; + if (ok) { + DBG_IO ("Data received: " << s); + } + else { + DBG_IO ("Binary data received size= " << N (s)); + } } qsnr->setEnabled (true); } @@ -274,17 +335,18 @@ socket_link::ready_to_send (int s) { using namespace wsoc; #endif qsnw->setEnabled (false); - int sz= N(outbuf); + int sz= N (outbuf); if (sz) { char* buf= as_charp (outbuf); - int ret= WRITE(s, buf, sz); + int ret= WRITE (s, buf, sz); DBG_IO ("Socket outcoming code= " << ret); - if (ret >0) { - if (ret == sz) outbuf= ""; else outbuf= outbuf (ret, sz); - sz -= ret; + if (ret > 0) { + if (ret == sz) outbuf= ""; + else outbuf= outbuf (ret, sz); + sz-= ret; if (sz) qsnw->setEnabled (true); } - else if (ret <0) { + else if (ret < 0) { DBG_IO ("Sending error: " << strerror (ERRNO)); stop (); } @@ -305,146 +367,148 @@ socket_link::listen (int msecs) { struct timeval tv; tv.tv_sec = msecs / 1000; tv.tv_usec= 1000 * (msecs % 1000); - int nr= select (sock+1, &rfds, NULL, NULL, &tv); + int nr = select (sock + 1, &rfds, NULL, NULL, &tv); if (nr == 1) data_set_ready (sock); DBG_IO ("Listenning result: " << nr); - if (nr == -1) stop(); + if (nr == -1) stop (); } void socket_link::write (string s, int channel) { - DBG_IO ("Socket write size= " << N(s)); - if ((!alive ()) || (channel != LINK_IN) || !N(s)) return; + DBG_IO ("Socket write size= " << N (s)); + if ((!alive ()) || (channel != LINK_IN) || !N (s)) return; outbuf << s; - qsnw->setEnabled(true); + qsnw->setEnabled (true); } socket_server::socket_server (string host, unsigned short port) { - c_string _port (as_string (port)); - c_string _host (host); - struct ADDRINFO hints; + c_string _port (as_string (port)); + c_string _host (host); + struct ADDRINFO hints; struct ADDRINFO *result, *rp; - memset(&hints, 0, sizeof(struct ADDRINFO)); - hints.ai_family = AF_UNSPEC; + memset (&hints, 0, sizeof (struct ADDRINFO)); + hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_PASSIVE; + hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; - hints.ai_canonname = NULL; - hints.ai_addr = NULL; - hints.ai_next = NULL; - int x = GETADDRINFO (host == "" ? (char*) NULL : (char*)_host, - _port, &hints, &result); - if (x != 0) { - DBG_IO(GAI_STRERROR(x)); + hints.ai_canonname= NULL; + hints.ai_addr = NULL; + hints.ai_next = NULL; + int x= GETADDRINFO (host == "" ? (char*) NULL : (char*) _host, _port, &hints, + &result); + if (x != 0) { + DBG_IO (GAI_STRERROR (x)); err= ERRNO; - st= ST_GETHOST; + st = ST_GETHOST; return; } - sock = -1; - for (rp = result; rp != NULL; rp = rp->ai_next) { + sock= -1; + for (rp= result; rp != NULL; rp= rp->ai_next) { DBG_IO ("Serving at " * - string_from_socket_address ((SOCKADDR_STORAGE*) rp->ai_addr)); + string_from_socket_address ((SOCKADDR_STORAGE*) rp->ai_addr)); sock= SOCKET (rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (sock < 0) - continue; + if (sock < 0) continue; #if !defined(OS_MINGW) && !defined(OS_WIN) - if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) - continue; -#else - { using namespace wsoc; - u_long flags = -1; - if (ioctlsocket (sock, FIONBIO, &flags) == SOCKET_ERROR) - continue; + if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) continue; +#else + { + using namespace wsoc; + u_long flags= -1; + if (ioctlsocket (sock, FIONBIO, &flags) == SOCKET_ERROR) continue; } #endif - if (BIND (sock, rp->ai_addr, rp->ai_addrlen) == 0) - break; + if (BIND (sock, rp->ai_addr, rp->ai_addrlen) == 0) break; DBG_IO (strerror (errno)); DBG_IO ("Socket bind failed"); CLOSE (sock); - sock = -1; + sock= -1; } - FREEADDRINFO (result); + FREEADDRINFO (result); if (sock == -1) { DBG_IO ("Cannot find socket binding for server"); err= ERRNO; - st= ST_BIND; - return; - } + st = ST_BIND; + return; + } if (LISTEN (sock, 10) != 0) { DBG_IO ("Cannot listen on server socket"); err= ERRNO; - st= ST_LISTEN; + st = ST_LISTEN; return; } qsnc= tm_new (sock, QSocketNotifier::Read); - QObject::connect (qsnc, SIGNAL (activated(int)), this, SLOT (connection(int))); + QObject::connect (qsnc, SIGNAL (activated (int)), this, + SLOT (connection (int))); DBG_IO ("Wait for connection"); } void socket_server::connection (int s) { - int sclt; socket_link* clt; + int sclt; + socket_link* clt; SOCKADDR_STORAGE cltadd; - socklen_t sz= sizeof (cltadd); + socklen_t sz= sizeof (cltadd); if (!qsnc->isEnabled ()) return; sclt= ACCEPT (s, (SOCKADDR*) &cltadd, &sz); if (sclt > 0) { clt= tm_new (sclt, &cltadd); if (clt) { if (clt->alive ()) { - connect (clt, SIGNAL (disconnection(socket_link*)), this, - SLOT (disconnection (socket_link*))); + connect (clt, SIGNAL (disconnection (socket_link*)), this, + SLOT (disconnection (socket_link*))); clts->insert ((pointer) clt); call ("server-add", object (clt->getid ())); - DBG_IO ("Client Connected from " - << string_from_socket_address (&cltadd) - << ", with id: " << clt->getid ()); + DBG_IO ("Client Connected from " << string_from_socket_address (&cltadd) + << ", with id: " << clt->getid ()); } else tm_delete (clt); } } else switch (ERRNO) { case ERRSOC (EWOULDBLOCK): - case ERRSOC (ECONNABORTED): break; - default: err= ERRNO; qsnc->setEnabled (false); st= ST_CONNECTION; + case ERRSOC (ECONNABORTED): + break; + default: + err= ERRNO; + qsnc->setEnabled (false); + st= ST_CONNECTION; } } -void +void socket_server::disconnection (class socket_link* clt) { - call ("server-remove", object (clt->getid())); + call ("server-remove", object (clt->getid ())); clts->remove ((pointer) clt); tm_delete (clt); } string socket_server::read (int id) { - socket_link *clt= find_client (id); + socket_link* clt= find_client (id); if (!clt) return ""; - bool success; + bool success; string back= clt->read_packet (LINK_OUT, 0, success); return back; } void socket_server::write (int id, string s) { - socket_link *clt= find_client (id); - if (clt) clt->write_packet(s, LINK_IN); + socket_link* clt= find_client (id); + if (clt) clt->write_packet (s, LINK_IN); } -socket_link * +socket_link* socket_server::find_client (int id) { iterator it= iterate (clts); while (it->busy ()) { socket_link* clt= (socket_link*) it->next (); - if (clt->getid() == id) return clt; + if (clt->getid () == id) return clt; } array ids; it= iterate (clts); while (it->busy ()) { socket_link* clt= (socket_link*) it->next (); - ids << clt->getid(); + ids << clt->getid (); } DBG_IO ("Client not found, id= " << id << ", among= " << ids); return NULL; @@ -460,9 +524,9 @@ socket_server::~socket_server () { string debug_io_string (string s) { - int i, n= N(s); + int i, n= N (s); string r; - for (i=0; i. -******************************************************************************/ + * MODULE : QTMSockets.hpp + * DESCRIPTION: QT TeXmacs sockets manager - Header + * COPYRIGHT : (C) 2015 Denis RAUX + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ -#include #include #include -#include #include +#include +#include #include "hashset.hpp" #include "string.hpp" -#include "tm_link.hpp" #include "tm_debug.hpp" +#include "tm_link.hpp" #if !defined(OS_MINGW) && !defined(OS_WIN) -#include -#include #include +#include +#include #define SOCKADDR_IN sockaddr_in #define SOCKADDR_IN6 sockaddr_in6 @@ -36,9 +36,9 @@ namespace wsoc { #include #include -} +} // namespace wsoc typedef uint32_t in_addr_t; -typedef int socklen_t; +typedef int socklen_t; #define SOCKADDR_IN wsoc::sockaddr_in #define SOCKADDR_IN6 wsoc::sockaddr_in6 #define SOCKADDR wsoc::sockaddr @@ -52,26 +52,39 @@ extern unsigned qtmsocket_debug_count; string debug_io_string (string s); -#define DBG_IO(a) \ - if (DEBUG_IO) debug_io << "TeXmacs " \ - << qtmsocket_debug_count++ << "] " << a << "\n" - -#define DBG_IOS(a,s) \ - if(N(s)) DBG_IO (a << debug_io_string (s)) - -enum state { ST_OK, ST_WSA, ST_SOCKET, ST_FCNTL, ST_BIND, - ST_LISTEN, ST_CONNECTION, ST_GETHOST, ST_NOTIF, - ST_VOID, ST_HALTED, ST_CLOSED }; +#define DBG_IO(a) \ + if (DEBUG_IO) \ + debug_io << "TeXmacs " << qtmsocket_debug_count++ << "] " << a << "\n" + +#define DBG_IOS(a, s) \ + if (N (s)) DBG_IO (a << debug_io_string (s)) + +enum state { + ST_OK, + ST_WSA, + ST_SOCKET, + ST_FCNTL, + ST_BIND, + ST_LISTEN, + ST_CONNECTION, + ST_GETHOST, + ST_NOTIF, + ST_VOID, + ST_HALTED, + ST_CLOSED +}; class socket_basic { public: bool alive () { return st == ST_OK; } + protected: - socket_basic(void); - ~socket_basic(); - int sock; - int err; + socket_basic (void); + ~socket_basic (); + int sock; + int err; enum state st; + private: static int count; #if defined(OS_MINGW) || defined(OS_WIN) @@ -81,21 +94,21 @@ class socket_basic { // Socket for clients -class socket_link: public QObject, public socket_basic, public tm_link_rep { +class socket_link : public QObject, public socket_basic, public tm_link_rep { Q_OBJECT public: socket_link (int s, SOCKADDR_STORAGE* addr); - socket_link (string host, unsigned short port=6561); + socket_link (string host, unsigned short port= 6561); ~socket_link (); string start (); - void write (string s, int channel=LINK_OUT); + void write (string s, int channel= LINK_OUT); string& watch (int channel); string read (int channel); void listen (int msecs); void interrupt () {} void stop (); - bool alive () { return socket_basic::alive(); } + bool alive () { return socket_basic::alive (); } int getid () { return id; } public slots: @@ -103,32 +116,34 @@ public slots: void ready_to_send (int); signals: void disconnection (socket_link* clt); -private : - int id; - string inbuf; - string outbuf; - QSocketNotifier *qsnr,*qsnw; - SOCKADDR_STORAGE add; + +private: + int id; + string inbuf; + string outbuf; + QSocketNotifier *qsnr, *qsnw; + SOCKADDR_STORAGE add; }; // Socket for servers -class socket_server: public QObject, public socket_basic { +class socket_server : public QObject, public socket_basic { Q_OBJECT public: - socket_server (string host, unsigned short port=6561); - ~socket_server(); - string read (int clt); - void write (int clt, string s); + socket_server (string host, unsigned short port= 6561); + ~socket_server (); + string read (int clt); + void write (int clt, string s); enum state st; - int err; - int srv_count() { return N(clts); } + int err; + int srv_count () { return N (clts); } public slots: void connection (int); void disconnection (socket_link* clt); -private : - socket_link* find_client (int id); + +private: + socket_link* find_client (int id); hashset clts; - QSocketNotifier *qsnc; + QSocketNotifier* qsnc; }; diff --git a/src/Plugins/Qt/QTMStyle.cpp b/src/Plugins/Qt/QTMStyle.cpp index 78d7a1e42c..85cd1882f3 100644 --- a/src/Plugins/Qt/QTMStyle.cpp +++ b/src/Plugins/Qt/QTMStyle.cpp @@ -9,17 +9,17 @@ * in the root directory or . ******************************************************************************/ -#include "tm_ostream.hpp" #include "renderer.hpp" +#include "tm_ostream.hpp" #include "QTMStyle.hpp" -#include -#include +#include +#include #include #include -#include -#include +#include +#include int qt_zoom (int sz) { @@ -28,9 +28,8 @@ qt_zoom (int sz) { QStyle* qtmstyle () { - static QStyle* qtmstyle = NULL; - if (!qtmstyle) - qtmstyle = new QTMStyle (qApp->style()); + static QStyle* qtmstyle= NULL; + if (!qtmstyle) qtmstyle= new QTMStyle (qApp->style ()); return qtmstyle; } @@ -38,421 +37,458 @@ qtmstyle () { * QTMProxyStyle (does not own *style) ******************************************************************************/ -QTMProxyStyle::QTMProxyStyle (QStyle* _base) : QStyle (), base (_base) { } +QTMProxyStyle::QTMProxyStyle (QStyle* _base) : QStyle (), base (_base) {} -inline QStyle *QTMProxyStyle::baseStyle() const { - return ( base ? base : qApp->style() ); +inline QStyle* +QTMProxyStyle::baseStyle () const { + return (base ? base : qApp->style ()); } int QTMProxyStyle::layoutSpacing (QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, - Qt::Orientation orientation, - const QStyleOption *option, - const QWidget *widget) const { - return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget); + Qt::Orientation orientation, + const QStyleOption* option, + const QWidget* widget) const { + return baseStyle ()->layoutSpacing (control1, control2, orientation, option, + widget); } void -QTMProxyStyle::drawComplexControl (ComplexControl control, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget) const { - baseStyle()->drawComplexControl (control, option, painter, widget); +QTMProxyStyle::drawComplexControl (ComplexControl control, + const QStyleOptionComplex* option, + QPainter* painter, + const QWidget* widget) const { + baseStyle ()->drawComplexControl (control, option, painter, widget); } void -QTMProxyStyle::drawControl (ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { - baseStyle()->drawControl (element, option, painter, widget); +QTMProxyStyle::drawControl (ControlElement element, const QStyleOption* option, + QPainter* painter, const QWidget* widget) const { + baseStyle ()->drawControl (element, option, painter, widget); } void -QTMProxyStyle::drawItemPixmap (QPainter* painter, const QRect& rect, int alignment, const QPixmap& pixmap) const { - baseStyle()->drawItemPixmap (painter, rect, alignment, pixmap); +QTMProxyStyle::drawItemPixmap (QPainter* painter, const QRect& rect, + int alignment, const QPixmap& pixmap) const { + baseStyle ()->drawItemPixmap (painter, rect, alignment, pixmap); } void -QTMProxyStyle::drawItemText (QPainter* painter, const QRect& rect, int alignment, const QPalette& pal, bool enabled, const QString& text, QPalette::ColorRole textRole) const { - baseStyle()->drawItemText (painter, rect, alignment, pal, enabled, text, textRole); +QTMProxyStyle::drawItemText (QPainter* painter, const QRect& rect, + int alignment, const QPalette& pal, bool enabled, + const QString& text, + QPalette::ColorRole textRole) const { + baseStyle ()->drawItemText (painter, rect, alignment, pal, enabled, text, + textRole); } void -QTMProxyStyle::drawPrimitive (PrimitiveElement elem, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { - baseStyle()->drawPrimitive (elem, option, painter, widget); +QTMProxyStyle::drawPrimitive (PrimitiveElement elem, const QStyleOption* option, + QPainter* painter, const QWidget* widget) const { + baseStyle ()->drawPrimitive (elem, option, painter, widget); } QPixmap -QTMProxyStyle::generatedIconPixmap (QIcon::Mode iconMode, const QPixmap& pixmap, const QStyleOption* option) const { - return baseStyle()->generatedIconPixmap (iconMode, pixmap, option); +QTMProxyStyle::generatedIconPixmap (QIcon::Mode iconMode, const QPixmap& pixmap, + const QStyleOption* option) const { + return baseStyle ()->generatedIconPixmap (iconMode, pixmap, option); } QStyle::SubControl -QTMProxyStyle::hitTestComplexControl (ComplexControl control, const QStyleOptionComplex* option, const QPoint& pos, const QWidget* widget) const { - return baseStyle()->hitTestComplexControl (control, option, pos, widget); +QTMProxyStyle::hitTestComplexControl (ComplexControl control, + const QStyleOptionComplex* option, + const QPoint& pos, + const QWidget* widget) const { + return baseStyle ()->hitTestComplexControl (control, option, pos, widget); } QRect -QTMProxyStyle::itemPixmapRect (const QRect& rect, int alignment, const QPixmap& pixmap) const { - return baseStyle()->itemPixmapRect (rect, alignment, pixmap); +QTMProxyStyle::itemPixmapRect (const QRect& rect, int alignment, + const QPixmap& pixmap) const { + return baseStyle ()->itemPixmapRect (rect, alignment, pixmap); } QRect -QTMProxyStyle::itemTextRect (const QFontMetrics& metrics, const QRect& rect, int alignment, bool enabled, const QString& text) const { - return baseStyle()->itemTextRect (metrics, rect, alignment, enabled, text); +QTMProxyStyle::itemTextRect (const QFontMetrics& metrics, const QRect& rect, + int alignment, bool enabled, + const QString& text) const { + return baseStyle ()->itemTextRect (metrics, rect, alignment, enabled, text); } int -QTMProxyStyle::pixelMetric (PixelMetric metric, const QStyleOption* option, const QWidget* widget) const { - return baseStyle()->pixelMetric (metric, option, widget); +QTMProxyStyle::pixelMetric (PixelMetric metric, const QStyleOption* option, + const QWidget* widget) const { + return baseStyle ()->pixelMetric (metric, option, widget); } void QTMProxyStyle::polish (QWidget* widget) { - baseStyle()->polish (widget); + baseStyle ()->polish (widget); } void QTMProxyStyle::polish (QApplication* app) { - baseStyle()->polish (app); + baseStyle ()->polish (app); } void QTMProxyStyle::polish (QPalette& pal) { - baseStyle()->polish (pal); + baseStyle ()->polish (pal); } QSize -QTMProxyStyle::sizeFromContents (ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget) const { - return baseStyle()->sizeFromContents (type, option, contentsSize, widget); +QTMProxyStyle::sizeFromContents (ContentsType type, const QStyleOption* option, + const QSize& contentsSize, + const QWidget* widget) const { + return baseStyle ()->sizeFromContents (type, option, contentsSize, widget); } QIcon -QTMProxyStyle::standardIcon (StandardPixmap standardIcon, const QStyleOption* option, const QWidget* widget) const { - return baseStyle()->standardIcon (standardIcon, option, widget); +QTMProxyStyle::standardIcon (StandardPixmap standardIcon, + const QStyleOption* option, + const QWidget* widget) const { + return baseStyle ()->standardIcon (standardIcon, option, widget); } QPalette QTMProxyStyle::standardPalette () const { - return baseStyle()->standardPalette (); + return baseStyle ()->standardPalette (); } QPixmap -QTMProxyStyle::standardPixmap (StandardPixmap standardPixmap, const QStyleOption* option, const QWidget* widget) const { - return baseStyle()->standardPixmap (standardPixmap, option, widget); +QTMProxyStyle::standardPixmap (StandardPixmap standardPixmap, + const QStyleOption* option, + const QWidget* widget) const { + return baseStyle ()->standardPixmap (standardPixmap, option, widget); } int -QTMProxyStyle::styleHint (StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { - return baseStyle()->styleHint (hint, option, widget, returnData); +QTMProxyStyle::styleHint (StyleHint hint, const QStyleOption* option, + const QWidget* widget, + QStyleHintReturn* returnData) const { + return baseStyle ()->styleHint (hint, option, widget, returnData); } QRect -QTMProxyStyle::subControlRect (ComplexControl control, const QStyleOptionComplex* option, SubControl subControl, const QWidget* widget) const { - return baseStyle()->subControlRect (control, option, subControl, widget); +QTMProxyStyle::subControlRect (ComplexControl control, + const QStyleOptionComplex* option, + SubControl subControl, + const QWidget* widget) const { + return baseStyle ()->subControlRect (control, option, subControl, widget); } QRect -QTMProxyStyle::subElementRect (SubElement element, const QStyleOption* option, const QWidget* widget) const { - return baseStyle()->subElementRect (element, option, widget); +QTMProxyStyle::subElementRect (SubElement element, const QStyleOption* option, + const QWidget* widget) const { + return baseStyle ()->subElementRect (element, option, widget); } void QTMProxyStyle::unpolish (QWidget* widget) { - baseStyle()->unpolish (widget); + baseStyle ()->unpolish (widget); } void QTMProxyStyle::unpolish (QApplication* app) { - baseStyle()->unpolish (app); + baseStyle ()->unpolish (app); } - /****************************************************************************** * QTMStyle ******************************************************************************/ -static void qtmDrawRoundedRect(QPainter *p, const QRectF &rect, qreal xRadius, qreal yRadius, - Qt::SizeMode mode) -{ - QRectF r = rect.normalized(); - - if (r.isNull()) - return; - +static void +qtmDrawRoundedRect (QPainter* p, const QRectF& rect, qreal xRadius, + qreal yRadius, Qt::SizeMode mode) { + QRectF r= rect.normalized (); + + if (r.isNull ()) return; + if (mode == Qt::AbsoluteSize) { - qreal w = r.width() / 2; - qreal h = r.height() / 2; - - xRadius = 100 * qMin(xRadius, w) / w; - yRadius = 100 * qMin(yRadius, h) / h; - } else { - if (xRadius > 100) // fix ranges - xRadius = 100; - - if (yRadius > 100) - yRadius = 100; + qreal w= r.width () / 2; + qreal h= r.height () / 2; + + xRadius= 100 * qMin (xRadius, w) / w; + yRadius= 100 * qMin (yRadius, h) / h; + } + else { + if (xRadius > 100) // fix ranges + xRadius= 100; + + if (yRadius > 100) yRadius= 100; } - + QPainterPath path; - - if (xRadius <= 0 || yRadius <= 0) { // add normal rectangle - path.addRect(r); - } else { - qreal x = r.x(); - qreal y = r.y(); - qreal w = r.width(); - qreal h = r.height(); - qreal rxx2 = w*xRadius/100; - qreal ryy2 = h*yRadius/100; - + + if (xRadius <= 0 || yRadius <= 0) { // add normal rectangle + path.addRect (r); + } + else { + qreal x = r.x (); + qreal y = r.y (); + qreal w = r.width (); + qreal h = r.height (); + qreal rxx2= w * xRadius / 100; + qreal ryy2= h * yRadius / 100; + #ifdef Q_OS_LINUX // There is a bug (probably in arcTo) for small sizes. // We use a rough linear approx. - rxx2 /= 4; - ryy2 /= 4; - path.moveTo(x+rxx2,y); - path.lineTo(x+w-rxx2, y); - path.lineTo(x+w, y+ryy2); - path.lineTo(x+w, y+h-ryy2); - path.lineTo(x+w-rxx2, y+h); - path.lineTo(x+rxx2, y+h); - path.lineTo(x, y+h-ryy2); - path.lineTo(x, y+ryy2); - path.closeSubpath(); + rxx2/= 4; + ryy2/= 4; + path.moveTo (x + rxx2, y); + path.lineTo (x + w - rxx2, y); + path.lineTo (x + w, y + ryy2); + path.lineTo (x + w, y + h - ryy2); + path.lineTo (x + w - rxx2, y + h); + path.lineTo (x + rxx2, y + h); + path.lineTo (x, y + h - ryy2); + path.lineTo (x, y + ryy2); + path.closeSubpath (); #else - path.moveTo(x+rxx2,y); - path.arcMoveTo(x, y, rxx2, ryy2, 90); - path.arcTo(x, y, rxx2, ryy2, 90, 90); - path.arcTo(x, y+h-ryy2, rxx2, ryy2, 2*90, 90); - path.arcTo(x+w-rxx2, y+h-ryy2, rxx2, ryy2, 3*90, 90); - path.arcTo(x+w-rxx2, y, rxx2, ryy2, 0, 90); - path.closeSubpath(); + path.moveTo (x + rxx2, y); + path.arcMoveTo (x, y, rxx2, ryy2, 90); + path.arcTo (x, y, rxx2, ryy2, 90, 90); + path.arcTo (x, y + h - ryy2, rxx2, ryy2, 2 * 90, 90); + path.arcTo (x + w - rxx2, y + h - ryy2, rxx2, ryy2, 3 * 90, 90); + path.arcTo (x + w - rxx2, y, rxx2, ryy2, 0, 90); + path.closeSubpath (); #endif } - - p->drawPath(path); + + p->drawPath (path); } -static void qtmDrawShadeRoundPanel(QPainter *p, const QRect &r, - const QPalette &pal, bool sunken, - int lineWidth, const QBrush *fill) -{ - if (r.width() == 0 || r.height() == 0) - return; - if (!(r.width() > 0 && r.height() > 0 && lineWidth >= 0)) { - qWarning("qtmDrawShadeRoundPanel: Invalid parameters"); +static void +qtmDrawShadeRoundPanel (QPainter* p, const QRect& r, const QPalette& pal, + bool sunken, int lineWidth, const QBrush* fill) { + if (r.width () == 0 || r.height () == 0) return; + if (!(r.width () > 0 && r.height () > 0 && lineWidth >= 0)) { + qWarning ("qtmDrawShadeRoundPanel: Invalid parameters"); } - - QColor shade = pal.dark().color(); - QColor light = pal.light().color(); + + QColor shade= pal.dark ().color (); + QColor light= pal.light ().color (); if (fill) { - if (fill->color() == shade) - shade = pal.shadow().color(); - if (fill->color() == light) - light = pal.midlight().color(); + if (fill->color () == shade) shade= pal.shadow ().color (); + if (fill->color () == light) light= pal.midlight ().color (); } - - QPen oldPen = p->pen(); // save pen - QBrush oldBrush = p->brush(); // save brush - QRect rect(r); - int border = 8; - - p->setPen(Qt::NoPen); - + + QPen oldPen = p->pen (); // save pen + QBrush oldBrush= p->brush (); // save brush + QRect rect (r); + int border= 8; + + p->setPen (Qt::NoPen); + if (sunken) { - p->setBrush(light); - qtmDrawRoundedRect(p,rect,border,border, Qt::AbsoluteSize); + p->setBrush (light); + qtmDrawRoundedRect (p, rect, border, border, Qt::AbsoluteSize); // p->drawRoundedRect(rect,border,border, Qt::AbsoluteSize); - rect.adjust(0,0,-1,-1); - p->setBrush(shade); - qtmDrawRoundedRect(p,rect,border,border, Qt::AbsoluteSize); + rect.adjust (0, 0, -1, -1); + p->setBrush (shade); + qtmDrawRoundedRect (p, rect, border, border, Qt::AbsoluteSize); // p->drawRoundedRect(rect,border,border, Qt::AbsoluteSize); - rect.adjust(1,1,0,0); + rect.adjust (1, 1, 0, 0); } - - p->setBrush(fill ? *fill : shade); - qtmDrawRoundedRect(p,rect,border,border, Qt::AbsoluteSize); - // p->drawRoundedRect(rect,border,border, Qt::AbsoluteSize); - - p->setPen(oldPen); // restore pen - p->setBrush(oldBrush); // restore brush -} + p->setBrush (fill ? *fill : shade); + qtmDrawRoundedRect (p, rect, border, border, Qt::AbsoluteSize); + // p->drawRoundedRect(rect,border,border, Qt::AbsoluteSize); + p->setPen (oldPen); // restore pen + p->setBrush (oldBrush); // restore brush +} void -QTMStyle::drawPrimitive (PrimitiveElement element, const QStyleOption *opt, QPainter *p, const QWidget *widget) const { +QTMStyle::drawPrimitive (PrimitiveElement element, const QStyleOption* opt, + QPainter* p, const QWidget* widget) const { // if (element == QStyle::PE_FrameStatusBarItem) return; switch (element) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - case PE_FrameStatusBar : - return; +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + case PE_FrameStatusBar: + return; #else - // Use PE_FrameStatusBarItem instead. - // see https://doc.qt.io/qt-5/qstyle.html - case PE_FrameStatusBarItem : - return; + // Use PE_FrameStatusBarItem instead. + // see https://doc.qt.io/qt-5/qstyle.html + case PE_FrameStatusBarItem: + return; #endif - case PE_PanelButtonTool: - if ((opt->state & (State_Sunken | State_On))) { - qtmDrawShadeRoundPanel(p, opt->rect, QPalette(opt->palette.color(QPalette::Mid)),//opt->palette, - (opt->state & (State_Sunken | State_On)), 2, - &opt->palette.brush(QPalette::Mid)); - } else { - qtmDrawShadeRoundPanel(p, opt->rect, opt->palette, //QPalette(opt->palette.color(QPalette::Mid)),//opt->palette, - (opt->state & (State_Sunken | State_On)), 0, - &opt->palette.brush(QPalette::Mid)); - } - return; - default: - ; + case PE_PanelButtonTool: + if ((opt->state & (State_Sunken | State_On))) { + qtmDrawShadeRoundPanel ( + p, opt->rect, + QPalette (opt->palette.color (QPalette::Mid)), // opt->palette, + (opt->state & (State_Sunken | State_On)), 2, + &opt->palette.brush (QPalette::Mid)); + } + else { + qtmDrawShadeRoundPanel ( + p, opt->rect, + opt->palette, // QPalette(opt->palette.color(QPalette::Mid)),//opt->palette, + (opt->state & (State_Sunken | State_On)), 0, + &opt->palette.brush (QPalette::Mid)); + } + return; + default:; } - baseStyle()->drawPrimitive(element,opt,p,widget); + baseStyle ()->drawPrimitive (element, opt, p, widget); } - -void -QTMStyle::drawComplexControl (ComplexControl cc, const QStyleOptionComplex* opt, QPainter* p, const QWidget* widget) const { +void +QTMStyle::drawComplexControl (ComplexControl cc, const QStyleOptionComplex* opt, + QPainter* p, const QWidget* widget) const { switch (cc) { - case CC_ToolButton: - if (const QStyleOptionToolButton *toolbutton - = qstyleoption_cast(opt)) { - QRect button, menuarea; - button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget); - menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget); - - State bflags = toolbutton->state & ~State_Sunken; - - if (bflags & State_AutoRaise) { - if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) { - bflags &= ~State_Raised; - } - } - State mflags = bflags; - if (toolbutton->state & State_Sunken) { - if (toolbutton->activeSubControls & SC_ToolButton) - bflags |= State_Sunken; - mflags |= State_Sunken; - } - - QStyleOption tool(0); - tool.palette = toolbutton->palette; - if (toolbutton->subControls & SC_ToolButton) { - if (bflags & (State_Sunken | State_On | State_Raised)) { - tool.rect = button; - tool.state = bflags; - proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget); - } - } - - if (toolbutton->state & State_HasFocus) { - QStyleOptionFocusRect fr; - fr.QStyleOption::operator=(*toolbutton); - fr.rect.adjust(3, 3, -3, -3); - if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup) - fr.rect.adjust(0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, - toolbutton, widget), 0); - proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget); + case CC_ToolButton: + if (const QStyleOptionToolButton* toolbutton= + qstyleoption_cast (opt)) { + QRect button, menuarea; + button= proxy ()->subControlRect (cc, toolbutton, SC_ToolButton, widget); + menuarea= + proxy ()->subControlRect (cc, toolbutton, SC_ToolButtonMenu, widget); + + State bflags= toolbutton->state & ~State_Sunken; + + if (bflags & State_AutoRaise) { + if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) { + bflags&= ~State_Raised; } - QStyleOptionToolButton label = *toolbutton; - label.state = bflags; - int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget); - label.rect = button.adjusted(fw, fw, -fw, -fw); - proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget); - - if (toolbutton->subControls & SC_ToolButtonMenu) { - tool.rect = menuarea; - tool.state = mflags; - if (mflags & (State_Sunken | State_On | State_Raised)) - proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget); - proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget); - } else if ((toolbutton->features & QStyleOptionToolButton::HasMenu) - && (mflags & State_MouseOver)) - { - int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget); - QRect ir = toolbutton->rect; - QStyleOptionToolButton newBtn = *toolbutton; - newBtn.rect = QRect(ir.right() + 5 - mbi, ir.y() + ir.height() - mbi + 4, mbi - 6, mbi - 6); - proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget); + } + State mflags= bflags; + if (toolbutton->state & State_Sunken) { + if (toolbutton->activeSubControls & SC_ToolButton) + bflags|= State_Sunken; + mflags|= State_Sunken; + } + + QStyleOption tool (0); + tool.palette= toolbutton->palette; + if (toolbutton->subControls & SC_ToolButton) { + if (bflags & (State_Sunken | State_On | State_Raised)) { + tool.rect = button; + tool.state= bflags; + proxy ()->drawPrimitive (PE_PanelButtonTool, &tool, p, widget); } } - break; - default: - baseStyle()->drawComplexControl (cc, opt, p, widget); + + if (toolbutton->state & State_HasFocus) { + QStyleOptionFocusRect fr; + fr.QStyleOption::operator= (*toolbutton); + fr.rect.adjust (3, 3, -3, -3); + if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup) + fr.rect.adjust ( + 0, 0, + -proxy ()->pixelMetric (QStyle::PM_MenuButtonIndicator, + toolbutton, widget), + 0); + proxy ()->drawPrimitive (PE_FrameFocusRect, &fr, p, widget); + } + QStyleOptionToolButton label= *toolbutton; + label.state = bflags; + int fw = proxy ()->pixelMetric (PM_DefaultFrameWidth, opt, widget); + label.rect= button.adjusted (fw, fw, -fw, -fw); + proxy ()->drawControl (CE_ToolButtonLabel, &label, p, widget); + + if (toolbutton->subControls & SC_ToolButtonMenu) { + tool.rect = menuarea; + tool.state= mflags; + if (mflags & (State_Sunken | State_On | State_Raised)) + proxy ()->drawPrimitive (PE_IndicatorButtonDropDown, &tool, p, + widget); + proxy ()->drawPrimitive (PE_IndicatorArrowDown, &tool, p, widget); + } + else if ((toolbutton->features & QStyleOptionToolButton::HasMenu) && + (mflags & State_MouseOver)) { + int mbi= + proxy ()->pixelMetric (PM_MenuButtonIndicator, toolbutton, widget); + QRect ir = toolbutton->rect; + QStyleOptionToolButton newBtn= *toolbutton; + newBtn.rect = QRect (ir.right () + 5 - mbi, + ir.y () + ir.height () - mbi + 4, mbi - 6, mbi - 6); + proxy ()->drawPrimitive (PE_IndicatorArrowDown, &newBtn, p, widget); + } + } + break; + default: + baseStyle ()->drawComplexControl (cc, opt, p, widget); } } +QSize +QTMStyle::sizeFromContents (ContentsType type, const QStyleOption* option, + const QSize& contentsSize, + const QWidget* widget) const { + QSize sz (contentsSize); + switch (type) { + case CT_LineEdit: + sz= QSize (sz.width () + 2, sz.height () + 2); + break; + case CT_ToolButton: + sz= QSize (sz.width () + 4, sz.height () + 6); + break; - -QSize -QTMStyle::sizeFromContents (ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget) const { - QSize sz(contentsSize); - switch (type) { - case CT_LineEdit: - sz = QSize(sz.width() + 2, sz.height() + 2); - break; - - case CT_ToolButton: - sz = QSize(sz.width() + 4, sz.height() + 6); - break; - - default: - sz = baseStyle()->sizeFromContents(type, option, contentsSize, widget); + default: + sz= baseStyle ()->sizeFromContents (type, option, contentsSize, widget); } return sz; } - int -QTMStyle::pixelMetric (PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const { +QTMStyle::pixelMetric (PixelMetric metric, const QStyleOption* opt, + const QWidget* widget) const { switch (metric) { - case PM_ToolBarItemSpacing: - return 0; - case PM_ToolBarIconSize: - return 17; - // case PM_ToolBarFrameWidth: - // return 2; - default: - ; + case PM_ToolBarItemSpacing: + return 0; + case PM_ToolBarIconSize: + return 17; + // case PM_ToolBarFrameWidth: + // return 2; + default:; } - return baseStyle()->pixelMetric(metric,opt,widget); + return baseStyle ()->pixelMetric (metric, opt, widget); } void -QTMStyle::drawControl (ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { +QTMStyle::drawControl (ControlElement element, const QStyleOption* option, + QPainter* painter, const QWidget* widget) const { switch (element) { case CE_ToolBar: #ifdef UNIFIED_TOOLBAR - if (use_unified_toolbar && - (widget) && (widget->windowTitle() == "main toolbar")) + if (use_unified_toolbar && (widget) && + (widget->windowTitle () == "main toolbar")) break; #endif // UNIFIED_TOOLBAR - if ((widget) && (widget->windowTitle() == "main toolbar")) - painter->fillRect(option->rect, QColor (208, 208, 208)); - //painter->fillRect(option->rect, QColor (192, 192, 192)); - else if ((widget) && (widget->windowTitle() == "mode toolbar")) - painter->fillRect(option->rect, QColor (224, 224, 224)); - //painter->fillRect(option->rect, QColor (216, 216, 216)); - else if ((widget) && (widget->windowTitle() == "focus toolbar")) - painter->fillRect(option->rect, QColor (240, 240, 240)); - else - baseStyle()->drawControl (element, option, painter, widget); + if ((widget) && (widget->windowTitle () == "main toolbar")) + painter->fillRect (option->rect, QColor (208, 208, 208)); + // painter->fillRect(option->rect, QColor (192, 192, 192)); + else if ((widget) && (widget->windowTitle () == "mode toolbar")) + painter->fillRect (option->rect, QColor (224, 224, 224)); + // painter->fillRect(option->rect, QColor (216, 216, 216)); + else if ((widget) && (widget->windowTitle () == "focus toolbar")) + painter->fillRect (option->rect, QColor (240, 240, 240)); + else baseStyle ()->drawControl (element, option, painter, widget); break; - + default: - baseStyle()->drawControl (element, option, painter, widget); + baseStyle ()->drawControl (element, option, painter, widget); } } int -QTMStyle::styleHint (StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { +QTMStyle::styleHint (StyleHint hint, const QStyleOption* option, + const QWidget* widget, + QStyleHintReturn* returnData) const { switch (hint) { - case SH_MenuBar_AltKeyNavigation: - return 0; - // Set SH_MenuBar_AltKeyNavigation to false. Typically this would be the job of the style that is selected. - // However: That mechanism seems to be broken with some Qt versions. Furthermore, the Alt key is heavily - // used within TeXmacs, so the menubar navigation gets in the way quite often. - default: - return baseStyle()->styleHint (hint, option, widget, returnData); + case SH_MenuBar_AltKeyNavigation: + return 0; + // Set SH_MenuBar_AltKeyNavigation to false. Typically this would be the job + // of the style that is selected. However: That mechanism seems to be broken + // with some Qt versions. Furthermore, the Alt key is heavily used within + // TeXmacs, so the menubar navigation gets in the way quite often. + default: + return baseStyle ()->styleHint (hint, option, widget, returnData); } } - diff --git a/src/Plugins/Qt/QTMStyle.hpp b/src/Plugins/Qt/QTMStyle.hpp index 5f1a05bd9a..968295fc41 100644 --- a/src/Plugins/Qt/QTMStyle.hpp +++ b/src/Plugins/Qt/QTMStyle.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : QTMStyle.hpp -* DESCRIPTION: QT Texmacs custom style (for some elements) -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMStyle.hpp + * DESCRIPTION: QT Texmacs custom style (for some elements) + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMSTYLE_HPP #define QTMSTYLE_HPP @@ -17,8 +17,9 @@ int qt_zoom (int sz); #ifdef Q_OS_MAC -#define QTM_MINI_FONTSIZE 12 // also see uses of preference "gui:mini-fontsize" - // toolbar creation and config should be in scheme +#define QTM_MINI_FONTSIZE \ + 12 // also see uses of preference "gui:mini-fontsize" + // toolbar creation and config should be in scheme #else #define QTM_MINI_FONTSIZE 9 #endif @@ -26,66 +27,99 @@ int qt_zoom (int sz); #ifdef Q_OS_MAC #define UNIFIED_TOOLBAR extern bool use_unified_toolbar; - // enable the unified toolbar style on the mac. To work properly this requires - // a modification of the widget hierarchy of the main window. +// enable the unified toolbar style on the mac. To work properly this requires +// a modification of the widget hierarchy of the main window. #endif - // custom style to override some Qt "features" like - // frame around widgets in the status bar +// custom style to override some Qt "features" like +// frame around widgets in the status bar -class QTMProxyStyle: public QStyle { +class QTMProxyStyle : public QStyle { Q_OBJECT - + protected: QStyle* base; - + public: - explicit QTMProxyStyle (QStyle* _base = NULL); - - QStyle *baseStyle() const; - - int layoutSpacing(QSizePolicy::ControlType control1, - QSizePolicy::ControlType control2, - Qt::Orientation orientation, - const QStyleOption *option = 0, - const QWidget *widget = 0) const; - - void drawComplexControl (ComplexControl control, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget = 0) const; - void drawControl (ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget = 0) const; - void drawItemPixmap (QPainter* painter, const QRect& rect, int alignment, const QPixmap& pixmap) const; - void drawItemText (QPainter* painter, const QRect& rect, int alignment, const QPalette& pal, bool enabled, const QString& text, QPalette::ColorRole textRole = QPalette::NoRole) const; - void drawPrimitive (PrimitiveElement elem, const QStyleOption* option, QPainter* painter, const QWidget* widget = 0) const; - QPixmap generatedIconPixmap (QIcon::Mode iconMode, const QPixmap& pixmap, const QStyleOption* option) const; - SubControl hitTestComplexControl (ComplexControl control, const QStyleOptionComplex* option, const QPoint& pos, const QWidget* widget = 0) const; - QRect itemPixmapRect (const QRect& rect, int alignment, const QPixmap& pixmap) const; - QRect itemTextRect (const QFontMetrics& metrics, const QRect& rect, int alignment, bool enabled, const QString& text) const; - int pixelMetric (PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const; - void polish (QWidget* widget); - void polish (QApplication* app); - void polish (QPalette& pal); - QSize sizeFromContents (ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget = 0) const; - QIcon standardIcon (StandardPixmap standardIcon, const QStyleOption* option = 0, const QWidget* widget = 0) const; - QPalette standardPalette () const; - QPixmap standardPixmap (StandardPixmap standardPixmap, const QStyleOption* option = 0, const QWidget* widget = 0) const; - int styleHint (StyleHint hint, const QStyleOption* option = 0, const QWidget* widget = 0, QStyleHintReturn* returnData = 0) const; - QRect subControlRect (ComplexControl control, const QStyleOptionComplex* option, SubControl subControl, const QWidget* widget = 0) const; - QRect subElementRect (SubElement element, const QStyleOption* option, const QWidget* widget = 0) const; - void unpolish (QWidget* widget); - void unpolish (QApplication* app); + explicit QTMProxyStyle (QStyle* _base= NULL); + + QStyle* baseStyle () const; + + int layoutSpacing (QSizePolicy::ControlType control1, + QSizePolicy::ControlType control2, + Qt::Orientation orientation, const QStyleOption* option= 0, + const QWidget* widget= 0) const; + + void drawComplexControl (ComplexControl control, + const QStyleOptionComplex* option, QPainter* painter, + const QWidget* widget= 0) const; + void drawControl (ControlElement element, const QStyleOption* option, + QPainter* painter, const QWidget* widget= 0) const; + void drawItemPixmap (QPainter* painter, const QRect& rect, int alignment, + const QPixmap& pixmap) const; + void drawItemText (QPainter* painter, const QRect& rect, int alignment, + const QPalette& pal, bool enabled, const QString& text, + QPalette::ColorRole textRole= QPalette::NoRole) const; + void drawPrimitive (PrimitiveElement elem, const QStyleOption* option, + QPainter* painter, const QWidget* widget= 0) const; + QPixmap generatedIconPixmap (QIcon::Mode iconMode, const QPixmap& pixmap, + const QStyleOption* option) const; + SubControl hitTestComplexControl (ComplexControl control, + const QStyleOptionComplex* option, + const QPoint& pos, + const QWidget* widget= 0) const; + QRect itemPixmapRect (const QRect& rect, int alignment, + const QPixmap& pixmap) const; + QRect itemTextRect (const QFontMetrics& metrics, const QRect& rect, + int alignment, bool enabled, const QString& text) const; + int pixelMetric (PixelMetric metric, const QStyleOption* option= 0, + const QWidget* widget= 0) const; + void polish (QWidget* widget); + void polish (QApplication* app); + void polish (QPalette& pal); + QSize sizeFromContents (ContentsType type, const QStyleOption* option, + const QSize& contentsSize, + const QWidget* widget= 0) const; + QIcon standardIcon (StandardPixmap standardIcon, + const QStyleOption* option= 0, + const QWidget* widget= 0) const; + QPalette standardPalette () const; + QPixmap standardPixmap (StandardPixmap standardPixmap, + const QStyleOption* option= 0, + const QWidget* widget= 0) const; + int styleHint (StyleHint hint, const QStyleOption* option= 0, + const QWidget* widget = 0, + QStyleHintReturn* returnData= 0) const; + QRect subControlRect (ComplexControl control, + const QStyleOptionComplex* option, + SubControl subControl, const QWidget* widget= 0) const; + QRect subElementRect (SubElement element, const QStyleOption* option, + const QWidget* widget= 0) const; + void unpolish (QWidget* widget); + void unpolish (QApplication* app); }; -class QTMStyle: public QTMProxyStyle { +class QTMStyle : public QTMProxyStyle { Q_OBJECT - + public: - QTMStyle (QStyle* _style = NULL): QTMProxyStyle (_style) { } - - void drawComplexControl (ComplexControl control, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget = 0) const; - void drawPrimitive (PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; - int pixelMetric (PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const; - QSize sizeFromContents (ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget = 0) const; - void drawControl (ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget = 0) const; - int styleHint (StyleHint hint, const QStyleOption* option = 0, const QWidget* widget = 0, QStyleHintReturn* returnData = 0) const; + QTMStyle (QStyle* _style= NULL) : QTMProxyStyle (_style) {} + + void drawComplexControl (ComplexControl control, + const QStyleOptionComplex* option, QPainter* painter, + const QWidget* widget= 0) const; + void drawPrimitive (PrimitiveElement element, const QStyleOption* option, + QPainter* painter, const QWidget* widget) const; + int pixelMetric (PixelMetric metric, const QStyleOption* opt, + const QWidget* widget) const; + QSize sizeFromContents (ContentsType type, const QStyleOption* option, + const QSize& contentsSize, + const QWidget* widget= 0) const; + void drawControl (ControlElement element, const QStyleOption* option, + QPainter* painter, const QWidget* widget= 0) const; + int styleHint (StyleHint hint, const QStyleOption* option= 0, + const QWidget* widget = 0, + QStyleHintReturn* returnData= 0) const; }; QStyle* qtmstyle (); diff --git a/src/Plugins/Qt/QTMTreeModel.cpp b/src/Plugins/Qt/QTMTreeModel.cpp index 636b8931fd..71065dbb17 100644 --- a/src/Plugins/Qt/QTMTreeModel.cpp +++ b/src/Plugins/Qt/QTMTreeModel.cpp @@ -9,64 +9,63 @@ * in the root directory or . ******************************************************************************/ -#include "QTMGuiHelper.hpp" #include "QTMTreeModel.hpp" +#include "QTMGuiHelper.hpp" -#include "path.hpp" -#include "observers.hpp" #include "modification.hpp" +#include "observers.hpp" +#include "path.hpp" #include "tm_url.hpp" #include "qt_utilities.hpp" #include -const char* QTMTreeModel::bad_tree_data_exception = - "QTMTreeModel: couldn't parse provided data"; -const char* QTMTreeModel::no_observer_exception = - "QTMTreeModel: tree lacks tree pointer or inverse path observer"; +const char* QTMTreeModel::bad_tree_data_exception= + "QTMTreeModel: couldn't parse provided data"; +const char* QTMTreeModel::no_observer_exception= + "QTMTreeModel: tree lacks tree pointer or inverse path observer"; /*! Creates a QTMTreeModel attached to a given tree or returns the one already attached if present. - + See the documentation for QTMTreeModel for the format for data roles. - + @note The tree pointer is marked const because we don't retain the tree_rep - inside. However, we do attach observers to the tree, so maybe it + inside. However, we do attach observers to the tree, so maybe it shouldn't be const after all. */ QTMTreeModel* QTMTreeModel::instance (const tree& data, const tree& roles, QObject* parent) { - tree& t = const_cast (data); + tree& t= const_cast (data); if (!is_nil (data) && !is_nil (t->obs) && t->obs->get_type () == OBSERVER_WIDGET) return static_cast (t->obs.rep)->model; - else - return new QTMTreeModel (data, roles, parent); + else return new QTMTreeModel (data, roles, parent); } /*! Internal construction of QTMTreeModels - + Construction of QTMTreeModels is done using QTMTreeModel::instance () to ensure only one model is built and attached to a given tree. This is done internally with a qt_tree_observer attached to trees. This observer takes ownership of the QTMTreeModel. */ QTMTreeModel::QTMTreeModel (const tree& data, const tree& roles, QObject* p) -: QAbstractItemModel (p), _t_rep (inside (data)) { - tree t = tree (_t_rep); + : QAbstractItemModel (p), _t_rep (inside (data)) { + tree t= tree (_t_rep); parse_roles (roles); - const path& ip = obtain_ip (t); - if (is_nil (ip) || const_cast(ip)->item == DETACHED) - attach_ip (t, path(0)); + const path& ip= obtain_ip (t); + if (is_nil (ip) || const_cast (ip)->item == DETACHED) + attach_ip (t, path (0)); - // the qt_tree_observer takes ownership of this object + // the qt_tree_observer takes ownership of this object attach_observer (t, qt_tree_observer (this)); } QTMTreeModel::~QTMTreeModel () { - // We must not detach our observers here: the qt_tree_observer_rep is the - // owner of this object: if we are here, it is dying + // We must not detach our observers here: the qt_tree_observer_rep is the + // owner of this object: if we are here, it is dying } inline int @@ -76,63 +75,63 @@ QTMTreeModel::row_offset (const tree& t) const { tree QTMTreeModel::item_from_index (const QModelIndex& index) const { - if (!index.isValid()) return tree (_t_rep); - return tree (static_cast (index.internalPointer())); + if (!index.isValid ()) return tree (_t_rep); + return tree (static_cast (index.internalPointer ())); } inline QModelIndex QTMTreeModel::index_from_item (const tree& tref) const { tree& t = const_cast (tref); - tree _t = tree (_t_rep); - path ip = obtain_ip (t); + tree _t= tree (_t_rep); + path ip= obtain_ip (t); if (ipath_has_parent (ip)) { - path p = reverse (ip->next) / reverse (obtain_ip (_t));// Look one item up - if (is_nil (p)) return createIndex (ip->item, 0, inside (t)); // parent is root? - tree& pt = subtree (_t, p); // pt is the parent - int row = ip->item - row_offset (pt); + path p= reverse (ip->next) / reverse (obtain_ip (_t)); // Look one item up + if (is_nil (p)) + return createIndex (ip->item, 0, inside (t)); // parent is root? + tree& pt = subtree (_t, p); // pt is the parent + int row= ip->item - row_offset (pt); return createIndex (row, 0, inside (t)); } - return QModelIndex(); + return QModelIndex (); } bool QTMTreeModel::hasIndex (int row, int column, const QModelIndex& parent) const { (void) column; - const tree& t = item_from_index (parent); - return is_compound(t) && row + row_offset(t) < N(t) && column == 0; + const tree& t= item_from_index (parent); + return is_compound (t) && row + row_offset (t) < N (t) && column == 0; } QModelIndex QTMTreeModel::index (int row, int column, const QModelIndex& parent) const { - if (!hasIndex (row, column, parent)) return QModelIndex(); - tree t = item_from_index (parent); + if (!hasIndex (row, column, parent)) return QModelIndex (); + tree t= item_from_index (parent); - if (is_compound (t) && row + row_offset(t) < N(t)) - return createIndex (row, column, inside (t[row + row_offset(t)])); - else - return QModelIndex(); + if (is_compound (t) && row + row_offset (t) < N (t)) + return createIndex (row, column, inside (t[row + row_offset (t)])); + else return QModelIndex (); } QModelIndex QTMTreeModel::parent (const QModelIndex& index) const { - if (!index.isValid()) return QModelIndex(); - tree t = item_from_index (index); - path ip = obtain_ip (t); + if (!index.isValid ()) return QModelIndex (); + tree t = item_from_index (index); + path ip= obtain_ip (t); if (ipath_has_parent (ip)) { - path p = reverse (ip->next); // Look one item up in the path - if (is_nil (p)) return QModelIndex(); - tree _t = tree (_t_rep); - p = p / reverse (obtain_ip(_t)); - tree& pt = subtree (_t, p); // pt is the parent + path p= reverse (ip->next); // Look one item up in the path + if (is_nil (p)) return QModelIndex (); + tree _t = tree (_t_rep); + p = p / reverse (obtain_ip (_t)); + tree& pt= subtree (_t, p); // pt is the parent return index_from_item (pt); } - return QModelIndex(); + return QModelIndex (); } int QTMTreeModel::rowCount (const QModelIndex& parent) const { - tree t = item_from_index (parent); - return is_compound (t) ? N(t) - row_offset (t) : 0; + tree t= item_from_index (parent); + return is_compound (t) ? N (t) - row_offset (t) : 0; } int @@ -141,151 +140,146 @@ QTMTreeModel::columnCount (const QModelIndex& parent) const { return 1; } - /// FIXME: this method is called quite often, maybe some (more?) caching is - // necessary +/// FIXME: this method is called quite often, maybe some (more?) caching is +// necessary QVariant QTMTreeModel::data (const QModelIndex& index, int role) const { - const tree& tref = item_from_index (index); - tree& t = const_cast (tref); - int pos = _roles.contains(t->op) && _roles[t->op].contains(role) - ? _roles[t->op][role] : -1; - if (role >= TMUserRole && pos > -1 && !is_atomic (t) && N(t) >= pos && + const tree& tref= item_from_index (index); + tree& t = const_cast (tref); + int pos = _roles.contains (t->op) && _roles[t->op].contains (role) + ? _roles[t->op][role] + : -1; + if (role >= TMUserRole && pos > -1 && !is_atomic (t) && N (t) >= pos && is_atomic (t[pos])) return QVariant (to_qstring (t[pos]->label)); - + switch (role) { - case Qt::DisplayRole: - case Qt::EditRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - if (is_atomic (t)) - return to_qstring (t->label); - else if (pos == -1 || !is_atomic (t[pos])) - return to_qstring (as_string (L(t))); - else - return to_qstring (t[pos]->label); - case Qt::DecorationRole: - { - // NOTE: By calling QPixmap's constructor with a file name, I'm bypassing - // TeXmacs' caching of pictures in qt_load_xpm(), but since I need a - // QPixmap and TeXmacs stores QImages this is preferable because Qt uses - // QPixmapCache for all files it loads. - // It might actually be better to cache the QIcons first and return them - url u = "$TEXMACS_PIXMAP_PATH"; - if (pos == -1 || is_atomic (t) || !is_atomic (t[pos])) - u = resolve ("$TEXMACS_PIXMAP_PATH" * - url ("treelabel-" * as_string (L(t)) * ".xpm")); - else - u = resolve (url (t[pos]->label)); - if (is_rooted_name (u)) - return QPixmap (to_qstring (concretize (u))); - else - return QVariant(); - } - break; - case CommandRole: - if (pos > -1 && !is_atomic (t) && N(t) >= pos && is_atomic (t[pos])) - return QVariant (to_qstring (t[pos]->label)); - else - return QVariant(); - case Qt::SizeHintRole: - default: - return QVariant(); + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + if (is_atomic (t)) return to_qstring (t->label); + else if (pos == -1 || !is_atomic (t[pos])) + return to_qstring (as_string (L (t))); + else return to_qstring (t[pos]->label); + case Qt::DecorationRole: { + // NOTE: By calling QPixmap's constructor with a file name, I'm bypassing + // TeXmacs' caching of pictures in qt_load_xpm(), but since I need a + // QPixmap and TeXmacs stores QImages this is preferable because Qt uses + // QPixmapCache for all files it loads. + // It might actually be better to cache the QIcons first and return them + url u= "$TEXMACS_PIXMAP_PATH"; + if (pos == -1 || is_atomic (t) || !is_atomic (t[pos])) + u= resolve ("$TEXMACS_PIXMAP_PATH" * + url ("treelabel-" * as_string (L (t)) * ".xpm")); + else u= resolve (url (t[pos]->label)); + if (is_rooted_name (u)) return QPixmap (to_qstring (concretize (u))); + else return QVariant (); + } break; + case CommandRole: + if (pos > -1 && !is_atomic (t) && N (t) >= pos && is_atomic (t[pos])) + return QVariant (to_qstring (t[pos]->label)); + else return QVariant (); + case Qt::SizeHintRole: + default: + return QVariant (); } - return QVariant(); + return QVariant (); } bool QTMTreeModel::hasChildren (const QModelIndex& parent) const { - tree t = item_from_index (parent); - return is_compound (t) && N(t) > row_offset(t); + tree t= item_from_index (parent); + return is_compound (t) && N (t) > row_offset (t); } Qt::ItemFlags QTMTreeModel::flags (const QModelIndex& index) const { (void) index; - // FIXME: to do (plus draggable, etc.) + // FIXME: to do (plus draggable, etc.) return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } QVariant QTMTreeModel::headerData (int section, Qt::Orientation orient, int role) const { - (void) section; (void) orient; (void) role; - return QVariant(); + (void) section; + (void) orient; + (void) role; + return QVariant (); } inline bool QTMTreeModel::ipath_has_parent (const path& ip) const { - // Careful: our root _t might be a subtree of some other tree in TeXmacs - // already with inverse paths which lead further up the hierarchy - // than we manage. That's why we need the extra check with obtain_ip() - tree _t = tree (_t_rep); - return !is_nil (ip) && const_cast(ip)->item != DETACHED - && obtain_ip (_t) != ip; + // Careful: our root _t might be a subtree of some other tree in TeXmacs + // already with inverse paths which lead further up the hierarchy + // than we manage. That's why we need the extra check with obtain_ip() + tree _t= tree (_t_rep); + return !is_nil (ip) && const_cast (ip)->item != DETACHED && + obtain_ip (_t) != ip; } void QTMTreeModel::parse_roles (const tree& roles) { - tree& r = const_cast (roles); - + tree& r= const_cast (roles); + if (!is_compound (roles)) return; - - for (int i = 0; i < N(roles); ++i) { + + for (int i= 0; i < N (roles); ++i) { if (is_compound (r[i])) { - int tag = r[i]->op; - _roles[tag][NumberOfArguments] = N(r[i]); - for (int j = 0; j < N(r[i]); ++j) { + int tag = r[i]->op; + _roles[tag][NumberOfArguments]= N (r[i]); + for (int j= 0; j < N (r[i]); ++j) { ASSERT (is_atomic (r[i][j]), "QTMTreeModel: bad format declaration"); - string role = r[i][j]->label; - if (role == "DisplayRole") _roles[tag][Qt::DisplayRole] = j; - else if (role == "EditRole") _roles[tag][Qt::EditRole] = j; - else if (role == "DecorationRole") _roles[tag][Qt::DecorationRole] = j; - else if (role == "ToolTipRole") _roles[tag][Qt::ToolTipRole] = j; - else if (role == "CommandRole") _roles[tag][CommandRole] = j; + string role= r[i][j]->label; + if (role == "DisplayRole") _roles[tag][Qt::DisplayRole]= j; + else if (role == "EditRole") _roles[tag][Qt::EditRole]= j; + else if (role == "DecorationRole") _roles[tag][Qt::DecorationRole]= j; + else if (role == "ToolTipRole") _roles[tag][Qt::ToolTipRole]= j; + else if (role == "CommandRole") _roles[tag][CommandRole]= j; else if (string ("UserRole:") <= role) { - int num = max (0, min (9, as_int (role (9, N(role))) - 1)); - _roles[tag][TMUserRole + num] = j; + int num= max (0, min (9, as_int (role (9, N (role))) - 1)); + _roles[tag][TMUserRole + num]= j; } } } } } - /****************************************************************************** * qt_tree_observer_rep ******************************************************************************/ -qt_tree_observer_rep::~qt_tree_observer_rep () { - delete model; -} +qt_tree_observer_rep::~qt_tree_observer_rep () { delete model; } void qt_tree_observer_rep::announce (tree& ref, modification mod) { - (void) ref; (void) mod; - //if (mod->k != MOD_SET_CURSOR) - // model->beginResetModel(); + (void) ref; + (void) mod; + // if (mod->k != MOD_SET_CURSOR) + // model->beginResetModel(); /* MOD_SET_CURSOR is announced only for TeXmacs buffers. We might want to also keep a pointer to a QItemSelectionModel, or maybe some QTMItemSelectionModel (which would allow for intermediate proxy models used by the views, as does - KProxyItemSelectionModel (see - http://steveire.wordpress.com/2010/04/20/sharing-a-qitemselection-between-views-through-proxy-models/ )) - - In this case we could tell the views that they might want to update their selections, e.g. - + KProxyItemSelectionModel (see + http://steveire.wordpress.com/2010/04/20/sharing-a-qitemselection-between-views-through-proxy-models/ + )) + + In this case we could tell the views that they might want to update their + selections, e.g. + selection->setCurrentIndex (model->index_from_item (mod->t)); - + Or if we have a QTMTreeSelectionModel: - + selection_model->set_cursor (ref, mod); - + and QTMTreeSelectionModel::set_cursor would do something like: - + if (current_item != mod->t) { current_item = mod->t; emit currentChanged (index_from_item (current_item)); } - + The problem is we may not want all views to see their selections follow the cursor position. Furthermore, this only makes sense for buffers... */ @@ -293,13 +287,13 @@ qt_tree_observer_rep::announce (tree& ref, modification mod) { void qt_tree_observer_rep::done (tree& ref, modification mod) { - (void) ref; (void) mod; - //if (mod->k != MOD_SET_CURSOR) - // model->endResetModel(); + (void) ref; + (void) mod; + // if (mod->k != MOD_SET_CURSOR) + // model->endResetModel(); } observer qt_tree_observer (QTMTreeModel* model) { return tm_new (model); } - diff --git a/src/Plugins/Qt/QTMTreeModel.hpp b/src/Plugins/Qt/QTMTreeModel.hpp index 9ca332dfbc..4f69ea04e7 100644 --- a/src/Plugins/Qt/QTMTreeModel.hpp +++ b/src/Plugins/Qt/QTMTreeModel.hpp @@ -14,23 +14,23 @@ #include -#include "tree.hpp" #include "hashmap.hpp" #include "observer.hpp" +#include "tree.hpp" class QTMTreeModel; /*! An observer to keep a tree in sync with a QTMTreeModel (QAbstractItemModel). - + This object does two things: - + * it tells the model when to notify its views of changes. * it owns the QTMTreeModel and deletes it when the observer is detached from the tree and deleted. - + NOTE: we might want to manage a QSelectionItemModel as well. See the comments in announce(). - + FIXME: Currently we just beginResetModel() in announce() and endResetModel() in done(). This is wasteful and will scale very badly. */ @@ -39,13 +39,13 @@ class qt_tree_observer_rep : public observer_rep { public: explicit qt_tree_observer_rep (QTMTreeModel* _model) - : observer_rep(), model (_model) { } + : observer_rep (), model (_model) {} virtual ~qt_tree_observer_rep (); - - virtual int get_type () { return OBSERVER_WIDGET; } - + + virtual int get_type () { return OBSERVER_WIDGET; } + virtual void announce (tree& ref, modification mod); - virtual void done (tree& ref, modification mod); + virtual void done (tree& ref, modification mod); friend class QTMTreeModel; }; @@ -53,11 +53,11 @@ class qt_tree_observer_rep : public observer_rep { observer qt_tree_observer (QTMTreeModel* model); /*! QTMTreeModel is a QT model around a TeXmacs tree. - - The tree may be part of a document or any other tree. The first node in the + + The tree may be part of a document or any other tree. The first node in the data won't be displayed by views. Together with the data one may specify data roles for nodes in a separate argument. If the data is - + (root (library "First library" "icon.xpm" 12345 (collection "First collection" 001) @@ -65,29 +65,29 @@ observer qt_tree_observer (QTMTreeModel* model); (collection "Third collection" 003 (collection "First subcollection" 004) (collection "Second subcollection" 005)))) - + Then one may define the data roles as: - + (list (library DisplayRole DecorationRole UserRole:1) (collection DisplayRole UserRole:1)) - + Here "UserRole:number" is intended to be used to store things like database ids (in the example) or anything else. In addition to (some) of Qt::ItemDataRole this object supports the CommandRole, intended to assign commands to items which will be executed when (double) clicked. (TODO) - - @note On memory management: This object installs a qt_tree_observer at the + + @note On memory management: This object installs a qt_tree_observer at the root of the tree it is passed, which acts as a proxy for announcements and - notifications of modifications performed on the tree elements by e.g. the editor. - Currently we are very crude and simply reset the whole (!) model each time - there's a modification. This is extremely wasteful, but a complete + notifications of modifications performed on the tree elements by e.g. the + editor. Currently we are very crude and simply reset the whole (!) model each + time there's a modification. This is extremely wasteful, but a complete implementation requires much more work, because there are tree operations which don't translate easily into the beginInsertRows / endInsertRows framework of QAbstractItemModel. In particular, raw_insert_node replaces a node and this isn't either an insertion or a deletion. In order to keep the views in sync we could: - + * Keep a local copy of the whole tree and decompose TeXmacs' operations into Qt's, keeping things in sync. * Tag subtrees as "dirty" when they are about to be edited and return phony @@ -96,57 +96,56 @@ observer qt_tree_observer (QTMTreeModel* model); */ class QTMTreeModel : public QAbstractItemModel { Q_OBJECT - + static const char* bad_tree_data_exception; - static const char* no_observer_exception; - - static const int DETACHED = -5; - // NOTE: for some reason using hashmap was resulting in overwritten values. - // The very same code with QHash works ok. ?!?! - //typedef hashmap > roles_t; - typedef QHash > roles_t; - - tree_rep* _t_rep; //!< Our data. Must be tree_rep* or we have a cycle! - roles_t _roles; //!< Where in the data tree each data role is. - - QTMTreeModel (const tree& data, const tree& roles, QObject* parent = 0); + static const char* no_observer_exception; + + static const int DETACHED= -5; + // NOTE: for some reason using hashmap was resulting in overwritten values. + // The very same code with QHash works ok. ?!?! + // typedef hashmap > roles_t; + typedef QHash> roles_t; + + tree_rep* _t_rep; //!< Our data. Must be tree_rep* or we have a cycle! + roles_t _roles; //!< Where in the data tree each data role is. + + QTMTreeModel (const tree& data, const tree& roles, QObject* parent= 0); QTMTreeModel (const QTMTreeModel& _other); QTMTreeModel& operator= (QTMTreeModel& other); - + public: enum QTMRoles { - NumberOfArguments = Qt::UserRole + 1, // shouldn'be here... - CommandRole = Qt::UserRole + 2, - TMUserRole = Qt::UserRole + 32 + NumberOfArguments= Qt::UserRole + 1, // shouldn'be here... + CommandRole = Qt::UserRole + 2, + TMUserRole = Qt::UserRole + 32 }; virtual ~QTMTreeModel (); static QTMTreeModel* instance (const tree& data, const tree& roles, - QObject* parent = 0); - - virtual QModelIndex index (int row, int column, - const QModelIndex& parent = QModelIndex()) const; - virtual bool hasIndex (int row, int column, - const QModelIndex& parent) const; - virtual QModelIndex parent (const QModelIndex& index) const; - virtual int rowCount (const QModelIndex& parent = QModelIndex()) const; - virtual int columnCount (const QModelIndex& parent = QModelIndex()) const; - virtual QVariant data (const QModelIndex& index, - int role = Qt::DisplayRole) const; + QObject* parent= 0); + + virtual QModelIndex index (int row, int column, + const QModelIndex& parent= QModelIndex ()) const; + virtual bool hasIndex (int row, int column, const QModelIndex& parent) const; + virtual QModelIndex parent (const QModelIndex& index) const; + virtual int rowCount (const QModelIndex& parent= QModelIndex ()) const; + virtual int columnCount (const QModelIndex& parent= QModelIndex ()) const; + virtual QVariant data (const QModelIndex& index, + int role= Qt::DisplayRole) const; virtual Qt::ItemFlags flags (const QModelIndex& index) const; - virtual QVariant headerData (int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; - virtual bool hasChildren (const QModelIndex& parent = QModelIndex()) const; - + virtual QVariant headerData (int section, Qt::Orientation orientation, + int role= Qt::DisplayRole) const; + virtual bool hasChildren (const QModelIndex& parent= QModelIndex ()) const; + QModelIndex index_from_item (const tree& ref) const; tree item_from_index (const QModelIndex& index) const; friend class qt_tree_observer_rep; - + private: - bool ipath_has_parent (const path& ip) const; - void parse_roles (const tree& roles); - int row_offset (const tree& t) const; + bool ipath_has_parent (const path& ip) const; + void parse_roles (const tree& roles); + int row_offset (const tree& t) const; }; #endif // QTMTREEMODEL_HPP diff --git a/src/Plugins/Qt/QTMWidget.cpp b/src/Plugins/Qt/QTMWidget.cpp index e00aa86688..2bc95d07ad 100644 --- a/src/Plugins/Qt/QTMWidget.cpp +++ b/src/Plugins/Qt/QTMWidget.cpp @@ -1,57 +1,56 @@ /****************************************************************************** -* MODULE : QTMWidget.cpp -* DESCRIPTION: QT Texmacs widget class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli and Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMWidget.cpp + * DESCRIPTION: QT Texmacs widget class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli and Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "QTMWidget.hpp" -#include "qt_gui.hpp" -#include "qt_utilities.hpp" -#include "qt_simple_widget.hpp" -#include "converter.hpp" #include "boot.hpp" -#include "preferences.hpp" +#include "converter.hpp" #include "object_l5.hpp" +#include "preferences.hpp" +#include "qt_gui.hpp" +#include "qt_simple_widget.hpp" +#include "qt_utilities.hpp" #include "scheme.hpp" #include "sys_utils.hpp" #include "config.h" +#include #include #include -#include +#include #include -#include #include -#include +#include #include -#include +#include #include -#include #include +#include #include +#include #include -#include - -hashmap qtkeymap (0); -hashmap qtdeadmap (0); -hashmap qtcomposemap (0); +hashmap qtkeymap (0); +hashmap qtdeadmap (0); +hashmap qtcomposemap (0); inline void map (int code, string name) { - qtkeymap (code) = name; + qtkeymap (code)= name; } inline void deadmap (int code, string name) { - qtdeadmap (code) = name; + qtdeadmap (code)= name; } void @@ -60,74 +59,74 @@ initkeymap () { if (fInit) return; fInit= true; if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "Initializing keymap\n"; - map (Qt::Key_Space , "space"); - map (Qt::Key_Tab , "tab"); - map (Qt::Key_Backtab , "tab"); - map (Qt::Key_Return , "return"); - map (Qt::Key_Enter , "enter"); - map (Qt::Key_Escape , "escape"); - map (Qt::Key_Backspace , "backspace"); - map (Qt::Key_Up , "up" ); - map (Qt::Key_Down , "down" ); - map (Qt::Key_Left , "left" ); - map (Qt::Key_Right , "right" ); - map (Qt::Key_F1 , "F1" ); - map (Qt::Key_F2 , "F2" ); - map (Qt::Key_F3 , "F3" ); - map (Qt::Key_F4 , "F4" ); - map (Qt::Key_F5 , "F5" ); - map (Qt::Key_F6 , "F6" ); - map (Qt::Key_F7 , "F7" ); - map (Qt::Key_F8 , "F8" ); - map (Qt::Key_F9 , "F9" ); - map (Qt::Key_F10 , "F10" ); - map (Qt::Key_F11 , "F11" ); - map (Qt::Key_F12 , "F12" ); - map (Qt::Key_F13 , "F13" ); - map (Qt::Key_F14 , "F14" ); - map (Qt::Key_F15 , "F15" ); - map (Qt::Key_F16 , "F16" ); - map (Qt::Key_F17 , "F17" ); - map (Qt::Key_F18 , "F18" ); - map (Qt::Key_F19 , "F19" ); - map (Qt::Key_F20 , "F20" ); - map (Qt::Key_F21 , "F21" ); - map (Qt::Key_F22 , "F22" ); - map (Qt::Key_F23 , "F23" ); - map (Qt::Key_F24 , "F24" ); - map (Qt::Key_F25 , "F25" ); - map (Qt::Key_F26 , "F26" ); - map (Qt::Key_F27 , "F27" ); - map (Qt::Key_F28 , "F28" ); - map (Qt::Key_F29 , "F29" ); - map (Qt::Key_F30 , "F30" ); - map (Qt::Key_F31 , "F31" ); - map (Qt::Key_F32 , "F32" ); - map (Qt::Key_F33 , "F33" ); - map (Qt::Key_F34 , "F34" ); - map (Qt::Key_F35 , "F35" ); - map (Qt::Key_Insert , "insert" ); - map (Qt::Key_Delete , "delete" ); - map (Qt::Key_Home , "home" ); - map (Qt::Key_End , "end" ); - map (Qt::Key_PageUp , "pageup" ); - map (Qt::Key_PageDown , "pagedown" ); - map (Qt::Key_ScrollLock, "scrolllock" ); - map (Qt::Key_Pause , "pause" ); - map (Qt::Key_SysReq , "sysreq" ); - map (Qt::Key_Stop , "stop" ); - map (Qt::Key_Menu , "menu" ); - map (Qt::Key_Print , "print" ); - map (Qt::Key_Select , "select" ); - map (Qt::Key_Execute , "execute" ); - map (Qt::Key_Help , "help" ); - map (Qt::Key_section , "section" ); - - deadmap (Qt::Key_Dead_Acute , "acute"); - deadmap (Qt::Key_Dead_Grave , "grave"); - deadmap (Qt::Key_Dead_Diaeresis , "umlaut"); + map (Qt::Key_Space, "space"); + map (Qt::Key_Tab, "tab"); + map (Qt::Key_Backtab, "tab"); + map (Qt::Key_Return, "return"); + map (Qt::Key_Enter, "enter"); + map (Qt::Key_Escape, "escape"); + map (Qt::Key_Backspace, "backspace"); + map (Qt::Key_Up, "up"); + map (Qt::Key_Down, "down"); + map (Qt::Key_Left, "left"); + map (Qt::Key_Right, "right"); + map (Qt::Key_F1, "F1"); + map (Qt::Key_F2, "F2"); + map (Qt::Key_F3, "F3"); + map (Qt::Key_F4, "F4"); + map (Qt::Key_F5, "F5"); + map (Qt::Key_F6, "F6"); + map (Qt::Key_F7, "F7"); + map (Qt::Key_F8, "F8"); + map (Qt::Key_F9, "F9"); + map (Qt::Key_F10, "F10"); + map (Qt::Key_F11, "F11"); + map (Qt::Key_F12, "F12"); + map (Qt::Key_F13, "F13"); + map (Qt::Key_F14, "F14"); + map (Qt::Key_F15, "F15"); + map (Qt::Key_F16, "F16"); + map (Qt::Key_F17, "F17"); + map (Qt::Key_F18, "F18"); + map (Qt::Key_F19, "F19"); + map (Qt::Key_F20, "F20"); + map (Qt::Key_F21, "F21"); + map (Qt::Key_F22, "F22"); + map (Qt::Key_F23, "F23"); + map (Qt::Key_F24, "F24"); + map (Qt::Key_F25, "F25"); + map (Qt::Key_F26, "F26"); + map (Qt::Key_F27, "F27"); + map (Qt::Key_F28, "F28"); + map (Qt::Key_F29, "F29"); + map (Qt::Key_F30, "F30"); + map (Qt::Key_F31, "F31"); + map (Qt::Key_F32, "F32"); + map (Qt::Key_F33, "F33"); + map (Qt::Key_F34, "F34"); + map (Qt::Key_F35, "F35"); + map (Qt::Key_Insert, "insert"); + map (Qt::Key_Delete, "delete"); + map (Qt::Key_Home, "home"); + map (Qt::Key_End, "end"); + map (Qt::Key_PageUp, "pageup"); + map (Qt::Key_PageDown, "pagedown"); + map (Qt::Key_ScrollLock, "scrolllock"); + map (Qt::Key_Pause, "pause"); + map (Qt::Key_SysReq, "sysreq"); + map (Qt::Key_Stop, "stop"); + map (Qt::Key_Menu, "menu"); + map (Qt::Key_Print, "print"); + map (Qt::Key_Select, "select"); + map (Qt::Key_Execute, "execute"); + map (Qt::Key_Help, "help"); + map (Qt::Key_section, "section"); + + deadmap (Qt::Key_Dead_Acute, "acute"); + deadmap (Qt::Key_Dead_Grave, "grave"); + deadmap (Qt::Key_Dead_Diaeresis, "umlaut"); deadmap (Qt::Key_Dead_Circumflex, "hat"); - deadmap (Qt::Key_Dead_Tilde , "tilde"); + deadmap (Qt::Key_Dead_Tilde, "tilde"); // map (0x0003 , "K-enter"); // map (Qt::Key_Begin , "begin" ); @@ -151,32 +150,33 @@ initkeymap () { } #if defined(OS_MINGW) || defined(OS_WIN) enum WindowsNativeModifiers { - ShiftLeft = 0x00000001, - ControlLeft = 0x00000002, - AltLeft = 0x00000004, - MetaLeft = 0x00000008, - ShiftRight = 0x00000010, - ControlRight = 0x00000020, - AltRight = 0x00000040, - MetaRight = 0x00000080, - CapsLock = 0x00000100, - NumLock = 0x00000200, - ScrollLock = 0x00000400, - ExtendedKey = 0x01000000, + ShiftLeft = 0x00000001, + ControlLeft = 0x00000002, + AltLeft = 0x00000004, + MetaLeft = 0x00000008, + ShiftRight = 0x00000010, + ControlRight= 0x00000020, + AltRight = 0x00000040, + MetaRight = 0x00000080, + CapsLock = 0x00000100, + NumLock = 0x00000200, + ScrollLock = 0x00000400, + ExtendedKey = 0x01000000, }; #endif -static long int QTMWcounter = 0; // debugging hack +static long int QTMWcounter= 0; // debugging hack /*! Constructor. - + \param _parent The parent QWidget. \param _tmwid the TeXmacs widget who owns this object. */ QTMWidget::QTMWidget (QWidget* _parent, qt_widget _tmwid) -: QTMScrollView (_parent), tmwid (_tmwid), imwidget (NULL), - preediting (false) -{ - setObjectName (to_qstring ("QTMWidget" * as_string (QTMWcounter++)));// What is this for? (maybe only debugging?) + : QTMScrollView (_parent), tmwid (_tmwid), imwidget (NULL), + preediting (false) { + setObjectName (to_qstring ( + "QTMWidget" * + as_string (QTMWcounter++))); // What is this for? (maybe only debugging?) setFocusPolicy (Qt::StrongFocus); setAttribute (Qt::WA_InputMethodEnabled); surface ()->setMouseTracking (true); @@ -185,87 +185,87 @@ QTMWidget::QTMWidget (QWidget* _parent, qt_widget _tmwid) grabGesture (Qt::PinchGesture); grabGesture (Qt::SwipeGesture); -#if (QT_VERSION >= QT_VERSION_CHECK(5,9,0)) +#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)) surface ()->setTabletTracking (true); - for (QWidget *parent = surface()->parentWidget(); - parent != nullptr; parent = parent->parentWidget()) - parent->setTabletTracking(true); + for (QWidget* parent= surface ()->parentWidget (); parent != nullptr; + parent = parent->parentWidget ()) + parent->setTabletTracking (true); #endif if (DEBUG_QT) - debug_qt << "Creating " << from_qstring(objectName()) << " of widget " - << (tm_widget() ? tm_widget()->type_as_string() : "NULL") << LF; + debug_qt << "Creating " << from_qstring (objectName ()) << " of widget " + << (tm_widget () ? tm_widget ()->type_as_string () : "NULL") << LF; } QTMWidget::~QTMWidget () { if (DEBUG_QT) - debug_qt << "Destroying " << from_qstring(objectName()) << " of widget " - << (tm_widget() ? tm_widget()->type_as_string() : "NULL") << LF; + debug_qt << "Destroying " << from_qstring (objectName ()) << " of widget " + << (tm_widget () ? tm_widget ()->type_as_string () : "NULL") << LF; } qt_simple_widget_rep* -QTMWidget::tm_widget () const { - return concrete_simple_widget (tmwid); +QTMWidget::tm_widget () const { + return concrete_simple_widget (tmwid); } -void +void QTMWidget::scrollContentsBy (int dx, int dy) { - QTMScrollView::scrollContentsBy (dx,dy); + QTMScrollView::scrollContentsBy (dx, dy); - the_gui->force_update(); + the_gui->force_update (); // we force an update of the internal state to be in sync with the moving // scrollbars } -void +void QTMWidget::resizeEvent (QResizeEvent* event) { (void) event; // Is this ok? - //coord2 s = from_qsize (event->size()); - //the_gui -> process_resize (tm_widget(), s.x1, s.x2); + // coord2 s = from_qsize (event->size()); + // the_gui -> process_resize (tm_widget(), s.x1, s.x2); // the_gui->force_update(); - //FIXME: I would like to have a force_update here but this causes a failed - //assertion in TeXmacs since the at the boot not every internal structure is - //initialized at this point. It seems not too difficult to fix but I - //postpone this to discuss with Joris. + // FIXME: I would like to have a force_update here but this causes a failed + // assertion in TeXmacs since the at the boot not every internal structure is + // initialized at this point. It seems not too difficult to fix but I + // postpone this to discuss with Joris. // - //Not having a force_update results in some lack of sync of the surface - //while the user is actively resizing with the mouse. + // Not having a force_update results in some lack of sync of the surface + // while the user is actively resizing with the mouse. } void -QTMWidget::resizeEventBis (QResizeEvent *event) { - coord2 s = from_qsize (event->size()); - the_gui -> process_resize (tm_widget(), s.x1, s.x2); +QTMWidget::resizeEventBis (QResizeEvent* event) { + coord2 s= from_qsize (event->size ()); + the_gui->process_resize (tm_widget (), s.x1, s.x2); } /*! In the current implementation repainting takes place during the call to the widget's repaint_invalid_regions() method in the_gui::update. All we have to do is to take the backing store and put it on screen according - to the QRegion marked invalid. - CHECK: Maybe just putting onscreen all the region bounding rectangles might + to the QRegion marked invalid. + CHECK: Maybe just putting onscreen all the region bounding rectangles might be less expensive. */ void QTMWidget::paintEvent (QPaintEvent* event) { - QPainter p (surface()); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QVector rects = event->region().rects(); - for (int i = 0; i < rects.count(); ++i) { - QRect qr = rects.at (i); + QPainter p (surface ()); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QVector rects= event->region ().rects (); + for (int i= 0; i < rects.count (); ++i) { + QRect qr= rects.at (i); #else - for (const QRect* it = event->region().begin(); it != event->region().end(); it++) { - QRect qr = *it; + for (const QRect* it= event->region ().begin (); + it != event->region ().end (); it++) { + QRect qr= *it; #endif - p.drawPixmap (QRect (qr.x(), qr.y(), qr.width(), qr.height()), - *(tm_widget()->backingPixmap), - QRect (retina_factor * qr.x(), - retina_factor * qr.y(), - retina_factor * qr.width(), - retina_factor * qr.height())); + p.drawPixmap (QRect (qr.x (), qr.y (), qr.width (), qr.height ()), + *(tm_widget ()->backingPixmap), + QRect (retina_factor * qr.x (), retina_factor * qr.y (), + retina_factor * qr.width (), + retina_factor * qr.height ())); } } @@ -287,23 +287,23 @@ get_shift_preference (char key_code) { void QTMWidget::keyPressEvent (QKeyEvent* event) { if (is_nil (tmwid)) return; - initkeymap(); + initkeymap (); if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "keypressed\n"; { - int key = event->key(); - Qt::KeyboardModifiers mods = event->modifiers(); + int key = event->key (); + Qt::KeyboardModifiers mods= event->modifiers (); if (DEBUG_QT && DEBUG_KEYBOARD) { debug_qt << "key : " << key << LF; - debug_qt << "text : " << event->text().toLatin1().data() << LF; - debug_qt << "count: " << event->text().size() << LF; - debug_qt << "unic : " << event->text().data()[0].unicode() << LF; + debug_qt << "text : " << event->text ().toLatin1 ().data () << LF; + debug_qt << "count: " << event->text ().size () << LF; + debug_qt << "unic : " << event->text ().data ()[0].unicode () << LF; #if defined(OS_MINGW) || defined(OS_WIN) - debug_qt << "nativeScanCode: " << event->nativeScanCode() << LF; - debug_qt << "nativeVirtualKey: " << event->nativeVirtualKey() << LF; - debug_qt << "nativeModifiers: " << event->nativeModifiers() << LF; + debug_qt << "nativeScanCode: " << event->nativeScanCode () << LF; + debug_qt << "nativeVirtualKey: " << event->nativeVirtualKey () << LF; + debug_qt << "nativeModifiers: " << event->nativeModifiers () << LF; #endif if (mods & Qt::ShiftModifier) debug_qt << "shift\n"; if (mods & Qt::MetaModifier) debug_qt << "meta\n"; @@ -314,33 +314,35 @@ QTMWidget::keyPressEvent (QKeyEvent* event) { string r; #if defined(OS_MINGW) || defined(OS_WIN) -/* "Qt::Key_AltGr On Windows, when the KeyDown event for this key is sent, -* the Ctrl+Alt modifiers are also set." (excerpt from Qt doc) -* However the AltGr key is used to obtain many symbols -* which should not be regarded as C-A- shortcuts. -* (e.g. \ or @ on a French keyboard) -* -* Hence, when "native modifiers" are (ControlLeft | AltRight) -* we clear Qt's Ctrl+Alt modifiers -*/ - if ((event->nativeModifiers() & (ControlLeft | AltRight)) == (ControlLeft | AltRight)) { - if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "assuming it's an AltGr key code"<nativeModifiers () & (ControlLeft | AltRight)) == + (ControlLeft | AltRight)) { + if (DEBUG_QT && DEBUG_KEYBOARD) + debug_qt << "assuming it's an AltGr key code" << LF; + mods&= ~Qt::AltModifier; + mods&= ~Qt::ControlModifier; } #endif if (qtkeymap->contains (key)) { - r = qtkeymap[key]; + r= qtkeymap[key]; } else if (qtdeadmap->contains (key)) { - mods &=~ Qt::ShiftModifier; - r = qtdeadmap[key]; + mods&= ~Qt::ShiftModifier; + r= qtdeadmap[key]; } else { - // We need to use text(): Alt-{5,6,7,8,9} are []|{} under MacOS, etc. - QString nss = event->text(); - unsigned int kc = event->nativeVirtualKey(); - unsigned short unic= nss.data()[0].unicode(); + // We need to use text(): Alt-{5,6,7,8,9} are []|{} under MacOS, etc. + QString nss = event->text (); + unsigned int kc = event->nativeVirtualKey (); + unsigned short unic= nss.data ()[0].unicode (); /* debug_qt << "key : " << key << LF; debug_qt << "text : " << event->text().toLatin1().data() << LF; @@ -353,10 +355,8 @@ QTMWidget::keyPressEvent (QKeyEvent* event) { cout << kc << ", " << ((mods & Qt::ShiftModifier) != 0) << " -> " << unic << LF; */ - if (unic > 32 && unic < 255 && - (mods & Qt::ShiftModifier) != 0 && - (mods & Qt::ControlModifier) == 0 && - (mods & Qt::AltModifier) == 0 && + if (unic > 32 && unic < 255 && (mods & Qt::ShiftModifier) != 0 && + (mods & Qt::ControlModifier) == 0 && (mods & Qt::AltModifier) == 0 && (mods & Qt::MetaModifier) == 0) set_shift_preference (kc, (char) unic); #ifdef Q_OS_WIN @@ -372,87 +372,99 @@ QTMWidget::keyPressEvent (QKeyEvent* event) { // dirty hacking to figure out the right shifted variant of a key // by ourselves... if (is_upcase ((char) key)) { - if ((mods & Qt::ShiftModifier) == 0) - key= (int) locase ((char) key); + if ((mods & Qt::ShiftModifier) == 0) key= (int) locase ((char) key); } - else if (has_shift_preference (kc) && - (mods & Qt::ShiftModifier) != 0 && + else if (has_shift_preference (kc) && (mods & Qt::ShiftModifier) != 0 && (mods & Qt::ControlModifier) != 0) { string pref= get_shift_preference (kc); - if (N(pref) > 0) key= (int) (unsigned char) pref [0]; + if (N (pref) > 0) key= (int) (unsigned char) pref[0]; if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "Control+Shift " << kc << " -> " << key << LF; } - mods &=~ Qt::ShiftModifier; + mods&= ~Qt::ShiftModifier; r= string ((char) key); } else { switch (unic) { - case 96: r= "`"; - // unicode to cork conversion not appropriate for this case... + case 96: + r= "`"; + // unicode to cork conversion not appropriate for this case... #ifdef Q_OS_MAC - // CHECKME: are these two MAC exceptions really needed? - if (mods & Qt::AltModifier) r= "grave"; + // CHECKME: are these two MAC exceptions really needed? + if (mods & Qt::AltModifier) r= "grave"; #endif - break; - case 168: r= "umlaut"; break; - case 180: r= "acute"; break; - // the following combining characters should be caught by qtdeadmap - case 0x300: r= "grave"; break; - case 0x301: r= "acute"; break; - case 0x302: r= "hat"; break; - case 0x308: r= "umlaut"; break; - case 0x33e: r= "tilde"; break; - default: - QByteArray buf= nss.toUtf8(); - string rr (buf.constData(), buf.size()); - string tstr= utf8_to_cork (rr); - // HACK! The encodings defined in langs/encoding and which - // utf8_to_cork uses (via the converters loaded in - // converter_rep::load()), enclose the texmacs symbols in "< >", - // but this format is not used for keypresses, so we must remove - // them. - int len= N (tstr); - if (len >= 1 && tstr[0] == '<' && tstr[1] != '#' && tstr[len-1] == '>') - r= tstr (1, len-1); - else - r= tstr; - if (r == "less") r= "<"; - else if (r == "gtr") r= ">"; + break; + case 168: + r= "umlaut"; + break; + case 180: + r= "acute"; + break; + // the following combining characters should be caught by qtdeadmap + case 0x300: + r= "grave"; + break; + case 0x301: + r= "acute"; + break; + case 0x302: + r= "hat"; + break; + case 0x308: + r= "umlaut"; + break; + case 0x33e: + r= "tilde"; + break; + default: + QByteArray buf= nss.toUtf8 (); + string rr (buf.constData (), buf.size ()); + string tstr= utf8_to_cork (rr); + // HACK! The encodings defined in langs/encoding and which + // utf8_to_cork uses (via the converters loaded in + // converter_rep::load()), enclose the texmacs symbols in "< >", + // but this format is not used for keypresses, so we must remove + // them. + int len= N (tstr); + if (len >= 1 && tstr[0] == '<' && tstr[1] != '#' && + tstr[len - 1] == '>') + r= tstr (1, len - 1); + else r= tstr; + if (r == "less") r= "<"; + else if (r == "gtr") r= ">"; } -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) if (os_macos () && (mods & Qt::AltModifier)) { // Alt produces many symbols in Mac keyboards: []|{} etc. - if ((N(r) != 1 || - ((int) (unsigned char) r[0]) < 32 || - ((int) (unsigned char) r[0]) >= 128) && + if ((N (r) != 1 || ((int) (unsigned char) r[0]) < 32 || + ((int) (unsigned char) r[0]) >= 128) && key >= 32 && key < 128 && ((mods & (Qt::MetaModifier + Qt::ControlModifier)) == 0)) { if ((mods & Qt::ShiftModifier) == 0 && key >= 65 && key <= 90) - key += 32; + key+= 32; qtcomposemap (key)= r; - r= string ((char) key); + r = string ((char) key); } - else mods &= ~Qt::AltModifier; //unset Alt + else mods&= ~Qt::AltModifier; // unset Alt } #endif - mods &= ~Qt::ShiftModifier; + mods&= ~Qt::ShiftModifier; } } if (r == "") return; if (mods & Qt::ShiftModifier) r= "S-" * r; if (mods & Qt::AltModifier) r= "A-" * r; - //if (mods & Qt::KeypadModifier) r= "K-" * r; + // if (mods & Qt::KeypadModifier) r= "K-" * r; #ifdef Q_OS_MAC - if (mods & Qt::MetaModifier) r= "C-" * r; // The "Control" key - if (mods & Qt::ControlModifier) r= "M-" * r; // The "Command" key + if (mods & Qt::MetaModifier) r= "C-" * r; // The "Control" key + if (mods & Qt::ControlModifier) r= "M-" * r; // The "Command" key #else if (mods & Qt::ControlModifier) r= "C-" * r; - if (mods & Qt::MetaModifier) r= "M-" * r; // The "Windows" key + if (mods & Qt::MetaModifier) r= "M-" * r; // The "Windows" key #endif if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "key press: " << r << LF; - the_gui->process_keypress (tm_widget(), r, texmacs_time()); + the_gui->process_keypress (tm_widget (), r, texmacs_time ()); } } @@ -460,16 +472,16 @@ void QTMWidget::keyReleaseEvent (QKeyEvent* event) { if (os_macos ()) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - Qt::KeyboardModifiers mods = event->modifiers(); - int key = event->key(); + Qt::KeyboardModifiers mods= event->modifiers (); + int key = event->key (); // see https://bugreports.qt.io/browse/QTBUG-115525 // This branch is only for Option-Command-x or Ctrl-Command-x - if ((mods & Qt::ControlModifier) && ((mods & Qt::AltModifier) || (mods & Qt::MetaModifier))) { + if ((mods & Qt::ControlModifier) && + ((mods & Qt::AltModifier) || (mods & Qt::MetaModifier))) { string r; - if (key >=32 && key < 128) { - if ((mods & Qt::ShiftModifier) == 0 && key >= 65 && key <= 90) - key += 32; + if (key >= 32 && key < 128) { + if ((mods & Qt::ShiftModifier) == 0 && key >= 65 && key <= 90) key+= 32; r= string ((char) key); if (mods & Qt::AltModifier) { r= "M-A-" * r; @@ -479,7 +491,7 @@ QTMWidget::keyReleaseEvent (QKeyEvent* event) { } } if (DEBUG_QT && DEBUG_KEYBOARD) debug_qt << "key press: " << r << LF; - the_gui->process_keypress (tm_widget(), r, texmacs_time()); + the_gui->process_keypress (tm_widget (), r, texmacs_time ()); } #endif } @@ -487,28 +499,28 @@ QTMWidget::keyReleaseEvent (QKeyEvent* event) { static unsigned int mouse_state (QMouseEvent* event, bool flag) { - unsigned int i= 0; - Qt::MouseButtons bstate= event->buttons (); - Qt::MouseButton tstate= event->button (); + unsigned int i = 0; + Qt::MouseButtons bstate= event->buttons (); + Qt::MouseButton tstate= event->button (); Qt::KeyboardModifiers kstate= event->modifiers (); if (flag) bstate= bstate | tstate; - if ((bstate & Qt::LeftButton ) != 0) i += 1; - if ((bstate & Qt::MiddleButton ) != 0) i += 2; - if ((bstate & Qt::RightButton ) != 0) i += 4; - if ((bstate & Qt::XButton1 ) != 0) i += 8; - if ((bstate & Qt::XButton2 ) != 0) i += 16; + if ((bstate & Qt::LeftButton) != 0) i+= 1; + if ((bstate & Qt::MiddleButton) != 0) i+= 2; + if ((bstate & Qt::RightButton) != 0) i+= 4; + if ((bstate & Qt::XButton1) != 0) i+= 8; + if ((bstate & Qt::XButton2) != 0) i+= 16; #ifdef Q_OS_MAC - // We emulate right and middle clicks with ctrl and option, but we pass the - // modifiers anyway: old code continues to work and new one can use them. - if ((kstate & Qt::MetaModifier ) != 0) i = 1024+4; // control key - if ((kstate & Qt::AltModifier ) != 0) i = 2048+2; // option key - if ((kstate & Qt::ShiftModifier ) != 0) i += 256; - if ((kstate & Qt::ControlModifier) != 0) i += 4096; // cmd key + // We emulate right and middle clicks with ctrl and option, but we pass the + // modifiers anyway: old code continues to work and new one can use them. + if ((kstate & Qt::MetaModifier) != 0) i= 1024 + 4; // control key + if ((kstate & Qt::AltModifier) != 0) i= 2048 + 2; // option key + if ((kstate & Qt::ShiftModifier) != 0) i+= 256; + if ((kstate & Qt::ControlModifier) != 0) i+= 4096; // cmd key #else - if ((kstate & Qt::ShiftModifier ) != 0) i += 256; - if ((kstate & Qt::ControlModifier) != 0) i += 1024; - if ((kstate & Qt::AltModifier ) != 0) i += 2048; - if ((kstate & Qt::MetaModifier ) != 0) i += 4096; + if ((kstate & Qt::ShiftModifier) != 0) i+= 256; + if ((kstate & Qt::ControlModifier) != 0) i+= 1024; + if ((kstate & Qt::AltModifier) != 0) i+= 2048; + if ((kstate & Qt::MetaModifier) != 0) i+= 4096; #endif return i; } @@ -517,7 +529,8 @@ static string mouse_decode (unsigned int mstate) { if (mstate & 2) return "middle"; else if (mstate & 4) return "right"; - // we check for left clicks after the others for macos (see ifdef in mouse_state) + // we check for left clicks after the others for macos (see ifdef in + // mouse_state) else if (mstate & 1) return "left"; else if (mstate & 8) return "up"; else if (mstate & 16) return "down"; @@ -532,165 +545,166 @@ QTMWidget::kbdEvent (int key, Qt::KeyboardModifiers mods, const QString& s) { void QTMWidget::inputMethodEvent (QInputMethodEvent* event) { - QString const & preedit_string = event->preeditString(); - QString const & commit_string = event->commitString(); - - if (!commit_string.isEmpty()) { + QString const& preedit_string= event->preeditString (); + QString const& commit_string = event->commitString (); + + if (!commit_string.isEmpty ()) { bool done= false; if (!done) { if (DEBUG_QT) - debug_qt << "IM committing: " << commit_string.toUtf8().data() << LF; + debug_qt << "IM committing: " << commit_string.toUtf8 ().data () << LF; if (get_preference ("speech", "off") == "on") { string s= "speech:" * from_qstring (commit_string); kbdEvent (0, Qt::NoModifier, to_qstring (s)); - } else { - for (int i = 0; i < commit_string.size(); ++i) + } + else { + for (int i= 0; i < commit_string.size (); ++i) kbdEvent (0, Qt::NoModifier, commit_string[i]); } } } - + if (DEBUG_QT) - debug_qt << "IM preediting :" << preedit_string.toUtf8().data() << LF; - - string r = "pre-edit:"; - if (!preedit_string.isEmpty()) - { - + debug_qt << "IM preediting :" << preedit_string.toUtf8 ().data () << LF; + + string r= "pre-edit:"; + if (!preedit_string.isEmpty ()) { + // find cursor position in the preedit string - QList const & attrs = event->attributes(); + QList const& attrs= event->attributes (); // int pos = preedit_string.count(); - int pos = 0; - bool visible_cur = false; - for (int i=0; i< attrs.count(); i++) + int pos = 0; + bool visible_cur= false; + for (int i= 0; i < attrs.count (); i++) if (attrs[i].type == QInputMethodEvent::Cursor) { - pos = attrs[i].start; - visible_cur = (attrs[i].length != 0); + pos = attrs[i].start; + visible_cur= (attrs[i].length != 0); } - + // find selection in the preedit string int sel_start = 0; - int sel_length = 0; - if (pos < preedit_string.size()) { - for (int i=0; i< attrs.count(); i++) + int sel_length= 0; + if (pos < preedit_string.size ()) { + for (int i= 0; i < attrs.count (); i++) if ((attrs[i].type == QInputMethodEvent::TextFormat) && (attrs[i].start <= pos) && (pos < attrs[i].start + attrs[i].length)) { sel_start = attrs[i].start; - sel_length = attrs[i].length; - if (!visible_cur) pos += attrs[i].length; + sel_length= attrs[i].length; + if (!visible_cur) pos+= attrs[i].length; } - } else { + } + else { sel_start = pos; - sel_length = 0; + sel_length= 0; } - (void) sel_start; (void) sel_length; - - r = r * as_string (pos) * ":" * from_qstring (preedit_string); + (void) sel_start; + (void) sel_length; + + r= r * as_string (pos) * ":" * from_qstring (preedit_string); } if (!is_nil (tmwid)) { - preediting = !preedit_string.isEmpty(); - the_gui->process_keypress (tm_widget(), r, texmacs_time()); + preediting= !preedit_string.isEmpty (); + the_gui->process_keypress (tm_widget (), r, texmacs_time ()); } - event->accept(); -} + event->accept (); +} -QVariant +QVariant QTMWidget::inputMethodQuery (Qt::InputMethodQuery query) const { switch (query) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - // This query is obsolete. Use ImCursorRectangle instead. - case Qt::ImMicroFocus : { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + // This query is obsolete. Use ImCursorRectangle instead. + case Qt::ImMicroFocus: { #else - case Qt::ImCursorRectangle : { + case Qt::ImCursorRectangle: { #endif - const QPoint &topleft= cursor_pos - tm_widget()->backing_pos + surface()->geometry().topLeft(); - return QVariant (QRect (topleft, QSize (5, 5))); - } - default: - return QWidget::inputMethodQuery (query); + const QPoint& topleft= cursor_pos - tm_widget ()->backing_pos + + surface ()->geometry ().topLeft (); + return QVariant (QRect (topleft, QSize (5, 5))); + } + default: + return QWidget::inputMethodQuery (query); } } void QTMWidget::mousePressEvent (QMouseEvent* event) { if (is_nil (tmwid)) return; - QPoint point = event->pos() + origin(); - coord2 pt = from_qpoint(point); + QPoint point = event->pos () + origin (); + coord2 pt = from_qpoint (point); unsigned int mstate= mouse_state (event, false); - string s= "press-" * mouse_decode (mstate); - the_gui -> process_mouse (tm_widget(), s, pt.x1, pt.x2, - mstate, texmacs_time ()); - event->accept(); + string s = "press-" * mouse_decode (mstate); + the_gui->process_mouse (tm_widget (), s, pt.x1, pt.x2, mstate, + texmacs_time ()); + event->accept (); } void QTMWidget::mouseReleaseEvent (QMouseEvent* event) { if (is_nil (tmwid)) return; - QPoint point = event->pos() + origin(); - coord2 pt = from_qpoint(point); - unsigned int mstate = mouse_state (event, true); - string s = "release-" * mouse_decode (mstate); - the_gui->process_mouse (tm_widget(), s, pt.x1, pt.x2, - mstate, texmacs_time()); - event->accept(); + QPoint point = event->pos () + origin (); + coord2 pt = from_qpoint (point); + unsigned int mstate= mouse_state (event, true); + string s = "release-" * mouse_decode (mstate); + the_gui->process_mouse (tm_widget (), s, pt.x1, pt.x2, mstate, + texmacs_time ()); + event->accept (); } void QTMWidget::mouseMoveEvent (QMouseEvent* event) { if (is_nil (tmwid)) return; - QPoint point = event->pos() + origin(); - coord2 pt = from_qpoint(point); - unsigned int mstate = mouse_state (event, false); - string s = "move"; - the_gui->process_mouse (tm_widget(), s, pt.x1, pt.x2, - mstate, texmacs_time ()); - event->accept(); + QPoint point = event->pos () + origin (); + coord2 pt = from_qpoint (point); + unsigned int mstate= mouse_state (event, false); + string s = "move"; + the_gui->process_mouse (tm_widget (), s, pt.x1, pt.x2, mstate, + texmacs_time ()); + event->accept (); } static unsigned int tablet_state (QTabletEvent* event, bool flag) { - unsigned int i= 0; + unsigned int i = 0; Qt::MouseButtons bstate= event->buttons (); Qt::MouseButton tstate= event->button (); if (flag) bstate= bstate | tstate; - if ((bstate & Qt::LeftButton ) != 0) i += 1; - if ((bstate & Qt::MiddleButton ) != 0) i += 2; - if ((bstate & Qt::RightButton ) != 0) i += 4; - if ((bstate & Qt::XButton1 ) != 0) i += 8; - if ((bstate & Qt::XButton2 ) != 0) i += 16; + if ((bstate & Qt::LeftButton) != 0) i+= 1; + if ((bstate & Qt::MiddleButton) != 0) i+= 2; + if ((bstate & Qt::RightButton) != 0) i+= 4; + if ((bstate & Qt::XButton1) != 0) i+= 8; + if ((bstate & Qt::XButton2) != 0) i+= 16; return i; } void QTMWidget::tabletEvent (QTabletEvent* event) { - if (is_nil (tmwid)) return; - unsigned int mstate = tablet_state (event, true); - string s= "move"; - if (event->button() != 0) { + if (is_nil (tmwid)) return; + unsigned int mstate= tablet_state (event, true); + string s = "move"; + if (event->button () != 0) { if (event->pressure () == 0) s= "release-" * mouse_decode (mstate); else s= "press-" * mouse_decode (mstate); } if ((mstate & 4) == 0 || s == "press-right") { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QPoint point = event->pos() + origin() - surface()->pos(); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + QPoint point= event->pos () + origin () - surface ()->pos (); #else - QPoint point = event->position().toPoint() + origin() - surface()->pos(); + QPoint point= + event->position ().toPoint () + origin () - surface ()->pos (); #endif - double x= point.x() + event->hiResGlobalX() - event->globalX(); - double y= point.y() + event->hiResGlobalY() - event->globalY(); - coord2 pt= coord2 ((SI) (x * PIXEL), (SI) (-y * PIXEL)); + double x = point.x () + event->hiResGlobalX () - event->globalX (); + double y = point.y () + event->hiResGlobalY () - event->globalY (); + coord2 pt= coord2 ((SI) (x * PIXEL), (SI) (-y * PIXEL)); array data; - data << ((double) event->pressure()) - << ((double) event->rotation()) - << ((double) event->xTilt()) - << ((double) event->yTilt()) - << ((double) event->z()) - << ((double) event->tangentialPressure()); - the_gui->process_mouse (tm_widget(), s, pt.x1, pt.x2, - mstate, texmacs_time (), data); + data << ((double) event->pressure ()) << ((double) event->rotation ()) + << ((double) event->xTilt ()) << ((double) event->yTilt ()) + << ((double) event->z ()) << ((double) event->tangentialPressure ()); + the_gui->process_mouse (tm_widget (), s, pt.x1, pt.x2, mstate, + texmacs_time (), data); } /* cout << HRULE << LF; @@ -712,27 +726,25 @@ QTMWidget::tabletEvent (QTabletEvent* event) { cout << "pointerType= " << event->pointerType() << LF; cout << "uniqueId= " << event->uniqueId() << LF; */ - event->accept(); + event->accept (); } void QTMWidget::gestureEvent (QGestureEvent* event) { if (is_nil (tmwid)) return; - string s= "gesture"; + string s= "gesture"; array data; - QPointF hotspot; - if (QGesture *swipe_gesture = event->gesture(Qt::SwipeGesture)) { - QSwipeGesture *swipe= static_cast (swipe_gesture); - s= "swipe"; - hotspot = swipe->hotSpot (); - if (swipe->state() == Qt::GestureFinished) { - if (swipe->horizontalDirection() == QSwipeGesture::Left) - s= "swipe-left"; - else if (swipe->horizontalDirection() == QSwipeGesture::Right) + QPointF hotspot; + if (QGesture* swipe_gesture= event->gesture (Qt::SwipeGesture)) { + QSwipeGesture* swipe= static_cast (swipe_gesture); + s = "swipe"; + hotspot = swipe->hotSpot (); + if (swipe->state () == Qt::GestureFinished) { + if (swipe->horizontalDirection () == QSwipeGesture::Left) s= "swipe-left"; + else if (swipe->horizontalDirection () == QSwipeGesture::Right) s= "swipe-right"; - else if (swipe->verticalDirection() == QSwipeGesture::Up) - s= "swipe-up"; - else if (swipe->verticalDirection() == QSwipeGesture::Down) + else if (swipe->verticalDirection () == QSwipeGesture::Up) s= "swipe-up"; + else if (swipe->verticalDirection () == QSwipeGesture::Down) s= "swipe-down"; } else { @@ -740,131 +752,128 @@ QTMWidget::gestureEvent (QGestureEvent* event) { return; } } - else if (QGesture *pan_gesture = event->gesture(Qt::PanGesture)) { - QPanGesture *pan= static_cast (pan_gesture); - string s= "pan"; - hotspot = pan->hotSpot (); - //QPointF delta = pan->delta(); - //cout << "Pan " << delta.x() << ", " << delta.y() << LF; + else if (QGesture* pan_gesture= event->gesture (Qt::PanGesture)) { + QPanGesture* pan= static_cast (pan_gesture); + string s = "pan"; + hotspot = pan->hotSpot (); + // QPointF delta = pan->delta(); + // cout << "Pan " << delta.x() << ", " << delta.y() << LF; } - else if (QGesture *pinch_gesture = event->gesture(Qt::PinchGesture)) { - QPinchGesture *pinch= static_cast (pinch_gesture); - s= "pinch"; - hotspot = pinch->hotSpot (); - QPinchGesture::ChangeFlags changeFlags = pinch->changeFlags(); - if (pinch->state() == Qt::GestureStarted) { + else if (QGesture* pinch_gesture= event->gesture (Qt::PinchGesture)) { + QPinchGesture* pinch= static_cast (pinch_gesture); + s = "pinch"; + hotspot = pinch->hotSpot (); + QPinchGesture::ChangeFlags changeFlags= pinch->changeFlags (); + if (pinch->state () == Qt::GestureStarted) { pinch->setRotationAngle (0.0); pinch->setScaleFactor (1.0); s= "pinch-start"; } - else if (pinch->state() == Qt::GestureFinished) { + else if (pinch->state () == Qt::GestureFinished) { pinch->setRotationAngle (0.0); pinch->setScaleFactor (1.0); s= "pinch-end"; } else if (changeFlags & QPinchGesture::RotationAngleChanged) { - qreal angle = pinch->rotationAngle(); - s= "rotate"; + qreal angle= pinch->rotationAngle (); + s = "rotate"; data << ((double) angle); } else if (changeFlags & QPinchGesture::ScaleFactorChanged) { - qreal scale = pinch->totalScaleFactor(); - s= "scale"; + qreal scale= pinch->totalScaleFactor (); + s = "scale"; data << ((double) scale); } } else return; - QPoint point (hotspot.x(), hotspot.y()); - coord2 pt = from_qpoint (point); - //cout << s << ", " << pt.x1 << ", " << pt.x2 << LF; - the_gui->process_mouse (tm_widget(), s, pt.x1, pt.x2, - 0, texmacs_time (), data); - event->accept(); + QPoint point (hotspot.x (), hotspot.y ()); + coord2 pt= from_qpoint (point); + // cout << s << ", " << pt.x1 << ", " << pt.x2 << LF; + the_gui->process_mouse (tm_widget (), s, pt.x1, pt.x2, 0, texmacs_time (), + data); + event->accept (); } - bool QTMWidget::event (QEvent* event) { - // Catch Keypresses to avoid default handling of (Shift+)Tab keys - if (event->type() == QEvent::KeyPress) { - QKeyEvent *ke = static_cast (event); + // Catch Keypresses to avoid default handling of (Shift+)Tab keys + if (event->type () == QEvent::KeyPress) { + QKeyEvent* ke= static_cast (event); keyPressEvent (ke); return true; - } + } /* NOTE: we catch ShortcutOverride in order to disable the QKeySequences we assigned to QActions while building menus, etc. In doing this, we keep the shortcut text in the menus while relaying all keypresses through the editor*/ - if (event->type() == QEvent::ShortcutOverride) { - event->accept(); + if (event->type () == QEvent::ShortcutOverride) { + event->accept (); return true; } - if (event->type() == QEvent::Gesture) { - gestureEvent(static_cast(event)); + if (event->type () == QEvent::Gesture) { + gestureEvent (static_cast (event)); return true; } return QTMScrollView::event (event); } void -QTMWidget::focusInEvent (QFocusEvent * event) { +QTMWidget::focusInEvent (QFocusEvent* event) { if (!is_nil (tmwid)) { - if (DEBUG_QT) debug_qt << "FOCUSIN: " << tm_widget()->type_as_string() << LF; - the_gui->process_keyboard_focus (tm_widget(), true, texmacs_time()); + if (DEBUG_QT) + debug_qt << "FOCUSIN: " << tm_widget ()->type_as_string () << LF; + the_gui->process_keyboard_focus (tm_widget (), true, texmacs_time ()); } QTMScrollView::focusInEvent (event); } void -QTMWidget::focusOutEvent (QFocusEvent * event) { +QTMWidget::focusOutEvent (QFocusEvent* event) { if (!is_nil (tmwid)) { - if (DEBUG_QT) debug_qt << "FOCUSOUT: " << tm_widget()->type_as_string() << LF; - the_gui -> process_keyboard_focus (tm_widget(), false, texmacs_time()); + if (DEBUG_QT) + debug_qt << "FOCUSOUT: " << tm_widget ()->type_as_string () << LF; + the_gui->process_keyboard_focus (tm_widget (), false, texmacs_time ()); } QTMScrollView::focusOutEvent (event); } QSize QTMWidget::sizeHint () const { - SI w = 0, h = 0; - if (!is_nil (tmwid)) tm_widget()->handle_get_size_hint (w, h); + SI w= 0, h= 0; + if (!is_nil (tmwid)) tm_widget ()->handle_get_size_hint (w, h); return to_qsize (w, h); } -void -QTMWidget::dragEnterEvent (QDragEnterEvent *event) -{ +void +QTMWidget::dragEnterEvent (QDragEnterEvent* event) { if (is_nil (tmwid)) return; - const QMimeData *md = event->mimeData(); + const QMimeData* md= event->mimeData (); - if (md->hasText() || - md->hasUrls() || - md->hasImage() || - md->hasFormat("application/pdf") || - md->hasFormat("application/postscript")) - event->acceptProposedAction(); + if (md->hasText () || md->hasUrls () || md->hasImage () || + md->hasFormat ("application/pdf") || + md->hasFormat ("application/postscript")) + event->acceptProposedAction (); } - // cache to transfer drop data to the editor // via standard mouse events, see dropEvent below -int drop_payload_serial =0; +int drop_payload_serial= 0; hashmap payloads; - + void -QTMWidget::dropEvent (QDropEvent *event) { +QTMWidget::dropEvent (QDropEvent* event) { if (is_nil (tmwid)) return; - - QPoint point = event->pos () + origin (); - coord2 pt= from_qpoint (point); - tree doc (CONCAT); - const QMimeData *md= event->mimeData (); - QByteArray buf; + QPoint point= event->pos () + origin (); + coord2 pt = from_qpoint (point); + + tree doc (CONCAT); + const QMimeData* md= event->mimeData (); + QByteArray buf; if (md->hasUrls ()) { QList l= md->urls (); - for (int i=0; i=2 && is_alpha (name[0]) && name[1] == ':') - name= "/" * locase_all (name (0, 1)) * name (2, N(name)); + if (N (name) >= 2 && is_alpha (name[0]) && name[1] == ':') + name= "/" * locase_all (name (0, 1)) * name (2, N (name)); #endif - string extension = suffix (name); - if ((extension == "eps") || (extension == "ps") || - (extension == "svg") || - (extension == "pdf") || (extension == "png") || + string extension= suffix (name); + if ((extension == "eps") || (extension == "ps") || (extension == "svg") || + (extension == "pdf") || (extension == "png") || (extension == "jpg") || (extension == "jpeg")) { string w, h; qt_pretty_image_size (url_system (orig_name), w, h); tree im (IMAGE, name, w, h, "", ""); doc << im; - } else { + } + else { doc << name; } } - } else if (md->hasImage ()) { + } + else if (md->hasImage ()) { QBuffer qbuf (&buf); - QImage image= qvariant_cast (md->imageData()); - QSize size= image.size (); + QImage image= qvariant_cast (md->imageData ()); + QSize size = image.size (); qbuf.open (QIODevice::WriteOnly); image.save (&qbuf, "PNG"); - int ww= size.width (), hh= size.height (); + int ww= size.width (), hh= size.height (); string w, h; qt_pretty_image_size (ww, hh, w, h); - tree t (IMAGE, tree (RAW_DATA, string (buf.constData (), buf.size()), "png"), - w, h, "", ""); + tree t (IMAGE, + tree (RAW_DATA, string (buf.constData (), buf.size ()), "png"), w, + h, "", ""); doc << t; - } else if (md->hasFormat("application/postscript")) { - buf= md->data("application/postscript"); - tree t (IMAGE, tree (RAW_DATA, string (buf.constData (), buf.size ()), "ps"), - "", "", "", ""); + } + else if (md->hasFormat ("application/postscript")) { + buf= md->data ("application/postscript"); + tree t (IMAGE, + tree (RAW_DATA, string (buf.constData (), buf.size ()), "ps"), "", + "", "", ""); doc << t; - } else if (md->hasFormat("application/pdf")) { - buf= md->data("application/pdf"); - tree t (IMAGE, tree (RAW_DATA, string (buf.constData (), buf.size ()), "pdf"), - "", "", "", ""); + } + else if (md->hasFormat ("application/pdf")) { + buf= md->data ("application/pdf"); + tree t (IMAGE, + tree (RAW_DATA, string (buf.constData (), buf.size ()), "pdf"), "", + "", "", ""); doc << t; - } else if (md->hasText ()) { + } + else if (md->hasText ()) { buf= md->text ().toUtf8 (); doc << string (buf.constData (), buf.size ()); } - if (N(doc)>0) { - if (N(doc) == 1) - doc= doc[0]; + if (N (doc) > 0) { + if (N (doc) == 1) doc= doc[0]; else { tree sec (CONCAT, doc[0]); - for (int i=1; iprocess_mouse (tm_widget(), "drop", pt.x1, pt.x2, - ticket, texmacs_time ()); - event->acceptProposedAction(); + the_gui->process_mouse (tm_widget (), "drop", pt.x1, pt.x2, ticket, + texmacs_time ()); + event->acceptProposedAction (); } } @@ -937,58 +952,58 @@ static unsigned int wheel_state (QWheelEvent* event) { // TODO: factor mouse_state, tablet_state, wheel_state // This should be easier on modern versions of Qt - unsigned int i= 0; - Qt::MouseButtons bstate= event->buttons (); + unsigned int i = 0; + Qt::MouseButtons bstate= event->buttons (); Qt::KeyboardModifiers kstate= event->modifiers (); - if ((bstate & Qt::LeftButton ) != 0) i += 1; - if ((bstate & Qt::MiddleButton ) != 0) i += 2; - if ((bstate & Qt::RightButton ) != 0) i += 4; - if ((bstate & Qt::XButton1 ) != 0) i += 8; - if ((bstate & Qt::XButton2 ) != 0) i += 16; + if ((bstate & Qt::LeftButton) != 0) i+= 1; + if ((bstate & Qt::MiddleButton) != 0) i+= 2; + if ((bstate & Qt::RightButton) != 0) i+= 4; + if ((bstate & Qt::XButton1) != 0) i+= 8; + if ((bstate & Qt::XButton2) != 0) i+= 16; #ifdef Q_OS_MAC - // We emulate right and middle clicks with ctrl and option, but we pass the - // modifiers anyway: old code continues to work and new one can use them. - if ((kstate & Qt::MetaModifier ) != 0) i = 1024+4; // control key - if ((kstate & Qt::AltModifier ) != 0) i = 2048+2; // option key - if ((kstate & Qt::ShiftModifier ) != 0) i += 256; - if ((kstate & Qt::ControlModifier) != 0) i += 4096; // cmd key + // We emulate right and middle clicks with ctrl and option, but we pass the + // modifiers anyway: old code continues to work and new one can use them. + if ((kstate & Qt::MetaModifier) != 0) i= 1024 + 4; // control key + if ((kstate & Qt::AltModifier) != 0) i= 2048 + 2; // option key + if ((kstate & Qt::ShiftModifier) != 0) i+= 256; + if ((kstate & Qt::ControlModifier) != 0) i+= 4096; // cmd key #else - if ((kstate & Qt::ShiftModifier ) != 0) i += 256; - if ((kstate & Qt::ControlModifier) != 0) i += 1024; - if ((kstate & Qt::AltModifier ) != 0) i += 2048; - if ((kstate & Qt::MetaModifier ) != 0) i += 4096; + if ((kstate & Qt::ShiftModifier) != 0) i+= 256; + if ((kstate & Qt::ControlModifier) != 0) i+= 1024; + if ((kstate & Qt::AltModifier) != 0) i+= 2048; + if ((kstate & Qt::MetaModifier) != 0) i+= 4096; #endif return i; } void -QTMWidget::wheelEvent(QWheelEvent *event) { - if (is_nil (tmwid)) return; +QTMWidget::wheelEvent (QWheelEvent* event) { + if (is_nil (tmwid)) return; if (as_bool (call ("wheel-capture?"))) { #if (QT_VERSION >= 0x060000) - QPoint point= (event->position()).toPoint() + origin(); + QPoint point= (event->position ()).toPoint () + origin (); #else - QPoint point= event->pos() + origin(); + QPoint point = event->pos () + origin (); #endif - QPoint wheel= event->pixelDelta(); - coord2 pt = from_qpoint (point); - coord2 wh = from_qpoint (wheel); - unsigned int mstate= wheel_state (event); - array data; data << ((double) wh.x1) << ((double) wh.x2); - the_gui -> process_mouse (tm_widget(), "wheel", pt.x1, pt.x2, - mstate, texmacs_time (), data); + QPoint wheel = event->pixelDelta (); + coord2 pt = from_qpoint (point); + coord2 wh = from_qpoint (wheel); + unsigned int mstate= wheel_state (event); + array data; + data << ((double) wh.x1) << ((double) wh.x2); + the_gui->process_mouse (tm_widget (), "wheel", pt.x1, pt.x2, mstate, + texmacs_time (), data); } - else if (QApplication::keyboardModifiers() == Qt::ControlModifier) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + else if (QApplication::keyboardModifiers () == Qt::ControlModifier) { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // see https://doc.qt.io/qt-5/qwheelevent-obsolete.html#delta - if (event->delta() > 0) + if (event->delta () > 0) #else - QPoint numDegrees = event->angleDelta() / 8; - if (numDegrees.y() > 0) + QPoint numDegrees= event->angleDelta () / 8; + if (numDegrees.y () > 0) #endif call ("zoom-in", object (sqrt (sqrt (2.0)))); - else - call ("zoom-out", object (sqrt (sqrt (2.0)))); + else call ("zoom-out", object (sqrt (sqrt (2.0)))); } else QAbstractScrollArea::wheelEvent (event); } diff --git a/src/Plugins/Qt/QTMWidget.hpp b/src/Plugins/Qt/QTMWidget.hpp index a03f49bf78..2434e468b9 100644 --- a/src/Plugins/Qt/QTMWidget.hpp +++ b/src/Plugins/Qt/QTMWidget.hpp @@ -1,57 +1,54 @@ /****************************************************************************** -* MODULE : QTMWidget.hpp -* DESCRIPTION: QT Texmacs widget class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMWidget.hpp + * DESCRIPTION: QT Texmacs widget class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QTMWIDGET_HPP #define QTMWIDGET_HPP -#include "qt_widget.hpp" #include "QTMScrollView.hpp" -#include +#include "qt_widget.hpp" #include #include +#include class qt_simple_widget_rep; -/*! The underlying QWidget for a qt_simple_widget_rep handles drawing for a +/*! The underlying QWidget for a qt_simple_widget_rep handles drawing for a texmacs canvas, as well as keypresses, international input methods, etc. - + QTMWidget needs a valid qt_simple_widget_rep object to function properly, see set_tm_widget() for more on this. - + */ -class QTMWidget: public QTMScrollView { +class QTMWidget : public QTMScrollView { Q_OBJECT - qt_widget tmwid; - QLabel* imwidget; - QPoint cursor_pos; - bool preediting; + qt_widget tmwid; + QLabel* imwidget; + QPoint cursor_pos; + bool preediting; public: - - - QTMWidget (QWidget* _parent=0, qt_widget _tmwid=0); + QTMWidget (QWidget* _parent= 0, qt_widget _tmwid= 0); virtual ~QTMWidget (); - - virtual QSize sizeHint () const; - virtual void scrollContentsBy (int dx, int dy); - void setCursorPos (QPoint pos) { cursor_pos = pos; } + virtual QSize sizeHint () const; + virtual void scrollContentsBy (int dx, int dy); + + void setCursorPos (QPoint pos) { cursor_pos= pos; } qt_simple_widget_rep* tm_widget () const; - + bool isPreediting () { return preediting; } - -protected: - virtual bool event (QEvent *event); +protected: + virtual bool event (QEvent* event); virtual void paintEvent (QPaintEvent* event); virtual void focusInEvent (QFocusEvent* event); @@ -65,15 +62,14 @@ class QTMWidget: public QTMScrollView { virtual void mouseMoveEvent (QMouseEvent* event); virtual void tabletEvent (QTabletEvent* event); virtual void gestureEvent (QGestureEvent* event); - virtual void resizeEvent (QResizeEvent *event); - virtual void resizeEventBis (QResizeEvent *e); - virtual void dragEnterEvent(QDragEnterEvent *event); - //virtual void dragMoveEvent (QDragMoveEvent *event); - virtual void dropEvent(QDropEvent *event); + virtual void resizeEvent (QResizeEvent* event); + virtual void resizeEventBis (QResizeEvent* e); + virtual void dragEnterEvent (QDragEnterEvent* event); + // virtual void dragMoveEvent (QDragMoveEvent *event); + virtual void dropEvent (QDropEvent* event); - virtual void wheelEvent(QWheelEvent *event); + virtual void wheelEvent (QWheelEvent* event); virtual QVariant inputMethodQuery (Qt::InputMethodQuery query) const; - }; #endif // QTMWIDGET_HPP diff --git a/src/Plugins/Qt/QTMWindow.cpp b/src/Plugins/Qt/QTMWindow.cpp index d13876cf09..fb019a1624 100644 --- a/src/Plugins/Qt/QTMWindow.cpp +++ b/src/Plugins/Qt/QTMWindow.cpp @@ -1,110 +1,111 @@ /****************************************************************************** -* MODULE : QTMWindow.cpp -* DESCRIPTION: QT Texmacs window class -* COPYRIGHT : (C) 2009 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : QTMWindow.cpp + * DESCRIPTION: QT Texmacs window class + * COPYRIGHT : (C) 2009 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "QTMWindow.hpp" -#include "tm_window.hpp" #include "qt_utilities.hpp" +#include "tm_window.hpp" #include -void QTMPlainWindow::closeEvent (QCloseEvent* event) -{ +void +QTMPlainWindow::closeEvent (QCloseEvent* event) { if (DEBUG_QT_WIDGETS) debug_widgets << "Close QTMPlainWindow" << LF; // Tell QT not to close the window, qt_window_widget_rep will if need be. event->ignore (); - emit closed(); + emit closed (); } -void QTMPlainWindow::moveEvent (QMoveEvent* event) -{ +void +QTMPlainWindow::moveEvent (QMoveEvent* event) { string name= from_qstring (windowTitle ()); - // FIXME: rather use a slot for this - coord2 pos= from_qpoint (frameGeometry().topLeft()); + // FIXME: rather use a slot for this + coord2 pos= from_qpoint (frameGeometry ().topLeft ()); notify_window_move (name, pos.x1, pos.x2); QWidget::moveEvent (event); } -void QTMPlainWindow::resizeEvent (QResizeEvent* event) -{ +void +QTMPlainWindow::resizeEvent (QResizeEvent* event) { string name= from_qstring (windowTitle ()); - // FIXME: rather use a slot for this - coord2 sz= from_qsize (frameSize()); + // FIXME: rather use a slot for this + coord2 sz= from_qsize (frameSize ()); notify_window_resize (name, sz.x1, sz.x2); QWidget::resizeEvent (event); } -void QTMWindow::closeEvent (QCloseEvent* event) -{ - widget tmwid = qt_window_widget_rep::widget_from_qwidget(this); - string name= ( !is_nil(tmwid) ? concrete(tmwid)->get_nickname () : "QTMWindow"); +void +QTMWindow::closeEvent (QCloseEvent* event) { + widget tmwid= qt_window_widget_rep::widget_from_qwidget (this); + string name= + (!is_nil (tmwid) ? concrete (tmwid)->get_nickname () : "QTMWindow"); if (DEBUG_QT_WIDGETS) debug_widgets << "Close QTMWindow " << name << LF; event->ignore (); - //notify_window_destroy (name); closing can still be cancelled - emit closed(); + // notify_window_destroy (name); closing can still be cancelled + emit closed (); } -void QTMWindow::moveEvent (QMoveEvent * event) -{ - widget tmwid = qt_window_widget_rep::widget_from_qwidget(this); - string name= ( !is_nil(tmwid) ? concrete(tmwid)->get_nickname () : "QTMWindow"); +void +QTMWindow::moveEvent (QMoveEvent* event) { + widget tmwid= qt_window_widget_rep::widget_from_qwidget (this); + string name= + (!is_nil (tmwid) ? concrete (tmwid)->get_nickname () : "QTMWindow"); // FIXME: rather use a slot for this - coord2 pt = from_qpoint (frameGeometry().topLeft()); + coord2 pt= from_qpoint (frameGeometry ().topLeft ()); notify_window_move (name, pt.x1, pt.x2); QMainWindow::moveEvent (event); } -void QTMWindow::resizeEvent (QResizeEvent * event) -{ - widget tmwid = qt_window_widget_rep::widget_from_qwidget(this); - string name= ( !is_nil(tmwid) ? concrete(tmwid)->get_nickname () : "QTMWindow"); +void +QTMWindow::resizeEvent (QResizeEvent* event) { + widget tmwid= qt_window_widget_rep::widget_from_qwidget (this); + string name= + (!is_nil (tmwid) ? concrete (tmwid)->get_nickname () : "QTMWindow"); // FIXME: rather use a slot for this - coord2 sz = from_qsize (frameSize()); + coord2 sz= from_qsize (frameSize ()); notify_window_resize (name, sz.x1, sz.x2); QMainWindow::resizeEvent (event); } - //////////////////// +//////////////////// +QTMPopupWidget::QTMPopupWidget (QWidget* contents) { -QTMPopupWidget::QTMPopupWidget(QWidget* contents) { - - QHBoxLayout* l = new QHBoxLayout(); + QHBoxLayout* l= new QHBoxLayout (); l->addWidget (contents); - l->setContentsMargins (0,0,0,0); - l->setEnabled (false); // Tell the layout not to adjust itself (!) + l->setContentsMargins (0, 0, 0, 0); + l->setEnabled (false); // Tell the layout not to adjust itself (!) setLayout (l); - resize (contents->size()); + resize (contents->size ()); setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); setWindowFlags (Qt::Popup); setAttribute (Qt::WA_NoSystemBackground); - setMouseTracking (true); // Receive mouse events -// setFocusPolicy(Qt::StrongFocus); // Don't! Receive key events -// setWindowOpacity(0.9); + setMouseTracking (true); // Receive mouse events + // setFocusPolicy(Qt::StrongFocus); // Don't! Receive key events + // setWindowOpacity(0.9); - //cout << "QTMPopupWidget created with size: " << size().width() - // << " x " << size().height() << LF; + // cout << "QTMPopupWidget created with size: " << size().width() + // << " x " << size().height() << LF; } - /* If our contents QWidget is of type QTMWidget it will capture mouse events - and we won't get called until the pointer exits the contents, so the check + and we won't get called until the pointer exits the contents, so the check inside is unnecessary unless the contents are of another kind. - + NOTE that this is intended for popups which appear under the cursor! */ void -QTMPopupWidget::mouseMoveEvent(QMouseEvent* event) { - +QTMPopupWidget::mouseMoveEvent (QMouseEvent* event) { + /* It'd be nice to have something like this... if (! drawArea().contains(event->globalPos())) { hide(); @@ -114,27 +115,25 @@ QTMPopupWidget::mouseMoveEvent(QMouseEvent* event) { } */ - if (! this->rect().contains(QCursor::pos())) { - hide(); - emit closed(); + if (!this->rect ().contains (QCursor::pos ())) { + hide (); + emit closed (); } - event->ignore(); + event->ignore (); } void -QTMPopupWidget::keyPressEvent(QKeyEvent* event) { +QTMPopupWidget::keyPressEvent (QKeyEvent* event) { (void) event; - hide(); - emit closed(); + hide (); + emit closed (); } void -QTMPopupWidget::closeEvent (QCloseEvent* event) -{ +QTMPopupWidget::closeEvent (QCloseEvent* event) { if (DEBUG_QT_WIDGETS) debug_widgets << "Close QTMPopupWidget" << LF; // Tell QT not to close the window, qt_window_widget_rep will if need be. event->ignore (); - emit closed(); + emit closed (); } - diff --git a/src/Plugins/Qt/QTMWindow.hpp b/src/Plugins/Qt/QTMWindow.hpp index 2c952e9c5d..d1b5294d3a 100644 --- a/src/Plugins/Qt/QTMWindow.hpp +++ b/src/Plugins/Qt/QTMWindow.hpp @@ -16,9 +16,8 @@ #include "qt_tm_widget.hpp" - /*! The interface that any QWidget must implement to become a window in TeXmacs. - + The underlying QWidget for a qt_window_widget_rep is of this type. We use it to inform the texmacs widget that the window has been closed. Because windows can be closed externally to TeXmacs, i.e. with the close button that the @@ -26,10 +25,10 @@ texmacs message to the owning texmacs widget (which is of type qt_window_widget_rep). This will allow it to call the associated texmacs quit command (and do anything else it requires). - + FIXME: Currently, we are bypassing this mechanism using QObject::connect() inside qt_window_widget's constructor. However, for QTMWindows, we do use it. - + NOTE: I would like to have a base class common to QTMPlainWindow and QTMWindow to enforce the data type for a qt_window_widget. But we cannot "virtual inherit" QWidget to do this in a nicer way because QMainWindow does not @@ -37,74 +36,67 @@ */ class QTMPlainWindow : public QWidget { Q_OBJECT - -public: - QTMPlainWindow (QWidget* parent) - : QWidget (parent) { +public: + QTMPlainWindow (QWidget* parent) : QWidget (parent) { if (DEBUG_QT) debug_qt << "Creating QTMPlainWindow" << LF; } virtual ~QTMPlainWindow () { if (DEBUG_QT) debug_qt << "Deleting QTMPlainWindow" << LF; } - + signals: void closed (); - + protected: - virtual void closeEvent (QCloseEvent* event); - virtual void moveEvent (QMoveEvent* event); + virtual void closeEvent (QCloseEvent* event); + virtual void moveEvent (QMoveEvent* event); virtual void resizeEvent (QResizeEvent* event); - }; /*! The underlying QWidget for a qt_tm_widget_rep. - + \sa QTMPlainWindow - + */ -class QTMWindow: public QMainWindow { +class QTMWindow : public QMainWindow { Q_OBJECT - + public: - - QTMWindow (QWidget* parent) - : QMainWindow (parent) { + QTMWindow (QWidget* parent) : QMainWindow (parent) { if (DEBUG_QT) debug_qt << "Creating QTMWindow" << LF; } virtual ~QTMWindow () { if (DEBUG_QT) debug_qt << "Deleting QTMWindow" << LF; } - + signals: void closed (); - + protected: - virtual void closeEvent (QCloseEvent* event); - virtual void moveEvent (QMoveEvent* event); + virtual void closeEvent (QCloseEvent* event); + virtual void moveEvent (QMoveEvent* event); virtual void resizeEvent (QResizeEvent* event); }; - /*! The underlying QWidget for a qt_popup_widget. - + This is just a container QWidget that disappears after the mouse leaves it. As usual, it takes ownership of its contents. */ class QTMPopupWidget : public QWidget { Q_OBJECT - + public: QTMPopupWidget (QWidget* contents); signals: - void closed(); - + void closed (); + protected: virtual void closeEvent (QCloseEvent* event); virtual void mouseMoveEvent (QMouseEvent* event); - virtual void keyPressEvent (QKeyEvent* event); + virtual void keyPressEvent (QKeyEvent* event); }; - #endif // QTMWINDOW_HPP diff --git a/src/Plugins/Qt/qt_chooser_widget.cpp b/src/Plugins/Qt/qt_chooser_widget.cpp index 8c52c5f074..05cc665157 100644 --- a/src/Plugins/Qt/qt_chooser_widget.cpp +++ b/src/Plugins/Qt/qt_chooser_widget.cpp @@ -1,32 +1,32 @@ /****************************************************************************** -* MODULE : qt_chooser_widget.cpp -* DESCRIPTION: File chooser widget, native and otherwise -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_chooser_widget.cpp + * DESCRIPTION: File chooser widget, native and otherwise + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "qt_chooser_widget.hpp" -#include "qt_utilities.hpp" -#include "widget.hpp" -#include "message.hpp" +#include "QTMFileDialog.hpp" #include "analyze.hpp" #include "convert.hpp" #include "converter.hpp" -#include "scheme.hpp" #include "dictionary.hpp" #include "editor.hpp" -#include "new_view.hpp" // get_current_editor() #include "image_files.hpp" -#include "QTMFileDialog.hpp" +#include "message.hpp" +#include "new_view.hpp" // get_current_editor() +#include "qt_utilities.hpp" +#include "scheme.hpp" +#include "widget.hpp" +#include +#include #include #include -#include -#include /*! \param _cmd Scheme closure to execute after the dialog is closed. @@ -34,116 +34,110 @@ or any of the supported file formats: "texmacs", "tmml", "postscript", etc. See perform_dialog() */ -qt_chooser_widget_rep::qt_chooser_widget_rep (command _cmd, string _type, string _prompt) - : qt_widget_rep (file_chooser), cmd (_cmd), prompt (_prompt), - position (coord2 (0, 0)), size (coord2 (100, 100)), file ("") -{ +qt_chooser_widget_rep::qt_chooser_widget_rep (command _cmd, string _type, + string _prompt) + : qt_widget_rep (file_chooser), cmd (_cmd), prompt (_prompt), + position (coord2 (0, 0)), size (coord2 (100, 100)), file ("") { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_chooser_widget_rep::qt_chooser_widget_rep type=\"" << type << "\" prompt=\"" << prompt << "\"" << LF; - if (! set_type (_type)) - set_type ("generic"); + if (!set_type (_type)) set_type ("generic"); } void qt_chooser_widget_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_VISIBILITY: - { - check_type (val, s); - bool flag = open_box (val); - (void) flag; - NOT_IMPLEMENTED("qt_chooser_widget::SLOT_VISIBILITY"); - } - break; - case SLOT_SIZE: - check_type(val, s); - size = open_box (val); - break; - case SLOT_POSITION: - check_type(val, s); - position = open_box (val); - break; - case SLOT_KEYBOARD_FOCUS: - check_type(val, s); - perform_dialog (); - break; - case SLOT_STRING_INPUT: - check_type(val, s); - if (DEBUG_QT_WIDGETS) - debug_widgets << "\tString input: " << open_box (val) << LF; - NOT_IMPLEMENTED("qt_chooser_widget::SLOT_STRING_INPUT"); - break; - case SLOT_INPUT_TYPE: - check_type(val, s); - set_type (open_box (val)); - break; - case SLOT_FILE: - //send_string (THIS, "file", val); - check_type(val, s); - if (DEBUG_QT_WIDGETS) - debug_widgets << "\tFile: " << open_box (val) << LF; - file = open_box (val); - break; - case SLOT_DIRECTORY: - check_type(val, s); - directory = open_box (val); - directory = as_string (url_pwd () * url_system (directory)); - break; - - default: - qt_widget_rep::send (s, val); + case SLOT_VISIBILITY: { + check_type (val, s); + bool flag= open_box (val); + (void) flag; + NOT_IMPLEMENTED ("qt_chooser_widget::SLOT_VISIBILITY"); + } break; + case SLOT_SIZE: + check_type (val, s); + size= open_box (val); + break; + case SLOT_POSITION: + check_type (val, s); + position= open_box (val); + break; + case SLOT_KEYBOARD_FOCUS: + check_type (val, s); + perform_dialog (); + break; + case SLOT_STRING_INPUT: + check_type (val, s); + if (DEBUG_QT_WIDGETS) + debug_widgets << "\tString input: " << open_box (val) << LF; + NOT_IMPLEMENTED ("qt_chooser_widget::SLOT_STRING_INPUT"); + break; + case SLOT_INPUT_TYPE: + check_type (val, s); + set_type (open_box (val)); + break; + case SLOT_FILE: + // send_string (THIS, "file", val); + check_type (val, s); + if (DEBUG_QT_WIDGETS) + debug_widgets << "\tFile: " << open_box (val) << LF; + file= open_box (val); + break; + case SLOT_DIRECTORY: + check_type (val, s); + directory= open_box (val); + directory= as_string (url_pwd () * url_system (directory)); + break; + + default: + qt_widget_rep::send (s, val); } if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_chooser_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + debug_widgets << "qt_chooser_widget_rep: sent " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; } blackbox qt_chooser_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_chooser_widget_rep::query " << slot_name(s) << LF; + debug_widgets << "qt_chooser_widget_rep::query " << slot_name (s) << LF; switch (s) { - case SLOT_POSITION: - { - check_type_id (type_id, s); - return close_box (position); - } - case SLOT_SIZE: - { - check_type_id (type_id, s); - return close_box (size); - } - case SLOT_STRING_INPUT: - { - check_type_id (type_id, s); - if (DEBUG_QT_WIDGETS) debug_widgets << "\tString: " << file << LF; - return close_box (file); - } - default: - return qt_widget_rep::query (s, type_id); + case SLOT_POSITION: { + check_type_id (type_id, s); + return close_box (position); + } + case SLOT_SIZE: { + check_type_id (type_id, s); + return close_box (size); + } + case SLOT_STRING_INPUT: { + check_type_id (type_id, s); + if (DEBUG_QT_WIDGETS) debug_widgets << "\tString: " << file << LF; + return close_box (file); + } + default: + return qt_widget_rep::query (s, type_id); } } widget qt_chooser_widget_rep::read (slot s, blackbox index) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_chooser_widget_rep::read " << slot_name(s) << LF; + debug_widgets << "qt_chooser_widget_rep::read " << slot_name (s) << LF; switch (s) { - case SLOT_WINDOW: - check_type_void (index, s); - return this; - case SLOT_FORM_FIELD: - check_type (index, s); - return this; - case SLOT_FILE: - check_type_void (index, s); - return this; - case SLOT_DIRECTORY: - check_type_void (index, s); - return this; - default: - return qt_widget_rep::read(s,index); + case SLOT_WINDOW: + check_type_void (index, s); + return this; + case SLOT_FORM_FIELD: + check_type (index, s); + return this; + case SLOT_FILE: + check_type_void (index, s); + return this; + case SLOT_DIRECTORY: + check_type_void (index, s); + return this; + default: + return qt_widget_rep::read (s, index); } } @@ -154,86 +148,82 @@ qt_chooser_widget_rep::read (slot s, blackbox index) { widget qt_chooser_widget_rep::plain_window_widget (string s, command q, int b) { (void) b; - win_title = s; - quit = q; + win_title= s; + quit = q; return this; } bool -qt_chooser_widget_rep::set_type (const string& _type) -{ +qt_chooser_widget_rep::set_type (const string& _type) { if (_type == "directory") { - type = _type; + type= _type; return true; - } else if (_type == "generic") { - nameFilter = ""; - type = _type; + } + else if (_type == "generic") { + nameFilter= ""; + type = _type; return true; } if (format_exists (_type)) { - nameFilter = to_qstring (translate - (as_string (call ("format-get-name", _type)) - * " file")); - } else if (_type == "image") { - nameFilter = to_qstring (translate ("Image file")); - } else { + nameFilter= to_qstring ( + translate (as_string (call ("format-get-name", _type)) * " file")); + } + else if (_type == "image") { + nameFilter= to_qstring (translate ("Image file")); + } + else { if (DEBUG_STD) - debug_widgets << "qt_chooser_widget: IGNORING unknown format " - << _type << LF; + debug_widgets << "qt_chooser_widget: IGNORING unknown format " << _type + << LF; return false; } - nameFilter += " ("; - object ret = call ("format-get-suffixes*", _type); - array suffixes = as_array_object (ret); - if (N(suffixes) > 1) - defaultSuffix = to_qstring (as_string (suffixes[1])); - for (int i = 1; i < N(suffixes); ++i) - nameFilter += " *." + to_qstring (as_string (suffixes[i])); - nameFilter += " )"; - - type = _type; + nameFilter+= " ("; + object ret = call ("format-get-suffixes*", _type); + array suffixes= as_array_object (ret); + if (N (suffixes) > 1) defaultSuffix= to_qstring (as_string (suffixes[1])); + for (int i= 1; i < N (suffixes); ++i) + nameFilter+= " *." + to_qstring (as_string (suffixes[i])); + nameFilter+= " )"; + + type= _type; return true; } - - /*! Actually displays the dialog with all the options set. * Uses a native dialog on Mac/Win and opens a custom dialog with image preview * for other platforms. */ void qt_chooser_widget_rep::perform_dialog () { - QString caption = to_qstring (win_title); + QString caption= to_qstring (win_title); c_string tmp (directory * "/" * file); - QString path = QString::fromUtf8 (tmp, -1); - -#if (defined(Q_OS_MAC) )// || defined(Q_WS_WIN)) //at least windows Xp and 7 lack image preview, switch to custom dialog - QFileDialog* dialog = new QFileDialog (NULL, caption, path); + QString path= QString::fromUtf8 (tmp, -1); + +#if (defined(Q_OS_MAC)) // || defined(Q_WS_WIN)) //at least windows Xp and 7 + // lack image preview, switch to custom dialog + QFileDialog* dialog= new QFileDialog (NULL, caption, path); #else QTMFileDialog* dialog; - QTMImageDialog* imgdialog = 0; // to avoid a dynamic_cast - + QTMImageDialog* imgdialog= 0; // to avoid a dynamic_cast + if (type == "image") - dialog = imgdialog = new QTMImageDialog (NULL, caption, path); - else - dialog = new QTMFileDialog (NULL, caption, path); + dialog= imgdialog= new QTMImageDialog (NULL, caption, path); + else dialog= new QTMFileDialog (NULL, caption, path); #endif - + dialog->setViewMode (QFileDialog::Detail); - if (type == "directory") - dialog->setFileMode (QFileDialog::Directory); + if (type == "directory") dialog->setFileMode (QFileDialog::Directory); else if (type == "image" && prompt == "") // check non saving mode just in case we support it dialog->setFileMode (QFileDialog::ExistingFile); - else - dialog->setFileMode (QFileDialog::AnyFile); + else dialog->setFileMode (QFileDialog::AnyFile); if (prompt != "") { string text= prompt; - if (ends (text, ":")) text= text (0, N(text) - 1); - if (ends (text, " as")) text= text (0, N(text) - 3); + if (ends (text, ":")) text= text (0, N (text) - 1); + if (ends (text, " as")) text= text (0, N (text) - 3); dialog->setDefaultSuffix (defaultSuffix); dialog->setAcceptMode (QFileDialog::AcceptSave); dialog->setLabelText (QFileDialog::Accept, to_qstring (translate (text))); @@ -241,48 +231,49 @@ qt_chooser_widget_rep::perform_dialog () { if (type != "directory") { QStringList filters; - if (nameFilter != "") - filters << nameFilter; + if (nameFilter != "") filters << nameFilter; filters << to_qstring (translate ("All files (*)")); dialog->setNameFilters (filters); } - dialog->updateGeometry(); - QSize sz = dialog->sizeHint(); - QPoint pos = to_qpoint (position); - QRect r; + dialog->updateGeometry (); + QSize sz = dialog->sizeHint (); + QPoint pos= to_qpoint (position); + QRect r; r.setSize (sz); r.moveCenter (pos); dialog->setGeometry (r); - + QStringList fileNames; - file = "#f"; + file= "#f"; if (dialog->exec ()) { - fileNames = dialog->selectedFiles(); - if (fileNames.count() > 0) { - QString imqstring = fileNames.first(); - // QTBUG-59401: QFileDialog::setDefaultSuffix doesn't work when file path contains a dot - if (!defaultSuffix.isEmpty() && imqstring.contains(QLatin1Char('/')) - && !imqstring.endsWith(QLatin1Char('/')) - && imqstring.indexOf(QLatin1Char('.'), imqstring.lastIndexOf(QLatin1Char('/'))) == -1) { - imqstring = imqstring + QLatin1Char('.') + defaultSuffix; - } - string imname = from_qstring_utf8 (imqstring); - file = "(system->url " * scm_quote (imname) * ")"; + fileNames= dialog->selectedFiles (); + if (fileNames.count () > 0) { + QString imqstring= fileNames.first (); + // QTBUG-59401: QFileDialog::setDefaultSuffix doesn't work when file path + // contains a dot + if (!defaultSuffix.isEmpty () && imqstring.contains (QLatin1Char ('/')) && + !imqstring.endsWith (QLatin1Char ('/')) && + imqstring.indexOf (QLatin1Char ('.'), + imqstring.lastIndexOf (QLatin1Char ('/'))) == -1) { + imqstring= imqstring + QLatin1Char ('.') + defaultSuffix; + } + string imname= from_qstring_utf8 (imqstring); + file = "(system->url " * scm_quote (imname) * ")"; if (type == "image") { -#if !defined(Q_OS_MAC) // && !defined(Q_WS_WIN) //at least windows Xp and 7 lack image preview, switch to custom dialog - file = "(list " * file * imgdialog->getParamsAsString () * ")"; //set image size from preview -#else //MacOs only now +#if !defined(Q_OS_MAC) // && !defined(Q_WS_WIN) //at least windows Xp and 7 + // lack image preview, switch to custom dialog + file= "(list " * file * imgdialog->getParamsAsString () * + ")"; // set image size from preview +#else // MacOs only now /* QPixmap pic (fileNames.first()); // Qt can't eps & pdf in windows. string params; // HACK: which value should we choose here? - //On other platforms we call image_size (u, w, h) which returns size in pt units. - int ww = get_current_editor()->get_page_width (false) / PIXEL; - int w = pic.width (); - int h = pic.height (); - string unit= "pt"; + //On other platforms we call image_size (u, w, h) which returns size + in pt units. int ww = get_current_editor()->get_page_width (false) / + PIXEL; int w = pic.width (); int h = pic.height (); string unit= "pt"; if (w == 0) image_size (url_system (imname), w, h); if (w >= ww) { @@ -303,22 +294,26 @@ qt_chooser_widget_rep::perform_dialog () { } file = "(list " * file * params * ")"; */ - url u= url_system (imname); + url u= url_system (imname); string w, h; qt_pretty_image_size (u, w, h); string params; params << "\"" << w << "\" " << "\"" << h << "\" " - << "\"" << "" << "\" " // xps ?? - << "\"" << "" << "\""; // yps ?? - file = "(list " * file * " " * params * ")"; + << "\"" + << "" + << "\" " // xps ?? + << "\"" + << "" + << "\""; // yps ?? + file= "(list " * file * " " * params * ")"; #endif } } } delete dialog; - + cmd (); if (!is_nil (quit)) quit (); } diff --git a/src/Plugins/Qt/qt_chooser_widget.hpp b/src/Plugins/Qt/qt_chooser_widget.hpp index dc075251bd..7209b21313 100644 --- a/src/Plugins/Qt/qt_chooser_widget.hpp +++ b/src/Plugins/Qt/qt_chooser_widget.hpp @@ -11,22 +11,22 @@ #ifndef QT_CHOOSER_WIDGET_HPP #define QT_CHOOSER_WIDGET_HPP -#include "qt_widget.hpp" #include "qt_utilities.hpp" +#include "qt_widget.hpp" /*! A file/directory chooser dialog, using native dialogs where available. See @link widget.cpp @endlink for an explanation of send(), query(), read(), etc. */ -class qt_chooser_widget_rep: public qt_widget_rep { -protected: - command cmd; //!< Scheme closure to execute when the file is chosen - command quit; //!< Execute when the dialog closes. - string type; //!< File types to filter in the dialog - string prompt; //!< Is this a "Save" dialog? - string win_title; //!< Set by plain_window_widget() - +class qt_chooser_widget_rep : public qt_widget_rep { +protected: + command cmd; //!< Scheme closure to execute when the file is chosen + command quit; //!< Execute when the dialog closes. + string type; //!< File types to filter in the dialog + string prompt; //!< Is this a "Save" dialog? + string win_title; //!< Set by plain_window_widget() + string directory; //!< Set this property sending SLOT_DIRECTORY to this widget coord2 position; //!< Set this property sending SLOT_POSITION to this widget coord2 size; //!< Set this property sending SLOT_SIZE to this widget @@ -37,14 +37,14 @@ class qt_chooser_widget_rep: public qt_widget_rep { public: qt_chooser_widget_rep (command, string, string); - - virtual void send (slot s, blackbox val); + + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); - virtual widget plain_window_widget (string s, command q, int b); - + virtual widget read (slot s, blackbox index); + virtual widget plain_window_widget (string s, command q, int b); + bool set_type (const string& _type); - void perform_dialog(); + void perform_dialog (); }; -#endif // QT_CHOOSER_WIDGET_HPP +#endif // QT_CHOOSER_WIDGET_HPP diff --git a/src/Plugins/Qt/qt_color_picker_widget.cpp b/src/Plugins/Qt/qt_color_picker_widget.cpp index 678c2b0c28..9f743b6311 100644 --- a/src/Plugins/Qt/qt_color_picker_widget.cpp +++ b/src/Plugins/Qt/qt_color_picker_widget.cpp @@ -1,7 +1,7 @@ /****************************************************************************** * MODULE : qt_color_picker_widget.cpp - * DESCRIPTION: + * DESCRIPTION: * COPYRIGHT : (C) 2010 Miguel de Benito Delgado ******************************************************************************* * This software falls under the GNU general public license version 3 or later. @@ -17,36 +17,34 @@ #include - /** * Needed for whitebox_rep::display */ -inline tm_ostream& -operator << (tm_ostream& out, const QColor& col) { +inline tm_ostream& +operator<< (tm_ostream& out, const QColor& col) { return out << "Color: " << from_qcolor (col) << "\n"; } -qt_color_picker_widget_rep::qt_color_picker_widget_rep - (command call_back, bool pickPattern, array proposals) -: _commandAfterExecution(call_back), _pickPattern(pickPattern) -{ +qt_color_picker_widget_rep::qt_color_picker_widget_rep (command call_back, + bool pickPattern, + array proposals) + : _commandAfterExecution (call_back), _pickPattern (pickPattern) { (void) proposals; } -qt_color_picker_widget_rep::~qt_color_picker_widget_rep() { } +qt_color_picker_widget_rep::~qt_color_picker_widget_rep () {} void qt_color_picker_widget_rep::send (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_color_picker_widget_rep::send " << slot_name(s) << LF; + debug_widgets << "qt_color_picker_widget_rep::send " << slot_name (s) << LF; switch (s) { - case SLOT_VISIBILITY: // Activates the widget - check_type(val, s); - if (open_box(val) == true) - showDialog(); - break; - default: - qt_widget_rep::send (s, val); + case SLOT_VISIBILITY: // Activates the widget + check_type (val, s); + if (open_box (val) == true) showDialog (); + break; + default: + qt_widget_rep::send (s, val); } } @@ -56,21 +54,23 @@ qt_color_picker_widget_rep::send (slot s, blackbox val) { identify it with the window title. This is not always the case. */ widget -qt_color_picker_widget_rep::plain_window_widget (string name, command q, int b) { - (void) b; (void) q; - _windowTitle = name; +qt_color_picker_widget_rep::plain_window_widget (string name, command q, + int b) { + (void) b; + (void) q; + _windowTitle= name; return this; } void -qt_color_picker_widget_rep::showDialog() { +qt_color_picker_widget_rep::showDialog () { if (_pickPattern) { // do stuff - } else { - QColor _sel = QColorDialog::getColor(Qt::white); - if(_sel.isValid()) { + } + else { + QColor _sel= QColorDialog::getColor (Qt::white); + if (_sel.isValid ()) { _commandAfterExecution (list_object (object (tree (from_qcolor (_sel))))); } } } - diff --git a/src/Plugins/Qt/qt_color_picker_widget.hpp b/src/Plugins/Qt/qt_color_picker_widget.hpp index 3892ece14b..a43aec53a1 100644 --- a/src/Plugins/Qt/qt_color_picker_widget.hpp +++ b/src/Plugins/Qt/qt_color_picker_widget.hpp @@ -1,7 +1,7 @@ /****************************************************************************** * MODULE : qt_color_picker_widget.hpp - * DESCRIPTION: + * DESCRIPTION: * COPYRIGHT : (C) 2010 Miguel de Benito Delgado ******************************************************************************* * This software falls under the GNU general public license version 3 or later. @@ -20,26 +20,25 @@ * This implements a color picker widget, using the native dialogs where * available. * - * The "factory" function for this widget is called color_picker_widget(), + * The "factory" function for this widget is called color_picker_widget(), * in qt_dialogues.cpp * * Please @see qt_widget_rep for some important info. - */ -class qt_color_picker_widget_rep: public qt_widget_rep { + */ +class qt_color_picker_widget_rep : public qt_widget_rep { public: qt_color_picker_widget_rep (command, bool, array); ~qt_color_picker_widget_rep (); - - virtual void send (slot s, blackbox val); - widget plain_window_widget (string s, command q, int b); - void showDialog(); - + virtual void send (slot s, blackbox val); + widget plain_window_widget (string s, command q, int b); + + void showDialog (); + protected: - string _windowTitle; + string _windowTitle; command _commandAfterExecution; - bool _pickPattern; + bool _pickPattern; }; - -#endif // QT_COLOR_PICKER_WIDGET_HPP +#endif // QT_COLOR_PICKER_WIDGET_HPP diff --git a/src/Plugins/Qt/qt_dialogues.cpp b/src/Plugins/Qt/qt_dialogues.cpp index a9f5ed9483..3944df4e3d 100644 --- a/src/Plugins/Qt/qt_dialogues.cpp +++ b/src/Plugins/Qt/qt_dialogues.cpp @@ -1,70 +1,67 @@ /****************************************************************************** -* MODULE : qt_dialogues.cpp -* DESCRIPTION: Widgets for automatically created dialogues (questions in popups) -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_dialogues.cpp + * DESCRIPTION: Widgets for automatically created dialogues (questions in + *popups) COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ -#include "widget.hpp" -#include "message.hpp" #include "qt_dialogues.hpp" -#include "qt_utilities.hpp" -#include "qt_tm_widget.hpp" +#include "QTMGuiHelper.hpp" +#include "QTMMenuHelper.hpp" +#include "analyze.hpp" +#include "converter.hpp" +#include "message.hpp" #include "qt_chooser_widget.hpp" #include "qt_color_picker_widget.hpp" +#include "qt_tm_widget.hpp" +#include "qt_utilities.hpp" #include "url.hpp" -#include "analyze.hpp" -#include "converter.hpp" -#include "QTMMenuHelper.hpp" -#include "QTMGuiHelper.hpp" +#include "widget.hpp" -#include -#include -#include -#include -#include +#include #include -#include +#include #include -#include +#include +#include +#include +#include +#include #include -#include -#include - +#include +#include -#include "string.hpp" #include "scheme.hpp" - +#include "string.hpp" /****************************************************************************** * qt_field_widget_rep ******************************************************************************/ qt_field_widget_rep::qt_field_widget_rep (qt_inputs_list_widget_rep* _parent, - string _prompt) - : qt_widget_rep (field_widget), - prompt (_prompt), input (""), proposals (), parent (_parent) -{ } + string _prompt) + : qt_widget_rep (field_widget), prompt (_prompt), input (""), proposals (), + parent (_parent) {} void qt_field_widget_rep::send (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_field_widget_rep::send " << slot_name(s) << LF; + debug_widgets << "qt_field_widget_rep::send " << slot_name (s) << LF; switch (s) { case SLOT_STRING_INPUT: - check_type(val, s); + check_type (val, s); input= scm_quote (open_box (val)); break; case SLOT_INPUT_TYPE: - check_type(val, s); + check_type (val, s); type= open_box (val); break; case SLOT_INPUT_PROPOSAL: - check_type(val, s); + check_type (val, s); proposals << open_box (val); break; case SLOT_KEYBOARD_FOCUS: @@ -78,7 +75,7 @@ qt_field_widget_rep::send (slot s, blackbox val) { blackbox qt_field_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_field_widget_rep::query " << slot_name(s) << LF; + debug_widgets << "qt_field_widget_rep::query " << slot_name (s) << LF; switch (s) { case SLOT_STRING_INPUT: check_type_id (type_id, s); @@ -90,34 +87,34 @@ qt_field_widget_rep::query (slot s, int type_id) { QWidget* qt_field_widget_rep::as_qwidget () { - qwid = new QWidget (); - + qwid= new QWidget (); + QHBoxLayout* hl = new QHBoxLayout (qwid); - QLabel* lab = new QLabel (to_qstring (prompt), qwid); - + QLabel* lab= new QLabel (to_qstring (prompt), qwid); + qwid->setLayout (hl); hl->addWidget (lab, 0, Qt::AlignRight); if (ends (type, "file") || type == "directory") { - widget wid = input_text_widget (command(), type, - array(0), 0, "20em"); - QLineEdit* le = qobject_cast (concrete(wid)->as_qwidget()); + widget wid= + input_text_widget (command (), type, array (0), 0, "20em"); + QLineEdit* le= qobject_cast (concrete (wid)->as_qwidget ()); ASSERT (le != NULL, "qt_field_widget_rep: expecting QTMLineEdit"); le->setObjectName (to_qstring (type)); lab->setBuddy (le); hl->addWidget (le); - } + } else if (type == "password") { - QTMLineEdit* le= new QTMLineEdit (qwid, "password", "20em", 0); - QTMFieldWidgetHelper* helper = new QTMFieldWidgetHelper (this, le); + QTMLineEdit* le = new QTMLineEdit (qwid, "password", "20em", 0); + QTMFieldWidgetHelper* helper= new QTMFieldWidgetHelper (this, le); (void) helper; le->setCompleter (0); lab->setBuddy (le); hl->addWidget (le); } else { - QTMComboBox* cb = new QTMComboBox (qwid); - QTMFieldWidgetHelper* helper = new QTMFieldWidgetHelper (this, cb); + QTMComboBox* cb = new QTMComboBox (qwid); + QTMFieldWidgetHelper* helper= new QTMFieldWidgetHelper (this, cb); (void) helper; cb->addItems (to_qstringlist (proposals)); cb->setEditText (to_qstring (scm_unquote (input))); @@ -126,17 +123,16 @@ qt_field_widget_rep::as_qwidget () { cb->setSizeAdjustPolicy (QComboBox::AdjustToContents); cb->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed); cb->setMinimumWidth (80); - cb->setDuplicatesEnabled (true); - cb->completer()->setCaseSensitivity (Qt::CaseSensitive); - if (N(type) == 0) cb->setObjectName ("default focus target"); - else cb->setObjectName (to_qstring (type)); + cb->setDuplicatesEnabled (true); + cb->completer ()->setCaseSensitivity (Qt::CaseSensitive); + if (N (type) == 0) cb->setObjectName ("default focus target"); + else cb->setObjectName (to_qstring (type)); lab->setBuddy (cb); hl->addWidget (cb); } return qwid; } - /****************************************************************************** * qt_inputs_list_widget_rep ******************************************************************************/ @@ -145,29 +141,28 @@ qt_field_widget_rep::as_qwidget () { #include /*! An event filter to circumvent a Qt Mac bug in QMessageBox. - + Pressing tab has no effect on QMessageBox dialogs under MacOS. See e.g. https://bugreports.qt-project.org/browse/QTBUG-13330 - + The bug is present at least in versions >= 4.6.1 and <= 4.8.5 */ class QTMFilterHack : public QWidget { typedef QList ButtonList; - ButtonList buttons; - int current; - int N; + ButtonList buttons; + int current; + int N; + public: - QTMFilterHack (ButtonList _buttons) : buttons (_buttons), current (1), - N (_buttons.size()) { } - bool eventFilter(QObject *target, QEvent *event) - { - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Tab) { - if (keyEvent->modifiers() & Qt::ShiftModifier) - current = current - 1 < 0 ? N-1 : current - 1; - else - current = current + 1 >= N? 0 : current + 1; + QTMFilterHack (ButtonList _buttons) + : buttons (_buttons), current (1), N (_buttons.size ()) {} + bool eventFilter (QObject* target, QEvent* event) { + if (event->type () == QEvent::KeyPress) { + QKeyEvent* keyEvent= static_cast (event); + if (keyEvent->key () == Qt::Key_Tab) { + if (keyEvent->modifiers () & Qt::ShiftModifier) + current= current - 1 < 0 ? N - 1 : current - 1; + else current= current + 1 >= N ? 0 : current + 1; buttons[current]->setFocus (Qt::TabFocusReason); return true; } @@ -177,44 +172,42 @@ class QTMFilterHack : public QWidget { }; #endif -qt_inputs_list_widget_rep::qt_inputs_list_widget_rep (command _cmd, +qt_inputs_list_widget_rep::qt_inputs_list_widget_rep (command _cmd, array _prompts) -: qt_widget_rep (input_widget), cmd (_cmd), size (coord2 (100, 100)), - position (coord2 (0, 0)), win_title (""), style (0) -{ - for (int i = 0; i < N(_prompts); i++) - add_child (tm_new ((qt_inputs_list_widget_rep*)this, _prompts[i])); + : qt_widget_rep (input_widget), cmd (_cmd), size (coord2 (100, 100)), + position (coord2 (0, 0)), win_title (""), style (0) { + for (int i= 0; i < N (_prompts); i++) + add_child (tm_new ((qt_inputs_list_widget_rep*) this, + _prompts[i])); } widget qt_inputs_list_widget_rep::plain_window_widget (string s, command q, int b) { (void) b; (void) q; // The widget already has a command (dialogue_command) - win_title = s; + win_title= s; return this; } void qt_inputs_list_widget_rep::send (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_inputs_list_widget_rep::send " << slot_name(s) << LF; + debug_widgets << "qt_inputs_list_widget_rep::send " << slot_name (s) << LF; switch (s) { - case SLOT_VISIBILITY: - { - check_type (val, s); - bool flag = open_box (val); - (void) flag; - NOT_IMPLEMENTED("qt_inputs_list_widget::SLOT_VISIBILITY") - } - break; + case SLOT_VISIBILITY: { + check_type (val, s); + bool flag= open_box (val); + (void) flag; + NOT_IMPLEMENTED ("qt_inputs_list_widget::SLOT_VISIBILITY") + } break; case SLOT_SIZE: check_type (val, s); - size = open_box (val); + size= open_box (val); break; case SLOT_POSITION: check_type (val, s); - position = open_box (val); + position= open_box (val); break; case SLOT_KEYBOARD_FOCUS: check_type (val, s); @@ -228,20 +221,18 @@ qt_inputs_list_widget_rep::send (slot s, blackbox val) { blackbox qt_inputs_list_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_inputs_list_widget_rep::query " << slot_name(s) << LF; + debug_widgets << "qt_inputs_list_widget_rep::query " << slot_name (s) << LF; switch (s) { - case SLOT_POSITION: - { - check_type_id (type_id, s); - return close_box (position); - } - case SLOT_SIZE: - { - check_type_id (type_id, s); - return close_box (size); - } + case SLOT_POSITION: { + check_type_id (type_id, s); + return close_box (position); + } + case SLOT_SIZE: { + check_type_id (type_id, s); + return close_box (size); + } case SLOT_STRING_INPUT: - if (N(children) > 0) return field(0)->query (s, type_id); + if (N (children) > 0) return field (0)->query (s, type_id); default: return qt_widget_rep::query (s, type_id); } @@ -250,16 +241,15 @@ qt_inputs_list_widget_rep::query (slot s, int type_id) { widget qt_inputs_list_widget_rep::read (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_inputs_list_widget_rep::read " << slot_name(s) << LF; + debug_widgets << "qt_inputs_list_widget_rep::read " << slot_name (s) << LF; switch (s) { case SLOT_WINDOW: check_type_void (val, s); return this; - case SLOT_FORM_FIELD: - { + case SLOT_FORM_FIELD: { check_type (val, s); - int index = open_box (val); - if (N(children) > index) + int index= open_box (val); + if (N (children) > index) return static_cast (children[index].rep); } default: @@ -273,102 +263,99 @@ qt_inputs_list_widget_rep::field (int i) { } void -qt_inputs_list_widget_rep::perform_dialog() { - if ((N(children)==1) && (field(0)->type == "question")) { - // then use Qt messagebox for smoother, more standard UI - QWidget* mainwindow = QApplication::activeWindow (); +qt_inputs_list_widget_rep::perform_dialog () { + if ((N (children) == 1) && (field (0)->type == "question")) { + // then use Qt messagebox for smoother, more standard UI + QWidget* mainwindow= QApplication::activeWindow (); // main texmacs window. There are probably better ways... // Presently not checking if the windows has the focus; // In case it has not, it should be brought into focus // before calling the dialog QMessageBox msgBox (mainwindow); - //sets parent widget, so that it appears at the proper location - msgBox.setText (to_qstring (field(0)->prompt)); + // sets parent widget, so that it appears at the proper location + msgBox.setText (to_qstring (field (0)->prompt)); msgBox.setStandardButtons (QMessageBox::Cancel); - - // Allow any number of choices. The first one is the default. - int choices = N(field(0)->proposals); + + // Allow any number of choices. The first one is the default. + int choices= N (field (0)->proposals); QVector buttonlist (choices); if (choices > 0) { - for(int i = 0; i < choices; ++i) { - // Capitalize the first character? - string blabel= "&" * upcase_first (field(0)->proposals[i]); - buttonlist[i] = msgBox.addButton (to_qstring (blabel), - QMessageBox::ActionRole); + for (int i= 0; i < choices; ++i) { + // Capitalize the first character? + string blabel= "&" * upcase_first (field (0)->proposals[i]); + buttonlist[i]= + msgBox.addButton (to_qstring (blabel), QMessageBox::ActionRole); } msgBox.setDefaultButton (buttonlist[0]); - for (int i = 0; i < choices - 1; ++i) - QWidget::setTabOrder (buttonlist[i], buttonlist[i+1]); - QWidget::setTabOrder (buttonlist[choices-1], msgBox.escapeButton()); + for (int i= 0; i < choices - 1; ++i) + QWidget::setTabOrder (buttonlist[i], buttonlist[i + 1]); + QWidget::setTabOrder (buttonlist[choices - 1], msgBox.escapeButton ()); } msgBox.setWindowTitle (qt_translate ("Question")); msgBox.setIcon (QMessageBox::Question); #ifdef Q_OS_MAC - QTMFilterHack filter (msgBox.buttons()); + QTMFilterHack filter (msgBox.buttons ()); msgBox.installEventFilter (&filter); #endif - msgBox.exec(); - bool buttonclicked=false; - for(int i=0; iinput = scm_quote (field(0)->proposals[i]); - buttonclicked=true; + msgBox.exec (); + bool buttonclicked= false; + for (int i= 0; i < choices; i++) { + if (msgBox.clickedButton () == buttonlist[i]) { + field (0)->input= scm_quote (field (0)->proposals[i]); + buttonclicked = true; break; } } - if (!buttonclicked) {field(0)->input = "#f";} //cancelled - } - - else { //usual dialog layout - QDialog d (0, Qt::Sheet); - QVBoxLayout* vl = new QVBoxLayout(&d); + if (!buttonclicked) { + field (0)->input= "#f"; + } // cancelled + } + + else { // usual dialog layout + QDialog d (0, Qt::Sheet); + QVBoxLayout* vl= new QVBoxLayout (&d); QVector widgets; - for(int i = 0; i < N(children); ++i) { - widgets.push_back (field(i)->as_qwidget()); - vl->addWidget(widgets[i]); + for (int i= 0; i < N (children); ++i) { + widgets.push_back (field (i)->as_qwidget ()); + vl->addWidget (widgets[i]); } - for (int i = 0; i < N(children) - 1; ++i) - QWidget::setTabOrder (widgets[i], widgets[i+1]); - - QDialogButtonBox* buttonBox = - new QDialogButtonBox (QDialogButtonBox::Ok | QDialogButtonBox::Cancel, - Qt::Horizontal, &d); - QObject::connect (buttonBox, SIGNAL (accepted()), &d, SLOT (accept())); - QObject::connect (buttonBox, SIGNAL (rejected()), &d, SLOT (reject())); + for (int i= 0; i < N (children) - 1; ++i) + QWidget::setTabOrder (widgets[i], widgets[i + 1]); + + QDialogButtonBox* buttonBox= new QDialogButtonBox ( + QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &d); + QObject::connect (buttonBox, SIGNAL (accepted ()), &d, SLOT (accept ())); + QObject::connect (buttonBox, SIGNAL (rejected ()), &d, SLOT (reject ())); vl->addWidget (buttonBox); - - d.setWindowTitle (to_qstring (win_title)); - d.updateGeometry(); + + d.setWindowTitle (to_qstring (win_title)); + d.updateGeometry (); QRect r; r.setSize (d.sizeHint ()); r.moveCenter (to_qpoint (position)); d.setGeometry (r); d.setSizePolicy (QSizePolicy::Preferred, QSizePolicy::Fixed); - - if (d.exec() != QDialog::Accepted) - for(int i=0; i < N(children); ++i) - field(i)->input = "#f"; + + if (d.exec () != QDialog::Accepted) + for (int i= 0; i < N (children); ++i) + field (i)->input= "#f"; } - if (!is_nil(cmd)) cmd (); + if (!is_nil (cmd)) cmd (); } - /****************************************************************************** * qt_input_text_widget_rep ******************************************************************************/ -qt_input_text_widget_rep::qt_input_text_widget_rep (command _cmd, - string _type, +qt_input_text_widget_rep::qt_input_text_widget_rep (command _cmd, string _type, array _proposals, - int _style, - string _width) -: qt_widget_rep (input_widget), cmd (_cmd), type (_type), - proposals (_proposals), input (""), style (_style), width (_width), - ok (false), done (false) -{ - if (type == "password") proposals = array (0); - if (N(proposals) > 0) input = proposals[0]; + int _style, string _width) + : qt_widget_rep (input_widget), cmd (_cmd), type (_type), + proposals (_proposals), input (""), style (_style), width (_width), + ok (false), done (false) { + if (type == "password") proposals= array (0); + if (N (proposals) > 0) input= proposals[0]; } QAction* @@ -382,26 +369,28 @@ qt_input_text_widget_rep::as_qaction () { */ QWidget* qt_input_text_widget_rep::as_qwidget () { - QTMLineEdit* le = new QTMLineEdit (NULL, type, width, style, cmd); - qwid = le; - bool can_autocommit= !(ends (type, "search") || - ends (type, "replace") || + QTMLineEdit* le = new QTMLineEdit (NULL, type, width, style, cmd); + qwid = le; + bool can_autocommit= !(ends (type, "search") || ends (type, "replace") || ends (type, "replace")); - QTMInputTextWidgetHelper* helper = - new QTMInputTextWidgetHelper (this, can_autocommit); + QTMInputTextWidgetHelper* helper= + new QTMInputTextWidgetHelper (this, can_autocommit); (void) helper; le->setText (to_qstring (input)); le->setObjectName (to_qstring (type)); if (ends (type, "file") || type == "directory") { - QCompleter* completer = new QCompleter(le); - QFileSystemModel* fsModel = new QFileSystemModel(le); - fsModel->setRootPath (QDir::homePath());// This is NOT the starting location + QCompleter* completer= new QCompleter (le); + QFileSystemModel* fsModel = new QFileSystemModel (le); + fsModel->setRootPath ( + QDir::homePath ()); // This is NOT the starting location completer->setModel (fsModel); le->setCompleter (completer); } - else if (type != "password" && N(proposals) > 0 && ! (N(proposals) == 1 && N(proposals[0]) == 0)){ - //else if (N(proposals) > 0 && ! (N(proposals) == 1 && N(proposals[0]) == 0)){ - QCompleter* completer = new QCompleter (to_qstringlist(proposals), le); + else if (type != "password" && N (proposals) > 0 && + !(N (proposals) == 1 && N (proposals[0]) == 0)) { + // else if (N(proposals) > 0 && ! (N(proposals) == 1 && N(proposals[0]) == + // 0)){ + QCompleter* completer= new QCompleter (to_qstringlist (proposals), le); completer->setCaseSensitivity (Qt::CaseSensitive); completer->setCompletionMode (QCompleter::InlineCompletion); le->setCompleter (completer); @@ -410,23 +399,23 @@ qt_input_text_widget_rep::as_qwidget () { } void -qt_input_text_widget_rep::commit(bool flag) { - QTMLineEdit* le = qobject_cast(qwid); - widget_rep* win = qt_window_widget_rep::widget_from_qwidget (le); +qt_input_text_widget_rep::commit (bool flag) { + QTMLineEdit* le = qobject_cast (qwid); + widget_rep* win= qt_window_widget_rep::widget_from_qwidget (le); if (flag) { - done = false; - ok = true; - input = from_qstring (le->text()); - } else { + done = false; + ok = true; + input= from_qstring (le->text ()); + } + else { le->setText (to_qstring (input)); } if (win) // This is 0 inside a dialog => no command { if (done) return; - done = true; - the_gui->process_command (cmd, ok - ? list_object (object (input)) - : list_object (object (false))); + done= true; + the_gui->process_command (cmd, ok ? list_object (object (input)) + : list_object (object (false))); } } diff --git a/src/Plugins/Qt/qt_dialogues.hpp b/src/Plugins/Qt/qt_dialogues.hpp index 2e506bd7c9..6dfea9f0be 100644 --- a/src/Plugins/Qt/qt_dialogues.hpp +++ b/src/Plugins/Qt/qt_dialogues.hpp @@ -1,19 +1,19 @@ /****************************************************************************** -* MODULE : qt_dialogues.hpp -* DESCRIPTION: Widgets for automatically created dialogues (questions in popups) -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_dialogues.hpp + * DESCRIPTION: Widgets for automatically created dialogues (questions in + *popups) COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_DIALOGUES_HPP #define QT_DIALOGUES_HPP -#include "qt_widget.hpp" #include "qt_utilities.hpp" +#include "qt_widget.hpp" class QTMInputTextWidgetHelper; class QTMFieldWidgetHelper; @@ -21,27 +21,28 @@ class qt_tm_widget_rep; /*! A text input field with autocompletion. */ -class qt_input_text_widget_rep: public qt_widget_rep { +class qt_input_text_widget_rep : public qt_widget_rep { protected: - command cmd; - string type; + command cmd; + string type; array proposals; - string input; - int style; - string width; - bool ok; + string input; + int style; + string width; + bool ok; - bool done; //!< Has the command been executed after a modification? + bool done; //!< Has the command been executed after a modification? public: - qt_input_text_widget_rep (command _cmd, string _type, array _proposals, - int _style, string _width); - - virtual QAction* as_qaction (); - virtual QWidget* as_qwidget (); - - void commit(bool ok); - + qt_input_text_widget_rep (command _cmd, string _type, + array _proposals, int _style, + string _width); + + virtual QAction* as_qaction (); + virtual QWidget* as_qwidget (); + + void commit (bool ok); + friend class QTMInputTextWidgetHelper; friend class QTMInteractiveInputHelper; friend class qt_tm_widget_rep; @@ -50,53 +51,53 @@ class qt_input_text_widget_rep: public qt_widget_rep { class qt_field_widget_rep; /*! A dialog with a list of inputs and ok and cancel buttons. - + In the general case each input is a qt_field_widget_rep which we lay out in a vertical table. However, for simple yes/no/cancel questions we try to use a - system default dialog - + system default dialog + TODO? We try to use OS dialogs whenever possible, but this still needs improvement. We should also use a custom Qt widget and then bundle it in a modal window if - required, so as to eventually be able to return something embeddable in + required, so as to eventually be able to return something embeddable in as_qwidget(), in case we want to reuse this. */ -class qt_inputs_list_widget_rep: public qt_widget_rep { +class qt_inputs_list_widget_rep : public qt_widget_rep { protected: command cmd; - coord2 size, position; - string win_title; - int style; + coord2 size, position; + string win_title; + int style; public: qt_inputs_list_widget_rep (command, array); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); - + virtual widget read (slot s, blackbox index); + virtual widget plain_window_widget (string s, command q, int b); - + protected: - void perform_dialog(); + void perform_dialog (); qt_field_widget_rep* field (int i); }; /*! Each of the fields in a qt_inputs_list_widget_rep. - + Each field is composed of a prompt (a label) and an input (a QTMComboBox). */ -class qt_field_widget_rep: public qt_widget_rep { - string prompt; - string input; - string type; - array proposals; +class qt_field_widget_rep : public qt_widget_rep { + string prompt; + string input; + string type; + array proposals; qt_inputs_list_widget_rep* parent; public: qt_field_widget_rep (qt_inputs_list_widget_rep* _parent, string _prompt); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); virtual QWidget* as_qwidget (); diff --git a/src/Plugins/Qt/qt_font.cpp b/src/Plugins/Qt/qt_font.cpp index e8e87e5538..9b832f4a0d 100644 --- a/src/Plugins/Qt/qt_font.cpp +++ b/src/Plugins/Qt/qt_font.cpp @@ -1,17 +1,17 @@ /****************************************************************************** -* MODULE : qt_font.cpp -* DESCRIPTION: Qt fonts -* COPYRIGHT : (C) 2012 Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_font.cpp + * DESCRIPTION: Qt fonts + * COPYRIGHT : (C) 2012 Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "Qt/qt_font.hpp" -#include "Qt/qt_utilities.hpp" #include "Qt/qt_renderer.hpp" +#include "Qt/qt_utilities.hpp" #include "analyze.hpp" #include "dictionary.hpp" @@ -19,46 +19,45 @@ #define MAGN (dpi * PIXEL / 72.0) #define ROUND(x) ((SI) round (x * MAGN)) #define FLOOR(x) ((SI) floor (x * MAGN)) -#define CEIL(x) ((SI) ceil (x * MAGN)) +#define CEIL(x) ((SI) ceil (x * MAGN)) /****************************************************************************** -* The implementation -******************************************************************************/ - -qt_font_rep::qt_font_rep (string name, string family2, int size2, int dpi2): - font_rep (name), family (family2), size (size2), dpi (dpi2), - qfn (to_qstring (family), size), - //qfn (to_qstring (family), size, QFont::Normal, false), - qfm (qfn) -{ + * The implementation + ******************************************************************************/ + +qt_font_rep::qt_font_rep (string name, string family2, int size2, int dpi2) + : font_rep (name), family (family2), size (size2), dpi (dpi2), + qfn (to_qstring (family), size), + // qfn (to_qstring (family), size, QFont::Normal, false), + qfm (qfn) { type= FONT_TYPE_QT; // get main font parameters - y1= FLOOR (-qfm.descent ()); - y2= CEIL (qfm.ascent () + 1); - display_size = y2-y1; - design_size = size << 8; + y1 = FLOOR (-qfm.descent ()); + y2 = CEIL (qfm.ascent () + 1); + display_size= y2 - y1; + design_size = size << 8; // get character dimensions metric ex; - yx = ROUND (qfm.xHeight ()); + yx= ROUND (qfm.xHeight ()); get_extents ("M", ex); - wquad = ex->x2; + wquad= ex->x2; // compute other heights - yfrac = yx >> 1; - ysub_lo_base = -yx/3; - ysub_hi_lim = (5*yx)/6; - ysup_lo_lim = yx/2; - ysup_lo_base = (5*yx)/6; - ysup_hi_lim = yx; - yshift = yx/6; + yfrac = yx >> 1; + ysub_lo_base= -yx / 3; + ysub_hi_lim = (5 * yx) / 6; + ysup_lo_lim = yx / 2; + ysup_lo_base= (5 * yx) / 6; + ysup_hi_lim = yx; + yshift = yx / 6; // compute other widths - wpt = (dpi*PIXEL)/72; - hpt = (dpi*PIXEL)/72; - wfn = (wpt*design_size) >> 8; - wline = wfn/20; + wpt = (dpi * PIXEL) / 72; + hpt = (dpi * PIXEL) / 72; + wfn = (wpt * design_size) >> 8; + wline= wfn / 20; // get fraction bar parameters get_extents ("-", ex); @@ -66,16 +65,17 @@ qt_font_rep::qt_font_rep (string name, string family2, int size2, int dpi2): // get space length get_extents (" ", ex); - spc = space ((3*(ex->x2-ex->x1))>>2, ex->x2-ex->x1, (ex->x2-ex->x1)<<1); + spc = space ((3 * (ex->x2 - ex->x1)) >> 2, ex->x2 - ex->x1, + (ex->x2 - ex->x1) << 1); extra= spc; mspc = spc; - sep = wfn/10; + sep = wfn / 10; // get_italic space get_extents ("f", ex); - SI italic_spc= (ex->x4-ex->x3)-(ex->x2-ex->x1); - slope= ((double) italic_spc) / ((double) display_size); - if (slope<0.15) slope= 0.0; + SI italic_spc= (ex->x4 - ex->x3) - (ex->x2 - ex->x1); + slope = ((double) italic_spc) / ((double) display_size); + if (slope < 0.15) slope= 0.0; } bool @@ -88,28 +88,28 @@ void qt_font_rep::get_extents (string s, metric& ex) { QString qs = utf8_to_qstring (cork_to_utf8 (s)); QRectF rect= qfm.tightBoundingRect (qs); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - qreal w = qfm.width (qs); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + qreal w= qfm.width (qs); #else - qreal w = qfm.horizontalAdvance (qs); + qreal w= qfm.horizontalAdvance (qs); #endif ex->x1= 0; ex->x2= ROUND (w); ex->y1= FLOOR (-rect.bottom ()); - ex->y2= CEIL (-rect.top ()); + ex->y2= CEIL (-rect.top ()); ex->x3= FLOOR (rect.left ()); - ex->x4= CEIL (rect.right ()); + ex->x4= CEIL (rect.right ()); ex->y3= ex->y1; ex->y4= ex->y2; } void qt_font_rep::draw_fixed (renderer ren, string s, SI x, SI y) { - if (N(s)!=0) { - QString qs= utf8_to_qstring (cork_to_utf8 (s)); - double zoom= dpi / (std_shrinkf * 72.0); + if (N (s) != 0) { + QString qs = utf8_to_qstring (cork_to_utf8 (s)); + double zoom= dpi / (std_shrinkf * 72.0); qt_renderer_rep* qren= (qt_renderer_rep*) ren->get_handle (); - qren -> draw (qfn, qs, x, y, zoom); + qren->draw (qfn, qs, x, y, zoom); } } @@ -120,12 +120,12 @@ qt_font_rep::magnify (double zoomx, double zoomy) { } /****************************************************************************** -* Interface -******************************************************************************/ + * Interface + ******************************************************************************/ font qt_font (string family, int size, int dpi) { string name= "qt:" * family * as_string (size) * "@" * as_string (dpi); - if (font::instances -> contains (name)) return font (name); + if (font::instances->contains (name)) return font (name); else return tm_new (name, family, size, dpi); } diff --git a/src/Plugins/Qt/qt_font.hpp b/src/Plugins/Qt/qt_font.hpp index 0c75249947..f1cd3e18d5 100644 --- a/src/Plugins/Qt/qt_font.hpp +++ b/src/Plugins/Qt/qt_font.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : qt_font.hpp -* DESCRIPTION: Qt fonts -* COPYRIGHT : (C) 2012 Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_font.hpp + * DESCRIPTION: Qt fonts + * COPYRIGHT : (C) 2012 Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_FONT_H #define QT_FONT_H @@ -18,24 +18,24 @@ #include "font.hpp" /****************************************************************************** -* The qt_font representation class -******************************************************************************/ - -struct qt_font_rep: font_rep { - string family; - int size; - int dpi; - QFont qfn; + * The qt_font representation class + ******************************************************************************/ + +struct qt_font_rep : font_rep { + string family; + int size; + int dpi; + QFont qfn; QFontMetricsF qfm; - + qt_font_rep (string name, string family, int size, int dpi); bool supports (string c); void get_extents (string s, metric& ex); void draw_fixed (renderer ren, string s, SI x, SI y); font magnify (double zoomx, double zoomy); - //void advance_glyph (string s, int& pos, bool ligf); - //glyph get_glyph (string s); - //int index_glyph (string s, font_metric& fnm, font_glyphs& fng); + // void advance_glyph (string s, int& pos, bool ligf); + // glyph get_glyph (string s); + // int index_glyph (string s, font_metric& fnm, font_glyphs& fng); }; #endif // defined QT_FONT_H diff --git a/src/Plugins/Qt/qt_gui.cpp b/src/Plugins/Qt/qt_gui.cpp index d2a08b4fee..df31e7d6d1 100644 --- a/src/Plugins/Qt/qt_gui.cpp +++ b/src/Plugins/Qt/qt_gui.cpp @@ -11,46 +11,46 @@ #include -#include "convert.hpp" -#include "Xml/xml.hpp" #include "Html/html.hpp" -#include "iterator.hpp" +#include "Xml/xml.hpp" +#include "analyze.hpp" +#include "convert.hpp" #include "dictionary.hpp" #include "file.hpp" // added for copy_as_graphics -#include "tm_file.hpp" -#include "analyze.hpp" +#include "iterator.hpp" #include "locale.hpp" #include "message.hpp" -#include "scheme.hpp" -#include "tm_window.hpp" #include "new_window.hpp" #include "preferences.hpp" +#include "scheme.hpp" +#include "tm_file.hpp" +#include "tm_window.hpp" #include "qt_gui.hpp" -#include "qt_utilities.hpp" #include "qt_renderer.hpp" // for the_qt_renderer #include "qt_simple_widget.hpp" +#include "qt_utilities.hpp" #include "qt_window_widget.hpp" -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // see https://doc.qt.io/qt-6/widgets-changes-qt6.html #include #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 -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include #endif #include @@ -65,32 +65,32 @@ #include #ifdef qt_static_plugin_qjpeg -Q_IMPORT_PLUGIN(qjpeg) +Q_IMPORT_PLUGIN (qjpeg) #endif #ifdef qt_static_plugin_qgif -Q_IMPORT_PLUGIN(qgif) +Q_IMPORT_PLUGIN (qgif) #endif #ifdef qt_static_plugin_qico -Q_IMPORT_PLUGIN(qico) +Q_IMPORT_PLUGIN (qico) #endif #ifdef qt_static_plugin_qsvg -Q_IMPORT_PLUGIN(qsvg) +Q_IMPORT_PLUGIN (qsvg) #endif -#ifdef WIN32 -Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) +#ifdef WIN32 +Q_IMPORT_PLUGIN (QWindowsIntegrationPlugin) #endif #ifdef QT_MAC_USE_COCOA -Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin) +Q_IMPORT_PLUGIN (QCocoaIntegrationPlugin) #endif -qt_gui_rep* the_gui = NULL; -int nr_windows = 0; // FIXME: fake variable, referenced in tm_server +qt_gui_rep* the_gui = NULL; +int nr_windows= 0; // FIXME: fake variable, referenced in tm_server /****************************************************************************** -* FIXME: temporary hack by Joris -* Additional wait mechanism to keep CPU usage down -******************************************************************************/ + * FIXME: temporary hack by Joris + * Additional wait mechanism to keep CPU usage down + ******************************************************************************/ #ifdef QT_CPU_FIX #include @@ -105,123 +105,125 @@ tm_wake_up () { void tm_sleep () { - //tm_count += 1.0; + // tm_count += 1.0; tm_delay= 1.0001 * tm_delay; if (tm_delay > 250000.0) tm_delay= 250000; - //cout << tm_count << ", " << tm_delay << "\r"; - //cout.flush (); + // cout << tm_count << ", " << tm_delay << "\r"; + // cout.flush (); usleep ((int) floor (tm_delay)); } #endif /****************************************************************************** -* Constructor and geometry -******************************************************************************/ - -qt_gui_rep::qt_gui_rep (int &argc, char **argv): -interrupted (false), waitWindow (NULL), popup_wid_time (0), q_translator (0), -time_credit (100), do_check_events (false), updating (false), -needing_update (false) -{ - (void) argc; (void) argv; - // argc = argc2; - // argv = argv2; - - interrupted = false; - time_credit = 100; - timeout_time = texmacs_time () + time_credit; - - //waitDialog = NULL; - - gui_helper = new QTMGuiHelper (this); + * Constructor and geometry + ******************************************************************************/ + +qt_gui_rep::qt_gui_rep (int& argc, char** argv) + : interrupted (false), waitWindow (NULL), popup_wid_time (0), + q_translator (0), time_credit (100), do_check_events (false), + updating (false), needing_update (false) { + (void) argc; + (void) argv; + // argc = argc2; + // argv = argv2; + + interrupted = false; + time_credit = 100; + timeout_time= texmacs_time () + time_credit; + + // waitDialog = NULL; + + gui_helper= new QTMGuiHelper (this); qApp->installEventFilter (gui_helper); - + #ifdef QT_MAC_USE_COCOA - //HACK: this filter is needed to overcome a bug in Qt/Cocoa - extern void mac_install_filter(); // defined in src/Plugins/MacOS/mac_app.mm - mac_install_filter(); + // HACK: this filter is needed to overcome a bug in Qt/Cocoa + extern void mac_install_filter (); // defined in src/Plugins/MacOS/mac_app.mm + mac_install_filter (); #endif - + set_output_language (get_locale_language ()); - refresh_language(); - - updatetimer = new QTimer (gui_helper); + refresh_language (); + + updatetimer= new QTimer (gui_helper); updatetimer->setSingleShot (true); - QObject::connect (updatetimer, SIGNAL (timeout()), - gui_helper, SLOT (doUpdate())); + QObject::connect (updatetimer, SIGNAL (timeout ()), gui_helper, + SLOT (doUpdate ())); // (void) default_font (); if (!retina_manual) { retina_manual= true; #ifdef MACOSX_EXTENSIONS - double mac_hidpi = mac_screen_scale_factor(); + double mac_hidpi= mac_screen_scale_factor (); if (DEBUG_STD) - debug_boot << "Mac Screen scaleFfactor: " << mac_hidpi << "\n"; - + debug_boot << "Mac Screen scaleFfactor: " << mac_hidpi << "\n"; + if (mac_hidpi == 2) { if (DEBUG_STD) debug_boot << "Setting up HiDPI mode\n"; - retina_factor= 2; + retina_factor= 2; } #else SI w, h; get_extents (w, h); if (DEBUG_STD) - debug_boot << "Screen extents: " << w/PIXEL << " x " << h/PIXEL << "\n"; + debug_boot << "Screen extents: " << w / PIXEL << " x " << h / PIXEL + << "\n"; if (min (w, h) >= 1440 * PIXEL) { retina_zoom = 2; - retina_scale= (tm_style_sheet == ""? 1.0: 1.6666); + retina_scale= (tm_style_sheet == "" ? 1.0 : 1.6666); if (!retina_iman) { - retina_iman = true; - retina_icons = 2; + retina_iman = true; + retina_icons= 2; } } #endif } if (has_user_preference ("retina-factor")) - retina_factor= get_user_preference ("retina-factor") == "on"? 2: 1; + retina_factor= get_user_preference ("retina-factor") == "on" ? 2 : 1; if (has_user_preference ("retina-zoom")) - retina_zoom= get_user_preference ("retina-zoom") == "on"? 2: 1; + retina_zoom= get_user_preference ("retina-zoom") == "on" ? 2 : 1; if (has_user_preference ("retina-icons")) - retina_icons= get_user_preference ("retina-icons") == "on"? 2: 1; + retina_icons= get_user_preference ("retina-icons") == "on" ? 2 : 1; if (has_user_preference ("retina-scale")) retina_scale= as_double (get_user_preference ("retina-scale")); - qApp->setAttribute(Qt::AA_UseHighDpiPixmaps); + qApp->setAttribute (Qt::AA_UseHighDpiPixmaps); } /* important routines */ void qt_gui_rep::get_extents (SI& width, SI& height) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - coord2 size = headless_mode ? coord2 (480, 320) - : from_qsize (QApplication::desktop()->size()); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + coord2 size= headless_mode ? coord2 (480, 320) + : from_qsize (QApplication::desktop ()->size ()); #else - coord2 size= headless_mode? coord2 (480, 320) - : from_qsize(QApplication::primaryScreen()->availableSize()); + coord2 size= + headless_mode + ? coord2 (480, 320) + : from_qsize (QApplication::primaryScreen ()->availableSize ()); #endif - width = size.x1; - height = size.x2; + width = size.x1; + height= size.x2; } void qt_gui_rep::get_max_size (SI& width, SI& height) { width = 8000 * PIXEL; - height = 6000 * PIXEL; + height= 6000 * PIXEL; } -qt_gui_rep::~qt_gui_rep() { +qt_gui_rep::~qt_gui_rep () { delete gui_helper; - - while (waitDialogs.count()) { - waitDialogs.last()->deleteLater(); - waitDialogs.removeLast(); + + while (waitDialogs.count ()) { + waitDialogs.last ()->deleteLater (); + waitDialogs.removeLast (); } if (waitWindow) delete waitWindow; - - // delete updatetimer; we do not need this given that gui_helper is the - // parent of updatetimer -} + // delete updatetimer; we do not need this given that gui_helper is the + // parent of updatetimer +} /****************************************************************************** * interclient communication @@ -229,167 +231,164 @@ qt_gui_rep::~qt_gui_rep() { bool qt_gui_rep::get_selection (string key, tree& t, string& s, string format) { - QClipboard *cb = QApplication::clipboard (); - QClipboard::Mode mode = QClipboard::Clipboard; + QClipboard* cb = QApplication::clipboard (); + QClipboard::Mode mode= QClipboard::Clipboard; if (key == "primary" || (key == "mouse" && cb->supportsSelection ())) - if (key == "mouse") mode = QClipboard::Selection; - - QString originalText = cb->text (mode); - const QMimeData *md = cb->mimeData (mode); - QByteArray buf; - string input_format; - - s = ""; - t = "none"; - // Knowing when we owns (or not) the content is not clear - bool owns = (format != "temp" && format != "wrapbuf" && key != "primary") && - !(key == "mouse" && cb->supportsSelection ()); - + if (key == "mouse") mode= QClipboard::Selection; + + QString originalText= cb->text (mode); + const QMimeData* md = cb->mimeData (mode); + QByteArray buf; + string input_format; + + s= ""; + t= "none"; + // Knowing when we owns (or not) the content is not clear + bool owns= (format != "temp" && format != "wrapbuf" && key != "primary") && + !(key == "mouse" && cb->supportsSelection ()); + if (!owns && md->hasFormat ("application/x-texmacs-pid")) { - buf = md->data ("application/x-texmacs-pid"); - if (!(buf.isEmpty())) { - owns = string (buf.constData(), buf.size()) - == as_string (QCoreApplication::applicationPid ()); + buf= md->data ("application/x-texmacs-pid"); + if (!(buf.isEmpty ())) { + owns= string (buf.constData (), buf.size ()) == + as_string (QCoreApplication::applicationPid ()); } } - + if (owns) { if (!selection_t->contains (key)) return false; - t = copy (selection_t [key]); - s = copy (selection_s [key]); + t= copy (selection_t[key]); + s= copy (selection_s[key]); return true; } - + if (format == "default") { if (md->hasFormat ("application/x-texmacs-clipboard")) { - buf = md->data ("application/x-texmacs-clipboard"); - input_format = "texmacs-snippet"; + buf = md->data ("application/x-texmacs-clipboard"); + input_format= "texmacs-snippet"; } else if (md->hasImage ()) { if (md->hasUrls ()) { QList l= md->urls (); if (l.size () == 1) { - s= from_qstring (l[0].toString ()); - input_format = "linked-picture"; + s = from_qstring (l[0].toString ()); + input_format= "linked-picture"; } } else { - QBuffer qbuf(&buf); - QImage image= qvariant_cast (md->imageData()); + QBuffer qbuf (&buf); + QImage image= qvariant_cast (md->imageData ()); qbuf.open (QIODevice::WriteOnly); image.save (&qbuf, "PNG"); - input_format = "picture"; + input_format= "picture"; } } else if (md->hasHtml ()) { - buf = md->html().toUtf8 (); - input_format = "html-snippet"; + buf = md->html ().toUtf8 (); + input_format= "html-snippet"; } else if (md->hasFormat ("text/plain;charset=utf8")) { - buf = md->data ("text/plain;charset=utf8"); - input_format = "verbatim-snippet"; + buf = md->data ("text/plain;charset=utf8"); + input_format= "verbatim-snippet"; } else { - buf = md->text().toUtf8 (); - input_format = "verbatim-snippet"; + buf = md->text ().toUtf8 (); + input_format= "verbatim-snippet"; } } - else if (format == "verbatim" - && (get_preference ("verbatim->texmacs:encoding") == "utf-8" || - get_preference ("verbatim->texmacs:encoding") == "auto" )) - buf = md->text().toUtf8 (); + else if (format == "verbatim" && + (get_preference ("verbatim->texmacs:encoding") == "utf-8" || + get_preference ("verbatim->texmacs:encoding") == "auto")) + buf= md->text ().toUtf8 (); else { - if (md->hasFormat ("plain/text")) buf = md->data ("plain/text").data(); - else buf = md->text().toUtf8 (); + if (md->hasFormat ("plain/text")) buf= md->data ("plain/text").data (); + else buf= md->text ().toUtf8 (); } - if (!(buf.isEmpty())) s << string (buf.constData(), buf.size()); + if (!(buf.isEmpty ())) s << string (buf.constData (), buf.size ()); if (input_format == "html-snippet" && seems_buggy_html_paste (s)) - s = correct_buggy_html_paste (s); + s= correct_buggy_html_paste (s); if (input_format != "picture" && seems_buggy_paste (s)) - s = correct_buggy_paste (s); - if (input_format != "" && - input_format != "picture" && + s= correct_buggy_paste (s); + if (input_format != "" && input_format != "picture" && input_format != "linked-picture") - s = as_string (call ("convert", s, input_format, "texmacs-snippet")); + s= as_string (call ("convert", s, input_format, "texmacs-snippet")); if (input_format == "html-snippet") { - tree t = as_tree (call ("convert", s, "texmacs-snippet", "texmacs-tree")); - t = default_with_simplify (t); - s = as_string (call ("convert", t, "texmacs-tree", "texmacs-snippet")); + tree t= as_tree (call ("convert", s, "texmacs-snippet", "texmacs-tree")); + t = default_with_simplify (t); + s = as_string (call ("convert", t, "texmacs-tree", "texmacs-snippet")); } if (input_format == "picture") { - tree t (IMAGE); - QSize size= qvariant_cast(md->imageData()).size (); - int ww= size.width (), hh= size.height (); + tree t (IMAGE); + QSize size= qvariant_cast (md->imageData ()).size (); + int ww= size.width (), hh= size.height (); string w, h; qt_pretty_image_size (ww, hh, w, h); - t << tuple (tree (RAW_DATA, s), "png") << w << h << "" << ""; + t << tuple (tree (RAW_DATA, s), "png") << w << h << "" + << ""; s= as_string (call ("convert", t, "texmacs-tree", "texmacs-snippet")); } if (input_format == "linked-picture") { tree im (IMAGE, s, "", "", "", ""); s= as_string (call ("convert", im, "texmacs-tree", "texmacs-snippet")); } - t = tuple ("extern", s); + t= tuple ("extern", s); return true; } bool -qt_gui_rep::set_selection (string key, tree t, - string s, string sv, string sh, string format) { +qt_gui_rep::set_selection (string key, tree t, string s, string sv, string sh, + string format) { selection_t (key)= copy (t); selection_s (key)= copy (s); - - QClipboard *cb = QApplication::clipboard (); - QClipboard::Mode mode = QClipboard::Clipboard; - if (key == "primary"); - else if (key == "mouse" && cb->supportsSelection()) - mode = QClipboard::Selection; + + QClipboard* cb = QApplication::clipboard (); + QClipboard::Mode mode= QClipboard::Clipboard; + if (key == "primary") + ; + else if (key == "mouse" && cb->supportsSelection ()) + mode= QClipboard::Selection; else return true; cb->clear (mode); - + c_string selection (s); cb->setText (QString::fromLatin1 (selection, -1), mode); - QMimeData *md = new QMimeData; - + QMimeData* md= new QMimeData; + if (format == "verbatim" || format == "default") { if (format == "default") { - md->setData ("application/x-texmacs-clipboard", (char*)selection); - + md->setData ("application/x-texmacs-clipboard", (char*) selection); + QString pid_str; pid_str.setNum (QCoreApplication::applicationPid ()); - md->setData ("application/x-texmacs-pid", pid_str.toLatin1()); - + md->setData ("application/x-texmacs-pid", pid_str.toLatin1 ()); + (void) sh; - //selection = c_string (sh); - //md->setHtml (selection); - //tm_delete_array (selection); - - selection = c_string (sv); + // selection = c_string (sh); + // md->setHtml (selection); + // tm_delete_array (selection); + + selection= c_string (sv); } - - string enc = get_preference ("texmacs->verbatim:encoding"); - if (enc == "auto") - enc = get_locale_charset (); - + + string enc= get_preference ("texmacs->verbatim:encoding"); + if (enc == "auto") enc= get_locale_charset (); + if (enc == "utf-8" || enc == "UTF-8") md->setText (QString::fromUtf8 (selection, -1)); else if (enc == "iso-8859-1" || enc == "ISO-8859-1") md->setText (QString::fromLatin1 (selection, -1)); - else - md->setText (QString::fromLatin1 (selection, -1)); + else md->setText (QString::fromLatin1 (selection, -1)); } else if (format == "latex") { - string enc = get_preference ("texmacs->latex:encoding"); + string enc= get_preference ("texmacs->latex:encoding"); if (enc == "utf-8" || enc == "UTF-8" || enc == "cork") md->setText (to_qstring (string (selection))); - else - md->setText (QString::fromLatin1 (selection, -1)); + else md->setText (QString::fromLatin1 (selection, -1)); } - else - md->setText (QString::fromLatin1 (selection, -1)); + else md->setText (QString::fromLatin1 (selection, -1)); cb->setMimeData (md, mode); - // according to the docs, ownership of mimedata is transferred to clipboard - // so no memory leak here + // according to the docs, ownership of mimedata is transferred to clipboard + // so no memory leak here return true; } @@ -397,132 +396,135 @@ void qt_gui_rep::clear_selection (string key) { selection_t->reset (key); selection_s->reset (key); - - QClipboard *cb = QApplication::clipboard(); - QClipboard::Mode mode = QClipboard::Clipboard; - if (key == "primary"); - else if (key == "mouse" && cb->supportsSelection()) - mode = QClipboard::Selection; + + QClipboard* cb = QApplication::clipboard (); + QClipboard::Mode mode= QClipboard::Clipboard; + if (key == "primary") + ; + else if (key == "mouse" && cb->supportsSelection ()) + mode= QClipboard::Selection; else return; - - bool owns = false; - const QMimeData *md = cb->mimeData (mode); - if (md) owns = md->hasFormat ("application/x-texmacs-clipboard"); + + bool owns= false; + const QMimeData* md = cb->mimeData (mode); + if (md) owns= md->hasFormat ("application/x-texmacs-clipboard"); if (owns) cb->clear (mode); } - /****************************************************************************** * Main loop ******************************************************************************/ void -qt_gui_rep::show_wait_indicator (widget w, string message, string arg) { +qt_gui_rep::show_wait_indicator (widget w, string message, string arg) { if (DEBUG_QT) debug_qt << "show_wait_indicator \"" << message << "\"\"" << arg << "\"\n"; - - qt_window_widget_rep* wid = static_cast (w.rep); - - // we move the texmacs window during an operation. - // We need to disable updates of the window to avoid erasure of the canvas - // area - // wid->wid->setUpdatesEnabled (false); - - //FIXME: we must center the wait widget wrt the current active window - + + qt_window_widget_rep* wid= static_cast (w.rep); + + // we move the texmacs window during an operation. + // We need to disable updates of the window to avoid erasure of the canvas + // area + // wid->wid->setUpdatesEnabled (false); + + // FIXME: we must center the wait widget wrt the current active window + if (!waitWindow) { - waitWindow = new QWidget (wid->qwid->window()); - waitWindow->setWindowFlags (Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); - QStackedLayout *layout = new QStackedLayout(); + waitWindow= new QWidget (wid->qwid->window ()); + waitWindow->setWindowFlags (Qt::Window | Qt::FramelessWindowHint | + Qt::WindowStaysOnTopHint); + QStackedLayout* layout= new QStackedLayout (); layout->setSizeConstraint (QLayout::SetFixedSize); waitWindow->setLayout (layout); } - - if (waitDialogs.count()) { - waitWindow->layout()->removeWidget (waitDialogs.last()); + + if (waitDialogs.count ()) { + waitWindow->layout ()->removeWidget (waitDialogs.last ()); } - - if (N(message)) { - // push a new wait message in the list - - if (arg != "") message = message * " " * arg * "..."; - - QLabel* lab = new QLabel(); + + if (N (message)) { + // push a new wait message in the list + + if (arg != "") message= message * " " * arg * "..."; + + QLabel* lab= new QLabel (); lab->setFocusPolicy (Qt::NoFocus); lab->setMargin (15); lab->setText (to_qstring (message)); waitDialogs << lab; - } else { - // pop the next wait message from the list - if (waitDialogs.count()) { - waitDialogs.last()->deleteLater(); - waitDialogs.removeLast(); + } + else { + // pop the next wait message from the list + if (waitDialogs.count ()) { + waitDialogs.last ()->deleteLater (); + waitDialogs.removeLast (); } } - - if (waitDialogs.count()) { - waitWindow->layout()->addWidget (waitDialogs.last()); - waitWindow->updateGeometry(); + + if (waitDialogs.count ()) { + waitWindow->layout ()->addWidget (waitDialogs.last ()); + waitWindow->updateGeometry (); { - QSize sz = waitWindow->geometry().size(); - QRect rect = QRect (QPoint (0,0),sz); - //HACK: - // processEvents is needed to let Qt update windows coordinates in the case + QSize sz = waitWindow->geometry ().size (); + QRect rect= QRect (QPoint (0, 0), sz); + // HACK: + // processEvents is needed to let Qt update windows coordinates in the + // case qApp->processEvents (QEventLoop::ExcludeUserInputEvents); - //ENDHACK - QPoint pt = wid->qwid->window()->geometry().center(); + // ENDHACK + QPoint pt= wid->qwid->window ()->geometry ().center (); rect.moveCenter (pt); - waitWindow->move (rect.topLeft()); - + waitWindow->move (rect.topLeft ()); } - waitWindow->show(); + waitWindow->show (); qApp->processEvents (QEventLoop::ExcludeUserInputEvents); - waitWindow->repaint(); - } else { - waitWindow->close(); + waitWindow->repaint (); + } + else { + waitWindow->close (); } - qApp->processEvents(); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + qApp->processEvents (); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // see https://doc.qt.io/qt-5/qcoreapplication-obsolete.html#flush - QApplication::flush(); + QApplication::flush (); #else #endif wid->qwid->activateWindow (); send_keyboard_focus (wid); - // next time we do update the dialog will disappear - need_update(); + // next time we do update the dialog will disappear + need_update (); } -void (*the_interpose_handler) (void) = NULL; +void (*the_interpose_handler) (void)= NULL; -void gui_interpose (void (*r) (void)) { the_interpose_handler = r; } +void +gui_interpose (void (*r) (void)) { + the_interpose_handler= r; +} void qt_gui_rep::event_loop () { QCoreApplication* app; - if (headless_mode) - app = QCoreApplication::instance (); - else - app = QApplication::instance (); - update(); - //need_update(); - app->exec(); + if (headless_mode) app= QCoreApplication::instance (); + else app= QApplication::instance (); + update (); + // need_update(); + app->exec (); } - /****************************************************************************** * Main routines ******************************************************************************/ void gui_open (int& argc, char** argv) { - // start the gui - // new QApplication (argc,argv); now in texmacs.cpp - the_gui = tm_new (argc, argv); - + // start the gui + // new QApplication (argc,argv); now in texmacs.cpp + the_gui= tm_new (argc, argv); + #ifdef MACOSX_EXTENSIONS - mac_begin_remote(); + mac_begin_remote (); #endif // Qt and Guile want to change the locale. @@ -544,37 +546,37 @@ gui_open (int& argc, char** argv) { void gui_start_loop () { - // start the main loop + // start the main loop the_gui->event_loop (); } void gui_close () { - // cleanly close the gui + // cleanly close the gui ASSERT (the_gui != NULL, "gui not yet open"); tm_delete (the_gui); - the_gui = NULL; - + the_gui= NULL; + #ifdef MACOSX_EXTENSIONS - mac_end_remote(); + mac_end_remote (); #endif } void gui_root_extents (SI& width, SI& height) { - // get the screen size + // get the screen size the_gui->get_extents (width, height); } void gui_maximal_extents (SI& width, SI& height) { - // get the maximal size of a window (can be larger than the screen size) + // get the maximal size of a window (can be larger than the screen size) the_gui->get_max_size (width, height); } void gui_refresh () { - the_gui->refresh_language(); + the_gui->refresh_language (); } string @@ -609,119 +611,104 @@ static int keyboard_special= 0; void qt_gui_rep::process_queued_events (int max) { - int count = 0; - while (max < 0 || count < max) { - const queued_event& ev = waiting_events.next(); + int count= 0; + while (max < 0 || count < max) { + const queued_event& ev= waiting_events.next (); if (ev.x1 == qp_type::QP_NULL) break; #ifdef QT_CPU_FIX - if (ev.x1 != qp_type::QP_NULL && - ev.x1 != qp_type::QP_SOCKET_NOTIFICATION && + if (ev.x1 != qp_type::QP_NULL && ev.x1 != qp_type::QP_SOCKET_NOTIFICATION && ev.x1 != qp_type::QP_DELAYED_COMMANDS) tm_wake_up (); #endif switch (ev.x1) { - case qp_type::QP_NULL : - break; - case qp_type::QP_KEYPRESS : - { - typedef triple T; - T x = open_box (ev.x2); - if (!is_nil (x.x1)) { - concrete_simple_widget (x.x1)->handle_keypress (x.x2, x.x3); - keyboard_events++; - if (N(x.x2) > 1) keyboard_special++; - } - } - break; - case qp_type::QP_KEYBOARD_FOCUS : - { - typedef triple T; - T x = open_box (ev.x2); - if (!is_nil (x.x1)) - concrete_simple_widget (x.x1)->handle_keyboard_focus (x.x2, x.x3); + case qp_type::QP_NULL: + break; + case qp_type::QP_KEYPRESS: { + typedef triple T; + T x= open_box (ev.x2); + if (!is_nil (x.x1)) { + concrete_simple_widget (x.x1)->handle_keypress (x.x2, x.x3); + keyboard_events++; + if (N (x.x2) > 1) keyboard_special++; } - break; - case qp_type::QP_MOUSE : - { - typedef sextuple > T1; - typedef pair T; - T x = open_box (ev.x2); - if (!is_nil (x.x1)) - concrete_simple_widget (x.x1)->handle_mouse (x.x2.x1, x.x2.x2, - x.x2.x3, x.x2.x4, - x.x2.x5, x.x2.x6); - } - break; - case qp_type::QP_RESIZE : - { - typedef triple T; - T x = open_box (ev.x2); - if (!is_nil (x.x1)) - concrete_simple_widget (x.x1)->handle_notify_resize (x.x2, x.x3) ; - } - break; - case qp_type::QP_COMMAND : - { - command cmd = open_box (ev.x2) ; - cmd->apply(); - } - break; - case qp_type::QP_COMMAND_ARGS : - { - typedef pair T; - T x = open_box (ev.x2); - x.x1->apply (x.x2); - } - break; - case qp_type::QP_DELAYED_COMMANDS : - { - delayed_commands.exec_pending(); - } - break; - - default: - TM_FAILED ("Unexpected queued event"); + } break; + case qp_type::QP_KEYBOARD_FOCUS: { + typedef triple T; + T x= open_box (ev.x2); + if (!is_nil (x.x1)) + concrete_simple_widget (x.x1)->handle_keyboard_focus (x.x2, x.x3); + } break; + case qp_type::QP_MOUSE: { + typedef sextuple> T1; + typedef pair T; + T x= open_box (ev.x2); + if (!is_nil (x.x1)) + concrete_simple_widget (x.x1)->handle_mouse (x.x2.x1, x.x2.x2, x.x2.x3, + x.x2.x4, x.x2.x5, x.x2.x6); + } break; + case qp_type::QP_RESIZE: { + typedef triple T; + T x= open_box (ev.x2); + if (!is_nil (x.x1)) + concrete_simple_widget (x.x1)->handle_notify_resize (x.x2, x.x3); + } break; + case qp_type::QP_COMMAND: { + command cmd= open_box (ev.x2); + cmd->apply (); + } break; + case qp_type::QP_COMMAND_ARGS: { + typedef pair T; + T x= open_box (ev.x2); + x.x1->apply (x.x2); + } break; + case qp_type::QP_DELAYED_COMMANDS: { + delayed_commands.exec_pending (); + } break; + + default: + TM_FAILED ("Unexpected queued event"); } switch (ev.x1) { - case qp_type::QP_COMMAND: - case qp_type::QP_COMMAND_ARGS: - case qp_type::QP_RESIZE: - case qp_type::QP_DELAYED_COMMANDS: - break; - default: - count++; - break; + case qp_type::QP_COMMAND: + case qp_type::QP_COMMAND_ARGS: + case qp_type::QP_RESIZE: + case qp_type::QP_DELAYED_COMMANDS: + break; + default: + count++; + break; } } } void -qt_gui_rep::process_keypress (qt_simple_widget_rep *wid, string key, time_t t) { - typedef triple T; - add_event (queued_event (qp_type::QP_KEYPRESS, - close_box (T (wid, key, t)))); +qt_gui_rep::process_keypress (qt_simple_widget_rep* wid, string key, time_t t) { + typedef triple T; + add_event ( + queued_event (qp_type::QP_KEYPRESS, close_box (T (wid, key, t)))); } void -qt_gui_rep::process_keyboard_focus (qt_simple_widget_rep *wid, bool has_focus, - time_t t ) { - typedef triple T; +qt_gui_rep::process_keyboard_focus (qt_simple_widget_rep* wid, bool has_focus, + time_t t) { + typedef triple T; add_event (queued_event (qp_type::QP_KEYBOARD_FOCUS, close_box (T (wid, has_focus, t)))); } void -qt_gui_rep::process_mouse (qt_simple_widget_rep *wid, string kind, SI x, SI y, +qt_gui_rep::process_mouse (qt_simple_widget_rep* wid, string kind, SI x, SI y, int mods, time_t t, array data) { - typedef sextuple > T1; - typedef pair T; - add_event (queued_event (qp_type::QP_MOUSE, - close_box (T (wid, T1 (kind, x, y, mods, t, data))))); + typedef sextuple> T1; + typedef pair T; + add_event ( + queued_event (qp_type::QP_MOUSE, + close_box (T (wid, T1 (kind, x, y, mods, t, data))))); } void -qt_gui_rep::process_resize (qt_simple_widget_rep *wid, SI x, SI y ) { - typedef triple T; +qt_gui_rep::process_resize (qt_simple_widget_rep* wid, SI x, SI y) { + typedef triple T; add_event (queued_event (qp_type::QP_RESIZE, close_box (T (wid, x, y)))); } @@ -732,14 +719,14 @@ qt_gui_rep::process_command (command _cmd) { void qt_gui_rep::process_command (command _cmd, object _args) { - typedef pair T; - add_event (queued_event (qp_type::QP_COMMAND_ARGS, - close_box (T (_cmd,_args)))); + typedef pair T; + add_event ( + queued_event (qp_type::QP_COMMAND_ARGS, close_box (T (_cmd, _args)))); } void qt_gui_rep::process_delayed_commands () { - add_event (queued_event (qp_type::QP_DELAYED_COMMANDS, blackbox())); + add_event (queued_event (qp_type::QP_DELAYED_COMMANDS, blackbox ())); } /*! @@ -747,48 +734,48 @@ qt_gui_rep::process_delayed_commands () { */ bool qt_gui_rep::check_event (int type) { - // do not interrupt if not updating (e.g. while painting the icons in menus) + // do not interrupt if not updating (e.g. while painting the icons in menus) if (!updating || !do_check_events) return false; - + switch (type) { - case INTERRUPT_EVENT: - if (interrupted) return true; - else { - time_t now = texmacs_time (); - if (now - timeout_time < 0) return false; - timeout_time = now + time_credit; - interrupted = !waiting_events.is_empty(); - return interrupted; - } - case INTERRUPTED_EVENT: + case INTERRUPT_EVENT: + if (interrupted) return true; + else { + time_t now= texmacs_time (); + if (now - timeout_time < 0) return false; + timeout_time= now + time_credit; + interrupted = !waiting_events.is_empty (); return interrupted; - default: - return false; + } + case INTERRUPTED_EVENT: + return interrupted; + default: + return false; } } void qt_gui_rep::set_check_events (bool enable_check) { - do_check_events = enable_check; + do_check_events= enable_check; } void qt_gui_rep::add_event (const queued_event& ev) { waiting_events.append (ev); if (updating) { - needing_update = true; - } else { - need_update(); - // NOTE: we cannot update now since sometimes this seems to give problems - // to the update of the window size after a resize. In that situation - // sometimes when the window receives focus again, update will be called - // for the focus_in event and interpose_handler is run which sends a - // slot_extent message to the widget causing a wrong resize of the window. - // This seems to cure the problem. + needing_update= true; + } + else { + need_update (); + // NOTE: we cannot update now since sometimes this seems to give problems + // to the update of the window size after a resize. In that situation + // sometimes when the window receives focus again, update will be called + // for the focus_in event and interpose_handler is run which sends a + // slot_extent message to the widget causing a wrong resize of the window. + // This seems to cure the problem. } } - /*! This is called by doUpdate(), which in turn is fired by a timer activated in needs_update(), and ensuring that interpose_handler() is run during a pass in @@ -806,123 +793,124 @@ qt_gui_rep::update () { if (updating) { cout << "NESTED UPDATING: This should not happen" << LF; - need_update(); + need_update (); return; } - - // cout << "<" << texmacs_time() << " " << N(delayed_queue) << " "; - - updatetimer->stop(); - updating = true; - - static int count_events = 0; - static int max_proc_events = 40; - - time_t now = texmacs_time(); - needing_update = false; - time_credit = 9 / (waiting_events.size() + 1); - - // 1. - // Check if a wait dialog is active and in that case remove it. - // If we are here then the long operation has finished. - - if (waitDialogs.count()) { - waitWindow->layout()->removeWidget (waitDialogs.last()); - waitWindow->close(); - while (waitDialogs.count()) { - waitDialogs.last()->deleteLater(); - waitDialogs.removeLast(); + + // cout << "<" << texmacs_time() << " " << N(delayed_queue) << " "; + + updatetimer->stop (); + updating= true; + + static int count_events = 0; + static int max_proc_events= 40; + + time_t now = texmacs_time (); + needing_update= false; + time_credit = 9 / (waiting_events.size () + 1); + + // 1. + // Check if a wait dialog is active and in that case remove it. + // If we are here then the long operation has finished. + + if (waitDialogs.count ()) { + waitWindow->layout ()->removeWidget (waitDialogs.last ()); + waitWindow->close (); + while (waitDialogs.count ()) { + waitDialogs.last ()->deleteLater (); + waitDialogs.removeLast (); } } - + if (popup_wid_time > 0 && now > popup_wid_time) { - popup_wid_time = 0; + popup_wid_time= 0; _popup_wid->send (SLOT_VISIBILITY, close_box (true)); } - - // 2. - // Manage delayed commands - - if (delayed_commands.must_wait (now)) - process_delayed_commands(); - - // 3. - // If there are pending events in the private queue process them until the - // limit in processed events is reached. - // If there are no events or the limit is reached then proceed to a redraw. - - if (waiting_events.size() == 0) { - // If there are no waiting events call the interpose handler at least once - //if (the_interpose_handler) the_interpose_handler(); - } - else while (waiting_events.size() > 0 && count_events < max_proc_events) { - process_queued_events (1); - count_events++; - //if (the_interpose_handler) the_interpose_handler(); + + // 2. + // Manage delayed commands + + if (delayed_commands.must_wait (now)) process_delayed_commands (); + + // 3. + // If there are pending events in the private queue process them until the + // limit in processed events is reached. + // If there are no events or the limit is reached then proceed to a redraw. + + if (waiting_events.size () == 0) { + // If there are no waiting events call the interpose handler at least once + // if (the_interpose_handler) the_interpose_handler(); } + else + while (waiting_events.size () > 0 && count_events < max_proc_events) { + process_queued_events (1); + count_events++; + // if (the_interpose_handler) the_interpose_handler(); + } // Repaint invalid regions and redraw bool postpone_treatment= (keyboard_events > 0 && keyboard_special == 0); - keyboard_events = 0; - keyboard_special= 0; - count_events = 0; - - interrupted = false; - timeout_time = texmacs_time() + time_credit; + keyboard_events = 0; + keyboard_special = 0; + count_events = 0; + + interrupted = false; + timeout_time= texmacs_time () + time_credit; if (!postpone_treatment) { - if (the_interpose_handler) the_interpose_handler(); + if (the_interpose_handler) the_interpose_handler (); qt_simple_widget_rep::repaint_all (); } - - if (waiting_events.size() > 0) needing_update = true; - if (interrupted) needing_update = true; - if (!headless_mode && nr_windows == 0) qApp->quit(); - - time_t delay = delayed_commands.lapse - texmacs_time(); - if (needing_update) delay = 0; - else delay = max (0, min (std_delay, static_cast(delay))); + + if (waiting_events.size () > 0) needing_update= true; + if (interrupted) needing_update= true; + if (!headless_mode && nr_windows == 0) qApp->quit (); + + time_t delay= delayed_commands.lapse - texmacs_time (); + if (needing_update) delay= 0; + else delay= max (0, min (std_delay, static_cast (delay))); if (postpone_treatment) delay= 9; // NOTE: force occasional display - + updatetimer->start (delay); - updating = false; - - // FIXME: we need to ensure that the interpose_handler is run at regular - // intervals (1/6th of sec) so that informations on the footbar are - // updated. (this should be better handled by promoting code in - // tm_editor::apply_changes (which is activated only after idle - // periods) at the level of delayed commands in the gui. - // The interval cannot be too small to keep CPU usage low in idle state + updating= false; + + // FIXME: we need to ensure that the interpose_handler is run at regular + // intervals (1/6th of sec) so that informations on the footbar are + // updated. (this should be better handled by promoting code in + // tm_editor::apply_changes (which is activated only after idle + // periods) at the level of delayed commands in the gui. + // The interval cannot be too small to keep CPU usage low in idle state } void -qt_gui_rep::force_update() { - if (updating) needing_update = true; - else update(); +qt_gui_rep::force_update () { + if (updating) needing_update= true; + else update (); } void qt_gui_rep::need_update () { - if (updating) needing_update = true; - else updatetimer->start (0); - // 0 ms - call immediately when all other events have been processed + if (updating) needing_update= true; + else updatetimer->start (0); + // 0 ms - call immediately when all other events have been processed } -void needs_update () { - the_gui->need_update(); +void +needs_update () { + the_gui->need_update (); } /*! Called upon change of output language. - + We currently emit a signal which forces every QTMAction to change his text according to the new language, but the preferred Qt way seems to use LanguageChange events (these are triggered upon installation of QTranslators) */ void -qt_gui_rep::refresh_language() { +qt_gui_rep::refresh_language () { /* FIXME: why is this here? We don't use QTranslators... QTranslator* qtr = new QTranslator(); if (qtr->load ("qt_" + - QLocale (to_qstring + QLocale (to_qstring (language_to_locale (get_output_language()))).name(), QLibraryInfo::location (QLibraryInfo::TranslationsPath))) { if (q_translator) @@ -933,11 +921,11 @@ qt_gui_rep::refresh_language() { delete qtr; } */ - gui_helper->doRefresh(); + gui_helper->doRefresh (); } /*! Display a popup help balloon (i.e. a tooltip) at window coordinates x, y - + We use a dedicated wrapper QWidget which handles mouse events: as soon as the mouse is moved out of we hide it. Problem: the widget need not appear below the mouse pointer, thus making it @@ -949,19 +937,18 @@ qt_gui_rep::refresh_language() { void qt_gui_rep::show_help_balloon (widget wid, SI x, SI y) { if (popup_wid_time > 0) return; - - _popup_wid = popup_window_widget (wid, "Balloon"); + + _popup_wid= popup_window_widget (wid, "Balloon"); SI winx, winy; // HACK around wrong? reporting of window widget for embedded texmacs-inputs: // call get_window on the current window (concrete_window()->win is set to // the texmacs-input widget whenever there is one) - get_position (get_window (concrete_window()->win), winx, winy); - set_position (_popup_wid, x+winx, y+winy); - popup_wid_time = texmacs_time() + 66; - // update() will eventually show the widget + get_position (get_window (concrete_window ()->win), winx, winy); + set_position (_popup_wid, x + winx, y + winy); + popup_wid_time= texmacs_time () + 66; + // update() will eventually show the widget } - /****************************************************************************** * Font support ******************************************************************************/ @@ -979,126 +966,132 @@ set_default_font (string name) { */ font get_default_font (bool tt, bool mini, bool bold) { - (void) tt; (void) mini; (void) bold; + (void) tt; + (void) mini; + (void) bold; if (DEBUG_QT) debug_qt << "get_default_font(): SHOULD NOT BE CALLED\n"; - return NULL; //return tex_font (this, "ecrm", 10, 300, 0); + return NULL; // return tex_font (this, "ecrm", 10, 300, 0); } /*! Loads the metric and glyphs of a system font. You are not forced to provide any system fonts. */ void -load_system_font (string fam, int sz, int dpi, font_metric& fnm, font_glyphs& fng) -{ - (void) fam; (void) sz; (void) dpi; (void) fnm; (void) fng; +load_system_font (string fam, int sz, int dpi, font_metric& fnm, + font_glyphs& fng) { + (void) fam; + (void) sz; + (void) dpi; + (void) fnm; + (void) fng; if (DEBUG_QT) debug_qt << "load_system_font(): SHOULD NOT BE CALLED\n"; } - /****************************************************************************** * Clipboard support ******************************************************************************/ bool -set_selection (string key, tree t, - string s, string sv, string sh, string format) { - // Copy a selection 't' with string equivalent 's' to the clipboard 'cb' - // and possibly the variants 'sv' and 'sh' for verbatim and html - // Returns true on success +set_selection (string key, tree t, string s, string sv, string sh, + string format) { + // Copy a selection 't' with string equivalent 's' to the clipboard 'cb' + // and possibly the variants 'sv' and 'sh' for verbatim and html + // Returns true on success return the_gui->set_selection (key, t, s, sv, sh, format); } bool get_selection (string key, tree& t, string& s, string format) { - // Retrieve the selection 't' with string equivalent 's' from clipboard 'cb' - // Returns true on success; sets t to (extern s) for external selections + // Retrieve the selection 't' with string equivalent 's' from clipboard 'cb' + // Returns true on success; sets t to (extern s) for external selections return the_gui->get_selection (key, t, s, format); } void clear_selection (string key) { - // Clear the selection on clipboard 'cb' + // Clear the selection on clipboard 'cb' the_gui->clear_selection (key); } bool qt_gui_rep::put_graphics_on_clipboard (url file) { - string extension = suffix (file) ; - - // for bitmaps this works : - if ((extension == "bmp") || (extension == "png") || - (extension == "jpg") || (extension == "jpeg")) { - QClipboard *clipboard = QApplication::clipboard(); - c_string tmp (concretize (file)); + string extension= suffix (file); + + // for bitmaps this works : + if ((extension == "bmp") || (extension == "png") || (extension == "jpg") || + (extension == "jpeg")) { + QClipboard* clipboard= QApplication::clipboard (); + c_string tmp (concretize (file)); clipboard->setImage (QImage (QString (tmp))); } else { - // vector formats - // Are there applications receiving eps, pdf,... through the clipboard? - // I have not experimented with EMF/WMF (windows) or SVM (Ooo) - QString mime ="image/*"; // generic image format; - if (extension == "eps") mime = "application/postscript"; - if (extension == "pdf") mime = "application/pdf"; - if (extension == "svg") mime = "image/svg+xml"; //this works with Inskcape version >= 0.47 - + // vector formats + // Are there applications receiving eps, pdf,... through the clipboard? + // I have not experimented with EMF/WMF (windows) or SVM (Ooo) + QString mime= "image/*"; // generic image format; + if (extension == "eps") mime= "application/postscript"; + if (extension == "pdf") mime= "application/pdf"; + if (extension == "svg") + mime= "image/svg+xml"; // this works with Inskcape version >= 0.47 + string filecontent; load_string (file, filecontent, true); - + // warning: we need to tell Qt the size of the byte buffer - c_string tmp (filecontent); - QByteArray rawdata (tmp, N(filecontent)); + c_string tmp (filecontent); + QByteArray rawdata (tmp, N (filecontent)); - QMimeData *mymimeData = new QMimeData; + QMimeData* mymimeData= new QMimeData; mymimeData->setData (mime, rawdata); - - QClipboard *clipboard = QApplication::clipboard(); - clipboard->setMimeData (mymimeData);// default mode = QClipboard::Clipboard + + QClipboard* clipboard= QApplication::clipboard (); + clipboard->setMimeData (mymimeData); // default mode = QClipboard::Clipboard } return true; } /****************************************************************************** -* Miscellaneous -******************************************************************************/ + * Miscellaneous + ******************************************************************************/ -bool char_clip = false; +bool char_clip= false; void beep () { - // Issue a beep - QApplication::beep(); + // Issue a beep + QApplication::beep (); } bool check_event (int type) { - // Check whether an event of one of the above types has occurred; - // we check for keyboard events while repainting windows + // Check whether an event of one of the above types has occurred; + // we check for keyboard events while repainting windows return the_gui->check_event (type); } void show_help_balloon (widget balloon, SI x, SI y) { - // Display a help balloon at position (x, y); the help balloon should - // disappear as soon as the user presses a key or moves the mouse + // Display a help balloon at position (x, y); the help balloon should + // disappear as soon as the user presses a key or moves the mouse the_gui->show_help_balloon (balloon, x, y); } void show_wait_indicator (widget base, string message, string argument) { - // Display a wait indicator with a message and an optional argument - // The indicator might for instance be displayed at the center of - // the base widget which triggered the lengthy operation; - // the indicator should be removed if the message is empty + // Display a wait indicator with a message and an optional argument + // The indicator might for instance be displayed at the center of + // the base widget which triggered the lengthy operation; + // the indicator should be removed if the message is empty the_gui->show_wait_indicator (base, message, argument); } void external_event (string type, time_t t) { - // External events, such as pushing a button of a remote infrared commander - QTMWidget *tm_focus = qobject_cast(qApp->focusWidget()); + // External events, such as pushing a button of a remote infrared commander + QTMWidget* tm_focus= qobject_cast (qApp->focusWidget ()); if (tm_focus) { - simple_widget_rep* wid = tm_focus->tm_widget(); - if (wid) the_gui -> process_keypress (wid, type, t); + simple_widget_rep* wid= tm_focus->tm_widget (); + if (wid) the_gui->process_keypress (wid, type, t); } } @@ -1106,15 +1099,15 @@ external_event (string type, time_t t) { * Delayed commands ******************************************************************************/ -command_queue::command_queue() : lapse (0), wait (true) { } -command_queue::~command_queue() { clear_pending(); /* implicit */ } +command_queue::command_queue () : lapse (0), wait (true) {} +command_queue::~command_queue () { clear_pending (); /* implicit */ } void command_queue::exec (object cmd) { q << cmd; start_times << (((time_t) texmacs_time ()) - 1000000000); - lapse = texmacs_time(); - the_gui->need_update(); + lapse= texmacs_time (); + the_gui->need_update (); wait= true; } @@ -1122,25 +1115,25 @@ void command_queue::exec_pause (object cmd) { q << cmd; start_times << ((time_t) texmacs_time ()); - lapse = texmacs_time(); - the_gui->need_update(); + lapse= texmacs_time (); + the_gui->need_update (); wait= true; } void command_queue::exec_pending () { - array a = q; - array b = start_times; - q = array (0); - start_times = array (0); - int i, n = N(a); - for (i = 0; i a= q; + array b= start_times; + q = array (0); + start_times = array (0); + int i, n= N (a); + for (i= 0; i < n; i++) { + time_t now= texmacs_time (); if ((now - b[i]) >= 0) { - object obj = call (a[i]); + object obj= call (a[i]); if (is_int (obj) && (now - b[i] < 1000000000)) { - time_t pause = as_int (obj); - //cout << "pause = " << obj << "\n"; + time_t pause= as_int (obj); + // cout << "pause = " << obj << "\n"; q << a[i]; start_times << (now + pause); } @@ -1150,22 +1143,22 @@ command_queue::exec_pending () { start_times << b[i]; } } - if (N(q) > 0) { - wait = true; // wait_for_delayed_commands - lapse = start_times[0]; - int n = N(start_times); - for (i = 1; i start_times[i]) lapse = start_times[i]; + if (N (q) > 0) { + wait = true; // wait_for_delayed_commands + lapse= start_times[0]; + int n= N (start_times); + for (i= 1; i < n; i++) { + if (lapse > start_times[i]) lapse= start_times[i]; } - } else - wait = false; + } + else wait= false; } void command_queue::clear_pending () { - q = array (0); - start_times = array (0); - wait = false; + q = array (0); + start_times= array (0); + wait = false; } bool @@ -1173,27 +1166,28 @@ command_queue::must_wait (time_t now) const { return wait && (lapse <= now); } - /****************************************************************************** * Delayed commands interface ******************************************************************************/ -void exec_delayed (object cmd) { - the_gui->delayed_commands.exec(cmd); +void +exec_delayed (object cmd) { + the_gui->delayed_commands.exec (cmd); } -void exec_delayed_pause (object cmd) { - the_gui->delayed_commands.exec_pause(cmd); +void +exec_delayed_pause (object cmd) { + the_gui->delayed_commands.exec_pause (cmd); } -void clear_pending_commands () { - the_gui->delayed_commands.clear_pending(); +void +clear_pending_commands () { + the_gui->delayed_commands.clear_pending (); } - /****************************************************************************** * Queued events ******************************************************************************/ -event_queue::event_queue() : n(0) { } +event_queue::event_queue () : n (0) {} void event_queue::append (const queued_event& ev) { @@ -1203,21 +1197,20 @@ event_queue::append (const queued_event& ev) { queued_event event_queue::next () { - if (is_nil(q)) - return queued_event(); - queued_event ev = q->item; - q = q->next; + if (is_nil (q)) return queued_event (); + queued_event ev= q->item; + q = q->next; --n; return ev; } bool -event_queue::is_empty() const { - ASSERT (!(n!=0 && is_nil(q)), "WTF?"); +event_queue::is_empty () const { + ASSERT (!(n != 0 && is_nil (q)), "WTF?"); return n == 0; } int -event_queue::size() const { +event_queue::size () const { return n; } diff --git a/src/Plugins/Qt/qt_gui.hpp b/src/Plugins/Qt/qt_gui.hpp index 27b5f24ad1..7ff9a4e247 100644 --- a/src/Plugins/Qt/qt_gui.hpp +++ b/src/Plugins/Qt/qt_gui.hpp @@ -1,30 +1,30 @@ /****************************************************************************** -* MODULE : qt_gui.hpp -* DESCRIPTION: QT GUI class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_gui.hpp + * DESCRIPTION: QT GUI class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_GUI_HPP #define QT_GUI_HPP -#include -#include #include #include +#include +#include -#include "qt_simple_widget.hpp" -#include "tm_timer.hpp" -#include "gui.hpp" -#include "font.hpp" -#include "widget.hpp" #include "array.hpp" +#include "font.hpp" +#include "gui.hpp" #include "hashmap.hpp" +#include "qt_simple_widget.hpp" #include "socket_notifier.hpp" +#include "tm_timer.hpp" +#include "widget.hpp" #if defined(OS_MACOS) && defined(CocoaPlugin) #ifndef QT_MAC_USE_COCOA @@ -33,7 +33,7 @@ #endif typedef class qt_gui_rep* qt_gui; -extern qt_gui the_gui; +extern qt_gui the_gui; /****************************************************************************** * Event queue @@ -42,47 +42,56 @@ extern qt_gui the_gui; class qp_type { public: enum id_t { - QP_NULL, QP_KEYPRESS, QP_KEYBOARD_FOCUS, - QP_MOUSE, QP_RESIZE, QP_SOCKET_NOTIFICATION, - QP_COMMAND, QP_COMMAND_ARGS, QP_DELAYED_COMMANDS }; + QP_NULL, + QP_KEYPRESS, + QP_KEYBOARD_FOCUS, + QP_MOUSE, + QP_RESIZE, + QP_SOCKET_NOTIFICATION, + QP_COMMAND, + QP_COMMAND_ARGS, + QP_DELAYED_COMMANDS + }; id_t sid; - inline qp_type (id_t sid2 = QP_NULL): sid (sid2) {} - inline qp_type (const qp_type& s): sid (s.sid) {} - inline qp_type& operator = (qp_type s) { sid = s.sid; return *this; } + inline qp_type (id_t sid2= QP_NULL) : sid (sid2) {} + inline qp_type (const qp_type& s) : sid (s.sid) {} + inline qp_type& operator= (qp_type s) { + sid= s.sid; + return *this; + } inline operator id_t () const { return sid; } - inline bool operator == (id_t sid2) { return sid == sid2; } - inline bool operator != (id_t sid2) { return sid != sid2; } - inline bool operator == (qp_type s) { return sid == s.sid; } - inline bool operator != (qp_type s) { return sid != s.sid; } - inline friend tm_ostream& operator << (tm_ostream& out, qp_type s) - { return out << s.sid; } + inline bool operator== (id_t sid2) { return sid == sid2; } + inline bool operator!= (id_t sid2) { return sid != sid2; } + inline bool operator== (qp_type s) { return sid == s.sid; } + inline bool operator!= (qp_type s) { return sid != s.sid; } + inline friend tm_ostream& operator<< (tm_ostream& out, qp_type s) { + return out << s.sid; + } }; -class queued_event : public pair -{ +class queued_event : public pair { public: - queued_event (qp_type _type = qp_type(), blackbox _bb = blackbox()) - : pair(_type, _bb) { } + queued_event (qp_type _type= qp_type (), blackbox _bb= blackbox ()) + : pair (_type, _bb) {} }; /*! */ class event_queue { list q; - event_queue (const event_queue& q2); // = delete; + event_queue (const event_queue& q2); // = delete; event_queue& operator= (const event_queue& q2); // = delete; - - unsigned int n; // ugly internal counter to avoid traversal of list in N(q) + + unsigned int n; // ugly internal counter to avoid traversal of list in N(q) public: - event_queue(); - - void append (const queued_event& ev); + event_queue (); + + void append (const queued_event& ev); queued_event next (); - bool is_empty() const; - int size() const; + bool is_empty () const; + int size () const; }; - /****************************************************************************** * Delayed commands ******************************************************************************/ @@ -92,63 +101,62 @@ class event_queue { class command_queue { array q; array start_times; - time_t lapse; - + time_t lapse; + bool wait; - // this flag is used in update() to insert QP_DELAYED_COMMANDS events in - // the TeXmacs event queue to have delayed command handling properly - // interspersed with the other events + // this flag is used in update() to insert QP_DELAYED_COMMANDS events in + // the TeXmacs event queue to have delayed command handling properly + // interspersed with the other events public: - command_queue(); - ~command_queue(); + command_queue (); + ~command_queue (); void exec (object cmd); void exec_pause (object cmd); void exec_pending (); void clear_pending (); bool must_wait (time_t now) const; - + friend class qt_gui_rep; }; - /****************************************************************************** -* The qt_gui class -******************************************************************************/ + * The qt_gui class + ******************************************************************************/ class QTMGuiHelper; class qt_gui_rep { bool interrupted; - time_t interrupt_time; + time_t interrupt_time; QTimer* updatetimer; QList waitDialogs; - QWidget* waitWindow; - widget _popup_wid; - time_t popup_wid_time; //!< 0 means not to show _popup_wid - - hashmap selection_t; - hashmap selection_s; - + QWidget* waitWindow; + widget _popup_wid; + time_t popup_wid_time; //!< 0 means not to show _popup_wid + + hashmap selection_t; + hashmap selection_s; + QTranslator* q_translator; - - time_t time_credit; // interval to interrupt long redrawings - time_t timeout_time; // new redraw interruption - - // marshalling flags between update, needs_update and check_event. + + time_t time_credit; // interval to interrupt long redrawings + time_t timeout_time; // new redraw interruption + + // marshalling flags between update, needs_update and check_event. bool do_check_events; - bool updating; - bool needing_update; + bool updating; + bool needing_update; - event_queue waiting_events; + event_queue waiting_events; command_queue delayed_commands; public: - QTMGuiHelper* gui_helper; + QTMGuiHelper* gui_helper; public: - qt_gui_rep (int &argc, char **argv); + qt_gui_rep (int& argc, char** argv); virtual ~qt_gui_rep (); /* extents, grabbing, selections */ @@ -164,7 +172,7 @@ class qt_gui_rep { virtual bool set_selection (string key, tree t, string s, string sv, string sh, string format); virtual void clear_selection (string key); - bool put_graphics_on_clipboard (url file); + bool put_graphics_on_clipboard (url file); /* miscellaneous */ void show_wait_indicator (widget w, string message, string arg); @@ -173,23 +181,23 @@ class qt_gui_rep { bool check_event (int type); void set_check_events (bool enable_check); - void update(); - void force_update(); - void need_update(); - void refresh_language(); - + void update (); + void force_update (); + void need_update (); + void refresh_language (); + /* queued processing */ - void process_keypress (qt_simple_widget_rep *wid, string key, time_t t); - void process_keyboard_focus (qt_simple_widget_rep *wid, bool has_focus, + void process_keypress (qt_simple_widget_rep* wid, string key, time_t t); + void process_keyboard_focus (qt_simple_widget_rep* wid, bool has_focus, time_t t); - void process_mouse (qt_simple_widget_rep *wid, string kind, SI x, SI y, + void process_mouse (qt_simple_widget_rep* wid, string kind, SI x, SI y, int mods, time_t t, array d= array ()); - void process_resize (qt_simple_widget_rep *wid, SI x, SI y); + void process_resize (qt_simple_widget_rep* wid, SI x, SI y); void process_command (command _cmd); void process_command (command _cmd, object _args); - void process_delayed_commands (); - void process_queued_events (int max = -1); - + void process_delayed_commands (); + void process_queued_events (int max= -1); + /* befriended interface functions */ friend class QTMGuiHelper; friend void exec_delayed (object cmd); @@ -199,14 +207,13 @@ class qt_gui_rep { }; /*! Force an immediate update of the internal texmacs state. */ -void force_update(); - -#define BEGIN_SLOT \ - try { -#define END_SLOT \ - } \ - catch (string s) { \ - the_exception= s; \ +void force_update (); + +#define BEGIN_SLOT try { +#define END_SLOT \ + } \ + catch (string s) { \ + the_exception= s; \ } #endif // defined QT_GUI_HPP diff --git a/src/Plugins/Qt/qt_menu.cpp b/src/Plugins/Qt/qt_menu.cpp index 32f30cea15..c62f59625a 100644 --- a/src/Plugins/Qt/qt_menu.cpp +++ b/src/Plugins/Qt/qt_menu.cpp @@ -1,34 +1,31 @@ /****************************************************************************** -* MODULE : qt_menu.cpp -* DESCRIPTION: QT menu proxies -* COPYRIGHT : (C) 2007 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_menu.cpp + * DESCRIPTION: QT menu proxies + * COPYRIGHT : (C) 2007 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "qt_menu.hpp" +#include "QTMMenuHelper.hpp" #include "qt_utilities.hpp" #include "qt_window_widget.hpp" -#include "QTMMenuHelper.hpp" - qt_menu_rep::qt_menu_rep (qt_widget _content) - : qt_widget_rep (vertical_menu), qact (NULL), content (_content) { } + : qt_widget_rep (vertical_menu), qact (NULL), content (_content) {} /*! Destructor. Remember that qt_menu is the only parsed widget which by default owns its actions. */ -qt_menu_rep::~qt_menu_rep () { - delete qact; -} +qt_menu_rep::~qt_menu_rep () { delete qact; } QMenu* -qt_menu_rep::get_qmenu() { - if (!qact) qact = content->as_qaction(); - return qact->menu(); +qt_menu_rep::get_qmenu () { + if (!qact) qact= content->as_qaction (); + return qact->menu (); } /*! @@ -44,44 +41,38 @@ qt_menu_rep::make_popup_widget () { widget qt_menu_rep::popup_window_widget (string s) { (void) s; -// as_qaction()->menu()->setWindowTitle (to_qstring (s)); // totally useless + // as_qaction()->menu()->setWindowTitle (to_qstring (s)); // totally useless return this; } void qt_menu_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_POSITION: - { - check_type(val, s); - get_qmenu()->move (to_qpoint (open_box (val))); + case SLOT_POSITION: { + check_type (val, s); + get_qmenu ()->move (to_qpoint (open_box (val))); + } break; + case SLOT_VISIBILITY: { + check_type (val, s); + get_qmenu ()->setVisible (open_box (val)); + } break; + case SLOT_MOUSE_GRAB: { + check_type (val, s); + bool flag= open_box (val); // true= get grab, false= release grab +#if defined(OS_WASM) + if (flag) { + QMenu* qm= get_qmenu (); + qm->popup (qm->pos ()); } - break; - case SLOT_VISIBILITY: - { - check_type (val, s); - get_qmenu()->setVisible (open_box (val)); - } - break; - case SLOT_MOUSE_GRAB: - { - check_type (val, s); - bool flag = open_box (val); // true= get grab, false= release grab -#if defined (OS_WASM) - if (flag) { - QMenu* qm = get_qmenu(); - qm->popup(qm->pos()); - } #else - if (flag) get_qmenu()->exec(); + if (flag) get_qmenu ()->exec (); #endif - } - break; + } break; default: - qt_widget_rep::send(s, val); - return; + qt_widget_rep::send (s, val); + return; } if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_menu_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + debug_widgets << "qt_menu_rep: sent " << slot_name (s) << "\t\tto widget\t" + << type_as_string () << LF; } diff --git a/src/Plugins/Qt/qt_menu.hpp b/src/Plugins/Qt/qt_menu.hpp index 8fbdfe4f42..debc3bc376 100644 --- a/src/Plugins/Qt/qt_menu.hpp +++ b/src/Plugins/Qt/qt_menu.hpp @@ -1,58 +1,57 @@ /****************************************************************************** -* MODULE : qt_menu.hpp -* DESCRIPTION: QT menu proxies -* COPYRIGHT : (C) 2007 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_menu.hpp + * DESCRIPTION: QT menu proxies + * COPYRIGHT : (C) 2007 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_MENU_HPP #define QT_MENU_HPP #include "qt_widget.hpp" -#include #include - +#include /*! Implements a system standard contextual popup menu. @note This object is *not intended* to be used in toolbars, menu bars or windows. - + This widget owns no underlying QWidget but a QAction. When SLOT_VISIBILITY or SLOT_MOUSE_GRAB are sent, it show()s or exec()s the QMenu associated to the action. - + REMARK on memory management: - + Once a qt_menu_rep is created with some qt_widget as content, it owns all the QActions in the latter and is responsible for their deletion. Access to the QObject generating virtual functions is set to private to enforce this rule (notice that the overriden methods in the base class return empty values). - The hierarchy of a QMenu must have parents correctly set to the proper + The hierarchy of a QMenu must have parents correctly set to the proper supermenu, in order to guarantee that deletion of the root menu correctly deletes all of the tree below it. The root menu itself (without parent QObject) is owned by us as explained. This ensures correct memory management between TeXmacs and Qt since qt_menu_rep is sometimes cached at TeXmacs level. */ -class qt_menu_rep: public qt_widget_rep { - QAction* qact; +class qt_menu_rep : public qt_widget_rep { + QAction* qact; qt_widget content; public: qt_menu_rep (qt_widget content); - virtual ~qt_menu_rep(); + virtual ~qt_menu_rep (); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual widget make_popup_widget (); virtual widget popup_window_widget (string s); private: - QMenu* get_qmenu(); + QMenu* get_qmenu (); }; #endif // defined QT_MENU_HPP diff --git a/src/Plugins/Qt/qt_picture.cpp b/src/Plugins/Qt/qt_picture.cpp index e577b66d95..d2a4366839 100644 --- a/src/Plugins/Qt/qt_picture.cpp +++ b/src/Plugins/Qt/qt_picture.cpp @@ -1,49 +1,70 @@ - + /****************************************************************************** -* MODULE : qt_picture.cpp -* DESCRIPTION: QT pictures -* COPYRIGHT : (C) 2013 Massimiliano Gubinelli, Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_picture.cpp + * DESCRIPTION: QT pictures + * COPYRIGHT : (C) 2013 Massimiliano Gubinelli, Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "qt_picture.hpp" #include "analyze.hpp" -#include "image_files.hpp" -#include "qt_utilities.hpp" +#include "effect.hpp" #include "file.hpp" -#include "tm_file.hpp" -#include "image_files.hpp" -#include "scheme.hpp" #include "frame.hpp" -#include "effect.hpp" +#include "image_files.hpp" #include "iterator.hpp" #include "language.hpp" +#include "qt_utilities.hpp" +#include "scheme.hpp" +#include "tm_file.hpp" #include -#include -#include #include +#include #include #include +#include /****************************************************************************** -* Abstract Qt pictures -******************************************************************************/ + * Abstract Qt pictures + ******************************************************************************/ -qt_picture_rep::qt_picture_rep (const QImage& im, int ox2, int oy2): - pict (im), w (im.width ()), h (im.height ()), ox (ox2), oy (oy2) {} +qt_picture_rep::qt_picture_rep (const QImage& im, int ox2, int oy2) + : pict (im), w (im.width ()), h (im.height ()), ox (ox2), oy (oy2) {} -picture_kind qt_picture_rep::get_type () { return picture_native; } -void* qt_picture_rep::get_handle () { return (void*) this; } +picture_kind +qt_picture_rep::get_type () { + return picture_native; +} +void* +qt_picture_rep::get_handle () { + return (void*) this; +} -int qt_picture_rep::get_width () { return w; } -int qt_picture_rep::get_height () { return h; } -int qt_picture_rep::get_origin_x () { return ox; } -int qt_picture_rep::get_origin_y () { return oy; } -void qt_picture_rep::set_origin (int ox2, int oy2) { ox= ox2; oy= oy2; } +int +qt_picture_rep::get_width () { + return w; +} +int +qt_picture_rep::get_height () { + return h; +} +int +qt_picture_rep::get_origin_x () { + return ox; +} +int +qt_picture_rep::get_origin_y () { + return oy; +} +void +qt_picture_rep::set_origin (int ox2, int oy2) { + ox= ox2; + oy= oy2; +} color qt_picture_rep::internal_get_pixel (int x, int y) { @@ -55,18 +76,17 @@ qt_picture_rep::internal_set_pixel (int x, int y, color c) { pict.setPixel (x, h - 1 - y, c); } - picture qt_picture (const QImage& im, int ox, int oy) { - return (picture) tm_new (im, ox, oy); + return (picture) tm_new (im, ox, oy); } picture as_qt_picture (picture pic) { if (pic->get_type () == picture_native) return pic; - picture ret= qt_picture (QImage (pic->get_width (), pic->get_height (), - QImage::Format_ARGB32), - pic->get_origin_x (), pic->get_origin_y ()); + picture ret= qt_picture ( + QImage (pic->get_width (), pic->get_height (), QImage::Format_ARGB32), + pic->get_origin_x (), pic->get_origin_y ()); ret->copy_from (pic); return ret; } @@ -78,7 +98,7 @@ as_native_picture (picture pict) { QImage* xpm_image (url file_name) { - picture p= load_xpm (file_name); + picture p = load_xpm (file_name); qt_picture_rep* rep= (qt_picture_rep*) p->get_handle (); return &(rep->pict); } @@ -88,24 +108,28 @@ qt_load_icon (url file_name) { string base_name; if (ends (as_string (file_name), ".xpm")) { base_name= replace (as_string (file_name), ".xpm", ""); - } else { + } + else { base_name= as_string (file_name); } - url svg= resolve("$TEXMACS_PIXMAP_PATH" * url_system(base_name * ".svg")); - url png= resolve("$TEXMACS_PIXMAP_PATH" * url_system(base_name * ".png")); + url svg= resolve ("$TEXMACS_PIXMAP_PATH" * url_system (base_name * ".svg")); + url png= resolve ("$TEXMACS_PIXMAP_PATH" * url_system (base_name * ".png")); if (exists (png)) { return QIcon (as_pixmap (*xpm_image (file_name))); - } else if (exists (svg)) { + } + else if (exists (svg)) { #ifdef OS_MINGW return QIcon (qt_load_svg_icon (svg)); #else - if (occurs ("dark", tm_style_sheet)) { - return QIcon (qt_load_svg_icon (svg)); - } else { - return QIcon (to_qstring (as_string (svg))); - } + if (occurs ("dark", tm_style_sheet)) { + return QIcon (qt_load_svg_icon (svg)); + } + else { + return QIcon (to_qstring (as_string (svg))); + } #endif - } else { + } + else { return QIcon (as_pixmap (*xpm_image (file_name))); } } @@ -117,9 +141,9 @@ native_picture (int w, int h, int ox, int oy) { void qt_renderer_rep::draw_picture (picture p, SI x, SI y, int alpha) { - p= as_qt_picture (p); + p = as_qt_picture (p); qt_picture_rep* pict= (qt_picture_rep*) p->get_handle (); - int x0= pict->ox, y0= pict->h - 1 - pict->oy; + int x0= pict->ox, y0= pict->h - 1 - pict->oy; decode (x, y); qreal old_opacity= painter->opacity (); painter->setOpacity (qreal (alpha) / qreal (255)); @@ -128,15 +152,14 @@ qt_renderer_rep::draw_picture (picture p, SI x, SI y, int alpha) { } /****************************************************************************** -* Rendering on images -******************************************************************************/ + * Rendering on images + ******************************************************************************/ -qt_image_renderer_rep::qt_image_renderer_rep (picture p, double zoom): - qt_renderer_rep (new QPainter ()), pict (p) -{ +qt_image_renderer_rep::qt_image_renderer_rep (picture p, double zoom) + : qt_renderer_rep (new QPainter ()), pict (p) { zoomf = zoom; shrinkf= (int) tm_round (std_shrinkf / zoomf); - pixel = (SI) tm_round ((std_shrinkf * PIXEL) / zoomf); + pixel = (SI) tm_round ((std_shrinkf * PIXEL) / zoomf); thicken= (shrinkf >> 1) * PIXEL; int pw = p->get_width (); @@ -144,8 +167,8 @@ qt_image_renderer_rep::qt_image_renderer_rep (picture p, double zoom): int pox= p->get_origin_x (); int poy= p->get_origin_y (); - ox = pox * pixel; - oy = poy * pixel; + ox= pox * pixel; + oy= poy * pixel; /* cx1= 0; cy1= 0; @@ -158,15 +181,15 @@ qt_image_renderer_rep::qt_image_renderer_rep (picture p, double zoom): cy2= 0; qt_picture_rep* handle= (qt_picture_rep*) pict->get_handle (); - QImage& im (handle->pict); + QImage& im (handle->pict); im.fill (QColor (0, 0, 0, 0)); painter->begin (&im); } qt_image_renderer_rep::~qt_image_renderer_rep () { - painter->end(); + painter->end (); delete painter; - painter = NULL; + painter= NULL; } void @@ -185,8 +208,8 @@ picture_renderer (picture p, double zoomf) { } /****************************************************************************** -* Reverse video mode for icons -******************************************************************************/ + * Reverse video mode for icons + ******************************************************************************/ void reverse (int& r, int& g, int& b); @@ -195,10 +218,13 @@ max (const QImage& im, bool sum) { int r, g, b, a; int w= im.width (), h= im.height (); int m= 0; - for (int y=0; y= 128) { if (sum) m= max (m, (r + g + b) / 3); else m= max (m, max (r, max (g, b))); @@ -212,17 +238,20 @@ saturate (QImage& im) { int m= max (im, false); int s= max (im, true); if (m == 0 || s >= 224) return; - double f= min (224.0 / s, 255.0 / m); + double f= min (224.0 / s, 255.0 / m); quint16 r, g, b, a; - int w= im.width (), h= im.height (); - for (int y=0; y lans= get_supported_languages (); - for (int i=0; ifill (Qt::transparent); QPainter painter (pm); renderer.render (&painter); - } else if (qt_supports (u)) { + } + else if (qt_supports (u)) { pm= new QImage (utf8_to_qstring (concretize (u))); - } else { + } + else { url temp= url_temp (".png"); image_to_png (u, temp, w, h); pm= new QImage (utf8_to_qstring (as_string (temp))); @@ -277,9 +311,9 @@ get_image_for_real (url u, int w, int h, tree eff, SI pixel) { // Error Handling if (pm == NULL || pm->isNull ()) { - if (pm != NULL) delete pm; - cout << "TeXmacs] warning: cannot render " << concretize (u) << "\n"; - return NULL; + if (pm != NULL) delete pm; + cout << "TeXmacs] warning: cannot render " << concretize (u) << "\n"; + return NULL; } // Scaling @@ -288,21 +322,21 @@ get_image_for_real (url u, int w, int h, tree eff, SI pixel) { // Build effect if (eff != "") { - effect e= build_effect (eff); - picture src= qt_picture (*pm, 0, 0); + effect e = build_effect (eff); + picture src= qt_picture (*pm, 0, 0); array a; a << src; - picture pic= e->apply (a, pixel); - picture dest= as_qt_picture (pic); - qt_picture_rep* rep= (qt_picture_rep*) dest->get_handle (); - QImage *trf= (QImage*) &(rep->pict); + picture pic = e->apply (a, pixel); + picture dest= as_qt_picture (pic); + qt_picture_rep* rep = (qt_picture_rep*) dest->get_handle (); + QImage* trf = (QImage*) &(rep->pict); delete pm; pm= new QImage (trf->copy ()); } return pm; } -static hashmap qt_pic_cache; +static hashmap qt_pic_cache; QImage* get_image (url u, int w, int h, tree eff, SI pixel) { @@ -318,12 +352,12 @@ void qt_clean_picture_cache () { iterator it= iterate (qt_pic_cache); while (it->busy ()) { - tree key= it->next (); - QImage* im= qt_pic_cache [key]; + tree key= it->next (); + QImage* im = qt_pic_cache[key]; delete im; qt_pic_cache (key)= (QImage*) NULL; } - qt_pic_cache= hashmap (); + qt_pic_cache= hashmap (); } picture @@ -336,14 +370,18 @@ load_picture (url u, int w, int h, tree eff, int pixel) { picture new_qt_load_xpm (url file_name) { string sss; - double f= 1.0; + double f = 1.0; double scale= max (retina_scale, (double) retina_icons); if (suffix (file_name) == "xpm" || suffix (file_name) == "png") { string suf= ".png"; - if (scale == 1.0) {} + if (scale == 1.0) { + } else if (scale == 2.0) suf= "_x2.png"; else if (scale == 4.0) suf= "_x4.png"; - else { suf= "_x4.png"; f= scale / 4.0; } + else { + suf= "_x4.png"; + f = scale / 4.0; + } url png_equiv= glue (unglue (file_name, 4), suf); load_string ("$TEXMACS_PIXMAP_PATH" * png_equiv, sss, false); } @@ -356,15 +394,15 @@ new_qt_load_xpm (url file_name) { load_string ("$TEXMACS_PATH/misc/pixmaps/TeXmacs.xpm", sss, true); } c_string buf (sss); - QImage pm; - pm.loadFromData ((uchar*) (char*) buf, N(sss)); + QImage pm; + pm.loadFromData ((uchar*) (char*) buf, N (sss)); if (occurs ("dark", tm_style_sheet) && may_transform (file_name, pm)) { invert_colors (pm); saturate (pm); } pm= pm.scaled ((int) floor (f * pm.width () + 0.5), - (int) floor (f * pm.height () + 0.5), - Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + (int) floor (f * pm.height () + 0.5), Qt::IgnoreAspectRatio, + Qt::SmoothTransformation); return qt_picture (pm, 0, 0); } @@ -372,22 +410,25 @@ QPixmap qt_load_svg_icon (url file_name) { string sss; - string sizeX =basename (url_parent (url_parent(file_name))); - QSize size; + string sizeX= basename (url_parent (url_parent (file_name))); + QSize size; double scale= max (retina_scale, (double) retina_icons); if (sizeX == "16x16") { - size= QSize(int(16*scale), int(16*scale)); - } else if (sizeX == "20x20") { - size= QSize(int(20*scale), int(20*scale)); - } else if (sizeX == "24x24") { - size= QSize(int(24*scale), int(24*scale)); - } else { - TM_FAILED("not a icon"); + size= QSize (int (16 * scale), int (16 * scale)); + } + else if (sizeX == "20x20") { + size= QSize (int (20 * scale), int (20 * scale)); + } + else if (sizeX == "24x24") { + size= QSize (int (24 * scale), int (24 * scale)); + } + else { + TM_FAILED ("not a icon"); } - QSvgRenderer renderer (to_qstring(as_string (file_name))); - QImage *pm= NULL; - pm= new QImage (size.width(), size.height(), QImage::Format_ARGB32); + QSvgRenderer renderer (to_qstring (as_string (file_name))); + QImage* pm= NULL; + pm= new QImage (size.width (), size.height (), QImage::Format_ARGB32); pm->fill (Qt::transparent); QPainter painter (pm); renderer.render (&painter); @@ -414,35 +455,34 @@ qt_load_xpm (url file_name) { url png_equiv= glue (unglue (file_name, 3), "png"); load_string ("$TEXMACS_PIXMAP_PATH" * png_equiv, sss, false); } - if (sss == "") - load_string ("$TEXMACS_PIXMAP_PATH" * file_name, sss, false); + if (sss == "") load_string ("$TEXMACS_PIXMAP_PATH" * file_name, sss, false); if (sss == "") load_string ("$TEXMACS_PATH/misc/pixmaps/TeXmacs.xpm", sss, true); c_string buf (sss); - QImage pm; - pm.loadFromData ((uchar*) (char*) buf, N(sss)); + QImage pm; + pm.loadFromData ((uchar*) (char*) buf, N (sss)); return qt_picture (pm, 0, 0); } /****************************************************************************** -* Applying effects to existing pictures -******************************************************************************/ + * Applying effects to existing pictures + ******************************************************************************/ void qt_apply_effect (tree eff, array src, url dest, int w, int h) { array a; - for (int i=0; iapply (a, PIXEL); - picture q= as_qt_picture (t); + effect e = build_effect (eff); + picture t = e->apply (a, PIXEL); + picture q = as_qt_picture (t); qt_picture_rep* pict= (qt_picture_rep*) q->get_handle (); pict->pict.save (utf8_to_qstring (concretize (dest))); } void save_picture (url dest, picture p) { - picture q= as_qt_picture (p); + picture q = as_qt_picture (p); qt_picture_rep* pict= (qt_picture_rep*) q->get_handle (); if (exists (dest)) remove (dest); pict->pict.save (utf8_to_qstring (concretize (dest))); diff --git a/src/Plugins/Qt/qt_picture.hpp b/src/Plugins/Qt/qt_picture.hpp index 489effeed2..19db0cfba4 100644 --- a/src/Plugins/Qt/qt_picture.hpp +++ b/src/Plugins/Qt/qt_picture.hpp @@ -1,56 +1,56 @@ /****************************************************************************** -* MODULE : qt_picture.hpp -* DESCRIPTION: QT pictures -* COPYRIGHT : (C) 2013 Massimiliano Gubinelli, Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_picture.hpp + * DESCRIPTION: QT pictures + * COPYRIGHT : (C) 2013 Massimiliano Gubinelli, Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_PICTURE_HPP #define QT_PICTURE_HPP -#include #include "qt_renderer.hpp" +#include -class qt_picture_rep: public picture_rep { +class qt_picture_rep : public picture_rep { public: QImage pict; - int w, h; - int ox, oy; + int w, h; + int ox, oy; protected: color internal_get_pixel (int x, int y); - void internal_set_pixel (int x, int y, color c); + void internal_set_pixel (int x, int y, color c); public: qt_picture_rep (const QImage& im, int ox2, int oy2); picture_kind get_type (); - void* get_handle (); - int get_width (); - int get_height (); - int get_origin_x (); - int get_origin_y (); - void set_origin (int ox2, int oy2); + void* get_handle (); + int get_width (); + int get_height (); + int get_origin_x (); + int get_origin_y (); + void set_origin (int ox2, int oy2); }; QImage* get_image (url u, int w, int h, tree eff, SI pixel); picture qt_picture (const QImage& im, int ox, int oy); QImage* xpm_image (url file_name); QPixmap qt_load_svg_icon (url file_name); -QIcon qt_load_icon (url file_name); +QIcon qt_load_icon (url file_name); -class qt_image_renderer_rep: public qt_renderer_rep { +class qt_image_renderer_rep : public qt_renderer_rep { public: picture pict; - int x1, y1, x2, y2; - + int x1, y1, x2, y2; + public: qt_image_renderer_rep (picture pict, double zoom); ~qt_image_renderer_rep (); - void set_zoom_factor (double zoom); + void set_zoom_factor (double zoom); void* get_data_handle (); }; diff --git a/src/Plugins/Qt/qt_pipe_link.cpp b/src/Plugins/Qt/qt_pipe_link.cpp index c0ab9f3cfe..439264e183 100644 --- a/src/Plugins/Qt/qt_pipe_link.cpp +++ b/src/Plugins/Qt/qt_pipe_link.cpp @@ -1,40 +1,41 @@ /****************************************************************************** -* MODULE : qt_pipe_link.cpp -* DESCRIPTION: TeXmacs links by pipes -* COPYRIGHT : (C) 2000 Joris van der Hoeven -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_pipe_link.cpp + * DESCRIPTION: TeXmacs links by pipes + * COPYRIGHT : (C) 2000 Joris van der Hoeven + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "basic.hpp" #include "tm_debug.hpp" -#if defined (QTTEXMACS) && (defined (OS_MINGW) || defined (OS_WIN) || defined (QTPIPES)) +#if defined(QTTEXMACS) && \ + (defined(OS_MINGW) || defined(OS_WIN) || defined(QTPIPES)) -#include "tm_link.hpp" #include "QTMPipeLink.hpp" #include "hashset.hpp" #include "iterator.hpp" +#include "tm_link.hpp" #include "tm_timer.hpp" -#include #include +#include #if defined(OS_MINGW) || defined(OS_WIN) #else -# include +#include #endif #include hashset pipe_link_set; /****************************************************************************** -* Definition of qt_pipe_link_rep class -******************************************************************************/ + * Definition of qt_pipe_link_rep class + ******************************************************************************/ -struct qt_pipe_link_rep: tm_link_rep { +struct qt_pipe_link_rep : tm_link_rep { QTMPipeLink PipeLink; public: @@ -53,9 +54,9 @@ struct qt_pipe_link_rep: tm_link_rep { }; qt_pipe_link_rep::qt_pipe_link_rep (string cmd) : PipeLink (cmd) { - PipeLink.feed_cmd = &feed_cmd; + PipeLink.feed_cmd= &feed_cmd; pipe_link_set->insert ((pointer) this); - alive = false; + alive= false; } qt_pipe_link_rep::~qt_pipe_link_rep () { @@ -64,15 +65,14 @@ qt_pipe_link_rep::~qt_pipe_link_rep () { } /****************************************************************************** -* Routines for qt_pipe_links -******************************************************************************/ + * Routines for qt_pipe_links + ******************************************************************************/ string qt_pipe_link_rep::start () { if (alive) return "busy"; - if (DEBUG_AUTO) - debug_shell << "Launching '" << PipeLink.cmd << "'\n"; - if (! PipeLink.launchCmd ()) { + if (DEBUG_AUTO) debug_shell << "Launching '" << PipeLink.cmd << "'\n"; + if (!PipeLink.launchCmd ()) { if (DEBUG_AUTO) debug_shell << "TeXmacs] Error: cannot start '" << PipeLink.cmd << "'\n"; return "Error: cannot start application"; @@ -86,7 +86,7 @@ qt_pipe_link_rep::write (string s, int channel) { if ((!alive) || (channel != LINK_IN)) return; if (-1 == PipeLink.writeStdin (s)) { io_error << "Error: cannot write to '" << PipeLink.cmd << "'\n"; - stop(); + stop (); } } @@ -102,7 +102,7 @@ qt_pipe_link_rep::watch (int channel) { static string empty_string= ""; if (channel == LINK_OUT) return PipeLink.getOutbuf (); else if (channel == LINK_ERR) return PipeLink.getErrbuf (); - else return empty_string; + else return empty_string; } string @@ -117,14 +117,14 @@ qt_pipe_link_rep::read (int channel) { PipeLink.setErrbuf (""); return r; } - else return string(""); + else return string (""); } void qt_pipe_link_rep::listen (int msecs) { if (!alive) return; time_t wait_until= texmacs_time () + msecs; - while ((PipeLink.getOutbuf() == "") && (PipeLink.getErrbuf() == "")) { + while ((PipeLink.getOutbuf () == "") && (PipeLink.getErrbuf () == "")) { PipeLink.listenChannel (QProcess::StandardOutput, 0); PipeLink.listenChannel (QProcess::StandardError, 0); if (texmacs_time () - wait_until > 0) break; @@ -137,8 +137,7 @@ qt_pipe_link_rep::is_readable (int channel) { return false; if (channel == LINK_OUT) return PipeLink.listenChannel (QProcess::StandardOutput, 0); - else - return PipeLink.listenChannel (QProcess::StandardError, 0); + else return PipeLink.listenChannel (QProcess::StandardError, 0); } void @@ -148,19 +147,21 @@ qt_pipe_link_rep::interrupt () { // Not implemented qt_error << "SIGINT not implemented on Windows\n"; #else -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - Q_PID pid = PipeLink.pid (); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + Q_PID pid= PipeLink.pid (); #else // see https://doc.qt.io/qt-5/qprocess-obsolete.html#pid - qint64 pid = PipeLink.processId(); + qint64 pid= PipeLink.processId (); #endif - - // REMARK: previously there were here below a call to ::killpg which does not seems to work on MacOS - // I (mgubi) replaced it with ::kill which does the job. But I do not undestand the difference. - - int ret = ::kill (pid, SIGINT); + + // REMARK: previously there were here below a call to ::killpg which does not + // seems to work on MacOS I (mgubi) replaced it with ::kill which does the + // job. But I do not undestand the difference. + + int ret= ::kill (pid, SIGINT); if (ret == -1) { - qt_error << "Interrupt not successful, pid: " << pid << " return code: " << errno << "\n"; + qt_error << "Interrupt not successful, pid: " << pid + << " return code: " << errno << "\n"; } #endif } @@ -172,8 +173,8 @@ qt_pipe_link_rep::stop () { } /****************************************************************************** -* Main builder function for qt_pipe_links -******************************************************************************/ + * Main builder function for qt_pipe_links + ******************************************************************************/ tm_link make_pipe_link (string cmd) { @@ -181,14 +182,14 @@ make_pipe_link (string cmd) { } /****************************************************************************** -* Emergency exit for all pipes -******************************************************************************/ + * Emergency exit for all pipes + ******************************************************************************/ void close_all_pipes () { iterator it= iterate (pipe_link_set); - while (it->busy()) { - qt_pipe_link_rep* con= (qt_pipe_link_rep*) it->next(); + while (it->busy ()) { + qt_pipe_link_rep* con= (qt_pipe_link_rep*) it->next (); if (con->alive) con->stop (); } } @@ -196,10 +197,11 @@ close_all_pipes () { void process_all_pipes () { iterator it= iterate (pipe_link_set); - while (it->busy()) { - qt_pipe_link_rep* con= (qt_pipe_link_rep*) it->next(); + while (it->busy ()) { + qt_pipe_link_rep* con= (qt_pipe_link_rep*) it->next (); if (con->alive) con->apply_command (); } } -#endif // defined (QTTEXMACS) && (defined (OS_MINGW) || defined (OS_WIN) || defined (QTPIPES)) +#endif // defined (QTTEXMACS) && (defined (OS_MINGW) || defined (OS_WIN) || + // defined (QTPIPES)) diff --git a/src/Plugins/Qt/qt_printer_widget.cpp b/src/Plugins/Qt/qt_printer_widget.cpp index 6f58482357..cda821f645 100644 --- a/src/Plugins/Qt/qt_printer_widget.cpp +++ b/src/Plugins/Qt/qt_printer_widget.cpp @@ -11,91 +11,83 @@ * in the root directory or . ******************************************************************************/ -#include "sys_utils.hpp" #include "qt_printer_widget.hpp" -#include "qt_utilities.hpp" // check_type -#include "message.hpp" // slot definitions -#include "lolly/system/subprocess.hpp" #include "QTMPrintDialog.hpp" #include "QTMPrinterSettings.hpp" +#include "lolly/system/subprocess.hpp" +#include "message.hpp" // slot definitions +#include "qt_utilities.hpp" // check_type +#include "sys_utils.hpp" -QTMPrinterSettings* qt_printer_widget_rep::_settings = NULL; +QTMPrinterSettings* qt_printer_widget_rep::_settings= NULL; /*! * @todo Load the default printer settings from somewhere. */ qt_printer_widget_rep::qt_printer_widget_rep (command _cmd, url _file) -: commandAfterExecution(_cmd) { + : commandAfterExecution (_cmd) { #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) - if (!_settings) - _settings = new CupsQTMPrinterSettings(); + if (!_settings) _settings= new CupsQTMPrinterSettings (); #endif #ifdef Q_OS_WIN - if (!_settings) - _settings = new WinQTMPrinterSettings(); + if (!_settings) _settings= new WinQTMPrinterSettings (); #endif - _settings->fileName = to_qstring(as_string(_file)); + _settings->fileName= to_qstring (as_string (_file)); } - - /*! - * - */ + * + */ void qt_printer_widget_rep::send (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_printer_widget_rep::send " << slot_name(s) << LF; + debug_widgets << "qt_printer_widget_rep::send " << slot_name (s) << LF; switch (s) { - case SLOT_VISIBILITY: // Activates the widget - check_type(val, s); - if (open_box(val) == true) - showDialog(); - break; - case SLOT_REFRESH: // ignore: this widget doesn't need refreshing. - break; - default: // unsupported slots - qt_widget_rep::send (s, val); - break; + case SLOT_VISIBILITY: // Activates the widget + check_type (val, s); + if (open_box (val) == true) showDialog (); + break; + case SLOT_REFRESH: // ignore: this widget doesn't need refreshing. + break; + default: // unsupported slots + qt_widget_rep::send (s, val); + break; } } - - /*! Return the widget as a top-level window to the eyes of TeXmacs. */ widget qt_printer_widget_rep::plain_window_widget (string s, command q, int b) { - (void) s; (void) b; - commandAfterExecution = q; + (void) s; + (void) b; + commandAfterExecution= q; return this; } - - /*! - * Shows the printer dialog. The native ones have more options than we can + * Shows the printer dialog. The native ones have more options than we can * handle so we don't use them. * @fixme Executing the scheme closure at the end crashes TeXmacs upon exit! * Looks like someone is trying to delete the command twice? */ void qt_printer_widget_rep::showDialog () { - - QString _cmd; - QTMPrintDialog pDialog(_settings); - - if (pDialog.exec() != QDialog::Accepted) + + QString _cmd; + QTMPrintDialog pDialog (_settings); + + if (pDialog.exec () != QDialog::Accepted) return; // TODO: display message in the status bar. - - _cmd = _settings->toSystemCommand(); - + + _cmd= _settings->toSystemCommand (); + // Send the document to the printer if (DEBUG_QT_WIDGETS) - debug_widgets << "Running print command: " << from_qstring(_cmd) << "\n"; - lolly::system::call (from_qstring (_cmd)); // FIXME? qt_system is synchronous (blocking!) - - // execute the scheme closure - if (!is_nil (commandAfterExecution)) - commandAfterExecution (); + debug_widgets << "Running print command: " << from_qstring (_cmd) << "\n"; + lolly::system::call ( + from_qstring (_cmd)); // FIXME? qt_system is synchronous (blocking!) + + // execute the scheme closure + if (!is_nil (commandAfterExecution)) commandAfterExecution (); } diff --git a/src/Plugins/Qt/qt_printer_widget.hpp b/src/Plugins/Qt/qt_printer_widget.hpp index 0b8b461545..c8742f3d7d 100644 --- a/src/Plugins/Qt/qt_printer_widget.hpp +++ b/src/Plugins/Qt/qt_printer_widget.hpp @@ -12,41 +12,39 @@ #ifndef QT_PRINTER_WIDGET_HPP #define QT_PRINTER_WIDGET_HPP -#include "qt_widget.hpp" #include "command.hpp" +#include "qt_widget.hpp" class QTMPrinterSettings; /*! * This implements a printer widget, using QTMPrinterDialog. * - * The "factory" function for this widget is called printer_widget(), + * The "factory" function for this widget is called printer_widget(), * in qt_widget.cpp * * All printing options set by the user at this stage are applied as a * postprocessing of an already typeset postscript document. - * Either we instruct the printing system to print specific pages, etc., or + * Either we instruct the printing system to print specific pages, etc., or * we take the Postscript file generated by TeXmacs and create a new temporary * one applying the options set by the user in the print dialog and then send * this new file to the printer. * * @see qt_printer_widget_rep::showDialog() - */ -class qt_printer_widget_rep: public qt_widget_rep { + */ +class qt_printer_widget_rep : public qt_widget_rep { public: qt_printer_widget_rep (command, url); - ~qt_printer_widget_rep () { }; - - virtual void send (slot s, blackbox val); + ~qt_printer_widget_rep (){}; + + virtual void send (slot s, blackbox val); virtual widget plain_window_widget (string s, command q, int b); void showDialog (); -private: +private: static QTMPrinterSettings* _settings; - command commandAfterExecution; //! scheme closure to execute after printing + command commandAfterExecution; //! scheme closure to execute after printing }; -#endif // QT_PRINTER_WIDGET_HPP - - +#endif // QT_PRINTER_WIDGET_HPP diff --git a/src/Plugins/Qt/qt_renderer.cpp b/src/Plugins/Qt/qt_renderer.cpp index 3292c71ae0..86311cf9c5 100644 --- a/src/Plugins/Qt/qt_renderer.cpp +++ b/src/Plugins/Qt/qt_renderer.cpp @@ -1,101 +1,102 @@ /****************************************************************************** -* MODULE : qt_renderer.cpp -* DESCRIPTION: QT drawing interface class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_renderer.cpp + * DESCRIPTION: QT drawing interface class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "qt_renderer.hpp" #include "analyze.hpp" -#include "image_files.hpp" -#include "qt_utilities.hpp" #include "file.hpp" +#include "frame.hpp" #include "image_files.hpp" +#include "qt_utilities.hpp" #include "scheme.hpp" -#include "frame.hpp" #include -#include #include #include #include +#include /****************************************************************************** -* Qt images -******************************************************************************/ - -struct qt_image_rep: concrete_struct { - QTMImage *img; - SI xo,yo; - int w,h; - qt_image_rep (QTMImage* img2, SI xo2, SI yo2, int w2, int h2): - img (img2), xo (xo2), yo (yo2), w (w2), h (h2) {}; - ~qt_image_rep() { delete img; }; + * Qt images + ******************************************************************************/ + +struct qt_image_rep : concrete_struct { + QTMImage* img; + SI xo, yo; + int w, h; + qt_image_rep (QTMImage* img2, SI xo2, SI yo2, int w2, int h2) + : img (img2), xo (xo2), yo (yo2), w (w2), h (h2){}; + ~qt_image_rep () { delete img; }; friend class qt_image; }; class qt_image { -CONCRETE_NULL(qt_image); - qt_image (QTMImage* img2, SI xo2, SI yo2, int w2, int h2): - rep (tm_new (img2, xo2, yo2, w2, h2)) {}; + CONCRETE_NULL (qt_image); + qt_image (QTMImage* img2, SI xo2, SI yo2, int w2, int h2) + : rep (tm_new (img2, xo2, yo2, w2, h2)){}; // qt_image (); }; -CONCRETE_NULL_CODE(qt_image); +CONCRETE_NULL_CODE (qt_image); /****************************************************************************** * Qt pixmaps ******************************************************************************/ -struct qt_pixmap_rep: concrete_struct { +struct qt_pixmap_rep : concrete_struct { QTMPixmapOrImage img; - SI xo,yo; - int w,h; - qt_pixmap_rep (QTMPixmapOrImage img2, SI xo2, SI yo2, int w2, int h2): - img (img2), xo (xo2), yo (yo2), w (w2), h (h2) {}; - ~qt_pixmap_rep() {}; + SI xo, yo; + int w, h; + qt_pixmap_rep (QTMPixmapOrImage img2, SI xo2, SI yo2, int w2, int h2) + : img (img2), xo (xo2), yo (yo2), w (w2), h (h2){}; + ~qt_pixmap_rep (){}; friend class qt_pixmap; }; class qt_pixmap { -CONCRETE_NULL(qt_pixmap); - qt_pixmap (QTMPixmapOrImage img2, SI xo2, SI yo2, int w2, int h2): - rep (tm_new (img2, xo2, yo2, w2, h2)) {}; + CONCRETE_NULL (qt_pixmap); + qt_pixmap (QTMPixmapOrImage img2, SI xo2, SI yo2, int w2, int h2) + : rep (tm_new (img2, xo2, yo2, w2, h2)){}; // qt_pixmap (); }; -CONCRETE_NULL_CODE(qt_pixmap); +CONCRETE_NULL_CODE (qt_pixmap); /****************************************************************************** -* Global support variables for all qt_renderers -******************************************************************************/ + * Global support variables for all qt_renderers + ******************************************************************************/ // bitmaps of all characters -static hashmap character_image; +static hashmap character_image; // image cache -static hashmap images; +static hashmap images; /* -** hash contents must be removed because -** the underlying objects are destroyed during +** hash contents must be removed because +** the underlying objects are destroyed during ** Qt exit function */ -void del_obj_qt_renderer(void) { - character_image= hashmap (); - images= hashmap() ; +void +del_obj_qt_renderer (void) { + character_image= hashmap (); + images = hashmap (); } /****************************************************************************** -* qt_renderer -******************************************************************************/ + * qt_renderer + ******************************************************************************/ -qt_renderer_rep::qt_renderer_rep (QPainter *_painter, int w2, int h2): - basic_renderer_rep (true, w2, h2), painter(_painter) { - reset_zoom_factor(); } +qt_renderer_rep::qt_renderer_rep (QPainter* _painter, int w2, int h2) + : basic_renderer_rep (true, w2, h2), painter (_painter) { + reset_zoom_factor (); +} qt_renderer_rep::~qt_renderer_rep () {} @@ -106,29 +107,35 @@ qt_renderer_rep::get_handle () { void qt_renderer_rep::begin (void* handle) { - QPaintDevice *device = static_cast(handle); + QPaintDevice* device= static_cast (handle); if (!painter->begin (device) && DEBUG_QT) { if (headless_mode) debug_qt << "qt_renderer_rep::begin(): uninitialized QImage of size " - << ((QImage*) handle)->width() << " x " - << ((QImage*) handle)->height() << LF; + << ((QImage*) handle)->width () << " x " + << ((QImage*) handle)->height () << LF; else debug_qt << "qt_renderer_rep::begin(): uninitialized QPixmap of size " - << ((QPixmap*) handle)->width() << " x " - << ((QPixmap*) handle)->height() << LF; + << ((QPixmap*) handle)->width () << " x " + << ((QPixmap*) handle)->height () << LF; } - w = painter->device()->width(); - h = painter->device()->height(); + w= painter->device ()->width (); + h= painter->device ()->height (); } -void qt_renderer_rep::end () { painter->end (); } +void +qt_renderer_rep::end () { + painter->end (); +} -void -qt_renderer_rep::get_extents (int& w2, int& h2) { - if (painter->device()) { - w2 = painter->device()->width(); h2 = painter->device()->height(); - } else { - w2 = w; h2 = h; +void +qt_renderer_rep::get_extents (int& w2, int& h2) { + if (painter->device ()) { + w2= painter->device ()->width (); + h2= painter->device ()->height (); + } + else { + w2= w; + h2= h; } } @@ -139,8 +146,8 @@ qt_renderer_rep::set_zoom_factor (double zoom) { } /****************************************************************************** -* Transformations -******************************************************************************/ + * Transformations + ******************************************************************************/ void qt_renderer_rep::set_transformation (frame fr) { @@ -155,12 +162,12 @@ qt_renderer_rep::set_transformation (frame fr) { point o = tr (point (0.0, 0.0)); point ux= tr (point (1.0, 0.0)) - o; point uy= tr (point (0.0, 1.0)) - o; - //cout << "Set transformation " << o << ", " << ux << ", " << uy << "\n"; + // cout << "Set transformation " << o << ", " << ux << ", " << uy << "\n"; QTransform qtr (ux[0], ux[1], uy[0], uy[1], o[0], o[1]); painter->save (); painter->setTransform (qtr, true); - rectangle nclip= fr [oclip]; + rectangle nclip= fr[oclip]; clip (nclip->x1, nclip->y1, nclip->x2, nclip->y2); } @@ -171,35 +178,35 @@ qt_renderer_rep::reset_transformation () { } /****************************************************************************** -* Clipping -******************************************************************************/ + * Clipping + ******************************************************************************/ void -qt_renderer_rep::set_clipping (SI x1, SI y1, SI x2, SI y2, bool restore) -{ +qt_renderer_rep::set_clipping (SI x1, SI y1, SI x2, SI y2, bool restore) { (void) restore; basic_renderer_rep::set_clipping (x1, y1, x2, y2); outer_round (x1, y1, x2, y2); decode (x1, y1); decode (x2, y2); - if ((x1setClipRect(r); - } else { - painter->setClipRect(QRect()); + if ((x1 < x2) && (y2 < y1)) { + QRect r (x1, y2, x2 - x1, y1 - y2); + painter->setClipRect (r); + } + else { + painter->setClipRect (QRect ()); } } /****************************************************************************** -* Drawing -******************************************************************************/ -bool is_percentage (tree t, string s= "%"); + * Drawing + ******************************************************************************/ +bool is_percentage (tree t, string s= "%"); double as_percentage (tree t); static QImage* get_pattern_image (brush br, SI pixel) { - url u; - SI w, h; + url u; + SI w, h; tree eff; get_pattern_data (u, w, h, eff, br, pixel); QImage* pm= get_image (u, w, h, eff, pixel); @@ -210,21 +217,21 @@ void qt_renderer_rep::set_pencil (pencil np) { painter->setOpacity (qreal (1.0)); basic_renderer_rep::set_pencil (np); - QPen p (painter->pen ()); + QPen p (painter->pen ()); QBrush b (painter->brush ()); QColor qc= to_qcolor (pen->get_color ()); p.setColor (qc); b.setColor (qc); - //SI pw= 0; - //if (pen->get_width () > pixel) - //pw= (pen->get_width () + thicken) / (1.0*pixel); - //p.setWidth (pw); + // SI pw= 0; + // if (pen->get_width () > pixel) + // pw= (pen->get_width () + thicken) / (1.0*pixel); + // p.setWidth (pw); qreal pw= (qreal) (((double) pen->get_width ()) / ((double) pixel)); p.setWidthF (pw); if (np->get_type () == pencil_brush) { - brush br= np->get_brush (); - QImage* pm= get_pattern_image (br, pixel); - int pattern_alpha= br->get_alpha (); + brush br = np->get_brush (); + QImage* pm = get_pattern_image (br, pixel); + int pattern_alpha= br->get_alpha (); painter->setOpacity (qreal (pattern_alpha) / qreal (255)); if (pm != NULL) { b= QBrush (*pm); @@ -237,7 +244,7 @@ qt_renderer_rep::set_pencil (pencil np) { } } p.setStyle (Qt::SolidLine); - p.setCapStyle (pen->get_cap () == cap_round? Qt::RoundCap: Qt::SquareCap); + p.setCapStyle (pen->get_cap () == cap_round ? Qt::RoundCap : Qt::SquareCap); p.setJoinStyle (Qt::RoundJoin); painter->setPen (p); painter->setBrush (b); @@ -251,7 +258,7 @@ qt_renderer_rep::set_brush (brush br) { painter->setBrush (QBrush (Qt::NoBrush)); } else { - QPen p (painter->pen ()); + QPen p (painter->pen ()); QBrush b (painter->brush ()); QColor col= to_qcolor (pen->get_color ()); p.setColor (col); @@ -260,8 +267,8 @@ qt_renderer_rep::set_brush (brush br) { painter->setBrush (b); } if (br->get_type () == brush_pattern) { - QImage* pm= get_pattern_image (br, pixel); - int pattern_alpha= br->get_alpha (); + QImage* pm = get_pattern_image (br, pixel); + int pattern_alpha= br->get_alpha (); painter->setOpacity (qreal (pattern_alpha) / qreal (255)); if (pm != NULL) { QBrush b (*pm); @@ -269,7 +276,7 @@ qt_renderer_rep::set_brush (brush br) { decode (0, 0, pox, poy); QTransform tr; tr.translate (pox, poy); - //tr.rotate (45.0); + // tr.rotate (45.0); b.setTransform (tr); painter->setBrush (b); } @@ -288,25 +295,28 @@ qt_renderer_rep::line (SI x1, SI y1, SI x2, SI y2) { void qt_renderer_rep::lines (array x, array y) { - int i, n= N(x); - if ((N(y) != n) || (n<2)) return; + int i, n= N (x); + if ((N (y) != n) || (n < 2)) return; STACK_NEW_ARRAY (pnt, QPointF, n); - for (i=0; ipen(); - p.setCapStyle (pen->get_cap () == cap_round? Qt::RoundCap: Qt::SquareCap); - if (x[N(x)-1] == x[0] && y[N(y)-1] == y[0]) p.setCapStyle (Qt::RoundCap); + QPen p= painter->pen (); + p.setCapStyle (pen->get_cap () == cap_round ? Qt::RoundCap : Qt::SquareCap); + if (x[N (x) - 1] == x[0] && y[N (y) - 1] == y[0]) + p.setCapStyle (Qt::RoundCap); p.setJoinStyle (Qt::RoundJoin); painter->setPen (p); @@ -317,64 +327,69 @@ qt_renderer_rep::lines (array x, array y) { void qt_renderer_rep::clear (SI x1, SI y1, SI x2, SI y2) { - x1= max (x1, cx1-ox); y1= max (y1, cy1-oy); - x2= min (x2, cx2-ox); y2= min (y2, cy2-oy); + x1= max (x1, cx1 - ox); + y1= max (y1, cy1 - oy); + x2= min (x2, cx2 - ox); + y2= min (y2, cy2 - oy); // outer_round (x1, y1, x2, y2); might still be needed somewhere decode (x1, y1); decode (x2, y2); - if ((x1>=x2) || (y1<=y2)) return; + if ((x1 >= x2) || (y1 <= y2)) return; QBrush br (to_qcolor (bg_brush->get_color ())); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) painter->setRenderHints (0); #else - painter->setRenderHints(QPainter::Antialiasing); + painter->setRenderHints (QPainter::Antialiasing); #endif - painter->fillRect (x1, y2, x2-x1, y1-y2, br); + painter->fillRect (x1, y2, x2 - x1, y1 - y2, br); } void qt_renderer_rep::fill (SI x1, SI y1, SI x2, SI y2) { - if ((x2>x1) && ((x2-x1)>1); - x2 += ((d+1)>>1); + if ((x2 > x1) && ((x2 - x1) < pixel)) { + SI d= pixel - (x2 - x1); + x1-= (d >> 1); + x2+= ((d + 1) >> 1); } - if ((y2>y1) && ((y2-y1)>1); - y2 += ((d+1)>>1); + if ((y2 > y1) && ((y2 - y1) < pixel)) { + SI d= pixel - (y2 - y1); + y1-= (d >> 1); + y2+= ((d + 1) >> 1); } - x1= max (x1, cx1-ox); y1= max (y1, cy1-oy); - x2= min (x2, cx2-ox); y2= min (y2, cy2-oy); + x1= max (x1, cx1 - ox); + y1= max (y1, cy1 - oy); + x2= min (x2, cx2 - ox); + y2= min (y2, cy2 - oy); // outer_round (x1, y1, x2, y2); might still be needed somewhere - if ((x1>=x2) || (y1>=y2)) return; + if ((x1 >= x2) || (y1 >= y2)) return; decode (x1, y1); decode (x2, y2); QBrush br (to_qcolor (pen->get_color ())); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) painter->setRenderHints (0); #else - painter->setRenderHints(QPainter::Antialiasing); + painter->setRenderHints (QPainter::Antialiasing); #endif - painter->fillRect (x1, y2, x2-x1, y1-y2, br); + painter->fillRect (x1, y2, x2 - x1, y1 - y2, br); } void qt_renderer_rep::arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta) { - if ((x1>=x2) || (y1>=y2)) return; + if ((x1 >= x2) || (y1 >= y2)) return; double rx1, ry1, rx2, ry2; decode (x1, y1, rx1, ry1); decode (x2, y2, rx2, ry2); painter->setRenderHints (QPainter::Antialiasing); - painter->drawArc (QRectF (rx1, ry2, rx2-rx1, ry1-ry2), alpha / 4, delta / 4); + painter->drawArc (QRectF (rx1, ry2, rx2 - rx1, ry1 - ry2), alpha / 4, + delta / 4); } void qt_renderer_rep::fill_arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta) { - if ((x1>=x2) || (y1>=y2)) return; + if ((x1 >= x2) || (y1 >= y2)) return; double rx1, ry1, rx2, ry2; decode (x1, y1, rx1, ry1); decode (x2, y2, rx2, ry2); @@ -382,8 +397,8 @@ qt_renderer_rep::fill_arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta) { if (is_nil (fg_brush) || fg_brush->get_type () != brush_pattern) br= QBrush (to_qcolor (pen->get_color ())); QPainterPath pp; - pp.arcMoveTo (QRectF (rx1, ry2, rx2-rx1, ry1-ry2), alpha / 64); - pp.arcTo (QRectF (rx1, ry2, rx2-rx1, ry1-ry2), alpha / 64, delta / 64); + pp.arcMoveTo (QRectF (rx1, ry2, rx2 - rx1, ry1 - ry2), alpha / 64); + pp.arcTo (QRectF (rx1, ry2, rx2 - rx1, ry1 - ry2), alpha / 64, delta / 64); pp.closeSubpath (); pp.setFillRule (Qt::WindingFill); painter->setRenderHints (QPainter::Antialiasing); @@ -392,13 +407,13 @@ qt_renderer_rep::fill_arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta) { void qt_renderer_rep::polygon (array x, array y, bool convex) { - int i, n= N(x); - if ((N(y) != n) || (n<1)) return; + int i, n= N (x); + if ((N (y) != n) || (n < 1)) return; QPolygonF poly (n); - for (i=0; ibrush (); if (is_nil (fg_brush) || fg_brush->get_type () != brush_pattern) @@ -408,7 +423,7 @@ qt_renderer_rep::polygon (array x, array y, bool convex) { QPainterPath pp; pp.addPolygon (poly); pp.closeSubpath (); - pp.setFillRule (convex? Qt::OddEvenFill: Qt::WindingFill); + pp.setFillRule (convex ? Qt::OddEvenFill : Qt::WindingFill); painter->setRenderHints (QPainter::Antialiasing); painter->fillPath (pp, br); } @@ -416,20 +431,23 @@ qt_renderer_rep::polygon (array x, array y, bool convex) { void qt_renderer_rep::draw_triangle (SI x1, SI y1, SI x2, SI y2, SI x3, SI y3) { array x (3), y (3); - x[0]= x1; y[0]= y1; - x[1]= x2; y[1]= y2; - x[2]= x3; y[2]= y3; - - int i, n= N(x); - if ((N(y) != n) || (n<1)) return; - QPolygonF poly(n); - for (i=0; ibrush (); if (is_nil (fg_brush) || fg_brush->get_type () != brush_pattern) @@ -445,39 +463,40 @@ qt_renderer_rep::draw_triangle (SI x1, SI y1, SI x2, SI y2, SI x3, SI y3) { } /****************************************************************************** -* Image rendering -******************************************************************************/ + * Image rendering + ******************************************************************************/ void -qt_renderer_rep::draw_clipped (QImage *im, int w, int h, SI x, SI y) { - (void) w; (void) h; - int x1=cx1-ox, y1=cy2-oy, x2= cx2-ox, y2= cy1-oy; - decode (x , y ); +qt_renderer_rep::draw_clipped (QImage* im, int w, int h, SI x, SI y) { + (void) w; + (void) h; + int x1= cx1 - ox, y1= cy2 - oy, x2= cx2 - ox, y2= cy1 - oy; + decode (x, y); decode (x1, y1); decode (x2, y2); y--; // top-left origin to bottom-left origin conversion // clear(x1,y1,x2,y2); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) painter->setRenderHints (0); #else - painter->setRenderHints(QPainter::Antialiasing); + painter->setRenderHints (QPainter::Antialiasing); #endif painter->drawImage (x, y, *im); } void -qt_renderer_rep::draw_clipped (QTMPixmapOrImage *im, int w, int h, SI x, SI y) { +qt_renderer_rep::draw_clipped (QTMPixmapOrImage* im, int w, int h, SI x, SI y) { if (headless_mode) { draw_clipped (im->QImage_ptr (), w, h, x, y); return; } - decode (x , y ); + decode (x, y); y--; // top-left origin to bottom-left origin conversion // clear(x1,y1,x2,y2); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) painter->setRenderHints (0); #else - painter->setRenderHints(QPainter::Antialiasing); + painter->setRenderHints (QPainter::Antialiasing); #endif painter->drawPixmap (x, y, w, h, *(im->QPixmap_ptr ())); } @@ -485,23 +504,25 @@ qt_renderer_rep::draw_clipped (QTMPixmapOrImage *im, int w, int h, SI x, SI y) { void qt_renderer_rep::draw_bis (int c, font_glyphs fng, SI x, SI y) { // draw with background pattern - SI xo, yo; - glyph pre_gl= fng->get (c); if (is_nil (pre_gl)) return; - glyph gl= shrink (pre_gl, std_shrinkf, std_shrinkf, xo, yo); - int w= gl->width, h= gl->height; - QImage *im= new QImage (w, h, QImage::Format_ARGB32); + SI xo, yo; + glyph pre_gl= fng->get (c); + if (is_nil (pre_gl)) return; + glyph gl= shrink (pre_gl, std_shrinkf, std_shrinkf, xo, yo); + int w= gl->width, h= gl->height; + QImage* im= new QImage (w, h, QImage::Format_ARGB32); im->fill (Qt::transparent); { - brush br= pen->get_brush (); - QImage* pm= get_pattern_image (br, brushpx==-1? pixel: brushpx); - int pattern_alpha= br->get_alpha (); + brush br= pen->get_brush (); + QImage* pm= get_pattern_image (br, brushpx == -1 ? pixel : brushpx); + int pattern_alpha= br->get_alpha (); QPainter glim (im); glim.setOpacity (qreal (pattern_alpha) / qreal (255)); if (pm != NULL) { - SI tx= x- xo*std_shrinkf, ty= y+ yo*std_shrinkf; - decode (tx, ty); ty--; - QBrush qbr (*pm); + SI tx= x - xo * std_shrinkf, ty= y + yo * std_shrinkf; + decode (tx, ty); + ty--; + QBrush qbr (*pm); QTransform qtf= painter->transform (); qbr.setTransform (qtf.translate (-tx, -ty)); glim.setBrush (qbr); @@ -509,20 +530,20 @@ qt_renderer_rep::draw_bis (int c, font_glyphs fng, SI x, SI y) { glim.setPen (Qt::NoPen); glim.drawRect (0, 0, w, h); - int nr_cols= std_shrinkf*std_shrinkf; + int nr_cols= std_shrinkf * std_shrinkf; if (nr_cols >= 64) nr_cols= 64; - for (int j=0; jpixel (i, j); - int r, g, b, a; + int r, g, b, a; get_rgb (patcol, r, g, b, a); if (get_reverse_colors ()) reverse (r, g, b); - int col = gl->get_x (i, j); - im->setPixel (i, j, qRgba (r, g, b, (a*col)/nr_cols)); + int col= gl->get_x (i, j); + im->setPixel (i, j, qRgba (r, g, b, (a * col) / nr_cols)); } } - draw_clipped (im, w, h, x- xo*std_shrinkf, y+ yo*std_shrinkf); + draw_clipped (im, w, h, x - xo * std_shrinkf, y + yo * std_shrinkf); delete im; } @@ -534,82 +555,84 @@ qt_renderer_rep::draw (int c, font_glyphs fng, SI x, SI y) { } // get the pixmap - color fgc= pen->get_color (); + color fgc= pen->get_color (); basic_character xc (c, fng, std_shrinkf, fgc, 0); - qt_image mi = character_image [xc]; - if (is_nil(mi)) { + qt_image mi= character_image[xc]; + if (is_nil (mi)) { int r, g, b, a; get_rgb (fgc, r, g, b, a); if (get_reverse_colors ()) reverse (r, g, b); - SI xo, yo; - glyph pre_gl= fng->get (c); if (is_nil (pre_gl)) return; + SI xo, yo; + glyph pre_gl= fng->get (c); + if (is_nil (pre_gl)) return; glyph gl= shrink (pre_gl, std_shrinkf, std_shrinkf, xo, yo); - int i, j, w= gl->width, h= gl->height; + int i, j, w= gl->width, h= gl->height; #ifdef QTMPIXMAPS QTMPixmapOrImage* im= new QTMPixmapOrImage (w, h); if (!headless_mode) { - int nr_cols= std_shrinkf*std_shrinkf; + int nr_cols= std_shrinkf * std_shrinkf; if (nr_cols >= 64) nr_cols= 64; im->fill (Qt::transparent); - QPainter pp(im->QPixmap_ptr ()); - QPen pen(painter->pen()); - QBrush br(pen.color()); - pp.setPen(Qt::NoPen); - for (j=0; jget_x (i, j); - br.setColor (QColor (r, g, b, (a*col)/nr_cols)); + QPainter pp (im->QPixmap_ptr ()); + QPen pen (painter->pen ()); + QBrush br (pen.color ()); + pp.setPen (Qt::NoPen); + for (j= 0; j < h; j++) + for (i= 0; i < w; i++) { + int col= gl->get_x (i, j); + br.setColor (QColor (r, g, b, (a * col) / nr_cols)); pp.fillRect (i, j, 1, 1, br); } - pp.end(); + pp.end (); } else { - QImage* aux= im->QImage_ptr (); - int nr_cols= std_shrinkf*std_shrinkf; + QImage* aux = im->QImage_ptr (); + int nr_cols= std_shrinkf * std_shrinkf; if (nr_cols >= 64) nr_cols= 64; im->fill (Qt::transparent); - for (j=0; jget_x (i, j); - aux->setPixel (i, j, qRgba (r, g, b, (a*col)/nr_cols)); + for (j= 0; j < h; j++) + for (i= 0; i < w; i++) { + int col= gl->get_x (i, j); + aux->setPixel (i, j, qRgba (r, g, b, (a * col) / nr_cols)); } } #else - QTMImage *im= new QImage (w, h, QImage::Format_ARGB32); - //QTMImage *im= new QImage (w, h, QImage::Format_ARGB32_Premultiplied); + QTMImage* im= new QImage (w, h, QImage::Format_ARGB32); + // QTMImage *im= new QImage (w, h, QImage::Format_ARGB32_Premultiplied); { - int nr_cols= std_shrinkf*std_shrinkf; + int nr_cols= std_shrinkf * std_shrinkf; if (nr_cols >= 64) nr_cols= 64; // the following line is disabled because // it causes a crash on Qt/X11 4.4.3 - //im->fill (Qt::transparent); + // im->fill (Qt::transparent); - for (j=0; jget_x (i, j); - im->setPixel (i, j, qRgba (r, g, b, (a*col)/nr_cols)); + for (j= 0; j < h; j++) + for (i= 0; i < w; i++) { + int col= gl->get_x (i, j); + im->setPixel (i, j, qRgba (r, g, b, (a * col) / nr_cols)); } } #endif qt_image mi2 (im, xo, yo, w, h); - mi = mi2; + mi= mi2; //[im release]; // qt_image retains im character_image (xc)= mi; - // FIXME: we must release the image at some point + // FIXME: we must release the image at some point // (this should be ok now, see qt_image) } // draw the character - //cout << (char)c << ": " << cx1/256 << "," << cy1/256 << "," - //<< cx2/256 << "," << cy2/256 << LF; - draw_clipped (mi->img, mi->w, mi->h, x- mi->xo*std_shrinkf, y+ mi->yo*std_shrinkf); + // cout << (char)c << ": " << cx1/256 << "," << cy1/256 << "," + //<< cx2/256 << "," << cy2/256 << LF; + draw_clipped (mi->img, mi->w, mi->h, x - mi->xo * std_shrinkf, + y + mi->yo * std_shrinkf); } void -qt_renderer_rep::draw (const QFont& qfn, const QString& qs, - SI x, SI y, double zoom) { +qt_renderer_rep::draw (const QFont& qfn, const QString& qs, SI x, SI y, + double zoom) { decode (x, y); painter->setFont (qfn); painter->translate (x, y); @@ -622,35 +645,33 @@ qt_renderer_rep::draw (const QFont& qfn, const QString& qs, * main qt renderer ******************************************************************************/ - qt_renderer_rep* the_qt_renderer () { - static QPainter *the_painter = NULL; + static QPainter* the_painter = NULL; static qt_renderer_rep* the_renderer= NULL; if (!the_renderer) { - the_painter = new QPainter(); + the_painter = new QPainter (); the_renderer= tm_new (the_painter); } return the_renderer; } - /****************************************************************************** - * Shadow management methods + * Shadow management methods ******************************************************************************/ /* Shadows are auxiliary renderers which allow double buffering and caching of * graphics. TeXmacs has explicit double buffering from the X11 port. Maybe - * it would be better to design a better API abstracting from the low level + * it would be better to design a better API abstracting from the low level * details but for the moment the following code and the qt_proxy_renderer_rep * and qt_shadow_renderer_rep classes are designed to solve two problems: - * + * * 1) Qt has already double buffering. * 2) in Qt we are not easily allowed to read onscreen pixels (we can only ask a * widget to redraw himself on a pixmap or read the screen pixels -- this has - * the drawback that if our widget is under another one we won't read the + * the drawback that if our widget is under another one we won't read the * right pixels) - * + * * qt_proxy_renderer_rep solves the double buffering problem: when texmacs asks * a qt_renderer_rep for a shadow it is given a proxy of the original renderer * texmacs uses this shadow for double buffering and the proxy will simply @@ -658,15 +679,14 @@ the_qt_renderer () { * syncronization operations * * to solve the second problem we do not draw directly on screen in QTMWidget. - * Instead we maintain an internal pixmap which represents the state of the pixels - * according to texmacs. When we are asked to initialize a qt_shadow_renderer_rep - * we simply read the pixels form this backing store. At the Qt level then - * (in QTMWidget) we make sure that the state of the backing store is in sync - * with the screen via paintEvent/repaint mechanism. + * Instead we maintain an internal pixmap which represents the state of the + * pixels according to texmacs. When we are asked to initialize a + * qt_shadow_renderer_rep we simply read the pixels form this backing store. At + * the Qt level then (in QTMWidget) we make sure that the state of the backing + * store is in sync with the screen via paintEvent/repaint mechanism. * */ - void qt_renderer_rep::new_shadow (renderer& ren) { SI mw, mh, sw, sh; @@ -679,99 +699,97 @@ qt_renderer_rep::new_shadow (renderer& ren) { } // cout << "Old: " << sw << ", " << sh << "\n"; } - if (ren == NULL) ren= (renderer) tm_new (this); - + if (ren == NULL) ren= (renderer) tm_new (this); + // cout << "Create " << mw << ", " << mh << "\n"; } -void -qt_renderer_rep::delete_shadow (renderer& ren) { +void +qt_renderer_rep::delete_shadow (renderer& ren) { if (ren != NULL) { tm_delete (ren); ren= NULL; } } -void +void qt_renderer_rep::get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2) { // FIXME: we should use the routine fetch later ASSERT (ren != NULL, "invalid renderer"); if (ren->is_printer ()) return; - qt_renderer_rep* shadow= static_cast(ren); + qt_renderer_rep* shadow= static_cast (ren); outer_round (x1, y1, x2, y2); - x1= max (x1, cx1- ox); - y1= max (y1, cy1- oy); - x2= min (x2, cx2- ox); - y2= min (y2, cy2- oy); - shadow->ox= ox; - shadow->oy= oy; + x1 = max (x1, cx1 - ox); + y1 = max (y1, cy1 - oy); + x2 = min (x2, cx2 - ox); + y2 = min (y2, cy2 - oy); + shadow->ox = ox; + shadow->oy = oy; shadow->master= this; - shadow->cx1= x1+ ox; - shadow->cy1= y1+ oy; - shadow->cx2= x2+ ox; - shadow->cy2= y2+ oy; - + shadow->cx1 = x1 + ox; + shadow->cy1 = y1 + oy; + shadow->cx2 = x2 + ox; + shadow->cy2 = y2 + oy; + decode (x1, y1); decode (x2, y2); - if (x1painter->setCompositionMode(QPainter::CompositionMode_Source); - shadow->painter->setClipRect(rect); -// shadow->painter->drawPixmap (rect, px, rect); - // cout << "qt_shadow_renderer_rep::get_shadow " + if (x1 < x2 && y2 < y1) { + QRect rect= QRect (x1, y2, x2 - x1, y1 - y2); + // shadow->painter->setCompositionMode(QPainter::CompositionMode_Source); + shadow->painter->setClipRect (rect); + // shadow->painter->drawPixmap (rect, px, rect); + // cout << "qt_shadow_renderer_rep::get_shadow " // << rectangle(x1,y2,x2,y1) << LF; // XCopyArea (dpy, win, shadow->win, gc, x1, y2, x2-x1, y1-y2, x1, y2); - } else { - shadow->painter->setClipRect(QRect()); + } + else { + shadow->painter->setClipRect (QRect ()); } } -void +void qt_renderer_rep::put_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2) { // FIXME: we should use the routine fetch later ASSERT (ren != NULL, "invalid renderer"); if (ren->is_printer ()) return; - if (painter == static_cast(ren)->painter) return; - qt_shadow_renderer_rep* shadow= static_cast(ren); + if (painter == static_cast (ren)->painter) return; + qt_shadow_renderer_rep* shadow= static_cast (ren); outer_round (x1, y1, x2, y2); - x1= max (x1, cx1- ox); - y1= max (y1, cy1- oy); - x2= min (x2, cx2- ox); - y2= min (y2, cy2- oy); + x1= max (x1, cx1 - ox); + y1= max (y1, cy1 - oy); + x2= min (x2, cx2 - ox); + y2= min (y2, cy2 - oy); decode (x1, y1); decode (x2, y2); - if (x1setCompositionMode(QPainter::CompositionMode_Source); if (headless_mode) painter->drawImage (rect, *(shadow->px.QImage_ptr ()), rect); - else - painter->drawPixmap (rect, *(shadow->px.QPixmap_ptr ()), rect); + else painter->drawPixmap (rect, *(shadow->px.QPixmap_ptr ()), rect); // XCopyArea (dpy, shadow->win, win, gc, x1, y2, x2-x1, y1-y2, x1, y2); } } - -void -qt_renderer_rep::apply_shadow (SI x1, SI y1, SI x2, SI y2) { +void +qt_renderer_rep::apply_shadow (SI x1, SI y1, SI x2, SI y2) { if (master == NULL) return; - if (painter == static_cast(master)->painter) return; + if (painter == static_cast (master)->painter) return; outer_round (x1, y1, x2, y2); decode (x1, y1); decode (x2, y2); - static_cast(master)->encode (x1, y1); - static_cast(master)->encode (x2, y2); + static_cast (master)->encode (x1, y1); + static_cast (master)->encode (x2, y2); master->put_shadow (this, x1, y1, x2, y2); } - /****************************************************************************** -* proxy qt renderer -******************************************************************************/ + * proxy qt renderer + ******************************************************************************/ -void +void qt_proxy_renderer_rep::new_shadow (renderer& ren) { SI mw, mh, sw, sh; get_extents (mw, mh); @@ -781,114 +799,109 @@ qt_proxy_renderer_rep::new_shadow (renderer& ren) { delete_shadow (ren); ren= NULL; } - else - static_cast(ren)->end(); + else static_cast (ren)->end (); // cout << "Old: " << sw << ", " << sh << "\n"; } if (ren == NULL) ren= (renderer) tm_new (QTMPixmapOrImage (mw, mh)); // cout << "Create " << mw << ", " << mh << "\n"; - static_cast(ren)->begin( - static_cast(ren)->px.rep); + static_cast (ren)->begin ( + static_cast (ren)->px.rep); } -void +void qt_proxy_renderer_rep::get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2) { // FIXME: we should use the routine fetch later ASSERT (ren != NULL, "invalid renderer"); if (ren->is_printer ()) return; - qt_renderer_rep* shadow= static_cast(ren); + qt_renderer_rep* shadow= static_cast (ren); outer_round (x1, y1, x2, y2); - x1= max (x1, cx1- ox); - y1= max (y1, cy1- oy); - x2= min (x2, cx2- ox); - y2= min (y2, cy2- oy); - shadow->ox= ox; - shadow->oy= oy; - shadow->cx1= x1+ ox; - shadow->cy1= y1+ oy; - shadow->cx2= x2+ ox; - shadow->cy2= y2+ oy; + x1 = max (x1, cx1 - ox); + y1 = max (y1, cy1 - oy); + x2 = min (x2, cx2 - ox); + y2 = min (y2, cy2 - oy); + shadow->ox = ox; + shadow->oy = oy; + shadow->cx1 = x1 + ox; + shadow->cy1 = y1 + oy; + shadow->cx2 = x2 + ox; + shadow->cy2 = y2 + oy; shadow->master= this; decode (x1, y1); decode (x2, y2); - if (x1painter->setClipRect(rect); + shadow->painter->setClipRect (rect); // shadow->painter->setCompositionMode(QPainter::CompositionMode_Source); if (headless_mode) { - QImage *_image = static_cast(painter->device()); - if (_image) - shadow->painter->drawImage (rect, *_image, rect); - } else { - QPixmap *_pixmap = static_cast(painter->device()); - if (_pixmap) - shadow->painter->drawPixmap (rect, *_pixmap, rect); + QImage* _image= static_cast (painter->device ()); + if (_image) shadow->painter->drawImage (rect, *_image, rect); + } + else { + QPixmap* _pixmap= static_cast (painter->device ()); + if (_pixmap) shadow->painter->drawPixmap (rect, *_pixmap, rect); } - // cout << "qt_shadow_renderer_rep::get_shadow " + // cout << "qt_shadow_renderer_rep::get_shadow " // << rectangle(x1,y2,x2,y1) << LF; // XCopyArea (dpy, win, shadow->win, gc, x1, y2, x2-x1, y1-y2, x1, y2); - } else { - shadow->painter->setClipRect(QRect()); } - + else { + shadow->painter->setClipRect (QRect ()); + } } - /****************************************************************************** * shadow qt renderer ******************************************************************************/ -qt_shadow_renderer_rep::qt_shadow_renderer_rep (QTMPixmapOrImage _px) -// : qt_renderer_rep (_px.width(),_px.height()), px(_px) -: qt_renderer_rep (new QPainter()), px(_px) -{ - //cout << px.width() << "," << px.height() << " " << LF; - // painter->begin(&px); +qt_shadow_renderer_rep::qt_shadow_renderer_rep (QTMPixmapOrImage _px) + // : qt_renderer_rep (_px.width(),_px.height()), px(_px) + : qt_renderer_rep (new QPainter ()), px (_px) { + // cout << px.width() << "," << px.height() << " " << LF; + // painter->begin(&px); } -qt_shadow_renderer_rep::~qt_shadow_renderer_rep () -{ - painter->end(); +qt_shadow_renderer_rep::~qt_shadow_renderer_rep () { + painter->end (); delete painter; - painter = NULL; + painter= NULL; } -void +void qt_shadow_renderer_rep::get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2) { // FIXME: we should use the routine fetch later ASSERT (ren != NULL, "invalid renderer"); if (ren->is_printer ()) return; - qt_shadow_renderer_rep* shadow= static_cast(ren); + qt_shadow_renderer_rep* shadow= static_cast (ren); outer_round (x1, y1, x2, y2); - x1= max (x1, cx1- ox); - y1= max (y1, cy1- oy); - x2= min (x2, cx2- ox); - y2= min (y2, cy2- oy); - shadow->ox= ox; - shadow->oy= oy; - shadow->cx1= x1+ ox; - shadow->cy1= y1+ oy; - shadow->cx2= x2+ ox; - shadow->cy2= y2+ oy; + x1 = max (x1, cx1 - ox); + y1 = max (y1, cy1 - oy); + x2 = min (x2, cx2 - ox); + y2 = min (y2, cy2 - oy); + shadow->ox = ox; + shadow->oy = oy; + shadow->cx1 = x1 + ox; + shadow->cy1 = y1 + oy; + shadow->cx2 = x2 + ox; + shadow->cy2 = y2 + oy; shadow->master= this; decode (x1, y1); decode (x2, y2); - if (x1painter->setClipRect(rect); + if (x1 < x2 && y2 < y1) { + QRect rect= QRect (x1, y2, x2 - x1, y1 - y2); + shadow->painter->setClipRect (rect); -// shadow->painter->setCompositionMode(QPainter::CompositionMode_Source); + // shadow->painter->setCompositionMode(QPainter::CompositionMode_Source); if (headless_mode) shadow->painter->drawImage (rect, *(px.QImage_ptr ()), rect); - else - shadow->painter->drawPixmap (rect, *(px.QPixmap_ptr ()), rect); -// cout << "qt_shadow_renderer_rep::get_shadow " -// << rectangle(x1,y2,x2,y1) << LF; -// XCopyArea (dpy, win, shadow->win, gc, x1, y2, x2-x1, y1-y2, x1, y2); - } else { - shadow->painter->setClipRect(QRect()); + else shadow->painter->drawPixmap (rect, *(px.QPixmap_ptr ()), rect); + // cout << "qt_shadow_renderer_rep::get_shadow " + // << rectangle(x1,y2,x2,y1) << LF; + // XCopyArea (dpy, win, shadow->win, gc, x1, y2, x2-x1, y1-y2, x1, y2); + } + else { + shadow->painter->setClipRect (QRect ()); } } diff --git a/src/Plugins/Qt/qt_renderer.hpp b/src/Plugins/Qt/qt_renderer.hpp index 089691693b..36b9be60cc 100644 --- a/src/Plugins/Qt/qt_renderer.hpp +++ b/src/Plugins/Qt/qt_renderer.hpp @@ -1,31 +1,31 @@ /****************************************************************************** -* MODULE : qt_renderer.hpp -* DESCRIPTION: QT drawing interface class -* COPYRIGHT : (C) 2006 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_renderer.hpp + * DESCRIPTION: QT drawing interface class + * COPYRIGHT : (C) 2006 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_RENDERER_HPP #define QT_RENDERER_HPP -#include "basic_renderer.hpp" #include "QTMPixmapOrImage.hpp" +#include "basic_renderer.hpp" +#include #include #include -#include -#include #include +#include -class qt_renderer_rep: public basic_renderer_rep { +class qt_renderer_rep : public basic_renderer_rep { public: - QPainter *painter; // FIXME: painter needs begin/end + QPainter* painter; // FIXME: painter needs begin/end public: - qt_renderer_rep (QPainter *_painter, int w = 0, int h = 0); + qt_renderer_rep (QPainter* _painter, int w= 0, int h= 0); ~qt_renderer_rep (); void* get_handle (); @@ -34,31 +34,31 @@ class qt_renderer_rep: public basic_renderer_rep { void begin (void* handle); void end (); - //void set_extent (int _w, int _h) { w = _w; h = _h; } + // void set_extent (int _w, int _h) { w = _w; h = _h; } void get_extents (int& w, int& h); void set_transformation (frame fr); void reset_transformation (); - void set_clipping (SI x1, SI y1, SI x2, SI y2, bool restore = false); - - void draw_bis (int char_code, font_glyphs fn, SI x, SI y); - void draw (int char_code, font_glyphs fn, SI x, SI y); - void draw (const QFont& qfn, const QString& s, SI x, SI y, double zoom); - void set_pencil (pencil p); - void set_brush (brush b); - void line (SI x1, SI y1, SI x2, SI y2); - void lines (array x, array y); - void clear (SI x1, SI y1, SI x2, SI y2); - void fill (SI x1, SI y1, SI x2, SI y2); - void arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta); - void fill_arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta); - void polygon (array x, array y, bool convex=true); - void draw_triangle (SI x1, SI y1, SI x2, SI y2, SI x3, SI y3); - - void draw_clipped (QImage * im, int w, int h, SI x, SI y); - void draw_clipped (QTMPixmapOrImage * im, int w, int h, SI x, SI y); - + void set_clipping (SI x1, SI y1, SI x2, SI y2, bool restore= false); + + void draw_bis (int char_code, font_glyphs fn, SI x, SI y); + void draw (int char_code, font_glyphs fn, SI x, SI y); + void draw (const QFont& qfn, const QString& s, SI x, SI y, double zoom); + void set_pencil (pencil p); + void set_brush (brush b); + void line (SI x1, SI y1, SI x2, SI y2); + void lines (array x, array y); + void clear (SI x1, SI y1, SI x2, SI y2); + void fill (SI x1, SI y1, SI x2, SI y2); + void arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta); + void fill_arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta); + void polygon (array x, array y, bool convex= true); + void draw_triangle (SI x1, SI y1, SI x2, SI y2, SI x3, SI y3); + + void draw_clipped (QImage* im, int w, int h, SI x, SI y); + void draw_clipped (QTMPixmapOrImage* im, int w, int h, SI x, SI y); + void new_shadow (renderer& ren); void delete_shadow (renderer& ren); void get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2); @@ -69,30 +69,30 @@ class qt_renderer_rep: public basic_renderer_rep { void draw_picture (picture pict, SI x, SI y, int alpha); }; -qt_renderer_rep* the_qt_renderer(); -QImage* get_image (url u, int w, int h, tree eff, SI pixel); +qt_renderer_rep* the_qt_renderer (); +QImage* get_image (url u, int w, int h, tree eff, SI pixel); -class qt_shadow_renderer_rep: public qt_renderer_rep { +class qt_shadow_renderer_rep : public qt_renderer_rep { public: - QTMPixmapOrImage px; - qt_renderer_rep *master; - + QTMPixmapOrImage px; + qt_renderer_rep* master; + public: qt_shadow_renderer_rep (QTMPixmapOrImage _px= QTMPixmapOrImage ()); ~qt_shadow_renderer_rep (); - + void get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2); }; -class qt_proxy_renderer_rep: public qt_renderer_rep { +class qt_proxy_renderer_rep : public qt_renderer_rep { public: - qt_renderer_rep *base; - + qt_renderer_rep* base; + public: - qt_proxy_renderer_rep (qt_renderer_rep *_base) - : qt_renderer_rep(_base->painter), base(_base) {} - ~qt_proxy_renderer_rep () {}; - + qt_proxy_renderer_rep (qt_renderer_rep* _base) + : qt_renderer_rep (_base->painter), base (_base) {} + ~qt_proxy_renderer_rep (){}; + void new_shadow (renderer& ren); void get_shadow (renderer ren, SI x1, SI y1, SI x2, SI y2); }; diff --git a/src/Plugins/Qt/qt_simple_widget.cpp b/src/Plugins/Qt/qt_simple_widget.cpp index 34fab926e0..21f90ee0b2 100644 --- a/src/Plugins/Qt/qt_simple_widget.cpp +++ b/src/Plugins/Qt/qt_simple_widget.cpp @@ -1,30 +1,29 @@ /****************************************************************************** -* MODULE : qt_simple_widget.hpp -* DESCRIPTION: A widget containing a TeXmacs canvas. -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_simple_widget.hpp + * DESCRIPTION: A widget containing a TeXmacs canvas. + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "blackbox.hpp" #include "iterator.hpp" +#include "qt_renderer.hpp" #include "qt_simple_widget.hpp" -#include "qt_window_widget.hpp" #include "qt_utilities.hpp" -#include "qt_renderer.hpp" +#include "qt_window_widget.hpp" -#include "QTMWidget.hpp" #include "QTMMenuHelper.hpp" -#include +#include "QTMWidget.hpp" #include - +#include qt_simple_widget_rep::qt_simple_widget_rep () - : qt_widget_rep (simple_widget), sequencer (0) { + : qt_widget_rep (simple_widget), sequencer (0) { backingPixmap= headless_mode ? NULL : new QPixmap (); } @@ -35,26 +34,25 @@ qt_simple_widget_rep::~qt_simple_widget_rep () { QWidget* qt_simple_widget_rep::as_qwidget () { - qwid = new QTMWidget (0, this); - reapply_sent_slots(); + qwid= new QTMWidget (0, this); + reapply_sent_slots (); SI width, height; handle_get_size_hint (width, height); - QSize sz = to_qsize (width, height); - scrollarea()->editor_flag= is_editor_widget (); - scrollarea()->setExtents (QRect (QPoint(0,0), sz)); - canvas()->resize (sz); - - - all_widgets->insert((pointer) this); - backing_pos = canvas()->origin (); + QSize sz = to_qsize (width, height); + scrollarea ()->editor_flag= is_editor_widget (); + scrollarea ()->setExtents (QRect (QPoint (0, 0), sz)); + canvas ()->resize (sz); + + all_widgets->insert ((pointer) this); + backing_pos= canvas ()->origin (); return qwid; } /****************************************************************************** -* Empty handlers for redefinition by our subclasses editor_rep, -* box_widget_rep... -******************************************************************************/ + * Empty handlers for redefinition by our subclasses editor_rep, + * box_widget_rep... + ******************************************************************************/ bool qt_simple_widget_rep::is_editor_widget () { @@ -68,23 +66,31 @@ qt_simple_widget_rep::handle_get_size_hint (SI& w, SI& h) { void qt_simple_widget_rep::handle_notify_resize (SI w, SI h) { - (void) w; (void) h; + (void) w; + (void) h; } void qt_simple_widget_rep::handle_keypress (string key, time_t t) { - (void) key; (void) t; + (void) key; + (void) t; } void qt_simple_widget_rep::handle_keyboard_focus (bool has_focus, time_t t) { - (void) has_focus; (void) t; + (void) has_focus; + (void) t; } void qt_simple_widget_rep::handle_mouse (string kind, SI x, SI y, int mods, time_t t, array data) { - (void) kind; (void) x; (void) y; (void) mods; (void) t; (void) data; + (void) kind; + (void) x; + (void) y; + (void) mods; + (void) t; + (void) data; } void @@ -94,55 +100,66 @@ qt_simple_widget_rep::handle_set_zoom_factor (double zoom) { void qt_simple_widget_rep::handle_clear (renderer win, SI x1, SI y1, SI x2, SI y2) { - (void) win; (void) x1; (void) y1; (void) x2; (void) y2; + (void) win; + (void) x1; + (void) y1; + (void) x2; + (void) y2; } void -qt_simple_widget_rep::handle_repaint (renderer win, SI x1, SI y1, SI x2, SI y2) { - (void) win; (void) x1; (void) y1; (void) x2; (void) y2; +qt_simple_widget_rep::handle_repaint (renderer win, SI x1, SI y1, SI x2, + SI y2) { + (void) win; + (void) x1; + (void) y1; + (void) x2; + (void) y2; } - /****************************************************************************** -* Handling of TeXmacs messages -******************************************************************************/ + * Handling of TeXmacs messages + ******************************************************************************/ /*! Stores messages (SLOTS) sent to this widget for later replay. - + This is useful for recompilation of the QWidget inside as_qwidget() in some cases, where state information of the parsed widget (i.e. the qt_widget) is stored by us directly in the QWidget, and thus is lost if we delete it. Each SLOT is stored only once, repeated occurrences of the same one overwriting - previous ones. Sequence information is also stored, allowing for correct replay. + previous ones. Sequence information is also stored, allowing for correct + replay. */ void qt_simple_widget_rep::save_send_slot (slot s, blackbox val) { - sent_slots[s].seq = sequencer; - sent_slots[s].val = val; - sent_slots[s].id = s.sid; - sequencer = (sequencer + 1) % slot_id__LAST; + sent_slots[s].seq= sequencer; + sent_slots[s].val= val; + sent_slots[s].id = s.sid; + sequencer = (sequencer + 1) % slot_id__LAST; } void qt_simple_widget_rep::reapply_sent_slots () { if (DEBUG_QT_WIDGETS) - debug_widgets << ">>>>>>>> reapply_sent_slots() for widget: " << type_as_string() << LF; - + debug_widgets << ">>>>>>>> reapply_sent_slots() for widget: " + << type_as_string () << LF; + t_slot_entry sorted_slots[slot_id__LAST]; - for (int i = 0; i < slot_id__LAST; ++i) - sorted_slots[i] = sent_slots[i]; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + for (int i= 0; i < slot_id__LAST; ++i) + sorted_slots[i]= sent_slots[i]; +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) qSort (&sorted_slots[0], &sorted_slots[slot_id__LAST]); #else std::sort (&sorted_slots[0], &sorted_slots[slot_id__LAST]); #endif - for (int i = 0; i < slot_id__LAST; ++i) + for (int i= 0; i < slot_id__LAST; ++i) if (sorted_slots[i].seq >= 0) - this->send(sorted_slots[i].id, sorted_slots[i].val); - + this->send (sorted_slots[i].id, sorted_slots[i].val); + if (DEBUG_QT_WIDGETS) - debug_widgets << "<<<<<<<< reapply_sent_slots() for widget: " << type_as_string() << LF; + debug_widgets << "<<<<<<<< reapply_sent_slots() for widget: " + << type_as_string () << LF; } void @@ -150,266 +167,237 @@ qt_simple_widget_rep::send (slot s, blackbox val) { save_send_slot (s, val); switch (s) { - case SLOT_INVALIDATE: + case SLOT_INVALIDATE: { + check_type (val, s); + coord4 p= open_box (val); + { - check_type(val, s); - coord4 p= open_box (val); - + qt_renderer_rep* ren= the_qt_renderer (); { - qt_renderer_rep* ren = the_qt_renderer(); - { - coord2 pt_or = from_qpoint(backing_pos); - SI ox = -pt_or.x1; - SI oy = -pt_or.x2; - ren->set_origin(ox,oy); - } - - SI x1 = p.x1, y1 = p.x2, x2 = p.x3, y2 = p.x4; - ren->outer_round (x1, y1, x2, y2); - ren->decode (x1, y1); - ren->decode (x2, y2); - invalidate_rect (x1, y2, x2, y1); + coord2 pt_or= from_qpoint (backing_pos); + SI ox = -pt_or.x1; + SI oy = -pt_or.x2; + ren->set_origin (ox, oy); } - } - break; - - case SLOT_INVALIDATE_ALL: - { - check_type_void (val, s); - invalidate_all (); - } - break; - - case SLOT_EXTENTS: - { - check_type(val, s); - coord4 p = open_box (val); - scrollarea()->setExtents (to_qrect (p)); - } - break; - - case SLOT_SIZE: - { - check_type(val, s); - coord2 p = open_box (val); - canvas()->resize (to_qsize(p)); // FIXME? - } - break; - - case SLOT_SCROLL_POSITION: - { - check_type(val, s); - coord2 p = open_box (val); - QPoint qp = to_qpoint (p); - QSize sz = canvas()->surface()->size(); - qp -= QPoint (sz.width() / 2, sz.height() / 2); - // NOTE: adjust because child is centered - scrollarea()->setOrigin (qp); - } - break; - - case SLOT_ZOOM_FACTOR: - { - check_type (val, s); - double new_zoom = open_box (val); - canvas()->tm_widget()->handle_set_zoom_factor (new_zoom); - } - break; - - case SLOT_MOUSE_GRAB: - { - check_type (val, s); - bool grab = open_box(val); - if (grab && canvas() && !canvas()->hasFocus()) - canvas()->setFocus (Qt::MouseFocusReason); - } - break; - - case SLOT_MOUSE_POINTER: - { - typedef pair T; - check_type (val, s); - T contents = open_box (val); // x1 = name, x2 = mask. - /* - if (contents.x2 == "") // mask == "" - ; // set default pointer. - else // set new pointer - ; - */ - NOT_IMPLEMENTED("qt_simple_widget::SLOT_MOUSE_POINTER"); - } - break; - case SLOT_CURSOR: - { - check_type(val, s); - coord2 p = open_box (val); - canvas()->setCursorPos(to_qpoint(p)); - } - break; - - case SLOT_CURSOR_STYLE: - { - check_type(val, s); - cursor_style style = open_box(val); - if (style == cursor_style::OPENHAND) - canvas()->setCursor (Qt::OpenHandCursor); - else if (style == cursor_style::NORMAL) - canvas()->setCursor (Qt::ArrowCursor); - else if (style == cursor_style::CLOSEHAND) - canvas()->setCursor (Qt::ClosedHandCursor); - else if (style == cursor_style::CROSS) - canvas()->setCursor (Qt::CrossCursor); - else if (style == cursor_style::UP_ARROW) - canvas()->setCursor (Qt::UpArrowCursor); - else if (style == cursor_style::IBEAM) - canvas()->setCursor (Qt::IBeamCursor); - else if (style == cursor_style::WAIT) - canvas()->setCursor (Qt::WaitCursor); - else if (style == cursor_style::FORBIDDEN) - canvas()->setCursor (Qt::ForbiddenCursor); - else if (style == cursor_style::POINTING_HAND) - canvas()->setCursor (Qt::PointingHandCursor); - else if (style == cursor_style::SIZE_VER) - canvas()->setCursor (Qt::SizeVerCursor); - else if (style == cursor_style::SIZE_HOR) - canvas()->setCursor (Qt::SizeHorCursor); - else if (style == cursor_style::SIZE_BDIAG) - canvas()->setCursor (Qt::SizeBDiagCursor); - else if (style == cursor_style::SIZE_FDIAG) - canvas()->setCursor (Qt::SizeFDiagCursor); - else if (style == cursor_style::SIZE_ALL) - canvas()->setCursor (Qt::SizeAllCursor); - else - TM_FAILED ("invalid cursor style"); + SI x1= p.x1, y1= p.x2, x2= p.x3, y2= p.x4; + ren->outer_round (x1, y1, x2, y2); + ren->decode (x1, y1); + ren->decode (x2, y2); + invalidate_rect (x1, y2, x2, y1); } - break; - - default: - qt_widget_rep::send(s, val); - return; + } break; + + case SLOT_INVALIDATE_ALL: { + check_type_void (val, s); + invalidate_all (); + } break; + + case SLOT_EXTENTS: { + check_type (val, s); + coord4 p= open_box (val); + scrollarea ()->setExtents (to_qrect (p)); + } break; + + case SLOT_SIZE: { + check_type (val, s); + coord2 p= open_box (val); + canvas ()->resize (to_qsize (p)); // FIXME? + } break; + + case SLOT_SCROLL_POSITION: { + check_type (val, s); + coord2 p = open_box (val); + QPoint qp= to_qpoint (p); + QSize sz= canvas ()->surface ()->size (); + qp-= QPoint (sz.width () / 2, sz.height () / 2); + // NOTE: adjust because child is centered + scrollarea ()->setOrigin (qp); + } break; + + case SLOT_ZOOM_FACTOR: { + check_type (val, s); + double new_zoom= open_box (val); + canvas ()->tm_widget ()->handle_set_zoom_factor (new_zoom); + } break; + + case SLOT_MOUSE_GRAB: { + check_type (val, s); + bool grab= open_box (val); + if (grab && canvas () && !canvas ()->hasFocus ()) + canvas ()->setFocus (Qt::MouseFocusReason); + } break; + + case SLOT_MOUSE_POINTER: { + typedef pair T; + check_type (val, s); + T contents= open_box (val); // x1 = name, x2 = mask. + /* + if (contents.x2 == "") // mask == "" + ; // set default pointer. + else // set new pointer + ; + */ + NOT_IMPLEMENTED ("qt_simple_widget::SLOT_MOUSE_POINTER"); + } break; + + case SLOT_CURSOR: { + check_type (val, s); + coord2 p= open_box (val); + canvas ()->setCursorPos (to_qpoint (p)); + } break; + + case SLOT_CURSOR_STYLE: { + check_type (val, s); + cursor_style style= open_box (val); + if (style == cursor_style::OPENHAND) + canvas ()->setCursor (Qt::OpenHandCursor); + else if (style == cursor_style::NORMAL) + canvas ()->setCursor (Qt::ArrowCursor); + else if (style == cursor_style::CLOSEHAND) + canvas ()->setCursor (Qt::ClosedHandCursor); + else if (style == cursor_style::CROSS) + canvas ()->setCursor (Qt::CrossCursor); + else if (style == cursor_style::UP_ARROW) + canvas ()->setCursor (Qt::UpArrowCursor); + else if (style == cursor_style::IBEAM) + canvas ()->setCursor (Qt::IBeamCursor); + else if (style == cursor_style::WAIT) canvas ()->setCursor (Qt::WaitCursor); + else if (style == cursor_style::FORBIDDEN) + canvas ()->setCursor (Qt::ForbiddenCursor); + else if (style == cursor_style::POINTING_HAND) + canvas ()->setCursor (Qt::PointingHandCursor); + else if (style == cursor_style::SIZE_VER) + canvas ()->setCursor (Qt::SizeVerCursor); + else if (style == cursor_style::SIZE_HOR) + canvas ()->setCursor (Qt::SizeHorCursor); + else if (style == cursor_style::SIZE_BDIAG) + canvas ()->setCursor (Qt::SizeBDiagCursor); + else if (style == cursor_style::SIZE_FDIAG) + canvas ()->setCursor (Qt::SizeFDiagCursor); + else if (style == cursor_style::SIZE_ALL) + canvas ()->setCursor (Qt::SizeAllCursor); + else TM_FAILED ("invalid cursor style"); + } break; + + default: + qt_widget_rep::send (s, val); + return; } - + if (DEBUG_QT_WIDGETS && s != SLOT_INVALIDATE) debug_widgets << "qt_simple_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + << "\t\tto widget\t" << type_as_string () << LF; } blackbox qt_simple_widget_rep::query (slot s, int type_id) { - // Some slots are too noisy + // Some slots are too noisy if (DEBUG_QT_WIDGETS && (s != SLOT_IDENTIFIER)) - debug_widgets << "qt_simple_widget_rep: queried " << slot_name(s) - << "\t\tto widget\t" << type_as_string() << LF; - + debug_widgets << "qt_simple_widget_rep: queried " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; + switch (s) { - case SLOT_IDENTIFIER: - { - if (qwid) { - widget_rep* wid = qt_window_widget_rep::widget_from_qwidget(qwid); - if (wid) - return wid->query(s, type_id); - } - return close_box(0); - } - case SLOT_INVALID: - { - return close_box (is_invalid()); - } - - case SLOT_POSITION: - { - check_type_id (type_id, s); - // HACK: mapTo() does not work as we expect on the Mac, so we manually - // calculate the global screen cordinates and substract - QPoint sg = scrollarea()->surface()->mapToGlobal (QPoint (0,0)); - QRect wg = scrollarea()->window()->frameGeometry(); - sg.ry() -= wg.y(); - sg.rx() -= wg.x(); - return close_box (from_qpoint (sg)); + case SLOT_IDENTIFIER: { + if (qwid) { + widget_rep* wid= qt_window_widget_rep::widget_from_qwidget (qwid); + if (wid) return wid->query (s, type_id); } - - case SLOT_SIZE: - { - check_type_id (type_id, s); - return close_box (from_qsize (canvas()->size())); - } - - case SLOT_SCROLL_POSITION: - { - check_type_id (type_id, s); - return close_box (from_qpoint (canvas()->origin())); - } - - case SLOT_EXTENTS: - { - check_type_id (type_id, s); - return close_box (from_qrect (canvas()->extents())); + return close_box (0); + } + case SLOT_INVALID: { + return close_box (is_invalid ()); + } + + case SLOT_POSITION: { + check_type_id (type_id, s); + // HACK: mapTo() does not work as we expect on the Mac, so we manually + // calculate the global screen cordinates and substract + QPoint sg= scrollarea ()->surface ()->mapToGlobal (QPoint (0, 0)); + QRect wg= scrollarea ()->window ()->frameGeometry (); + sg.ry ()-= wg.y (); + sg.rx ()-= wg.x (); + return close_box (from_qpoint (sg)); + } + + case SLOT_SIZE: { + check_type_id (type_id, s); + return close_box (from_qsize (canvas ()->size ())); + } + + case SLOT_SCROLL_POSITION: { + check_type_id (type_id, s); + return close_box (from_qpoint (canvas ()->origin ())); + } + + case SLOT_EXTENTS: { + check_type_id (type_id, s); + return close_box (from_qrect (canvas ()->extents ())); + } + + case SLOT_VISIBLE_PART: { + check_type_id (type_id, s); + if (canvas ()) { + QSize sz = canvas ()->surface ()->size (); // sz.setWidth(sz.width()-2); + QPoint pos= backing_pos; + return close_box (from_qrect (QRect (pos, sz))); } - - case SLOT_VISIBLE_PART: - { - check_type_id (type_id, s); - if (canvas()) { - QSize sz = canvas()->surface()->size(); // sz.setWidth(sz.width()-2); - QPoint pos = backing_pos; - return close_box (from_qrect(QRect(pos, sz))); - } else { - return close_box(coord4(0,0,0,0)); - } + else { + return close_box (coord4 (0, 0, 0, 0)); } - - default: - return qt_widget_rep::query(s, type_id); + } + + default: + return qt_widget_rep::query (s, type_id); } } widget qt_simple_widget_rep::read (slot s, blackbox index) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_simple_widget_rep::read " << slot_name(s) - << "\tWidget id: " << id << LF; - + debug_widgets << "qt_simple_widget_rep::read " << slot_name (s) + << "\tWidget id: " << id << LF; + switch (s) { - case SLOT_WINDOW: - check_type_void (index, s); - return qt_window_widget_rep::widget_from_qwidget(qwid); - default: - return qt_widget_rep::read (s, index); + case SLOT_WINDOW: + check_type_void (index, s); + return qt_window_widget_rep::widget_from_qwidget (qwid); + default: + return qt_widget_rep::read (s, index); } } - /****************************************************************************** -* Translation into QAction for insertion in menus (i.e. for buttons) -******************************************************************************/ + * Translation into QAction for insertion in menus (i.e. for buttons) + ******************************************************************************/ // Prints the current contents of the canvas onto a QPixmap QPixmap impress (qt_simple_widget_rep* wid) { int width, height; wid->handle_get_size_hint (width, height); - QSize s = to_qsize (width, height); - QSize phys_s = s; phys_s *= retina_factor; + QSize s = to_qsize (width, height); + QSize phys_s= s; + phys_s*= retina_factor; QPixmap pxm (phys_s); if (DEBUG_QT) - debug_qt << "impress (" << s.width() << "," << s.height() << ")\n"; + debug_qt << "impress (" << s.width () << "," << s.height () << ")\n"; pxm.fill (Qt::transparent); { - qt_renderer_rep *ren = the_qt_renderer(); - ren->begin (static_cast(&pxm)); - rectangle r = rectangle (0, 0, phys_s.width(), phys_s.height()); + qt_renderer_rep* ren= the_qt_renderer (); + ren->begin (static_cast (&pxm)); + rectangle r= rectangle (0, 0, phys_s.width (), phys_s.height ()); ren->set_origin (0, 0); ren->encode (r->x1, r->y1); ren->encode (r->x2, r->y2); ren->set_clipping (r->x1, r->y2, r->x2, r->y1); { - // we do not want to be interrupted here... + // we do not want to be interrupted here... the_gui->set_check_events (false); wid->handle_repaint (ren, r->x1, r->y2, r->x2, r->y1); the_gui->set_check_events (true); } - ren->end(); + ren->end (); } return pxm; } @@ -417,8 +405,8 @@ impress (qt_simple_widget_rep* wid) { QAction* qt_simple_widget_rep::as_qaction () { QAction* a= new QTMAction (NULL); - QPixmap pxm (impress (this)); - QIcon icon (pxm); + QPixmap pxm (impress (this)); + QIcon icon (pxm); a->setIcon (icon); return a; } @@ -427,29 +415,28 @@ qt_simple_widget_rep::as_qaction () { * Backing store management ******************************************************************************/ - void qt_simple_widget_rep::invalidate_rect (int x1, int y1, int x2, int y2) { #ifdef Q_OS_MAC - //HACK: for unknown reasons we need to enlarge the invalid rect to prevent - //artifacts while moving the cursor (for example at the end of a formula like - // $a+f$. These artifacts seems present only on 64 bit Macs. - rectangle r = rectangle (x1-10, y1-10, x2+10, y2+10); + // HACK: for unknown reasons we need to enlarge the invalid rect to prevent + // artifacts while moving the cursor (for example at the end of a formula like + // $a+f$. These artifacts seems present only on 64 bit Macs. + rectangle r= rectangle (x1 - 10, y1 - 10, x2 + 10, y2 + 10); #else - rectangle r = rectangle (x1, y1, x2, y2); + rectangle r= rectangle (x1, y1, x2, y2); #endif // cout << "invalidating " << r << LF; - invalid_regions = invalid_regions | rectangles (r); + invalid_regions= invalid_regions | rectangles (r); } void qt_simple_widget_rep::invalidate_all () { - QSize sz = canvas()->surface()->size(); + QSize sz= canvas ()->surface ()->size (); // QPoint pt = QAbstractScrollArea::viewport()->pos(); - //cout << "invalidate all " << LF; - invalid_regions = rectangles(); - invalidate_rect (0, 0, retina_factor * sz.width(), - retina_factor * sz.height()); + // cout << "invalidate all " << LF; + invalid_regions= rectangles (); + invalidate_rect (0, 0, retina_factor * sz.width (), + retina_factor * sz.height ()); } bool @@ -457,14 +444,11 @@ qt_simple_widget_rep::is_invalid () { return !is_nil (invalid_regions); } - - - basic_renderer -qt_simple_widget_rep::get_renderer() { +qt_simple_widget_rep::get_renderer () { ASSERT (backingPixmap != NULL, - "internal error in qt_simple_widget_rep::get_renderer"); - qt_renderer_rep * ren = the_qt_renderer(); + "internal error in qt_simple_widget_rep::get_renderer"); + qt_renderer_rep* ren= the_qt_renderer (); ren->begin ((void*) backingPixmap); return ren; } @@ -482,94 +466,98 @@ qt_simple_widget_rep::get_renderer() { void qt_simple_widget_rep::repaint_invalid_regions () { - + QRegion qrgn; - QPoint origin = canvas()->origin(); + QPoint origin= canvas ()->origin (); // qrgn is to keep track of the area on the screen which needs to be updated - + // update backing store origin wrt. TeXmacs document if (backing_pos != origin) { - - int dx = retina_factor * (origin.x() - backing_pos.x()); - int dy = retina_factor * (origin.y() - backing_pos.y()); - backing_pos = origin; - - QPixmap newBackingPixmap (backingPixmap->size()); + + int dx = retina_factor * (origin.x () - backing_pos.x ()); + int dy = retina_factor * (origin.y () - backing_pos.y ()); + backing_pos= origin; + + QPixmap newBackingPixmap (backingPixmap->size ()); QPainter p (&newBackingPixmap); - //newBackingPixmap.fill (Qt::black); - p.drawPixmap (-dx,-dy,*backingPixmap); - p.end(); - *backingPixmap = newBackingPixmap; - //cout << "SCROLL CONTENTS BY " << dx << " " << dy << LF; - - + // newBackingPixmap.fill (Qt::black); + p.drawPixmap (-dx, -dy, *backingPixmap); + p.end (); + *backingPixmap= newBackingPixmap; + // cout << "SCROLL CONTENTS BY " << dx << " " << dy << LF; + rectangles invalid; while (!is_nil (invalid_regions)) { - rectangle r = invalid_regions->item ; + rectangle r= invalid_regions->item; // rectangle q = rectangle (r->x1+dx,r->y1-dy,r->x2+dx,r->y2-dy); - rectangle q = rectangle (r->x1-dx,r->y1-dy,r->x2-dx,r->y2-dy); - invalid = rectangles (q, invalid); - //cout << r << " ---> " << q << LF; - invalid_regions = invalid_regions->next; + rectangle q= rectangle (r->x1 - dx, r->y1 - dy, r->x2 - dx, r->y2 - dy); + invalid = rectangles (q, invalid); + // cout << r << " ---> " << q << LF; + invalid_regions= invalid_regions->next; } - - QSize sz = backingPixmap->size(); - - invalid_regions= invalid & rectangles (rectangle (0,0, - sz.width(),sz.height())); - - if (dy<0) - invalidate_rect (0,0,sz.width(),min (sz.height(),-dy)); - else if (dy>0) - invalidate_rect (0,max (0,sz.height()-dy),sz.width(),sz.height()); - - if (dx<0) - invalidate_rect (0,0,min (-dx,sz.width()),sz.height()); - else if (dx>0) - invalidate_rect (max (0,sz.width()-dx),0,sz.width(),sz.height()); - + + QSize sz= backingPixmap->size (); + + invalid_regions= + invalid & rectangles (rectangle (0, 0, sz.width (), sz.height ())); + + if (dy < 0) invalidate_rect (0, 0, sz.width (), min (sz.height (), -dy)); + else if (dy > 0) + invalidate_rect (0, max (0, sz.height () - dy), sz.width (), + sz.height ()); + + if (dx < 0) invalidate_rect (0, 0, min (-dx, sz.width ()), sz.height ()); + else if (dx > 0) + invalidate_rect (max (0, sz.width () - dx), 0, sz.width (), sz.height ()); + // we call update now to allow repainting of invalid regions // this cannot be done directly since interpose_handler needs // to be run at least once in some situations // (for example when scrolling is initiated by TeXmacs itself) - //the_gui->update(); + // the_gui->update(); // QAbstractScrollArea::viewport()->scroll (-dx,-dy); // QAbstractScrollArea::viewport()->update(); - qrgn += QRect (QPoint (0,0),sz); + qrgn+= QRect (QPoint (0, 0), sz); } - - //cout << " repaint QPixmap of size " << backingPixmap.width() << " x " - // << backingPixmap.height() << LF; - // update backing store size + + // cout << " repaint QPixmap of size " << backingPixmap.width() << " x " + // << backingPixmap.height() << LF; + // update backing store size { - QSize _oldSize = backingPixmap->size(); - QSize _new_logical_Size = canvas()->surface()->size(); - QSize _newSize = _new_logical_Size; - _newSize *= retina_factor; - - //cout << " surface size of " << _newSize.width() << " x " - // << _newSize.height() << LF; - - + QSize _oldSize = backingPixmap->size (); + QSize _new_logical_Size= canvas ()->surface ()->size (); + QSize _newSize = _new_logical_Size; + _newSize*= retina_factor; + + // cout << " surface size of " << _newSize.width() << " x " + // << _newSize.height() << LF; + if (_newSize != _oldSize) { // cout << "RESIZING BITMAP"<< LF; - QPixmap newBackingPixmap (_newSize); + QPixmap newBackingPixmap (_newSize); QPainter p (&newBackingPixmap); - p.drawPixmap (0,0,*backingPixmap); - //p.fillRect (0, 0, _newSize.width(), _newSize.height(), Qt::red); - if (_newSize.width() >= _oldSize.width()) { - invalidate_rect (_oldSize.width(), 0, _newSize.width(), _newSize.height()); - p.fillRect (QRect (_oldSize.width(), 0, _newSize.width()-_oldSize.width(), _newSize.height()), Qt::gray); + p.drawPixmap (0, 0, *backingPixmap); + // p.fillRect (0, 0, _newSize.width(), _newSize.height(), Qt::red); + if (_newSize.width () >= _oldSize.width ()) { + invalidate_rect (_oldSize.width (), 0, _newSize.width (), + _newSize.height ()); + p.fillRect (QRect (_oldSize.width (), 0, + _newSize.width () - _oldSize.width (), + _newSize.height ()), + Qt::gray); } - if (_newSize.height() >= _oldSize.height()) { - invalidate_rect (0,_oldSize.height(), _newSize.width(), _newSize.height()); - p.fillRect (QRect (0,_oldSize.height(), _newSize.width(), _newSize.height()-_oldSize.height()), Qt::gray); + if (_newSize.height () >= _oldSize.height ()) { + invalidate_rect (0, _oldSize.height (), _newSize.width (), + _newSize.height ()); + p.fillRect (QRect (0, _oldSize.height (), _newSize.width (), + _newSize.height () - _oldSize.height ()), + Qt::gray); } - p.end(); - *backingPixmap = newBackingPixmap; + p.end (); + *backingPixmap= newBackingPixmap; } } - + // repaint invalid rectangles { rectangles new_regions; @@ -577,54 +565,55 @@ qt_simple_widget_rep::repaint_invalid_regions () { rectangle lub= least_upper_bound (invalid_regions); if (area (lub) < 1.2 * area (invalid_regions)) invalid_regions= rectangles (lub); - - basic_renderer_rep* ren = get_renderer(); - - coord2 pt_or = from_qpoint(backing_pos); - SI ox = -pt_or.x1; - SI oy = -pt_or.x2; - - rectangles rects = invalid_regions; - invalid_regions = rectangles(); - + + basic_renderer_rep* ren= get_renderer (); + + coord2 pt_or= from_qpoint (backing_pos); + SI ox = -pt_or.x1; + SI oy = -pt_or.x2; + + rectangles rects= invalid_regions; + invalid_regions = rectangles (); + while (!is_nil (rects)) { rectangle r = copy (rects->item); - rectangle r0 = rects->item; - QRect qr = QRect (r0->x1 / retina_factor, r0->y1 / retina_factor, - (r0->x2 - r0->x1) / retina_factor, - (r0->y2 - r0->y1) / retina_factor); - //cout << "repainting " << r0 << "\n"; + rectangle r0= rects->item; + QRect qr= QRect (r0->x1 / retina_factor, r0->y1 / retina_factor, + (r0->x2 - r0->x1) / retina_factor, + (r0->y2 - r0->y1) / retina_factor); + // cout << "repainting " << r0 << "\n"; ren->set_origin (ox, oy); ren->encode (r->x1, r->y1); ren->encode (r->x2, r->y2); ren->set_clipping (r->x1, r->y2, r->x2, r->y1); handle_repaint (ren, r->x1, r->y2, r->x2, r->y1); if (gui_interrupted ()) { - //cout << "interrupted repainting of " << r0 << "\n"; - //ren->set_pencil (green); - //ren->line (r->x1, r->y1, r->x2, r->y2); - //ren->line (r->x1, r->y2, r->x2, r->y1); + // cout << "interrupted repainting of " << r0 << "\n"; + // ren->set_pencil (green); + // ren->line (r->x1, r->y1, r->x2, r->y2); + // ren->line (r->x1, r->y2, r->x2, r->y1); invalidate_rect (r0->x1, r0->y1, r0->x2, r0->y2); } - qrgn += qr; - rects = rects->next; + qrgn+= qr; + rects= rects->next; } - - ren->end(); + + ren->end (); } // !is_nil (invalid_regions) } - + // propagate immediately the changes to the screen - canvas()->surface()->repaint (qrgn); + canvas ()->surface ()->repaint (qrgn); } hashset qt_simple_widget_rep::all_widgets; void qt_simple_widget_rep::repaint_all () { - iterator i = iterate(qt_simple_widget_rep::all_widgets); - while (i->busy()) { - qt_simple_widget_rep *w = static_cast(i->next()); - if (w->canvas() && w->canvas()->isVisible()) w->repaint_invalid_regions(); + iterator i= iterate (qt_simple_widget_rep::all_widgets); + while (i->busy ()) { + qt_simple_widget_rep* w= static_cast (i->next ()); + if (w->canvas () && w->canvas ()->isVisible ()) + w->repaint_invalid_regions (); } } diff --git a/src/Plugins/Qt/qt_simple_widget.hpp b/src/Plugins/Qt/qt_simple_widget.hpp index 9175978bc3..656837f80b 100644 --- a/src/Plugins/Qt/qt_simple_widget.hpp +++ b/src/Plugins/Qt/qt_simple_widget.hpp @@ -1,61 +1,60 @@ /****************************************************************************** -* MODULE : qt_simple_widget.hpp -* DESCRIPTION: A widget containing a TeXmacs canvas. -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_simple_widget.hpp + * DESCRIPTION: A widget containing a TeXmacs canvas. + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_SIMPLE_WIDGET_HPP #define QT_SIMPLE_WIDGET_HPP -#include "hashset.hpp" #include "basic_renderer.hpp" +#include "hashset.hpp" -#include "qt_widget.hpp" #include "QTMScrollView.hpp" #include "QTMWidget.hpp" +#include "qt_widget.hpp" /*! A widget containing a TeXmacs canvas. - - This canvas can be used both for input or output of typesetted documents. + + This canvas can be used both for input or output of typesetted documents. Editors (editor_rep), output-only widgets (box_widget_rep) and other classes are extensions to a "simple_widget", quite a misnomer... - + MEMORY POLICY: as usual, we give ownership of the QWidget to the caller of - as_qwidget(), which in our case will be one of qt_tm_widget_rep or + as_qwidget(), which in our case will be one of qt_tm_widget_rep or qt_tm_embedded_rep. These will embed our QWidget in a QLayout who will reparent it to the QWidget using the layout (e.g. QTMWindow::centralWidget()) */ -class qt_simple_widget_rep: public qt_widget_rep { +class qt_simple_widget_rep : public qt_widget_rep { + + // We keep a pointer to ourselves to avoid accidental deletion by our own + // QTMWidget, who keeps a smart pointer to us. + // (not sure whether this works/is necessary, though) + // qt_widget self; - // We keep a pointer to ourselves to avoid accidental deletion by our own - // QTMWidget, who keeps a smart pointer to us. - // (not sure whether this works/is necessary, though) - //qt_widget self; - typedef struct t_slot_entry { - int seq; - slot_id id; + int seq; + slot_id id; blackbox val; - t_slot_entry() : seq(-1), id (slot_id__LAST), val (blackbox()) { } - t_slot_entry(const t_slot_entry& other) - : seq (other.seq), id (other.id), val (other.val) { }; + t_slot_entry () : seq (-1), id (slot_id__LAST), val (blackbox ()) {} + t_slot_entry (const t_slot_entry& other) + : seq (other.seq), id (other.id), val (other.val){}; bool operator< (const t_slot_entry& b) const { return this->seq < b.seq; } } t_slot_entry; - + t_slot_entry sent_slots[slot_id__LAST]; - + int sequencer; - - + public: qt_simple_widget_rep (); ~qt_simple_widget_rep (); - + virtual bool is_editor_widget (); virtual void handle_get_size_hint (SI& w, SI& h); virtual void handle_notify_resize (SI w, SI h); @@ -66,53 +65,52 @@ class qt_simple_widget_rep: public qt_widget_rep { virtual void handle_set_zoom_factor (double zoom); virtual void handle_clear (renderer win, SI x1, SI y1, SI x2, SI y2); virtual void handle_repaint (renderer win, SI x1, SI y1, SI x2, SI y2); - - ////////////////////// Handling of TeXmacs' messages - - void save_send_slot (slot s, blackbox val); - void reapply_sent_slots(); - virtual void send (slot s, blackbox val); + + ////////////////////// Handling of TeXmacs' messages + + void save_send_slot (slot s, blackbox val); + void reapply_sent_slots (); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); - - ////////////////////// Qt semantics of abstract texmacs widgets + virtual widget read (slot s, blackbox index); - virtual QAction* as_qaction(); - virtual QWidget* as_qwidget(); - - ////////////////////// Qt widget counterparts + ////////////////////// Qt semantics of abstract texmacs widgets - QTMWidget* canvas () { return qobject_cast (qwid); } + virtual QAction* as_qaction (); + virtual QWidget* as_qwidget (); + + ////////////////////// Qt widget counterparts + + QTMWidget* canvas () { return qobject_cast (qwid); } QTMScrollView* scrollarea () { return qobject_cast (qwid); } - ////////////////////// backing store management + ////////////////////// backing store management static void repaint_all (); // called by qt_gui_rep::update() protected: - static hashset all_widgets; - rectangles invalid_regions; - QPixmap* backingPixmap; - QPoint backing_pos; - - - void invalidate_rect (int x1, int y1, int x2, int y2); - void invalidate_all (); - bool is_invalid (); - void repaint_invalid_regions (); - basic_renderer get_renderer(); - - + rectangles invalid_regions; + QPixmap* backingPixmap; + QPoint backing_pos; + + void invalidate_rect (int x1, int y1, int x2, int y2); + void invalidate_all (); + bool is_invalid (); + void repaint_invalid_regions (); + basic_renderer get_renderer (); + friend class QTMWidget; }; -inline qt_simple_widget_rep* concrete_simple_widget (qt_widget w) { - return static_cast(w.rep); +inline qt_simple_widget_rep* +concrete_simple_widget (qt_widget w) { + return static_cast (w.rep); } -inline qt_simple_widget_rep* concrete_simple_widget (widget w) { - return static_cast(w.rep); +inline qt_simple_widget_rep* +concrete_simple_widget (widget w) { + return static_cast (w.rep); } // Export for TeXmacs' use diff --git a/src/Plugins/Qt/qt_sys_utils.cpp b/src/Plugins/Qt/qt_sys_utils.cpp index 9404e8952e..d587fcbc1e 100644 --- a/src/Plugins/Qt/qt_sys_utils.cpp +++ b/src/Plugins/Qt/qt_sys_utils.cpp @@ -1,42 +1,45 @@ /****************************************************************************** -* MODULE : qt_sys_utils.cpp -* DESCRIPTION: external command launcher -* COPYRIGHT : (C) 2009, 2016 David MICHEL, Denis Raux -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_sys_utils.cpp + * DESCRIPTION: external command launcher + * COPYRIGHT : (C) 2009, 2016 David MICHEL, Denis Raux + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #include "qt_sys_utils.hpp" -#include "qt_utilities.hpp" #include "basic.hpp" +#include "file.hpp" +#include "qt_utilities.hpp" #include "string.hpp" #include "tm_debug.hpp" -#include "file.hpp" +#include #include #include #include -#include #include - -string qt_get_current_cpu_arch () { +string +qt_get_current_cpu_arch () { return from_qstring (QSysInfo::currentCpuArchitecture ()); } -string qt_get_pretty_os_name () { +string +qt_get_pretty_os_name () { return from_qstring (QSysInfo::prettyProductName ()); } -void qt_open_url (url u) { +void +qt_open_url (url u) { if (is_rooted_web (u) || is_rooted (u, "file")) { - QString link = to_qstring (as_string (u)); + QString link= to_qstring (as_string (u)); QDesktopServices::openUrl (QUrl (link)); - } else if (is_local_and_single (u)) { - QString link = to_qstring ("file:///" * as_string (u)); + } + else if (is_local_and_single (u)) { + QString link= to_qstring ("file:///" * as_string (u)); QDesktopServices::openUrl (QUrl (link)); } } diff --git a/src/Plugins/Qt/qt_sys_utils.hpp b/src/Plugins/Qt/qt_sys_utils.hpp index 951de90b27..d2ec0d85a2 100644 --- a/src/Plugins/Qt/qt_sys_utils.hpp +++ b/src/Plugins/Qt/qt_sys_utils.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : qt_sys_utils.hpp -* DESCRIPTION: external command handling -* COPYRIGHT : (C) 2009-2016 David MICHEL, Denis RAUX -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_sys_utils.hpp + * DESCRIPTION: external command handling + * COPYRIGHT : (C) 2009-2016 David MICHEL, Denis RAUX + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_SYS_UTILS_H #define QT_SYS_UTILS_H @@ -15,7 +15,6 @@ #include "string.hpp" #include "url.hpp" - string qt_get_current_cpu_arch (); string qt_get_pretty_os_name (); diff --git a/src/Plugins/Qt/qt_tm_widget.cpp b/src/Plugins/Qt/qt_tm_widget.cpp index e7e1233d16..8000304822 100644 --- a/src/Plugins/Qt/qt_tm_widget.cpp +++ b/src/Plugins/Qt/qt_tm_widget.cpp @@ -9,55 +9,55 @@ * in the root directory or . ******************************************************************************/ -#include -#include -#include #include -#include +#include #include +#include #include #include -#include +#include +#include +#include -#include "config.h" #include "analyze.hpp" +#include "config.h" #include "scheme.hpp" -#include "qt_tm_widget.hpp" -#include "qt_utilities.hpp" -#include "qt_renderer.hpp" #include "qt_gui.hpp" #include "qt_picture.hpp" +#include "qt_renderer.hpp" +#include "qt_tm_widget.hpp" +#include "qt_utilities.hpp" +#include "QTMGuiHelper.hpp" // needed to connect() +#include "QTMInteractiveInputHelper.hpp" +#include "QTMInteractivePrompt.hpp" +#include "QTMStyle.hpp" // qtstyle() +#include "QTMWindow.hpp" #include "qt_dialogues.hpp" +#include "qt_menu.hpp" #include "qt_simple_widget.hpp" #include "qt_window_widget.hpp" -#include "qt_menu.hpp" -#include "QTMWindow.hpp" -#include "QTMStyle.hpp" // qtstyle() -#include "QTMGuiHelper.hpp" // needed to connect() -#include "QTMInteractivePrompt.hpp" -#include "QTMInteractiveInputHelper.hpp" -int menu_count = 0; // zero if no menu is currently being displayed +int menu_count= 0; // zero if no menu is currently being displayed list waiting_widgets; static void -replaceActions (QWidget* dest, QList* src) { - //NOTE: the parent hierarchy of the actions is not modified while installing - // the menu in the GUI (see qt_menu.hpp for this memory management - // policy) +replaceActions (QWidget* dest, QList* src) { + // NOTE: the parent hierarchy of the actions is not modified while installing + // the menu in the GUI (see qt_menu.hpp for this memory management + // policy) if (src == NULL || dest == NULL) TM_FAILED ("replaceActions expects valid objects"); dest->setUpdatesEnabled (false); - QList list = dest->actions(); - for (int i = 0; i < list.count(); i++) { - QAction* a = list[i]; + QList list= dest->actions (); + for (int i= 0; i < list.count (); i++) { + QAction* a= list[i]; dest->removeAction (a); } - for (int i = 0; i < src->count(); i++) { - QAction* a = (*src)[i]; - dest->addAction(a); + for (int i= 0; i < src->count (); i++) { + QAction* a= (*src)[i]; + dest->addAction (a); } dest->setUpdatesEnabled (true); } @@ -67,116 +67,112 @@ replaceButtons (QToolBar* dest, QList* src) { if (src == NULL || dest == NULL) TM_FAILED ("replaceButtons expects valid objects"); dest->setUpdatesEnabled (false); - bool visible = dest->isVisible(); - if (visible) dest->hide(); //TRICK: to avoid flicker of the dest widget + bool visible= dest->isVisible (); + if (visible) dest->hide (); // TRICK: to avoid flicker of the dest widget replaceActions (dest, src); - QList list = dest->children(); - for (int i = 0; i < list.count(); ++i) { - QToolButton* button = qobject_cast (list[i]); + QList list= dest->children (); + for (int i= 0; i < list.count (); ++i) { + QToolButton* button= qobject_cast (list[i]); if (button) { button->setPopupMode (QToolButton::InstantPopup); - if (tm_style_sheet == "") - button->setStyle (qtmstyle()); + if (tm_style_sheet == "") button->setStyle (qtmstyle ()); } } - if (visible) dest->show(); //TRICK: see above + if (visible) dest->show (); // TRICK: see above dest->setUpdatesEnabled (true); } void QTMInteractiveInputHelper::commit (int result) { if (wid && result == QDialog::Accepted) { - QString item = "#f"; - QComboBox* cb = sender()->findChild ("input"); - if (cb) item = cb->currentText(); - static_cast(wid->int_input.rep)->input = - from_qstring (item); - static_cast(wid->int_input.rep)->cmd (); + QString item= "#f"; + QComboBox* cb = sender ()->findChild ("input"); + if (cb) item= cb->currentText (); + static_cast (wid->int_input.rep)->input= + from_qstring (item); + static_cast (wid->int_input.rep)->cmd (); } - sender()->deleteLater(); + sender ()->deleteLater (); } - /****************************************************************************** -* qt_tm_widget_rep -******************************************************************************/ + * qt_tm_widget_rep + ******************************************************************************/ + +qt_tm_widget_rep::qt_tm_widget_rep (int mask, command _quit) + : qt_window_widget_rep (new QTMWindow (0), "popup", _quit), helper (this), + prompt (NULL), full_screen (false) { + type= texmacs_widget; -qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) - : qt_window_widget_rep (new QTMWindow (0), "popup", _quit), helper (this), - prompt (NULL), full_screen (false) -{ - type = texmacs_widget; + main_widget= concrete (::glue_widget (true, true, 1, 1)); - main_widget = concrete (::glue_widget (true, true, 1, 1)); - // decode mask - visibility[0] = (mask & 1) == 1; // header - visibility[1] = (mask & 2) == 2; // main - visibility[2] = (mask & 4) == 4; // mode - visibility[3] = (mask & 8) == 8; // focus - visibility[4] = (mask & 16) == 16; // user - visibility[5] = (mask & 32) == 32; // footer - visibility[6] = (mask & 64) == 64; // side tools #0 - visibility[7] = (mask & 128) == 128; // bottom tools + visibility[0]= (mask & 1) == 1; // header + visibility[1]= (mask & 2) == 2; // main + visibility[2]= (mask & 4) == 4; // mode + visibility[3]= (mask & 8) == 8; // focus + visibility[4]= (mask & 16) == 16; // user + visibility[5]= (mask & 32) == 32; // footer + visibility[6]= (mask & 64) == 64; // side tools #0 + visibility[7]= (mask & 128) == 128; // bottom tools #ifdef OS_WASM - visibility[1] = false; // main - visibility[2] = false; // mode - visibility[3] = false; // focus - visibility[4] = false; // user + visibility[1]= false; // main + visibility[2]= false; // mode + visibility[3]= false; // focus + visibility[4]= false; // user #endif // general setup for main window - + QMainWindow* mw= mainwindow (); if (tm_style_sheet == "") { mw->setStyle (qtmstyle ()); - mw->menuBar()->setStyle (qtmstyle ()); + mw->menuBar ()->setStyle (qtmstyle ()); } #ifdef Q_OS_MAC if (!use_native_menubar) { - mw->menuBar()->setNativeMenuBar(false); + mw->menuBar ()->setNativeMenuBar (false); if (tm_style_sheet != "") { int min_h= (int) floor (28 * retina_scale); - mw->menuBar()->setMinimumHeight (min_h); + mw->menuBar ()->setMinimumHeight (min_h); } } #else if (tm_style_sheet != "") { int min_h= (int) floor (28 * retina_scale); - mw->menuBar()->setMinimumHeight (min_h); + mw->menuBar ()->setMinimumHeight (min_h); } #endif mw->setIconSize (QSize (17, 17)); mw->setFocusPolicy (Qt::NoFocus); - + // status bar - - QStatusBar* bar= new QStatusBar(mw); - leftLabel= new QLabel (qt_translate ("Welcome to TeXmacs"), mw); - rightLabel= new QLabel (qt_translate ("Booting"), mw); + + QStatusBar* bar= new QStatusBar (mw); + leftLabel = new QLabel (qt_translate ("Welcome to TeXmacs"), mw); + rightLabel = new QLabel (qt_translate ("Booting"), mw); leftLabel->setFrameStyle (QFrame::NoFrame); rightLabel->setFrameStyle (QFrame::NoFrame); leftLabel->setIndent (8); bar->addWidget (leftLabel, 1); bar->addPermanentWidget (rightLabel); - if (tm_style_sheet == "") - bar->setStyle (qtmstyle ()); - - // NOTE (mg): the following setMinimumWidth command disable automatic - // enlarging of the status bar and consequently of the main window due to + if (tm_style_sheet == "") bar->setStyle (qtmstyle ()); + + // NOTE (mg): the following setMinimumWidth command disable automatic + // enlarging of the status bar and consequently of the main window due to // long messages in the left label. I found this strange solution here // http://www.archivum.info/qt-interest@trolltech.com/2007-05/01453/Re:-QStatusBar-size.html // The solution if due to Martin Petricek. He adds: - // The docs says: If minimumSize() is set, the minimum size hint will be ignored. - // Probably the minimum size hint was size of the lengthy message and - // internal layout was enlarging the satusbar and the main window - // Maybe the notice about QLayout that is at minimumSizeHint should be - // also at minimumSize, didn't notice it first time and spend lot of time - // trying to figure this out :) - + // The docs says: If minimumSize() is set, the minimum size hint will be + // ignored. Probably the minimum size hint was size of the lengthy message + // and internal layout was enlarging the satusbar and the main window Maybe + // the notice about QLayout that is at minimumSizeHint should be also at + // minimumSize, didn't notice it first time and spend lot of time trying to + // figure this out :) + bar->setMinimumWidth (2); #ifdef Q_OS_LINUX int min_h= (int) floor (28 * retina_scale); @@ -188,23 +184,23 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) } #endif mw->setStatusBar (bar); - + // toolbars - - mainToolBar = new QToolBar ("main toolbar", mw); - modeToolBar = new QToolBar ("mode toolbar", mw); - focusToolBar = new QToolBar ("focus toolbar", mw); - userToolBar = new QToolBar ("user toolbar", mw); - - bottomTools = new QDockWidget ("bottom tools", mw); - sideTools = new QDockWidget ("side tools", 0); - // HACK: Wrap the dock in a "fake" window widget (last parameter = true) to - // have clicks report the right position. - static int cnt=0; - string dock_name = "dock:" * as_string(cnt++); - dock_window_widget = tm_new (sideTools, dock_name, - command(), true); - + + mainToolBar = new QToolBar ("main toolbar", mw); + modeToolBar = new QToolBar ("mode toolbar", mw); + focusToolBar= new QToolBar ("focus toolbar", mw); + userToolBar = new QToolBar ("user toolbar", mw); + + bottomTools= new QDockWidget ("bottom tools", mw); + sideTools = new QDockWidget ("side tools", 0); + // HACK: Wrap the dock in a "fake" window widget (last parameter = true) to + // have clicks report the right position. + static int cnt = 0; + string dock_name= "dock:" * as_string (cnt++); + dock_window_widget= + tm_new (sideTools, dock_name, command (), true); + if (tm_style_sheet == "") { mainToolBar->setStyle (qtmstyle ()); modeToolBar->setStyle (qtmstyle ()); @@ -213,17 +209,17 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) sideTools->setStyle (qtmstyle ()); bottomTools->setStyle (qtmstyle ()); } - + { // set proper sizes for icons double scale= max (retina_scale, (double) retina_icons); - QSize sz= QSize (int(24*scale), int(24*scale)); + QSize sz = QSize (int (24 * scale), int (24 * scale)); tweak_iconbar_size (sz); mainToolBar->setIconSize (sz); - sz= QSize (int(20*scale), int(20*scale)); + sz= QSize (int (20 * scale), int (20 * scale)); tweak_iconbar_size (sz); modeToolBar->setIconSize (sz); - sz= QSize (int(16*scale), int(16*scale)); + sz= QSize (int (16 * scale), int (16 * scale)); tweak_iconbar_size (sz); focusToolBar->setIconSize (sz); } @@ -236,7 +232,7 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) // // NOTICE: setFixedHeight must be after setIconSize // TODO: the size of the toolbar should be calculated dynamically -#if defined (Q_OS_MAC) || defined (Q_OS_WIN) +#if defined(Q_OS_MAC) || defined(Q_OS_WIN) int toolbarHeight= 30 * retina_icons; mainToolBar->setFixedHeight (toolbarHeight + 8 * retina_icons); modeToolBar->setFixedHeight (toolbarHeight + 4 * retina_icons); @@ -249,27 +245,29 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) #endif if (tm_style_sheet != "") { double scale= retina_scale; - int h1= (int) floor (38 * scale + 0.5); - int h2= (int) floor (34 * scale + 0.5); - int h3= (int) floor (30 * scale + 0.5); + int h1 = (int) floor (38 * scale + 0.5); + int h2 = (int) floor (34 * scale + 0.5); + int h3 = (int) floor (30 * scale + 0.5); mainToolBar->setFixedHeight (h1); modeToolBar->setFixedHeight (h2); focusToolBar->setFixedHeight (h3); } - - QWidget *cw= new QWidget(); - cw->setObjectName("centralWidget"); // this is important for styling toolbars. - - // The main layout - - QVBoxLayout *bl = new QVBoxLayout (cw); + + QWidget* cw= new QWidget (); + cw->setObjectName ( + "centralWidget"); // this is important for styling toolbars. + + // The main layout + + QVBoxLayout* bl= new QVBoxLayout (cw); bl->setContentsMargins (0, 1, 0, 0); bl->setSpacing (0); cw->setLayout (bl); - QWidget* q = main_widget->as_qwidget(); // force creation of QWidget - q->setParent (qwid); // q->layout()->removeWidget(q) will reset the parent to this + QWidget* q= main_widget->as_qwidget (); // force creation of QWidget + q->setParent ( + qwid); // q->layout()->removeWidget(q) will reset the parent to this bl->addWidget (q); - + mw->setCentralWidget (cw); mainToolBar->setObjectName ("mainToolBar"); @@ -282,48 +280,47 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) #ifdef UNIFIED_TOOLBAR if (use_unified_toolbar) { - mw->setUnifiedTitleAndToolBarOnMac(true); - - //WARNING: dumbToolBar is the toolbar installed on the top area of the - //main widget which is then unified in the title bar. - //to overcome some limitations of the unified toolbar implementation we - //install the real toolbars as widgets in this toolbar. - - dumbToolBar = mw->addToolBar("dumb toolbar"); - dumbToolBar->setMinimumHeight(30); - - //these are the actions related to the various toolbars to be installed in - //the dumb toolbar. - - mainToolBarAction = dumbToolBar->addWidget(mainToolBar); - modeToolBarAction = NULL; - - + mw->setUnifiedTitleAndToolBarOnMac (true); + + // WARNING: dumbToolBar is the toolbar installed on the top area of the + // main widget which is then unified in the title bar. + // to overcome some limitations of the unified toolbar implementation we + // install the real toolbars as widgets in this toolbar. + + dumbToolBar= mw->addToolBar ("dumb toolbar"); + dumbToolBar->setMinimumHeight (30); + + // these are the actions related to the various toolbars to be installed in + // the dumb toolbar. + + mainToolBarAction= dumbToolBar->addWidget (mainToolBar); + modeToolBarAction= NULL; + // A ruler - rulerWidget = new QWidget(cw); - rulerWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); - rulerWidget->setMinimumHeight(1); - rulerWidget->setBackgroundRole(QPalette::Mid); + rulerWidget= new QWidget (cw); + rulerWidget->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Fixed); + rulerWidget->setMinimumHeight (1); + rulerWidget->setBackgroundRole (QPalette::Mid); // FIXME: how to use 112 (active) and 146 (passive) - rulerWidget->setVisible(false); - rulerWidget->setAutoFillBackground(true); + rulerWidget->setVisible (false); + rulerWidget->setAutoFillBackground (true); // rulerWidget = new QLabel("pippo", cw); - + // A second ruler (this one always visible) to separate from the canvas. - QWidget* r2 = new QWidget(mw); - r2->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); - r2->setMinimumHeight(1); - r2->setBackgroundRole(QPalette::Mid); - r2->setVisible(true); - r2->setAutoFillBackground(true); - - bl->insertWidget(0, modeToolBar); - bl->insertWidget(1, rulerWidget); - bl->insertWidget(2, focusToolBar); - bl->insertWidget(3, userToolBar); - bl->insertWidget(5, r2); - - //mw->setContentsMargins (-2, -2, -2, -2); // Why this? + QWidget* r2= new QWidget (mw); + r2->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Fixed); + r2->setMinimumHeight (1); + r2->setBackgroundRole (QPalette::Mid); + r2->setVisible (true); + r2->setAutoFillBackground (true); + + bl->insertWidget (0, modeToolBar); + bl->insertWidget (1, rulerWidget); + bl->insertWidget (2, focusToolBar); + bl->insertWidget (3, userToolBar); + bl->insertWidget (5, r2); + + // mw->setContentsMargins (-2, -2, -2, -2); // Why this? bar->setContentsMargins (0, 1, 0, 1); } else { @@ -350,54 +347,52 @@ qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit) sideTools->setAllowedAreas (Qt::AllDockWidgetAreas); sideTools->setFeatures (QDockWidget::DockWidgetMovable | - QDockWidget::DockWidgetFloatable); + QDockWidget::DockWidgetFloatable); sideTools->setFloating (false); - sideTools->setTitleBarWidget (new QWidget()); // Disables title bar + sideTools->setTitleBarWidget (new QWidget ()); // Disables title bar mw->addDockWidget (Qt::RightDockWidgetArea, sideTools); bottomTools->setAllowedAreas (Qt::BottomDockWidgetArea); bottomTools->setFeatures (QDockWidget::NoDockWidgetFeatures); bottomTools->setFloating (false); - bottomTools->setTitleBarWidget (new QWidget()); // Disables title bar - bottomTools->setMinimumHeight (10); // Avoids warning - bottomTools->setContentsMargins (3, 6, 3, -2); // Hacks hacks hacks... :( + bottomTools->setTitleBarWidget (new QWidget ()); // Disables title bar + bottomTools->setMinimumHeight (10); // Avoids warning + bottomTools->setContentsMargins (3, 6, 3, -2); // Hacks hacks hacks... :( mw->addDockWidget (Qt::BottomDockWidgetArea, bottomTools); - - // FIXME? add DockWidgetClosable and connect the close signal - // to the scheme code - // QObject::connect(sideDock, SIGNAL(closeEvent()), - // someHelper, SLOT(call_scheme_hide_side_tools())); + // FIXME? add DockWidgetClosable and connect the close signal + // to the scheme code + // QObject::connect(sideDock, SIGNAL(closeEvent()), + // someHelper, SLOT(call_scheme_hide_side_tools())); - // handles visibility // at this point all the toolbars are empty so we avoid showing them // same for the menu bar if we are not on the Mac (where we do not have // other options) - + mainToolBar->setVisible (false); modeToolBar->setVisible (false); focusToolBar->setVisible (false); userToolBar->setVisible (false); sideTools->setVisible (false); bottomTools->setVisible (false); - mainwindow()->statusBar()->setVisible (true); + mainwindow ()->statusBar ()->setVisible (true); #ifndef Q_OS_MAC - mainwindow()->menuBar()->setVisible (false); + mainwindow ()->menuBar ()->setVisible (false); #endif QPalette pal; - QColor bgcol= to_qcolor (tm_background); + QColor bgcol= to_qcolor (tm_background); pal.setColor (QPalette::Mid, bgcol); - mainwindow()->setPalette(pal); + mainwindow ()->setPalette (pal); } qt_tm_widget_rep::~qt_tm_widget_rep () { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_tm_widget_rep::~qt_tm_widget_rep of widget " - << type_as_string() << LF; - - // clear any residual waiting menu installation - waiting_widgets = remove(waiting_widgets, this); + << type_as_string () << LF; + + // clear any residual waiting menu installation + waiting_widgets= remove (waiting_widgets, this); } void @@ -426,415 +421,378 @@ qt_tm_widget_rep::tweak_iconbar_size (QSize& sz) { sz.setHeight (sz.height () + 2); } #endif - //sz.setHeight ((int) floor (sz.height () * retina_scale + 0.5)); + // sz.setHeight ((int) floor (sz.height () * retina_scale + 0.5)); } - /*! Return ourselves as a window widget. \param name A unique identifier for the window (e.g. "TeXmacs:3") */ widget qt_tm_widget_rep::plain_window_widget (string name, command _quit, int b) { (void) b; - (void) _quit; // The widget already has a command. Don't overwrite. - orig_name = name; + (void) _quit; // The widget already has a command. Don't overwrite. + orig_name= name; return this; } void qt_tm_widget_rep::update_visibility () { -#define XOR(exp1,exp2) (((!exp1) && (exp2)) || ((exp1) && (!exp2))) - - bool old_mainVisibility = mainToolBar->isVisible(); - bool old_modeVisibility = modeToolBar->isVisible(); - bool old_focusVisibility = focusToolBar->isVisible(); - bool old_userVisibility = userToolBar->isVisible(); - bool old_sideVisibility = sideTools->isVisible(); - bool old_bottomVisibility = bottomTools->isVisible(); - bool old_statusVisibility = mainwindow()->statusBar()->isVisible(); - - bool new_mainVisibility = visibility[1] && visibility[0]; - bool new_modeVisibility = visibility[2] && visibility[0]; +#define XOR(exp1, exp2) (((!exp1) && (exp2)) || ((exp1) && (!exp2))) + + bool old_mainVisibility = mainToolBar->isVisible (); + bool old_modeVisibility = modeToolBar->isVisible (); + bool old_focusVisibility = focusToolBar->isVisible (); + bool old_userVisibility = userToolBar->isVisible (); + bool old_sideVisibility = sideTools->isVisible (); + bool old_bottomVisibility= bottomTools->isVisible (); + bool old_statusVisibility= mainwindow ()->statusBar ()->isVisible (); + + bool new_mainVisibility = visibility[1] && visibility[0]; + bool new_modeVisibility = visibility[2] && visibility[0]; bool new_focusVisibility = visibility[3] && visibility[0]; - bool new_userVisibility = visibility[4] && visibility[0]; - bool new_statusVisibility = visibility[5]; - bool new_sideVisibility = visibility[6]; - bool new_bottomVisibility = visibility[7]; - - if ( XOR(old_mainVisibility, new_mainVisibility) ) + bool new_userVisibility = visibility[4] && visibility[0]; + bool new_statusVisibility= visibility[5]; + bool new_sideVisibility = visibility[6]; + bool new_bottomVisibility= visibility[7]; + + if (XOR (old_mainVisibility, new_mainVisibility)) mainToolBar->setVisible (new_mainVisibility); - if ( XOR(old_modeVisibility, new_modeVisibility) ) + if (XOR (old_modeVisibility, new_modeVisibility)) modeToolBar->setVisible (new_modeVisibility); - if ( XOR(old_focusVisibility, new_focusVisibility) ) + if (XOR (old_focusVisibility, new_focusVisibility)) focusToolBar->setVisible (new_focusVisibility); - if ( XOR(old_userVisibility, new_userVisibility) ) + if (XOR (old_userVisibility, new_userVisibility)) userToolBar->setVisible (new_userVisibility); - if ( XOR(old_sideVisibility, new_sideVisibility) ) + if (XOR (old_sideVisibility, new_sideVisibility)) sideTools->setVisible (new_sideVisibility); - if ( XOR(old_bottomVisibility, new_bottomVisibility) ) + if (XOR (old_bottomVisibility, new_bottomVisibility)) bottomTools->setVisible (new_bottomVisibility); - if ( XOR(old_statusVisibility, new_statusVisibility) ) - mainwindow()->statusBar()->setVisible (new_statusVisibility); + if (XOR (old_statusVisibility, new_statusVisibility)) + mainwindow ()->statusBar ()->setVisible (new_statusVisibility); #ifndef Q_OS_MAC - bool old_menuVisibility = mainwindow()->menuBar()->isVisible(); - bool new_menuVisibility = visibility[0]; + bool old_menuVisibility= mainwindow ()->menuBar ()->isVisible (); + bool new_menuVisibility= visibility[0]; - if ( XOR(old_menuVisibility, new_menuVisibility) ) - mainwindow()->menuBar()->setVisible (new_menuVisibility); + if (XOR (old_menuVisibility, new_menuVisibility)) + mainwindow ()->menuBar ()->setVisible (new_menuVisibility); #endif -//#if 0 +// #if 0 #ifdef UNIFIED_TOOLBAR // do modifications only if needed to reduce flicker - if (use_unified_toolbar && - (XOR(old_mainVisibility, new_mainVisibility) || - XOR(old_modeVisibility, new_modeVisibility) )) - { + if (use_unified_toolbar && (XOR (old_mainVisibility, new_mainVisibility) || + XOR (old_modeVisibility, new_modeVisibility))) { // ensure that the topmost visible toolbar is always unified on Mac // (actually only for main and mode toolbars, unifying focus is not // appropriate) - - QBoxLayout *bl = qobject_cast(mainwindow()->centralWidget()->layout()); - + + QBoxLayout* bl= + qobject_cast (mainwindow ()->centralWidget ()->layout ()); + if (modeToolBarAction) - modeToolBarAction->setVisible(modeToolBar->isVisible()); - mainToolBarAction->setVisible(mainToolBar->isVisible()); - - //WARNING: jugglying around bugs in Qt unified toolbar implementation - //do not try to change the order of the following operations.... - - if (mainToolBar->isVisible()) { - bool tmp = modeToolBar->isVisible(); - dumbToolBar->removeAction(modeToolBarAction); - dumbToolBar->addAction(mainToolBarAction); - bl->insertWidget(0, rulerWidget); - bl->insertWidget(0, modeToolBar); - mainToolBarAction->setVisible(true); - rulerWidget->setVisible(true); - modeToolBar->setVisible(tmp); - if (modeToolBarAction) - modeToolBarAction->setVisible(tmp); - dumbToolBar->setVisible(true); - } else { - dumbToolBar->removeAction(mainToolBarAction); - if (modeToolBar->isVisible()) { - bl->removeWidget(rulerWidget); - rulerWidget->setVisible(false); - bl->removeWidget(modeToolBar); + modeToolBarAction->setVisible (modeToolBar->isVisible ()); + mainToolBarAction->setVisible (mainToolBar->isVisible ()); + + // WARNING: jugglying around bugs in Qt unified toolbar implementation + // do not try to change the order of the following operations.... + + if (mainToolBar->isVisible ()) { + bool tmp= modeToolBar->isVisible (); + dumbToolBar->removeAction (modeToolBarAction); + dumbToolBar->addAction (mainToolBarAction); + bl->insertWidget (0, rulerWidget); + bl->insertWidget (0, modeToolBar); + mainToolBarAction->setVisible (true); + rulerWidget->setVisible (true); + modeToolBar->setVisible (tmp); + if (modeToolBarAction) modeToolBarAction->setVisible (tmp); + dumbToolBar->setVisible (true); + } + else { + dumbToolBar->removeAction (mainToolBarAction); + if (modeToolBar->isVisible ()) { + bl->removeWidget (rulerWidget); + rulerWidget->setVisible (false); + bl->removeWidget (modeToolBar); if (modeToolBarAction == NULL) { - modeToolBarAction = dumbToolBar->addWidget(modeToolBar); - } else { - dumbToolBar->addAction(modeToolBarAction); + modeToolBarAction= dumbToolBar->addWidget (modeToolBar); + } + else { + dumbToolBar->addAction (modeToolBarAction); } - dumbToolBar->setVisible(true); - } else { - dumbToolBar->setVisible(false); - dumbToolBar->removeAction(modeToolBarAction); + dumbToolBar->setVisible (true); + } + else { + dumbToolBar->setVisible (false); + dumbToolBar->removeAction (modeToolBarAction); } } } else { - bool old_menuVisibility = mainwindow()->menuBar()->isVisible(); - bool new_menuVisibility = visibility[0]; + bool old_menuVisibility= mainwindow ()->menuBar ()->isVisible (); + bool new_menuVisibility= visibility[0]; - if ( XOR(old_menuVisibility, new_menuVisibility) ) - mainwindow()->menuBar()->setVisible (new_menuVisibility); + if (XOR (old_menuVisibility, new_menuVisibility)) + mainwindow ()->menuBar ()->setVisible (new_menuVisibility); } #endif // UNIFIED_TOOLBAR #undef XOR if (tm_style_sheet == "" && use_mini_bars) { - QFont f = leftLabel->font(); - int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); + QFont f = leftLabel->font (); + int fs= as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); f.setPointSize (qt_zoom (fs > 0 ? fs : QTM_MINI_FONTSIZE)); - leftLabel->setFont(f); - rightLabel->setFont(f); + leftLabel->setFont (f); + rightLabel->setFont (f); } } widget -qt_tm_widget_rep::read(slot s, blackbox index) { +qt_tm_widget_rep::read (slot s, blackbox index) { widget ret; - + switch (s) { - case SLOT_CANVAS: - check_type_void (index, s); - ret = abstract (main_widget); - break; - - default: - return qt_window_widget_rep::read(s, index); + case SLOT_CANVAS: + check_type_void (index, s); + ret= abstract (main_widget); + break; + + default: + return qt_window_widget_rep::read (s, index); } - + if (DEBUG_QT_WIDGETS) debug_widgets << "qt_tm_widget_rep::read " << slot_name (s) - << "\t\tfor widget\t" << type_as_string() << LF; - + << "\t\tfor widget\t" << type_as_string () << LF; + return ret; } void qt_tm_widget_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_INVALIDATE: - case SLOT_INVALIDATE_ALL: - case SLOT_EXTENTS: - case SLOT_SCROLL_POSITION: - case SLOT_ZOOM_FACTOR: - case SLOT_MOUSE_GRAB: - main_widget->send(s, val); - return; - case SLOT_KEYBOARD_FOCUS: - { - check_type (val, s); - bool focus = open_box (val); - if (focus && canvas() && !canvas()->hasFocus()) - canvas()->setFocus (Qt::OtherFocusReason); - } - break; - case SLOT_HEADER_VISIBILITY: - { - check_type(val, s); - visibility[0] = open_box (val); - update_visibility(); - } - break; - case SLOT_MAIN_ICONS_VISIBILITY: - { - check_type(val, s); - visibility[1] = open_box (val); - update_visibility(); - } - break; - case SLOT_MODE_ICONS_VISIBILITY: - { - check_type(val, s); - visibility[2] = open_box (val); - update_visibility(); + case SLOT_INVALIDATE: + case SLOT_INVALIDATE_ALL: + case SLOT_EXTENTS: + case SLOT_SCROLL_POSITION: + case SLOT_ZOOM_FACTOR: + case SLOT_MOUSE_GRAB: + main_widget->send (s, val); + return; + case SLOT_KEYBOARD_FOCUS: { + check_type (val, s); + bool focus= open_box (val); + if (focus && canvas () && !canvas ()->hasFocus ()) + canvas ()->setFocus (Qt::OtherFocusReason); + } break; + case SLOT_HEADER_VISIBILITY: { + check_type (val, s); + visibility[0]= open_box (val); + update_visibility (); + } break; + case SLOT_MAIN_ICONS_VISIBILITY: { + check_type (val, s); + visibility[1]= open_box (val); + update_visibility (); + } break; + case SLOT_MODE_ICONS_VISIBILITY: { + check_type (val, s); + visibility[2]= open_box (val); + update_visibility (); + } break; + case SLOT_FOCUS_ICONS_VISIBILITY: { + check_type (val, s); + visibility[3]= open_box (val); + update_visibility (); + } break; + case SLOT_USER_ICONS_VISIBILITY: { + check_type (val, s); + visibility[4]= open_box (val); + update_visibility (); + } break; + + case SLOT_FOOTER_VISIBILITY: { + check_type (val, s); + visibility[5]= open_box (val); + update_visibility (); + } break; + case SLOT_SIDE_TOOLS_VISIBILITY: { + check_type (val, s); + visibility[6]= open_box (val); + update_visibility (); + } break; + case SLOT_BOTTOM_TOOLS_VISIBILITY: { + check_type (val, s); + visibility[7]= open_box (val); + update_visibility (); + } break; + + case SLOT_LEFT_FOOTER: { + check_type (val, s); + string msg= open_box (val); + leftLabel->setText (to_qstring (msg)); + leftLabel->update (); + } break; + case SLOT_RIGHT_FOOTER: { + check_type (val, s); + string msg= open_box (val); + rightLabel->setText (to_qstring (msg)); + rightLabel->update (); + } break; + case SLOT_SCROLLBARS_VISIBILITY: + // ignore this: qt handles scrollbars independently + // send_int (THIS, "scrollbars", val); + break; + case SLOT_INTERACTIVE_MODE: { + check_type (val, s); + + if (open_box (val) == true) { + prompt= new QTMInteractivePrompt (int_prompt, int_input); + mainwindow ()->statusBar ()->removeWidget (leftLabel); + mainwindow ()->statusBar ()->removeWidget (rightLabel); + mainwindow ()->statusBar ()->addWidget (prompt, 1); + prompt->start (); } - break; - case SLOT_FOCUS_ICONS_VISIBILITY: - { - check_type(val, s); - visibility[3] = open_box (val); - update_visibility(); - } - break; - case SLOT_USER_ICONS_VISIBILITY: - { - check_type(val, s); - visibility[4] = open_box (val); - update_visibility(); - } - break; - - case SLOT_FOOTER_VISIBILITY: - { - check_type(val, s); - visibility[5] = open_box (val); - update_visibility(); - } - break; - case SLOT_SIDE_TOOLS_VISIBILITY: - { - check_type(val, s); - visibility[6] = open_box (val); - update_visibility(); - } - break; - case SLOT_BOTTOM_TOOLS_VISIBILITY: - { - check_type(val, s); - visibility[7] = open_box (val); - update_visibility(); - } - break; - - case SLOT_LEFT_FOOTER: - { - check_type(val, s); - string msg = open_box (val); - leftLabel->setText (to_qstring (msg)); - leftLabel->update (); - } - break; - case SLOT_RIGHT_FOOTER: - { - check_type(val, s); - string msg= open_box (val); - rightLabel->setText (to_qstring (msg)); - rightLabel->update (); - } - break; - case SLOT_SCROLLBARS_VISIBILITY: - // ignore this: qt handles scrollbars independently - // send_int (THIS, "scrollbars", val); - break; - case SLOT_INTERACTIVE_MODE: - { - check_type(val, s); - - if (open_box (val) == true) { - prompt = new QTMInteractivePrompt (int_prompt, int_input); - mainwindow()->statusBar()->removeWidget (leftLabel); - mainwindow()->statusBar()->removeWidget (rightLabel); - mainwindow()->statusBar()->addWidget (prompt, 1); - prompt->start(); - } else { - if (prompt) prompt->end(); - mainwindow()->statusBar()->removeWidget (prompt); - mainwindow()->statusBar()->addWidget (leftLabel); - mainwindow()->statusBar()->addPermanentWidget (rightLabel); - leftLabel->show(); - rightLabel->show(); - prompt->deleteLater(); - prompt = NULL; - } - } - break; - case SLOT_FILE: - { - check_type(val, s); - string file = open_box (val); - if (DEBUG_QT_WIDGETS) debug_widgets << "\tFile: " << file << LF; - mainwindow()->setWindowFilePath (utf8_to_qstring (file)); - } - break; - case SLOT_POSITION: - { - check_type(val, s); - coord2 p= open_box (val); - mainwindow()->move (to_qpoint (p)); - } - break; - case SLOT_SIZE: - { - check_type(val, s); - coord2 p= open_box (val); - mainwindow()->resize (to_qsize (p)); - } - break; - case SLOT_DESTROY: - { - ASSERT (is_nil (val), "type mismatch"); - if (!is_nil (quit)) - quit (); - the_gui->need_update (); - } - break; - case SLOT_FULL_SCREEN: - { - check_type (val, s); - set_full_screen(open_box (val)); + else { + if (prompt) prompt->end (); + mainwindow ()->statusBar ()->removeWidget (prompt); + mainwindow ()->statusBar ()->addWidget (leftLabel); + mainwindow ()->statusBar ()->addPermanentWidget (rightLabel); + leftLabel->show (); + rightLabel->show (); + prompt->deleteLater (); + prompt= NULL; } - break; - default: - qt_window_widget_rep::send (s, val); - return; + } break; + case SLOT_FILE: { + check_type (val, s); + string file= open_box (val); + if (DEBUG_QT_WIDGETS) debug_widgets << "\tFile: " << file << LF; + mainwindow ()->setWindowFilePath (utf8_to_qstring (file)); + } break; + case SLOT_POSITION: { + check_type (val, s); + coord2 p= open_box (val); + mainwindow ()->move (to_qpoint (p)); + } break; + case SLOT_SIZE: { + check_type (val, s); + coord2 p= open_box (val); + mainwindow ()->resize (to_qsize (p)); + } break; + case SLOT_DESTROY: { + ASSERT (is_nil (val), "type mismatch"); + if (!is_nil (quit)) quit (); + the_gui->need_update (); + } break; + case SLOT_FULL_SCREEN: { + check_type (val, s); + set_full_screen (open_box (val)); + } break; + default: + qt_window_widget_rep::send (s, val); + return; } - + if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_tm_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + debug_widgets << "qt_tm_widget_rep: sent " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; } blackbox qt_tm_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_tm_widget_rep: queried " << slot_name(s) - << "\t\tto widget\t" << type_as_string() << LF; - + debug_widgets << "qt_tm_widget_rep: queried " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; + switch (s) { - case SLOT_SCROLL_POSITION: - case SLOT_EXTENTS: - case SLOT_VISIBLE_PART: - case SLOT_ZOOM_FACTOR: - return main_widget->query(s, type_id); - - case SLOT_HEADER_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[0]); - - case SLOT_MAIN_ICONS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[1]); - - case SLOT_MODE_ICONS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[2]); - - case SLOT_FOCUS_ICONS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[3]); - - case SLOT_USER_ICONS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[4]); - - case SLOT_FOOTER_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[5]); - - case SLOT_SIDE_TOOLS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[6]); - case SLOT_BOTTOM_TOOLS_VISIBILITY: - check_type_id (type_id, s); - return close_box (visibility[7]); - - case SLOT_INTERACTIVE_INPUT: - { - check_type_id (type_id, s); - qt_input_text_widget_rep* w = + case SLOT_SCROLL_POSITION: + case SLOT_EXTENTS: + case SLOT_VISIBLE_PART: + case SLOT_ZOOM_FACTOR: + return main_widget->query (s, type_id); + + case SLOT_HEADER_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[0]); + + case SLOT_MAIN_ICONS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[1]); + + case SLOT_MODE_ICONS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[2]); + + case SLOT_FOCUS_ICONS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[3]); + + case SLOT_USER_ICONS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[4]); + + case SLOT_FOOTER_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[5]); + + case SLOT_SIDE_TOOLS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[6]); + case SLOT_BOTTOM_TOOLS_VISIBILITY: + check_type_id (type_id, s); + return close_box (visibility[7]); + + case SLOT_INTERACTIVE_INPUT: { + check_type_id (type_id, s); + qt_input_text_widget_rep* w= static_cast (int_input.rep); - if (w->ok) - return close_box (scm_quote (w->input)); - else - return close_box ("#f"); - } + if (w->ok) return close_box (scm_quote (w->input)); + else return close_box ("#f"); + } - case SLOT_POSITION: - { - check_type_id (type_id, s); - return close_box (from_qpoint (mainwindow()->pos())); - } - - case SLOT_SIZE: - { - check_type_id (type_id, s); - return close_box (from_qsize (mainwindow()->size())); - } + case SLOT_POSITION: { + check_type_id (type_id, s); + return close_box (from_qpoint (mainwindow ()->pos ())); + } - case SLOT_INTERACTIVE_MODE: - check_type_id (type_id, s); - return close_box (prompt && prompt->isActive()); + case SLOT_SIZE: { + check_type_id (type_id, s); + return close_box (from_qsize (mainwindow ()->size ())); + } - default: - return qt_window_widget_rep::query (s, type_id); + case SLOT_INTERACTIVE_MODE: + check_type_id (type_id, s); + return close_box (prompt && prompt->isActive ()); + + default: + return qt_window_widget_rep::query (s, type_id); } } void qt_tm_widget_rep::install_main_menu () { if (main_menu_widget == waiting_main_menu_widget) return; - main_menu_widget = waiting_main_menu_widget; - QList* src = main_menu_widget->get_qactionlist(); + main_menu_widget = waiting_main_menu_widget; + QList* src= main_menu_widget->get_qactionlist (); if (!src) return; - QMenuBar* dest = mainwindow()->menuBar(); - dest->clear(); - for (int i = 0; i < src->count(); i++) { - QAction* a = (*src)[i]; - if (a->menu()) { - //TRICK: Mac native QMenuBar accepts only menus which are already populated - // this will cause a problem for us, since menus are lazy and populated only after triggering - // this is the reason we add a dummy action before inserting the menu - a->menu()->addAction("native menubar trick"); - dest->addAction(a->menu()->menuAction()); - QObject::connect (a->menu(), SIGNAL (aboutToShow()), - the_gui->gui_helper, SLOT (aboutToShowMainMenu())); - QObject::connect (a->menu(), SIGNAL (aboutToHide()), - the_gui->gui_helper, SLOT (aboutToHideMainMenu())); + QMenuBar* dest= mainwindow ()->menuBar (); + dest->clear (); + for (int i= 0; i < src->count (); i++) { + QAction* a= (*src)[i]; + if (a->menu ()) { + // TRICK: Mac native QMenuBar accepts only menus which are already + // populated + // this will cause a problem for us, since menus are lazy and populated + // only after triggering this is the reason we add a dummy action before + // inserting the menu + a->menu ()->addAction ("native menubar trick"); + dest->addAction (a->menu ()->menuAction ()); + QObject::connect (a->menu (), SIGNAL (aboutToShow ()), + the_gui->gui_helper, SLOT (aboutToShowMainMenu ())); + QObject::connect (a->menu (), SIGNAL (aboutToHide ()), + the_gui->gui_helper, SLOT (aboutToHideMainMenu ())); } } } @@ -843,77 +801,74 @@ void qt_tm_widget_rep::write (slot s, blackbox index, widget w) { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_tm_widget_rep::write " << slot_name (s) << LF; - + switch (s) { - // Widget w is usually a qt_simple_widget_rep, with a QTMWidget as - // underlying widget. We must discard the current main_widget and - // display the new. But while switching buffers the widget w is a - // glue_widget, so we may not just use canvas() everywhere. - case SLOT_SCROLLABLE: - { - check_type_void (index, s); - - QWidget* q = main_widget->qwid; - q->hide(); - QLayout* l = centralwidget()->layout(); - l->removeWidget(q); - - q = concrete(w)->as_qwidget(); // force creation of the new QWidget - l->addWidget(q); - /* " When you use a layout, you do not need to pass a parent when - constructing the child widgets. The layout will automatically reparent - the widgets (using QWidget::setParent()) so that they are children of - the widget on which the layout is installed " */ - main_widget = concrete (w); - // canvas() now returns the new QTMWidget (or 0) - - if (scrollarea()) // Fix size to draw margins around. - scrollarea()->surface()->setSizePolicy (QSizePolicy::Fixed, + // Widget w is usually a qt_simple_widget_rep, with a QTMWidget as + // underlying widget. We must discard the current main_widget and + // display the new. But while switching buffers the widget w is a + // glue_widget, so we may not just use canvas() everywhere. + case SLOT_SCROLLABLE: { + check_type_void (index, s); + + QWidget* q= main_widget->qwid; + q->hide (); + QLayout* l= centralwidget ()->layout (); + l->removeWidget (q); + + q= concrete (w)->as_qwidget (); // force creation of the new QWidget + l->addWidget (q); + /* " When you use a layout, you do not need to pass a parent when + constructing the child widgets. The layout will automatically reparent + the widgets (using QWidget::setParent()) so that they are children of + the widget on which the layout is installed " */ + main_widget= concrete (w); + // canvas() now returns the new QTMWidget (or 0) + + if (scrollarea ()) // Fix size to draw margins around. + scrollarea ()->surface ()->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); - send_keyboard_focus (abstract (main_widget)); - } - break; - - case SLOT_MAIN_MENU: - check_type_void (index, s); + send_keyboard_focus (abstract (main_widget)); + } break; + + case SLOT_MAIN_MENU: + check_type_void (index, s); { - waiting_main_menu_widget = concrete (w); - if (menu_count <= 0) - install_main_menu(); + waiting_main_menu_widget= concrete (w); + if (menu_count <= 0) install_main_menu (); else if (!contains (waiting_widgets, this)) - // menu interaction ongoing, postpone new menu installation until done + // menu interaction ongoing, postpone new menu installation until done waiting_widgets << this; } - break; - - case SLOT_MAIN_ICONS: - check_type_void (index, s); + break; + + case SLOT_MAIN_ICONS: + check_type_void (index, s); { - main_icons_widget = concrete (w); - QList* list = main_icons_widget->get_qactionlist(); + main_icons_widget = concrete (w); + QList* list= main_icons_widget->get_qactionlist (); if (list) { replaceButtons (mainToolBar, list); - update_visibility(); + update_visibility (); } } - break; - - case SLOT_MODE_ICONS: - check_type_void (index, s); + break; + + case SLOT_MODE_ICONS: + check_type_void (index, s); { - mode_icons_widget = concrete (w); - QList* list = mode_icons_widget->get_qactionlist(); + mode_icons_widget = concrete (w); + QList* list= mode_icons_widget->get_qactionlist (); if (list) { replaceButtons (modeToolBar, list); - update_visibility(); + update_visibility (); } } - break; - - case SLOT_FOCUS_ICONS: - check_type_void (index, s); + break; + + case SLOT_FOCUS_ICONS: + check_type_void (index, s); { - bool can_update = true; + bool can_update= true; // BUG: // there is a problem with updateActions which apparently // reset a running input method in Qt5. @@ -921,245 +876,242 @@ qt_tm_widget_rep::write (slot s, blackbox index, widget w) { // This is (probably) also relate to // bug #47338 [CJK] input disappears immediately // see http://lists.gnu.org/archive/html/texmacs-dev/2017-09/msg00000.html - + // HACK: we just disable the focus bar updating while preediting. // This seems enough since the other toolbars are not usually updated // while performing an input method keyboard sequence - if (canvas()) can_update = !canvas()->isPreediting(); + if (canvas ()) can_update= !canvas ()->isPreediting (); if (can_update) { - focus_icons_widget = concrete (w); - QList* list = focus_icons_widget->get_qactionlist(); + focus_icons_widget = concrete (w); + QList* list= focus_icons_widget->get_qactionlist (); if (list) { replaceButtons (focusToolBar, list); - update_visibility(); + update_visibility (); } } } - break; - - case SLOT_USER_ICONS: - check_type_void (index, s); - { - user_icons_widget = concrete (w); - QList* list = user_icons_widget->get_qactionlist(); + break; + + case SLOT_USER_ICONS: + check_type_void (index, s); + { + user_icons_widget = concrete (w); + QList* list= user_icons_widget->get_qactionlist (); if (list) { replaceButtons (userToolBar, list); - update_visibility(); + update_visibility (); } } - break; - - case SLOT_SIDE_TOOLS: - check_type_void (index, s); + break; + + case SLOT_SIDE_TOOLS: + check_type_void (index, s); { - side_tools_widget = concrete (w); - QWidget* new_qwidget = side_tools_widget->as_qwidget(); - QWidget* old_qwidget = sideTools->widget(); - if (old_qwidget) old_qwidget->deleteLater(); + side_tools_widget = concrete (w); + QWidget* new_qwidget= side_tools_widget->as_qwidget (); + QWidget* old_qwidget= sideTools->widget (); + if (old_qwidget) old_qwidget->deleteLater (); sideTools->setWidget (new_qwidget); - update_visibility(); - new_qwidget->show(); + update_visibility (); + new_qwidget->show (); } - break; + break; - case SLOT_BOTTOM_TOOLS: - check_type_void (index, s); - { + case SLOT_BOTTOM_TOOLS: + check_type_void (index, s); + { bottom_tools_widget = concrete (w); - QWidget* new_qwidget = bottom_tools_widget->as_qwidget(); - QWidget* old_qwidget = bottomTools->widget(); - if (old_qwidget) old_qwidget->deleteLater(); + QWidget* new_qwidget= bottom_tools_widget->as_qwidget (); + QWidget* old_qwidget= bottomTools->widget (); + if (old_qwidget) old_qwidget->deleteLater (); bottomTools->setWidget (new_qwidget); - update_visibility(); - new_qwidget->show(); + update_visibility (); + new_qwidget->show (); } - break; - - case SLOT_INTERACTIVE_PROMPT: - check_type_void (index, s); - int_prompt= concrete (w); - break; - - case SLOT_INTERACTIVE_INPUT: - check_type_void (index, s); - int_input= concrete (w); - break; - - default: - qt_window_widget_rep::write (s, index, w); + break; + + case SLOT_INTERACTIVE_PROMPT: + check_type_void (index, s); + int_prompt= concrete (w); + break; + + case SLOT_INTERACTIVE_INPUT: + check_type_void (index, s); + int_input= concrete (w); + break; + + default: + qt_window_widget_rep::write (s, index, w); } } void set_standard_style_sheet (QWidget* w); void -qt_tm_widget_rep::set_full_screen(bool flag) { +qt_tm_widget_rep::set_full_screen (bool flag) { full_screen = flag; - QWidget *win = mainwindow()->window(); + QWidget* win= mainwindow ()->window (); if (win) { - if (flag ) { + if (flag) { QPalette pal; - pal.setColor(QPalette::Mid, QColor (0, 0, 0)); - mainwindow()->setPalette(pal); - mainwindow()->setStyleSheet ("* { background: #000000; }"); + pal.setColor (QPalette::Mid, QColor (0, 0, 0)); + mainwindow ()->setPalette (pal); + mainwindow ()->setStyleSheet ("* { background: #000000; }"); #ifdef UNIFIED_TOOLBAR if (use_unified_toolbar) { - //HACK: we disable unified toolbar since otherwise - // the application will crash when we return to normal mode - // (bug in Qt? present at least with 4.7.1) - mainwindow()->setUnifiedTitleAndToolBarOnMac(false); - mainwindow()->centralWidget()->layout()->setContentsMargins(0,0,0,0); + // HACK: we disable unified toolbar since otherwise + // the application will crash when we return to normal mode + // (bug in Qt? present at least with 4.7.1) + mainwindow ()->setUnifiedTitleAndToolBarOnMac (false); + mainwindow ()->centralWidget ()->layout ()->setContentsMargins (0, 0, 0, + 0); } #endif -// mainwindow()->window()->setContentsMargins(0,0,0,0); - //win->showFullScreen(); - win->setWindowState(win->windowState() | Qt::WindowFullScreen); + // mainwindow()->window()->setContentsMargins(0,0,0,0); + // win->showFullScreen(); + win->setWindowState (win->windowState () | Qt::WindowFullScreen); } else { QPalette pal; - QColor bgcol= to_qcolor (tm_background); + QColor bgcol= to_qcolor (tm_background); pal.setColor (QPalette::Mid, bgcol); - mainwindow()->setPalette(pal); - set_standard_style_sheet (mainwindow()); - bool cache = visibility[0]; - visibility[0] = false; - update_visibility(); -// win->showNormal(); - win->setWindowState(win->windowState() & ~Qt::WindowFullScreen); - - visibility[0] = cache; - update_visibility(); + mainwindow ()->setPalette (pal); + set_standard_style_sheet (mainwindow ()); + bool cache = visibility[0]; + visibility[0]= false; + update_visibility (); + // win->showNormal(); + win->setWindowState (win->windowState () & ~Qt::WindowFullScreen); + + visibility[0]= cache; + update_visibility (); #ifdef UNIFIED_TOOLBAR if (use_unified_toolbar) { - mainwindow()->centralWidget()->layout()->setContentsMargins (0,1,0,0); - //HACK: we reenable unified toolbar (see above HACK) - // the application will crash when we return to normal mode - mainwindow()->setUnifiedTitleAndToolBarOnMac(true); + mainwindow ()->centralWidget ()->layout ()->setContentsMargins (0, 1, 0, + 0); + // HACK: we reenable unified toolbar (see above HACK) + // the application will crash when we return to normal mode + mainwindow ()->setUnifiedTitleAndToolBarOnMac (true); } #endif } } - - scrollarea()->setHorizontalScrollBarPolicy(flag ? Qt::ScrollBarAlwaysOff : Qt::ScrollBarAsNeeded); - scrollarea()->setVerticalScrollBarPolicy(flag ? Qt::ScrollBarAlwaysOff : Qt::ScrollBarAsNeeded); -} + scrollarea ()->setHorizontalScrollBarPolicy (flag ? Qt::ScrollBarAlwaysOff + : Qt::ScrollBarAsNeeded); + scrollarea ()->setVerticalScrollBarPolicy (flag ? Qt::ScrollBarAlwaysOff + : Qt::ScrollBarAsNeeded); +} /****************************************************************************** * qt_tm_embedded_widget_rep ******************************************************************************/ -qt_tm_embedded_widget_rep::qt_tm_embedded_widget_rep (command _quit) - : qt_widget_rep (embedded_tm_widget), quit (_quit) { - main_widget = ::glue_widget (true, true, 1, 1); +qt_tm_embedded_widget_rep::qt_tm_embedded_widget_rep (command _quit) + : qt_widget_rep (embedded_tm_widget), quit (_quit) { + main_widget= ::glue_widget (true, true, 1, 1); } void qt_tm_embedded_widget_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_INVALIDATE: - case SLOT_INVALIDATE_ALL: - case SLOT_EXTENTS: - case SLOT_SCROLL_POSITION: - case SLOT_ZOOM_FACTOR: - case SLOT_MOUSE_GRAB: - main_widget->send(s, val); - return; - - /// FIXME: decide what to do with these for embedded widgets - case SLOT_HEADER_VISIBILITY: - case SLOT_MAIN_ICONS_VISIBILITY: - case SLOT_MODE_ICONS_VISIBILITY: - case SLOT_FOCUS_ICONS_VISIBILITY: - case SLOT_USER_ICONS_VISIBILITY: - case SLOT_FOOTER_VISIBILITY: - case SLOT_SIDE_TOOLS_VISIBILITY: - case SLOT_BOTTOM_TOOLS_VISIBILITY: - case SLOT_LEFT_FOOTER: - case SLOT_RIGHT_FOOTER: - case SLOT_SCROLLBARS_VISIBILITY: - case SLOT_INTERACTIVE_MODE: - case SLOT_FILE: - break; - - case SLOT_DESTROY: - { - ASSERT (is_nil (val), "type mismatch"); - if (!is_nil (quit)) - quit (); - the_gui->need_update (); - } - break; - - default: - qt_widget_rep::send (s, val); - return; + case SLOT_INVALIDATE: + case SLOT_INVALIDATE_ALL: + case SLOT_EXTENTS: + case SLOT_SCROLL_POSITION: + case SLOT_ZOOM_FACTOR: + case SLOT_MOUSE_GRAB: + main_widget->send (s, val); + return; + + /// FIXME: decide what to do with these for embedded widgets + case SLOT_HEADER_VISIBILITY: + case SLOT_MAIN_ICONS_VISIBILITY: + case SLOT_MODE_ICONS_VISIBILITY: + case SLOT_FOCUS_ICONS_VISIBILITY: + case SLOT_USER_ICONS_VISIBILITY: + case SLOT_FOOTER_VISIBILITY: + case SLOT_SIDE_TOOLS_VISIBILITY: + case SLOT_BOTTOM_TOOLS_VISIBILITY: + case SLOT_LEFT_FOOTER: + case SLOT_RIGHT_FOOTER: + case SLOT_SCROLLBARS_VISIBILITY: + case SLOT_INTERACTIVE_MODE: + case SLOT_FILE: + break; + + case SLOT_DESTROY: { + ASSERT (is_nil (val), "type mismatch"); + if (!is_nil (quit)) quit (); + the_gui->need_update (); + } break; + + default: + qt_widget_rep::send (s, val); + return; } if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_tm_embedded_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + debug_widgets << "qt_tm_embedded_widget_rep: sent " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; } blackbox qt_tm_embedded_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_tm_embedded_widget_rep::query " << slot_name (s) << LF; - + switch (s) { - case SLOT_IDENTIFIER: - { - if (qwid) { - widget_rep* wid = qt_window_widget_rep::widget_from_qwidget(qwid); - if (wid) return wid->query (s, type_id); - } - return close_box(0); + case SLOT_IDENTIFIER: { + if (qwid) { + widget_rep* wid= qt_window_widget_rep::widget_from_qwidget (qwid); + if (wid) return wid->query (s, type_id); } + return close_box (0); + } - case SLOT_SCROLL_POSITION: - case SLOT_EXTENTS: - case SLOT_VISIBLE_PART: - case SLOT_ZOOM_FACTOR: - case SLOT_POSITION: - case SLOT_SIZE: - if (!is_nil (main_widget)) - return main_widget->query (s, type_id); - else - return qt_widget_rep::query (s, type_id); - /// FIXME: decide what to do with these for embedded widgets - case SLOT_HEADER_VISIBILITY: - case SLOT_MAIN_ICONS_VISIBILITY: - case SLOT_MODE_ICONS_VISIBILITY: - case SLOT_FOCUS_ICONS_VISIBILITY: - case SLOT_USER_ICONS_VISIBILITY: - case SLOT_FOOTER_VISIBILITY: - case SLOT_SIDE_TOOLS_VISIBILITY: - case SLOT_BOTTOM_TOOLS_VISIBILITY: - check_type_id (type_id, s); - return close_box (false); - - default: - return qt_widget_rep::query (s, type_id); + case SLOT_SCROLL_POSITION: + case SLOT_EXTENTS: + case SLOT_VISIBLE_PART: + case SLOT_ZOOM_FACTOR: + case SLOT_POSITION: + case SLOT_SIZE: + if (!is_nil (main_widget)) return main_widget->query (s, type_id); + else return qt_widget_rep::query (s, type_id); + /// FIXME: decide what to do with these for embedded widgets + case SLOT_HEADER_VISIBILITY: + case SLOT_MAIN_ICONS_VISIBILITY: + case SLOT_MODE_ICONS_VISIBILITY: + case SLOT_FOCUS_ICONS_VISIBILITY: + case SLOT_USER_ICONS_VISIBILITY: + case SLOT_FOOTER_VISIBILITY: + case SLOT_SIDE_TOOLS_VISIBILITY: + case SLOT_BOTTOM_TOOLS_VISIBILITY: + check_type_id (type_id, s); + return close_box (false); + + default: + return qt_widget_rep::query (s, type_id); } } widget qt_tm_embedded_widget_rep::read (slot s, blackbox index) { widget ret; - + switch (s) { - case SLOT_CANVAS: - check_type_void (index, s); - ret = main_widget; - break; - default: - return qt_widget_rep::read(s, index); + case SLOT_CANVAS: + check_type_void (index, s); + ret= main_widget; + break; + default: + return qt_widget_rep::read (s, index); } - + if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_tm_widget_rep::read " << slot_name (s) - << "\t\tfor widget\t" << type_as_string() << LF; - + debug_widgets << "qt_tm_widget_rep::read " << slot_name (s) + << "\t\tfor widget\t" << type_as_string () << LF; + return ret; } @@ -1169,41 +1121,39 @@ qt_tm_embedded_widget_rep::write (slot s, blackbox index, widget w) { debug_widgets << "qt_tm_embedded_widget_rep::write " << slot_name (s) << LF; switch (s) { - // Widget w is a qt_simple_widget_rep, with a QTMWidget as underlying - // widget. We must discard the current QTMWidget and display the new. - // see qt_tm_widget_rep::write() - case SLOT_SCROLLABLE: - { - check_type_void (index, s); - main_widget = w; - } - break; - /// FIXME: decide what to do with these for embedded widgets - case SLOT_MAIN_MENU: - case SLOT_MAIN_ICONS: - case SLOT_MODE_ICONS: - case SLOT_FOCUS_ICONS: - case SLOT_USER_ICONS: - case SLOT_SIDE_TOOLS: - case SLOT_BOTTOM_TOOLS: - case SLOT_INTERACTIVE_INPUT: - case SLOT_INTERACTIVE_PROMPT: - default: - qt_widget_rep::write (s, index, w); + // Widget w is a qt_simple_widget_rep, with a QTMWidget as underlying + // widget. We must discard the current QTMWidget and display the new. + // see qt_tm_widget_rep::write() + case SLOT_SCROLLABLE: { + check_type_void (index, s); + main_widget= w; + } break; + /// FIXME: decide what to do with these for embedded widgets + case SLOT_MAIN_MENU: + case SLOT_MAIN_ICONS: + case SLOT_MODE_ICONS: + case SLOT_FOCUS_ICONS: + case SLOT_USER_ICONS: + case SLOT_SIDE_TOOLS: + case SLOT_BOTTOM_TOOLS: + case SLOT_INTERACTIVE_INPUT: + case SLOT_INTERACTIVE_PROMPT: + default: + qt_widget_rep::write (s, index, w); } } QWidget* -qt_tm_embedded_widget_rep::as_qwidget() { - qwid = new QWidget(); - QVBoxLayout* l = new QVBoxLayout(); - l->setContentsMargins (0,0,0,0); +qt_tm_embedded_widget_rep::as_qwidget () { + qwid = new QWidget (); + QVBoxLayout* l= new QVBoxLayout (); + l->setContentsMargins (0, 0, 0, 0); qwid->setLayout (l); - l->addWidget (concrete(main_widget)->as_qwidget()); + l->addWidget (concrete (main_widget)->as_qwidget ()); return qwid; } QLayoutItem* qt_tm_embedded_widget_rep::as_qlayoutitem () { - return new QWidgetItem(as_qwidget()); + return new QWidgetItem (as_qwidget ()); } diff --git a/src/Plugins/Qt/qt_tm_widget.hpp b/src/Plugins/Qt/qt_tm_widget.hpp index 13ca392405..3c261f130e 100644 --- a/src/Plugins/Qt/qt_tm_widget.hpp +++ b/src/Plugins/Qt/qt_tm_widget.hpp @@ -14,34 +14,34 @@ #include "list.hpp" -#include "qt_widget.hpp" #include "qt_simple_widget.hpp" +#include "qt_widget.hpp" #include "qt_window_widget.hpp" #include "QTMInteractiveInputHelper.hpp" -#include "QTMWidget.hpp" #include "QTMScrollView.hpp" +#include "QTMWidget.hpp" +#include #include #include -#include -class QLabel; +class QLabel; class QToolBar; class QTMInteractivePrompt; /*! Models one main window with toolbars, an associated view, etc. - + The underlying QWidget is a QTMWindow, whose central widget is a QWidget holding the extra toolbars and the canvas for the open buffer. Each canvas is of type QTMWidget and belongs to one qt_simple_widget_rep. */ -class qt_tm_widget_rep: public qt_window_widget_rep { +class qt_tm_widget_rep : public qt_window_widget_rep { /* - enum { + enum { header_visibility = 1, // all toolbars - main_toolbar_visibility = 2, + main_toolbar_visibility = 2, mode_toolbar_visibility = 4, focus_toolbar_visibility = 8, user_toolbar_visibility = 16, @@ -50,30 +50,30 @@ class qt_tm_widget_rep: public qt_window_widget_rep { bottom_tools_visibility = 128 } visibility_t; */ - QLabel* rightLabel; - QLabel* leftLabel; + QLabel* rightLabel; + QLabel* leftLabel; QToolBar* mainToolBar; QToolBar* modeToolBar; - QToolBar* focusToolBar; + QToolBar* focusToolBar; QToolBar* userToolBar; - QDockWidget* sideTools; + QDockWidget* sideTools; QDockWidget* bottomTools; #ifdef Q_OS_MAC - QToolBar* dumbToolBar; - QAction* modeToolBarAction; - QAction* mainToolBarAction; - QWidget* rulerWidget; + QToolBar* dumbToolBar; + QAction* modeToolBarAction; + QAction* mainToolBarAction; + QWidget* rulerWidget; #endif QTMInteractiveInputHelper helper; QTMInteractivePrompt* prompt; - qt_widget int_prompt; - qt_widget int_input; - + qt_widget int_prompt; + qt_widget int_input; + bool visibility[8]; bool full_screen; - + qt_widget main_widget; qt_widget main_menu_widget; qt_widget waiting_main_menu_widget; @@ -83,74 +83,64 @@ class qt_tm_widget_rep: public qt_window_widget_rep { qt_widget user_icons_widget; qt_widget side_tools_widget; qt_widget bottom_tools_widget; - qt_widget dock_window_widget; // trick to return correct widget position + qt_widget dock_window_widget; // trick to return correct widget position - public: qt_tm_widget_rep (int mask, command _quit); ~qt_tm_widget_rep (); - + virtual widget plain_window_widget (string name, command quit, int b); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); + virtual widget read (slot s, blackbox index); virtual void write (slot s, blackbox index, widget w); - - void set_full_screen (bool flag); - void update_visibility(); - void install_main_menu (); + + void set_full_screen (bool flag); + void update_visibility (); + void install_main_menu (); static void tweak_iconbar_size (QSize& sz); friend class QTMInteractiveInputHelper; - + protected: - - ////// Convenience methods to access our QWidgets - - QMainWindow* mainwindow () { - return qobject_cast (qwid); - } - QWidget* centralwidget () { - return mainwindow()->centralWidget(); - } + ////// Convenience methods to access our QWidgets + + QMainWindow* mainwindow () { return qobject_cast (qwid); } + QWidget* centralwidget () { return mainwindow ()->centralWidget (); } QTMScrollView* scrollarea () { return qobject_cast (main_widget->qwid); } - QTMWidget* canvas () { - return qobject_cast (main_widget->qwid); - } + QTMWidget* canvas () { return qobject_cast (main_widget->qwid); } }; - //! List of widgets wanting to install their menu bar extern list waiting_widgets; //! Positive means the menu is busy. extern int menu_count; - /*! A simple texmacs input widget. - + This is a stripped down version of qt_tm_widget_rep, whose underlying widget isn't a QTMWindow anymore, but a regular QTMWidget because it is intended to be embedded somewhere else. */ -class qt_tm_embedded_widget_rep: public qt_widget_rep { +class qt_tm_embedded_widget_rep : public qt_widget_rep { widget main_widget; public: command quit; - + qt_tm_embedded_widget_rep (command _quit); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); + virtual widget read (slot s, blackbox index); virtual void write (slot s, blackbox index, widget w); - - virtual QWidget* as_qwidget (); + + virtual QWidget* as_qwidget (); virtual QLayoutItem* as_qlayoutitem (); }; diff --git a/src/Plugins/Qt/qt_ui_element.cpp b/src/Plugins/Qt/qt_ui_element.cpp index 08aba6c727..6c2341d62b 100644 --- a/src/Plugins/Qt/qt_ui_element.cpp +++ b/src/Plugins/Qt/qt_ui_element.cpp @@ -8,127 +8,128 @@ * in the root directory or . ******************************************************************************/ -#include "qt_utilities.hpp" -#include "qt_renderer.hpp" -#include "qt_widget.hpp" #include "qt_ui_element.hpp" -#include "qt_simple_widget.hpp" -#include "qt_window_widget.hpp" -#include "qt_menu.hpp" #include "qt_gui.hpp" +#include "qt_menu.hpp" #include "qt_picture.hpp" +#include "qt_renderer.hpp" +#include "qt_simple_widget.hpp" +#include "qt_utilities.hpp" +#include "qt_widget.hpp" +#include "qt_window_widget.hpp" #include "analyze.hpp" -#include "widget.hpp" #include "message.hpp" #include "promise.hpp" #include "scheme.hpp" +#include "widget.hpp" -#include "QTMWindow.hpp" #include "QTMGuiHelper.hpp" #include "QTMMenuHelper.hpp" #include "QTMStyle.hpp" #include "QTMTreeModel.hpp" +#include "QTMWindow.hpp" +#include #include #include #include -#include #include - /****************************************************************************** * Ad-hoc command_rep derivates for different UI elements in qt_ui_element_rep ******************************************************************************/ /*! Ad-hoc command to be used with toggle widgets. - - The command associated with a qt_ui_element::toggle_widget has as a parameter the state - of the QCheckBox. Since it is assumed everywhere else that commands injected into - the gui's queue accept no parameters, and changes would be too big, we choose to - encapsulate the original command in a new one which will execute the first with - its argument. - \sa qt_ui_element, , qt_ui_element_rep::as_qwidget, qt_ui_element_rep::toggle_widget + + The command associated with a qt_ui_element::toggle_widget has as a parameter + the state of the QCheckBox. Since it is assumed everywhere else that commands + injected into the gui's queue accept no parameters, and changes would be too + big, we choose to encapsulate the original command in a new one which will + execute the first with its argument. \sa qt_ui_element, , + qt_ui_element_rep::as_qwidget, qt_ui_element_rep::toggle_widget */ -class qt_toggle_command_rep: public command_rep { +class qt_toggle_command_rep : public command_rep { QPointer qwid; - command cmd; - + command cmd; + public: - qt_toggle_command_rep(QCheckBox* w, command c) : qwid(w), cmd(c) { } - void apply () { if (qwid) cmd (list_object (object (qwid->isChecked()))); } + qt_toggle_command_rep (QCheckBox* w, command c) : qwid (w), cmd (c) {} + void apply () { + if (qwid) cmd (list_object (object (qwid->isChecked ()))); + } tm_ostream& print (tm_ostream& out) { return out << "Toggle"; } }; /*! Ad-hoc command to be used with enum widgets. - - The command associated with a qt_ui_element::enum_widget has one parameter. For the - reason to be of this class, see \sa qt_toggle_command_rep . - \sa qt_ui_element, , qt_ui_element_rep::as_qwidget, qt_ui_element_rep::enum_widget + + The command associated with a qt_ui_element::enum_widget has one parameter. For + the reason to be of this class, see \sa qt_toggle_command_rep . \sa + qt_ui_element, , qt_ui_element_rep::as_qwidget, qt_ui_element_rep::enum_widget */ -class qt_enum_command_rep: public command_rep { +class qt_enum_command_rep : public command_rep { QPointer qwid; - command cmd; - + command cmd; + public: - qt_enum_command_rep(QComboBox* w, command c) : qwid(w), cmd(c) {} - void apply () { - if (qwid) - cmd (list_object (object (from_qstring(qwid->currentText())))); + qt_enum_command_rep (QComboBox* w, command c) : qwid (w), cmd (c) {} + void apply () { + if (qwid) cmd (list_object (object (from_qstring (qwid->currentText ())))); } - + tm_ostream& print (tm_ostream& out) { return out << "Enum"; } }; - /****************************************************************************** * glue widget ******************************************************************************/ -QTMPixmapOrImage +QTMPixmapOrImage qt_glue_widget_rep::render () { - QSize s = to_qsize (w, h); + QSize s= to_qsize (w, h); QTMPixmapOrImage pxm (s); - //cout << "glue (" << s.width() << "," << s.height() << ")\n"; + // cout << "glue (" << s.width() << "," << s.height() << ")\n"; pxm.fill (Qt::transparent); - QPaintDevice *pd; - pd = static_cast(pxm.rep); - if (pd && !pxm.isNull()) { - qt_renderer_rep* ren = the_qt_renderer(); + QPaintDevice* pd; + pd= static_cast (pxm.rep); + if (pd && !pxm.isNull ()) { + qt_renderer_rep* ren= the_qt_renderer (); ren->begin (pd); - rectangle r = rectangle (0, 0, s.width(), s.height()); - ren->set_origin (0,0); + rectangle r= rectangle (0, 0, s.width (), s.height ()); + ren->set_origin (0, 0); ren->encode (r->x1, r->y1); ren->encode (r->x2, r->y2); ren->set_clipping (r->x1, r->y2, r->x2, r->y1); - + if (col == "") { - // do nothing - } else { + // do nothing + } + else { if (is_atomic (col)) { - color c = named_color (col->label); + color c= named_color (col->label); ren->set_background (c); ren->set_pencil (c); ren->fill (r->x1, r->y2, r->x2, r->y1); - } else { + } + else { ren->set_shrinking_factor (std_shrinkf); - brush old_b = ren->get_background (); + brush old_b= ren->get_background (); ren->set_background (col); - ren->clear_pattern (5*r->x1, 5*r->y2, 5*r->x2, 5*r->y1); + ren->clear_pattern (5 * r->x1, 5 * r->y2, 5 * r->x2, 5 * r->y1); ren->set_background (old_b); ren->set_shrinking_factor (1); } } - ren->end(); + ren->end (); } - + return pxm; } -QAction * -qt_glue_widget_rep::as_qaction() { - QAction* a = new QTMAction(); +QAction* +qt_glue_widget_rep::as_qaction () { + QAction* a= new QTMAction (); a->setText (to_qstring (as_string (col))); QIcon icon; #if 0 @@ -138,27 +139,24 @@ qt_glue_widget_rep::as_qaction() { icon.addPixmap (render(), QIcon::Normal, QIcon::On); col = old_col; #else - if (!headless_mode) - icon.addPixmap (*(render ().QPixmap_ptr ())); + if (!headless_mode) icon.addPixmap (*(render ().QPixmap_ptr ())); #endif - a->setIcon (icon); + a->setIcon (icon); a->setEnabled (false); return a; } -QWidget * -qt_glue_widget_rep::as_qwidget() { - QLabel* qw = new QLabel(); +QWidget* +qt_glue_widget_rep::as_qwidget () { + QLabel* qw= new QLabel (); qw->setText (to_qstring (as_string (col))); - if (!headless_mode) - qw->setPixmap (*(render ().QPixmap_ptr ())); + if (!headless_mode) qw->setPixmap (*(render ().QPixmap_ptr ())); qw->setMinimumSize (to_qsize (w, h)); - // w->setEnabled(false); - qwid = qw; + // w->setEnabled(false); + qwid= qw; return qwid; } - /****************************************************************************** * The following hack has been implemented by Joris in order to avoid * a focus bug when a menu contains a text input field. To provoke @@ -169,7 +167,7 @@ qt_glue_widget_rep::as_qwidget() { ******************************************************************************/ static list to_be_destroyed; -static time_t last_addition; +static time_t last_addition; void schedule_destruction (QAction* a) { @@ -177,13 +175,13 @@ schedule_destruction (QAction* a) { if (!is_nil (to_be_destroyed) && last_addition + 3000 < now) { to_be_destroyed= reverse (to_be_destroyed); while (!is_nil (to_be_destroyed)) { - //cout << "Destroy\n"; + // cout << "Destroy\n"; delete to_be_destroyed->item; to_be_destroyed= to_be_destroyed->next; } } - //cout << "Postpone\n"; - last_addition= now; + // cout << "Postpone\n"; + last_addition = now; to_be_destroyed= list (a, to_be_destroyed); } @@ -192,13 +190,13 @@ schedule_destruction (QAction* a) { ******************************************************************************/ qt_ui_element_rep::qt_ui_element_rep (types _type, blackbox _load) -: qt_widget_rep (_type), load (_load), cachedActionList (NULL) {} + : qt_widget_rep (_type), load (_load), cachedActionList (NULL) {} -qt_ui_element_rep::~qt_ui_element_rep() { +qt_ui_element_rep::~qt_ui_element_rep () { if (cachedActionList) { - while (!cachedActionList->empty()) { - QAction *a = cachedActionList->takeFirst(); - //if (a) delete a; + while (!cachedActionList->empty ()) { + QAction* a= cachedActionList->takeFirst (); + // if (a) delete a; if (a) schedule_destruction (a); } delete cachedActionList; @@ -208,26 +206,43 @@ qt_ui_element_rep::~qt_ui_element_rep() { blackbox qt_ui_element_rep::get_payload (qt_widget qtw, types check_type) { ASSERT (check_type == none || qtw->type == check_type, - c_string ("get_payload: widget " * qtw->type_as_string() * + c_string ("get_payload: widget " * qtw->type_as_string () * " was not of the expected type.")); switch (qtw->type) { - case horizontal_menu: case vertical_menu: case horizontal_list: - case vertical_list: case tile_menu: case aligned_widget: - case minibar_menu: case menu_separator: case menu_group: - case pulldown_button: case pullright_button: case menu_button: - case text_widget: case xpm_widget: case toggle_widget: - case enum_widget: case choice_widget: case filtered_choice_widget: - case scrollable_widget: case hsplit_widget: case vsplit_widget: - case tabs_widget: case icon_tabs_widget: case resize_widget: - case refresh_widget: case refreshable_widget: case balloon_widget: - case glue_widget: case division_widget: - { - qt_ui_element_rep* rep = static_cast (qtw.rep); - return rep->load; - } - break; - default: - return blackbox(); + case horizontal_menu: + case vertical_menu: + case horizontal_list: + case vertical_list: + case tile_menu: + case aligned_widget: + case minibar_menu: + case menu_separator: + case menu_group: + case pulldown_button: + case pullright_button: + case menu_button: + case text_widget: + case xpm_widget: + case toggle_widget: + case enum_widget: + case choice_widget: + case filtered_choice_widget: + case scrollable_widget: + case hsplit_widget: + case vsplit_widget: + case tabs_widget: + case icon_tabs_widget: + case resize_widget: + case refresh_widget: + case refreshable_widget: + case balloon_widget: + case glue_widget: + case division_widget: { + qt_ui_element_rep* rep= static_cast (qtw.rep); + return rep->load; + } break; + default: + return blackbox (); } } @@ -236,41 +251,37 @@ qt_ui_element_rep::get_payload (qt_widget qtw, types check_type) { must be of the standard OS dependent type implemented by qt_menu_rep using QMenu. */ -widget +widget qt_ui_element_rep::make_popup_widget () { - if (type == qt_widget_rep::vertical_menu) - return tm_new (this); - else - return qt_widget_rep::make_popup_widget(); + if (type == qt_widget_rep::vertical_menu) return tm_new (this); + else return qt_widget_rep::make_popup_widget (); } QList* -qt_ui_element_rep::get_qactionlist() { - if (cachedActionList) return cachedActionList; - - QList *list = new QList(); - - switch (type) { - case vertical_menu: - case horizontal_menu: - case vertical_list: - { - typedef array T; - array arr = open_box (load); - - for (int i = 0; i < N(arr); i++) { - if (is_nil (arr[i])) break; - QAction* a = concrete (arr[i])->as_qaction (); - list->append(a); - } - } - break; - - default: - break; +qt_ui_element_rep::get_qactionlist () { + if (cachedActionList) return cachedActionList; + + QList* list= new QList (); + + switch (type) { + case vertical_menu: + case horizontal_menu: + case vertical_list: { + typedef array T; + array arr= open_box (load); + + for (int i= 0; i < N (arr); i++) { + if (is_nil (arr[i])) break; + QAction* a= concrete (arr[i])->as_qaction (); + list->append (a); } - cachedActionList = list; - return list; + } break; + + default: + break; + } + cachedActionList= list; + return list; } /*! For the refresh_widget @@ -279,905 +290,861 @@ qt_ui_element_rep::get_qactionlist() { qt_ui_element_rep::operator tree () { if (type == refresh_widget) { typedef pair T; - T x= open_box (load); + T x= open_box (load); return tree (TUPLE, "refresh", x.x1, x.x2); } else if (type == refreshable_widget) { typedef pair T; - T x= open_box (load); + T x= open_box (load); return tree (TUPLE, "refreshable", x.x2); } else { - return tree(); + return tree (); } } -QAction* +QAction* qt_ui_element_rep::as_qaction () { - //if (DEBUG_QT_WIDGETS) - //debug_widgets << "as_qaction: " << type_as_string() << LF; + // if (DEBUG_QT_WIDGETS) + // debug_widgets << "as_qaction: " << type_as_string() << LF; + + // DON'T try to always cache the action returned: this breaks dynamic menus! + QAction* act= NULL; - // DON'T try to always cache the action returned: this breaks dynamic menus! - QAction* act = NULL; - switch (type) { - case vertical_menu: - case horizontal_menu: - case vertical_list: - // a vertical menu made up of the widgets in arr + case vertical_menu: + case horizontal_menu: + case vertical_list: + // a vertical menu made up of the widgets in arr { typedef array T; - array arr = open_box (load); - - act = new QTMAction (NULL); + array arr= open_box (load); + + act= new QTMAction (NULL); act->setText (qt_translate ("Menu")); - QMenu* m = new QMenu (); - for (int i = 0; i < N(arr); i++) { + QMenu* m= new QMenu (); + for (int i= 0; i < N (arr); i++) { if (is_nil (arr[i])) break; - QAction* a = concrete (arr[i])->as_qaction (); + QAction* a= concrete (arr[i])->as_qaction (); m->addAction (a); a->setParent (act); } act->setMenu (m); // The QTMAction takes ownership of the QMenu } - break; - - case horizontal_list: - // an horizontal list made up of the widgets in arr + break; + + case horizontal_list: + // an horizontal list made up of the widgets in arr { typedef array T; - array arr = open_box (load); - act = new QTMMinibarAction (arr); + array arr= open_box (load); + act = new QTMMinibarAction (arr); } - break; - - case aligned_widget: - // a table with two columns FIXME!!!! + break; + + case aligned_widget: + // a table with two columns FIXME!!!! { - typedef triple, array, coord4 > T; - T x = open_box(load); - array lhs = x.x1; - array rhs = x.x2; - - if (N(lhs) != N(rhs)) TM_FAILED ("aligned_widget: N(lhs) != N(rhs) "); - - array wids(N(lhs)*3); - for (int i=0; i < N(lhs); ++i) { - wids[3*i] = lhs[i]; - wids[3*i+1] = rhs[i]; - wids[3*i+2] = ::glue_widget(false, true, 1, 1); + typedef triple, array, coord4> T; + T x = open_box (load); + array lhs= x.x1; + array rhs= x.x2; + + if (N (lhs) != N (rhs)) TM_FAILED ("aligned_widget: N(lhs) != N(rhs) "); + + array wids (N (lhs) * 3); + for (int i= 0; i < N (lhs); ++i) { + wids[3 * i] = lhs[i]; + wids[3 * i + 1]= rhs[i]; + wids[3 * i + 2]= ::glue_widget (false, true, 1, 1); } - act = new QTMMinibarAction (wids); + act= new QTMMinibarAction (wids); } - break; + break; - case tile_menu: - // a menu rendered as a table of "cols" columns & made up of the widgets - // in array a + case tile_menu: + // a menu rendered as a table of "cols" columns & made up of the widgets + // in array a { typedef pair, int> T; - T x = open_box(load); - array a = x.x1; - int cols = x.x2; + T x = open_box (load); + array a = x.x1; + int cols= x.x2; - act = new QTMTileAction (a, cols); + act= new QTMTileAction (a, cols); } - break; - - case minibar_menu: - { - typedef array T; - array arr = open_box (load); + break; - act = new QTMMinibarAction (arr); - } - break; - - case menu_separator: - // a horizontal or vertical menu separator + case minibar_menu: { + typedef array T; + array arr= open_box (load); + + act= new QTMMinibarAction (arr); + } break; + + case menu_separator: + // a horizontal or vertical menu separator { - act = new QTMAction (NULL); + act= new QTMAction (NULL); act->setSeparator (true); } - break; + break; - case glue_widget: - { - act = new QTMAction(); - act->setEnabled(false); - } - break; + case glue_widget: { + act= new QTMAction (); + act->setEnabled (false); + } break; - case menu_group: - // a menu group; the name should be greyed and centered + case menu_group: + // a menu group; the name should be greyed and centered { typedef pair T; - T x = open_box (load); - string name = x.x1; - int style = x.x2; //FIXME: ignored. Use a QWidgeAction to use it? - - act = new QTMAction (NULL); + T x = open_box (load); + string name= x.x1; + int style= x.x2; // FIXME: ignored. Use a QWidgeAction to use it? + + act= new QTMAction (NULL); act->setText (to_qstring (name)); act->setEnabled (false); - act->setFont (to_qfont (style, act->font())); + act->setFont (to_qfont (style, act->font ())); } - break; - - case pulldown_button: - case pullright_button: - // a button w with a lazy pulldown menu pw + break; + + case pulldown_button: + case pullright_button: + // a button w with a lazy pulldown menu pw { - typedef pair > T; - T x = open_box (load); - qt_widget qtw = concrete (x.x1); - promise pw = x.x2; - - act = qtw->as_qaction (); - QTMLazyMenu* lm = new QTMLazyMenu (pw); - lm->attachTo (act); // lm deletes itself after action dies + typedef pair> T; + T x = open_box (load); + qt_widget qtw= concrete (x.x1); + promise pw = x.x2; + + act = qtw->as_qaction (); + QTMLazyMenu* lm= new QTMLazyMenu (pw); + lm->attachTo (act); // lm deletes itself after action dies act->setEnabled (true); } - break; - - case menu_button: - // a command button with an optional prefix (o, * or v) and - // keyboard shortcut; if ok does not hold, then the button is greyed + break; + + case menu_button: + // a command button with an optional prefix (o, * or v) and + // keyboard shortcut; if ok does not hold, then the button is greyed { typedef quintuple T; - T x = open_box (load); - - qt_widget qtw = concrete (x.x1); - command cmd = x.x2; - string pre = x.x3; - string ks = x.x4; - int style = x.x5; - - act = qtw->as_qaction(); - /* NOTE: we install shortcuts but in QTMWidget::event() we also handle - QEvent::ShortcutOverride, effectively disabling the shortcuts. This - allows us to keep the shortcut text in the menus while relaying all - keypresses through the editor. - */ - const QKeySequence& qks = to_qkeysequence (ks); - if (!qks.isEmpty()) { + T x= open_box (load); + + qt_widget qtw = concrete (x.x1); + command cmd = x.x2; + string pre = x.x3; + string ks = x.x4; + int style= x.x5; + + act= qtw->as_qaction (); + /* NOTE: we install shortcuts but in QTMWidget::event() we also handle + QEvent::ShortcutOverride, effectively disabling the shortcuts. This + allows us to keep the shortcut text in the menus while relaying all + keypresses through the editor. + */ + const QKeySequence& qks= to_qkeysequence (ks); + if (!qks.isEmpty ()) { act->setShortcut (qks); - act->setShortcutVisibleInContextMenu(true); + act->setShortcutVisibleInContextMenu (true); } // NOTE: this used to be a Qt::QueuedConnection, but the slot would not // be called if in a contextual menu QTMCommand* c= new QTMCommand (act, cmd); - QObject::connect (act, SIGNAL (triggered()), c, SLOT (apply())); - - bool ok = (style & WIDGET_STYLE_INERT) == 0; - act->setEnabled (ok? true: false); - - // FIXME: implement complete prefix handling - bool check = (pre != "") || (style & WIDGET_STYLE_PRESSED); - act->setCheckable (check? true: false); - act->setChecked (check? true: false); - if (pre == "v") {} - else if (pre == "*") {} + QObject::connect (act, SIGNAL (triggered ()), c, SLOT (apply ())); + + bool ok= (style & WIDGET_STYLE_INERT) == 0; + act->setEnabled (ok ? true : false); + + // FIXME: implement complete prefix handling + bool check= (pre != "") || (style & WIDGET_STYLE_PRESSED); + act->setCheckable (check ? true : false); + act->setChecked (check ? true : false); + if (pre == "v") { + } + else if (pre == "*") { + } // [mi setOnStateImage:[NSImage imageNamed:@"TMStarMenuBullet"]]; - else if (pre == "o") {} + else if (pre == "o") { + } } - break; - - case balloon_widget: - // Given a button widget w, specify a help balloon which should be - // displayed when the user leaves the mouse pointer on the button for a - // small while + break; + + case balloon_widget: + // Given a button widget w, specify a help balloon which should be + // displayed when the user leaves the mouse pointer on the button for a + // small while { typedef pair T; - T x = open_box (load); - qt_widget qtw = concrete (x.x1); - qt_widget help = concrete (x.x2); + T x = open_box (load); + qt_widget qtw = concrete (x.x1); + qt_widget help= concrete (x.x2); - act = qtw->as_qaction(); + act= qtw->as_qaction (); { typedef quartet T1; - T1 y = open_box (get_payload (help, text_widget)); + T1 y= open_box (get_payload (help, text_widget)); act->setToolTip (to_qstring (y.x1)); - // HACK: force displaying of the tooltip (needed for items in the QMenuBar) - QObject::connect (act, SIGNAL(hovered()), - act, SLOT(showToolTip())); + // HACK: force displaying of the tooltip (needed for items in the + // QMenuBar) + QObject::connect (act, SIGNAL (hovered ()), act, SLOT (showToolTip ())); } } - break; - - case text_widget: - // A text widget with a given color and transparency + break; + + case text_widget: + // A text widget with a given color and transparency { typedef quartet T; - T x = open_box(load); - string str = x.x1; - int style = x.x2; - //color col = x.x3; - //bool tsp = x.x4; + T x = open_box (load); + string str = x.x1; + int style= x.x2; + // color col = x.x3; + // bool tsp = x.x4; - QTMAction* a = new QTMAction (NULL); + QTMAction* a= new QTMAction (NULL); a->set_text (str); - a->setFont (to_qfont (style, a->font())); - act = a; + a->setFont (to_qfont (style, a->font ())); + act= a; } - break; - - case xpm_widget: - // a widget with an X pixmap icon + break; + + case xpm_widget: + // a widget with an X pixmap icon { - url image = open_box(load); - act = new QTMAction (NULL); + url image= open_box (load); + act = new QTMAction (NULL); act->setIcon (qt_load_icon (image)); } - break; + break; - default: - TM_FAILED (c_string ("qt_ui_element: unknown type for as_qaction, " - * type_as_string())); + default: + TM_FAILED (c_string ("qt_ui_element: unknown type for as_qaction, " * + type_as_string ())); } return act; } - -QLayoutItem * +QLayoutItem* qt_ui_element_rep::as_qlayoutitem () { if (DEBUG_QT_WIDGETS) - debug_widgets << "as_qlayoutitem: " << type_as_string() << LF; + debug_widgets << "as_qlayoutitem: " << type_as_string () << LF; switch (type) { - case horizontal_menu: - case vertical_menu: - case horizontal_list: - case vertical_list: - { - typedef array T; - T arr = open_box (load); - - QLayout *l; - if ((type == horizontal_list) || (type==horizontal_menu)) - l = new QHBoxLayout(); - else - l = new QVBoxLayout(); - - l->setSpacing(0); - - if (N(arr) > 0 && concrete(arr[0]).rep && - (concrete(arr[0]).rep->type == tabs_widget || - concrete(arr[0]).rep->type == icon_tabs_widget)) // HACK! - l->setContentsMargins(0, 6, 0, 0); - else - l->setContentsMargins(0, 0, 0, 0); - - for (int i = 0; i < N(arr); i++) { - if (is_nil (arr[i])) break; - QLayoutItem* li = concrete (arr[i])->as_qlayoutitem (); - if (li) l->addItem(li); // ownership transferred - } - - return l; + case horizontal_menu: + case vertical_menu: + case horizontal_list: + case vertical_list: { + typedef array T; + T arr= open_box (load); + + QLayout* l; + if ((type == horizontal_list) || (type == horizontal_menu)) + l= new QHBoxLayout (); + else l= new QVBoxLayout (); + + l->setSpacing (0); + + if (N (arr) > 0 && concrete (arr[0]).rep && + (concrete (arr[0]).rep->type == tabs_widget || + concrete (arr[0]).rep->type == icon_tabs_widget)) // HACK! + l->setContentsMargins (0, 6, 0, 0); + else l->setContentsMargins (0, 0, 0, 0); + + for (int i= 0; i < N (arr); i++) { + if (is_nil (arr[i])) break; + QLayoutItem* li= concrete (arr[i])->as_qlayoutitem (); + if (li) l->addItem (li); // ownership transferred } - case tile_menu: - { - typedef array T1; - typedef pair T; - T x = open_box (load); - T1 a = x.x1; - int cols = x.x2; - - QGridLayout* l = new QGridLayout (); - l->setSizeConstraint (QLayout::SetFixedSize); - l->setHorizontalSpacing (2); - l->setVerticalSpacing (2); - l->setContentsMargins (4, 0, 4, 0); - int row= 0, col= 0; - for (int i=0; i < N(a); i++) { - QLayoutItem* li = concrete(a[i])->as_qlayoutitem(); - l->addItem(li, row, col); - col++; - if (col >= cols) { col = 0; row++; } + return l; + } + + case tile_menu: { + typedef array T1; + typedef pair T; + T x = open_box (load); + T1 a = x.x1; + int cols= x.x2; + + QGridLayout* l= new QGridLayout (); + l->setSizeConstraint (QLayout::SetFixedSize); + l->setHorizontalSpacing (2); + l->setVerticalSpacing (2); + l->setContentsMargins (4, 0, 4, 0); + int row= 0, col= 0; + for (int i= 0; i < N (a); i++) { + QLayoutItem* li= concrete (a[i])->as_qlayoutitem (); + l->addItem (li, row, col); + col++; + if (col >= cols) { + col= 0; + row++; } - return l; } + return l; + } - case aligned_widget: - // a table with two columns (FIXME!) + case aligned_widget: + // a table with two columns (FIXME!) { - typedef array T2; - typedef triple T; - T x = open_box(load); - T2 lhs = x.x1; - T2 rhs = x.x2; - coord4 y = x.x3; + typedef array T2; + typedef triple T; + T x = open_box (load); + T2 lhs= x.x1; + T2 rhs= x.x2; + coord4 y = x.x3; // FIXME: lpad and rpad ignored. - SI hsep = y.x1; SI vsep = y.x2; SI lpad = y.x3; SI rpad = y.x4; + SI hsep= y.x1; + SI vsep= y.x2; + SI lpad= y.x3; + SI rpad= y.x4; if (tm_style_sheet != "") { hsep= (SI) (floor (retina_scale * hsep / 256.0 + 0.5) * PIXEL); vsep= (SI) (floor (retina_scale * vsep / 256.0 + 0.5) * PIXEL); lpad= (SI) (floor (retina_scale * lpad / 256.0 + 0.5) * PIXEL); rpad= (SI) (floor (retina_scale * rpad / 256.0 + 0.5) * PIXEL); } - (void) lpad; (void) rpad; - - if (N(lhs) != N(rhs)) TM_FAILED ("aligned_widget: N(lhs) != N(rhs) "); - - /* FIXME? From the docs: - If the QGridLayout is not the top-level layout (i.e. does not manage - all of the widget's area and children), you must add it to its parent - layout when you create it, but before you do anything with it. - */ - QGridLayout* l = new QGridLayout (); - l->setAlignment (Qt::AlignLeft); // Don't center items automatically + (void) lpad; + (void) rpad; + + if (N (lhs) != N (rhs)) TM_FAILED ("aligned_widget: N(lhs) != N(rhs) "); + + /* FIXME? From the docs: + If the QGridLayout is not the top-level layout (i.e. does not manage + all of the widget's area and children), you must add it to its parent + layout when you create it, but before you do anything with it. + */ + QGridLayout* l= new QGridLayout (); + l->setAlignment (Qt::AlignLeft); // Don't center items automatically l->setSizeConstraint (QLayout::SetMinAndMaxSize); - l->setHorizontalSpacing (6+hsep/PIXEL); - l->setVerticalSpacing (6+vsep/PIXEL); - for (int i=0; i < N(lhs); i++) { - QLayoutItem* lli = concrete(lhs[i])->as_qlayoutitem(); - QLayoutItem* rli = concrete(rhs[i])->as_qlayoutitem(); - if (lli) l->addItem (lli, i, 0, 1, 1, Qt::AlignRight | Qt::AlignVCenter); + l->setHorizontalSpacing (6 + hsep / PIXEL); + l->setVerticalSpacing (6 + vsep / PIXEL); + for (int i= 0; i < N (lhs); i++) { + QLayoutItem* lli= concrete (lhs[i])->as_qlayoutitem (); + QLayoutItem* rli= concrete (rhs[i])->as_qlayoutitem (); + if (lli) + l->addItem (lli, i, 0, 1, 1, Qt::AlignRight | Qt::AlignVCenter); if (rli) l->addItem (rli, i, 1, 1, 1, Qt::AlignLeft | Qt::AlignVCenter); } return l; } - - case minibar_menu: - { - typedef array T; - array arr = open_box (load); - QBoxLayout* l= new QBoxLayout (QBoxLayout::LeftToRight); - l->setContentsMargins (0, 0, 0, 0); - l->setSpacing (0); - for (int i = 0; i < N(arr); i++) { - QLayoutItem* li = concrete(arr[i])->as_qlayoutitem(); - l->addItem(li); - } - return l; - } - - case menu_separator: - { - typedef bool T; - T vertical = open_box (load); - QSizePolicy::Policy hpolicy = vertical ? QSizePolicy::Fixed - : QSizePolicy::Preferred; - QSizePolicy::Policy vpolicy = vertical ? QSizePolicy::Preferred - : QSizePolicy::Fixed; - return new QSpacerItem (1, 1, hpolicy, vpolicy); - } - - case menu_group: - { - return NULL; - } - case pulldown_button: - case pullright_button: - case menu_button: - case text_widget: - case xpm_widget: - case toggle_widget: - case enum_widget: - case choice_widget: - case filtered_choice_widget: - case tree_view_widget: - case scrollable_widget: - case hsplit_widget: - case vsplit_widget: - case tabs_widget: - case icon_tabs_widget: - case resize_widget: - case refresh_widget: - case refreshable_widget: - case balloon_widget: - case division_widget: - { - QWidgetItem* wi = new QWidgetItem (this->as_qwidget()); - return wi; + case minibar_menu: { + typedef array T; + array arr= open_box (load); + QBoxLayout* l = new QBoxLayout (QBoxLayout::LeftToRight); + l->setContentsMargins (0, 0, 0, 0); + l->setSpacing (0); + for (int i= 0; i < N (arr); i++) { + QLayoutItem* li= concrete (arr[i])->as_qlayoutitem (); + l->addItem (li); } - break; + return l; + } - case glue_widget: - // Used only for non-colored glue widgets (skips qt_glue_widget_rep) + case menu_separator: { + typedef bool T; + T vertical= open_box (load); + QSizePolicy::Policy hpolicy= + vertical ? QSizePolicy::Fixed : QSizePolicy::Preferred; + QSizePolicy::Policy vpolicy= + vertical ? QSizePolicy::Preferred : QSizePolicy::Fixed; + return new QSpacerItem (1, 1, hpolicy, vpolicy); + } + + case menu_group: { + return NULL; + } + + case pulldown_button: + case pullright_button: + case menu_button: + case text_widget: + case xpm_widget: + case toggle_widget: + case enum_widget: + case choice_widget: + case filtered_choice_widget: + case tree_view_widget: + case scrollable_widget: + case hsplit_widget: + case vsplit_widget: + case tabs_widget: + case icon_tabs_widget: + case resize_widget: + case refresh_widget: + case refreshable_widget: + case balloon_widget: + case division_widget: { + QWidgetItem* wi= new QWidgetItem (this->as_qwidget ()); + return wi; + } break; + + case glue_widget: + // Used only for non-colored glue widgets (skips qt_glue_widget_rep) { typedef quartet T; - T x = open_box (load); - SI w= x.x3, h= x.x4; + T x= open_box (load); + SI w= x.x3, h= x.x4; if (tm_style_sheet != "") { w= (SI) floor (retina_scale * w + 0.5); h= (SI) floor (retina_scale * h + 0.5); } - QSize sz = QSize (w, h); - QSizePolicy::Policy hpolicy = x.x1 ? QSizePolicy::MinimumExpanding - : QSizePolicy::Minimum; - QSizePolicy::Policy vpolicy = x.x2 ? QSizePolicy::MinimumExpanding - : QSizePolicy::Minimum; + QSize sz= QSize (w, h); + QSizePolicy::Policy hpolicy= + x.x1 ? QSizePolicy::MinimumExpanding : QSizePolicy::Minimum; + QSizePolicy::Policy vpolicy= + x.x2 ? QSizePolicy::MinimumExpanding : QSizePolicy::Minimum; return new QSpacerItem (sz.width (), sz.height (), hpolicy, vpolicy); } - break; - default: - ; + break; + default:; } - + return NULL; } /* Because our policy is that the returned QWidget is owned by the caller, we - must be careful and any QObjects we construct here must have the returned + must be careful and any QObjects we construct here must have the returned QWidget as parent. */ -QWidget * +QWidget* qt_ui_element_rep::as_qwidget () { if (DEBUG_QT_WIDGETS) - debug_widgets << "as_qwidget: " << type_as_string() << LF; + debug_widgets << "as_qwidget: " << type_as_string () << LF; + + // Don't return the cached widget, this only happens for refresh_widgets + // and then we crash. + // if (qwid) return qwid; - // Don't return the cached widget, this only happens for refresh_widgets - // and then we crash. -// if (qwid) return qwid; - switch (type) { - case horizontal_menu: - case vertical_menu: - case horizontal_list: - case vertical_list: - case tile_menu: - case minibar_menu: - case aligned_widget: - { - // note that the QLayout is the same object as the QLayoutItem - // so no need to free the layoutitem - QLayout* l = this->as_qlayoutitem()->layout(); - QWidget* w = new QWidget(); - if (l) - w->setLayout(l); - else if (DEBUG_QT_WIDGETS) - // should we create a default layout? - debug_widgets << "qt_ui_element_rep::as_qwidget(): " - << "invalid situation" << LF; - qwid = w; - } - break; - - case resize_widget: - { - typedef triple T1; - typedef quartet T; - T x = open_box(load); - - qt_widget wid = concrete(x.x1); - int style = x.x2; - T1 widths = x.x3; - T1 heights = x.x4; - - qwid = wid->as_qwidget(); - qt_apply_tm_style (qwid, style); - - QSize minSize = qt_decode_length (widths.x1, heights.x1, - qwid->minimumSizeHint(), - qwid->fontMetrics()); - QSize defSize = qt_decode_length (widths.x2, heights.x2, - qwid->minimumSizeHint(), - qwid->fontMetrics()); - QSize maxSize = qt_decode_length (widths.x3, heights.x3, - qwid->minimumSizeHint(), - qwid->fontMetrics()); - - if (minSize == defSize && defSize == maxSize) { - qwid->setFixedSize (defSize); - qwid->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); - } else { - qwid->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); - qwid->setMinimumSize (minSize); - qwid->setMaximumSize (maxSize); - qwid->resize (defSize); - } + case horizontal_menu: + case vertical_menu: + case horizontal_list: + case vertical_list: + case tile_menu: + case minibar_menu: + case aligned_widget: { + // note that the QLayout is the same object as the QLayoutItem + // so no need to free the layoutitem + QLayout* l= this->as_qlayoutitem ()->layout (); + QWidget* w= new QWidget (); + if (l) w->setLayout (l); + else if (DEBUG_QT_WIDGETS) + // should we create a default layout? + debug_widgets << "qt_ui_element_rep::as_qwidget(): " + << "invalid situation" << LF; + qwid= w; + } break; + + case resize_widget: { + typedef triple T1; + typedef quartet T; + T x= open_box (load); + + qt_widget wid = concrete (x.x1); + int style = x.x2; + T1 widths = x.x3; + T1 heights= x.x4; + + qwid= wid->as_qwidget (); + qt_apply_tm_style (qwid, style); + + QSize minSize= qt_decode_length ( + widths.x1, heights.x1, qwid->minimumSizeHint (), qwid->fontMetrics ()); + QSize defSize= qt_decode_length ( + widths.x2, heights.x2, qwid->minimumSizeHint (), qwid->fontMetrics ()); + QSize maxSize= qt_decode_length ( + widths.x3, heights.x3, qwid->minimumSizeHint (), qwid->fontMetrics ()); + + if (minSize == defSize && defSize == maxSize) { + qwid->setFixedSize (defSize); + qwid->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); } - break; - - case menu_separator: - case menu_group: - { - qwid = new QWidget(); + else { + qwid->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); + qwid->setMinimumSize (minSize); + qwid->setMaximumSize (maxSize); + qwid->resize (defSize); } - break; - - case glue_widget: + } break; + + case menu_separator: + case menu_group: { + qwid= new QWidget (); + } break; + + case glue_widget: // Used only for non-colored glue widgets (skips qt_glue_widget_rep) { typedef quartet T; - T x = open_box(load); - SI w= x.x3, h= x.x4; + T x= open_box (load); + SI w= x.x3, h= x.x4; if (tm_style_sheet != "") { w= (SI) floor (retina_scale * w + 0.5); h= (SI) floor (retina_scale * h + 0.5); } - QSize sz = QSize (w, h); - QSizePolicy::Policy hpolicy = x.x1 ? QSizePolicy::MinimumExpanding - : QSizePolicy::Minimum; - QSizePolicy::Policy vpolicy = x.x2 ? QSizePolicy::MinimumExpanding - : QSizePolicy::Minimum; - qwid = new QWidget(); + QSize sz= QSize (w, h); + QSizePolicy::Policy hpolicy= + x.x1 ? QSizePolicy::MinimumExpanding : QSizePolicy::Minimum; + QSizePolicy::Policy vpolicy= + x.x2 ? QSizePolicy::MinimumExpanding : QSizePolicy::Minimum; + qwid= new QWidget (); qwid->setMinimumSize (sz); qwid->setSizePolicy (hpolicy, vpolicy); } - break; - - - case pulldown_button: - case pullright_button: - { - typedef pair > T; - T x = open_box (load); - qt_widget qtw = concrete (x.x1); - promise pw = x.x2; - - if (qtw->type == xpm_widget) { - url image = open_box (get_payload (qtw)); - QToolButton* b = new QToolButton(); - - QTMLazyMenu* lm = new QTMLazyMenu (pw, b, type == pullright_button); - b->setIcon (qt_load_icon (image)); - b->setPopupMode (QToolButton::InstantPopup); - b->setAutoRaise (true); - b->setMenu (lm); - qwid = b; - } else if (qtw->type == text_widget) { - typedef quartet T1; - T1 y = open_box (get_payload (qtw)); - QPushButton* b = new QPushButton(); - QTMLazyMenu* lm = new QTMLazyMenu (pw, b, type == pullright_button); - b->setMenu (lm); - b->setAutoDefault (false); - b->setText (to_qstring (y.x1)); - b->setEnabled (! (y.x2 & WIDGET_STYLE_INERT)); - qt_apply_tm_style (b, y.x2, y.x3); - qwid = b; - } - qwid->setStyle (qtmstyle()); - + break; + + case pulldown_button: + case pullright_button: { + typedef pair> T; + T x = open_box (load); + qt_widget qtw= concrete (x.x1); + promise pw = x.x2; + + if (qtw->type == xpm_widget) { + url image= open_box (get_payload (qtw)); + QToolButton* b = new QToolButton (); + + QTMLazyMenu* lm= new QTMLazyMenu (pw, b, type == pullright_button); + b->setIcon (qt_load_icon (image)); + b->setPopupMode (QToolButton::InstantPopup); + b->setAutoRaise (true); + b->setMenu (lm); + qwid= b; } - break; - - // a command button with an optional prefix (o, * or v) and (sometimes) - // keyboard shortcut - case menu_button: - { - typedef quintuple T; - T x = open_box(load); - qt_widget qtw = concrete(x.x1); // contents: xpm_widget, text_widget, ...? - command cmd = x.x2; - string pre = x.x3; - string ks = x.x4; - int style = x.x5; - - if (qtw->type == xpm_widget) { // Toolbar button - QAction* a = as_qaction(); // Create key shortcuts and actions - QToolButton* b = new QToolButton (); - b->setIcon (a->icon()); - b->setPopupMode (QToolButton::InstantPopup); - b->setAutoRaise (true); - b->setDefaultAction (a); - a->setParent (b); - qwid = b; - } else { // text_widget - QPushButton* b = new QPushButton(); - QTMCommand* qtmcmd = new QTMCommand (b, cmd); - QObject::connect (b, SIGNAL (clicked ()), qtmcmd, SLOT (apply ())); - if (qtw->type == text_widget) { - typedef quartet T1; - b->setText (to_qstring (open_box (get_payload (qtw)).x1)); - } - b->setFlat (! (style & WIDGET_STYLE_BUTTON)); - qwid = b; - } - qwid->setStyle (qtmstyle()); - qt_apply_tm_style (qwid, style); - qwid->setEnabled (! (style & WIDGET_STYLE_INERT)); - qwid->setFocusPolicy (Qt::StrongFocus); - } - break; - - // given a button widget w, specify a help balloon which should be displayed - // when the user leaves the mouse pointer on the button for a small while - case balloon_widget: - { - typedef pair T; - T x = open_box(load); - qt_widget qtw = concrete (x.x1); - qt_widget help = concrete (x.x2); - + else if (qtw->type == text_widget) { typedef quartet T1; - T1 y = open_box(get_payload (help, text_widget)); - QWidget* w = qtw->as_qwidget(); - w->setToolTip (to_qstring (y.x1)); - qwid = w; - } - break; - - // a text widget with a given color and transparency - case text_widget: - { - typedef quartet T; - T x = open_box(load); - string str = x.x1; - int style = x.x2; - color c = x.x3; - //bool tsp = x.x4; // FIXME: add transparency support - - QLabel* w = new QLabel(); - /* - //FIXME: implement refresh when changing language - QTMAction* a= new QTMAction (NULL); - a->set_text (str); - */ - w->setText (to_qstring (str)); - w->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); - // Workaround too small sizeHint() when the text has letters with descent: - w->setMinimumHeight (w->fontMetrics().height()); - w->setFocusPolicy (Qt::NoFocus); - - qt_apply_tm_style (w, style, c); - qwid = w; + T1 y = open_box (get_payload (qtw)); + QPushButton* b = new QPushButton (); + QTMLazyMenu* lm= new QTMLazyMenu (pw, b, type == pullright_button); + b->setMenu (lm); + b->setAutoDefault (false); + b->setText (to_qstring (y.x1)); + b->setEnabled (!(y.x2 & WIDGET_STYLE_INERT)); + qt_apply_tm_style (b, y.x2, y.x3); + qwid= b; } - break; - - // a widget with an X pixmap icon - case xpm_widget: - { - url image = open_box(load); - QLabel* l = new QLabel (NULL); - l->setPixmap (as_pixmap (*xpm_image (image))); - qwid = l; - } - break; - - case toggle_widget: - { - typedef triple T; - T x = open_box(load); - command cmd = x.x1; - bool check = x.x2; - int style = x.x3; - - QCheckBox* w = new QCheckBox (NULL); - w->setCheckState (check ? Qt::Checked : Qt::Unchecked); - qt_apply_tm_style (w, style); - w->setFocusPolicy (Qt::StrongFocus); - - command tcmd = tm_new (w, cmd); - QTMCommand* c = new QTMCommand (w, tcmd); - QObject::connect (w, SIGNAL (stateChanged(int)), c, SLOT (apply())); - - qwid = w; + qwid->setStyle (qtmstyle ()); + + } break; + + // a command button with an optional prefix (o, * or v) and (sometimes) + // keyboard shortcut + case menu_button: { + typedef quintuple T; + T x = open_box (load); + qt_widget qtw = concrete (x.x1); // contents: xpm_widget, text_widget, ...? + command cmd = x.x2; + string pre = x.x3; + string ks = x.x4; + int style= x.x5; + + if (qtw->type == xpm_widget) { // Toolbar button + QAction* a= as_qaction (); // Create key shortcuts and actions + QToolButton* b= new QToolButton (); + b->setIcon (a->icon ()); + b->setPopupMode (QToolButton::InstantPopup); + b->setAutoRaise (true); + b->setDefaultAction (a); + a->setParent (b); + qwid= b; } - break; - - case enum_widget: - { - typedef quintuple, string, int, string> T; - T x = open_box(load); - command cmd = x.x1; - QStringList values = to_qstringlist (x.x2); - QString value = to_qstring (x.x3); - int style = x.x4; - - QTMComboBox* w = new QTMComboBox (NULL); - if (values.isEmpty()) - values << QString(""); // safeguard - - w->setEditable (value.isEmpty() || values.last().isEmpty()); // weird convention?! - if (values.last().isEmpty()) - values.removeLast(); - - w->addItemsAndResize (values, x.x5, ""); - int index = w->findText (value, Qt::MatchFixedString | Qt::MatchCaseSensitive); - if (index != -1) - w->setCurrentIndex (index); - - qt_apply_tm_style (w, style); - - command ecmd = tm_new (w, cmd); - QTMCommand* c = new QTMCommand (w, ecmd); - // NOTE: with QueuedConnections, the slots are sometimes not invoked. - QObject::connect (w, SIGNAL (currentIndexChanged(int)), c, SLOT (apply())); - - qwid = w; - } - break; - - // select one or multiple values from a list - case choice_widget: - { - typedef quartet, array, bool> T; - T x = open_box(load); - qwid = new QTMListView (x.x1, to_qstringlist(x.x2), to_qstringlist(x.x3), - x.x4); - } - break; - - case filtered_choice_widget: - { - typedef quartet, string, string> T; - T x = open_box(load); - string filter = x.x4; - QTMListView* choiceWidget = new QTMListView (x.x1, to_qstringlist (x.x2), - QStringList (to_qstring (x.x3)), - false, true, true); - - QTMLineEdit* lineEdit = new QTMLineEdit (0, "string", "1w"); - QObject::connect (lineEdit, SIGNAL (textChanged (const QString&)), - choiceWidget->filter(), SLOT (setFilterRegExp (const QString&))); - lineEdit->setText (to_qstring (filter)); - lineEdit->setFocusPolicy (Qt::StrongFocus); - - QVBoxLayout* layout = new QVBoxLayout (); - layout->addWidget (lineEdit); - layout->addWidget (choiceWidget); - layout->setSpacing (0); - layout->setContentsMargins (0, 0, 0, 0); - - qwid = new QWidget(); - qwid->setLayout (layout); + else { // text_widget + QPushButton* b = new QPushButton (); + QTMCommand* qtmcmd= new QTMCommand (b, cmd); + QObject::connect (b, SIGNAL (clicked ()), qtmcmd, SLOT (apply ())); + if (qtw->type == text_widget) { + typedef quartet T1; + b->setText (to_qstring (open_box (get_payload (qtw)).x1)); + } + b->setFlat (!(style & WIDGET_STYLE_BUTTON)); + qwid= b; } - break; - - case tree_view_widget: - { - typedef triple T; - T x = open_box(load); - qwid = new QTMTreeView (x.x1, x.x2, x.x3); // command, data, roles + qwid->setStyle (qtmstyle ()); + qt_apply_tm_style (qwid, style); + qwid->setEnabled (!(style & WIDGET_STYLE_INERT)); + qwid->setFocusPolicy (Qt::StrongFocus); + } break; + + // given a button widget w, specify a help balloon which should be displayed + // when the user leaves the mouse pointer on the button for a small while + case balloon_widget: { + typedef pair T; + T x = open_box (load); + qt_widget qtw = concrete (x.x1); + qt_widget help= concrete (x.x2); + + typedef quartet T1; + T1 y= open_box (get_payload (help, text_widget)); + QWidget* w= qtw->as_qwidget (); + w->setToolTip (to_qstring (y.x1)); + qwid= w; + } break; + + // a text widget with a given color and transparency + case text_widget: { + typedef quartet T; + T x = open_box (load); + string str = x.x1; + int style= x.x2; + color c = x.x3; + // bool tsp = x.x4; // FIXME: add transparency support + + QLabel* w= new QLabel (); + /* + //FIXME: implement refresh when changing language + QTMAction* a= new QTMAction (NULL); + a->set_text (str); + */ + w->setText (to_qstring (str)); + w->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); + // Workaround too small sizeHint() when the text has letters with descent: + w->setMinimumHeight (w->fontMetrics ().height ()); + w->setFocusPolicy (Qt::NoFocus); + + qt_apply_tm_style (w, style, c); + qwid= w; + } break; + + // a widget with an X pixmap icon + case xpm_widget: { + url image= open_box (load); + QLabel* l = new QLabel (NULL); + l->setPixmap (as_pixmap (*xpm_image (image))); + qwid= l; + } break; + + case toggle_widget: { + typedef triple T; + T x = open_box (load); + command cmd = x.x1; + bool check= x.x2; + int style= x.x3; + + QCheckBox* w= new QCheckBox (NULL); + w->setCheckState (check ? Qt::Checked : Qt::Unchecked); + qt_apply_tm_style (w, style); + w->setFocusPolicy (Qt::StrongFocus); + + command tcmd= tm_new (w, cmd); + QTMCommand* c = new QTMCommand (w, tcmd); + QObject::connect (w, SIGNAL (stateChanged (int)), c, SLOT (apply ())); + + qwid= w; + } break; + + case enum_widget: { + typedef quintuple, string, int, string> T; + T x = open_box (load); + command cmd = x.x1; + QStringList values= to_qstringlist (x.x2); + QString value = to_qstring (x.x3); + int style = x.x4; + + QTMComboBox* w= new QTMComboBox (NULL); + if (values.isEmpty ()) values << QString (""); // safeguard + + w->setEditable (value.isEmpty () || + values.last ().isEmpty ()); // weird convention?! + if (values.last ().isEmpty ()) values.removeLast (); + + w->addItemsAndResize (values, x.x5, ""); + int index= + w->findText (value, Qt::MatchFixedString | Qt::MatchCaseSensitive); + if (index != -1) w->setCurrentIndex (index); + + qt_apply_tm_style (w, style); + + command ecmd= tm_new (w, cmd); + QTMCommand* c = new QTMCommand (w, ecmd); + // NOTE: with QueuedConnections, the slots are sometimes not invoked. + QObject::connect (w, SIGNAL (currentIndexChanged (int)), c, + SLOT (apply ())); + + qwid= w; + } break; + + // select one or multiple values from a list + case choice_widget: { + typedef quartet, array, bool> T; + T x = open_box (load); + qwid= new QTMListView (x.x1, to_qstringlist (x.x2), to_qstringlist (x.x3), + x.x4); + } break; + + case filtered_choice_widget: { + typedef quartet, string, string> T; + T x = open_box (load); + string filter= x.x4; + QTMListView* choiceWidget= + new QTMListView (x.x1, to_qstringlist (x.x2), + QStringList (to_qstring (x.x3)), false, true, true); + + QTMLineEdit* lineEdit= new QTMLineEdit (0, "string", "1w"); + QObject::connect (lineEdit, SIGNAL (textChanged (const QString&)), + choiceWidget->filter (), + SLOT (setFilterRegExp (const QString&))); + lineEdit->setText (to_qstring (filter)); + lineEdit->setFocusPolicy (Qt::StrongFocus); + + QVBoxLayout* layout= new QVBoxLayout (); + layout->addWidget (lineEdit); + layout->addWidget (choiceWidget); + layout->setSpacing (0); + layout->setContentsMargins (0, 0, 0, 0); + + qwid= new QWidget (); + qwid->setLayout (layout); + } break; + + case tree_view_widget: { + typedef triple T; + T x= open_box (load); + qwid= new QTMTreeView (x.x1, x.x2, x.x3); // command, data, roles + } break; + + case scrollable_widget: { + typedef pair T; + T x = open_box (load); + qt_widget wid = concrete (x.x1); + int style= x.x2; + + QTMScrollArea* w= new QTMScrollArea (); + w->setWidgetAndConnect (wid->as_qwidget ()); + w->setWidgetResizable (true); + + qt_apply_tm_style (w, style); + // FIXME???? + // "Note that You must add the layout of widget before you call this + // function; + // if you add it later, the widget will not be visible - regardless of when + // you show() the scroll area. In this case, you can also not show() the + // widget later." + qwid= w; + + } break; + + case hsplit_widget: + case vsplit_widget: { + typedef pair T; + T x = open_box (load); + qt_widget w1= concrete (x.x1); + qt_widget w2= concrete (x.x2); + + QWidget* qw1 = w1->as_qwidget (); + QWidget* qw2 = w2->as_qwidget (); + QSplitter* split= new QSplitter (); + split->setOrientation (type == hsplit_widget ? Qt::Horizontal + : Qt::Vertical); + split->addWidget (qw1); + split->addWidget (qw2); + + qwid= split; + } break; + + case division_widget: { + typedef pair T; + T x = open_box (load); + string name= x.x1; + qt_widget w = concrete (x.x2); + + /* NOTE: we might wish to wrap the widget in something else, + but there does not semm to be any easy Qt widget constructor + that allows us to do so. A splitter with one child comes close, + but adds a bit of padding. + + QWidget* qw = w->as_qwidget(); + QSplitter* split = new QSplitter(); + split->setOrientation (Qt::Horizontal); + split->addWidget (qw); + + qwid = split; + qwid->setObjectName (to_qstring (name)); + */ + + QWidget* qw= w->as_qwidget (); + qwid = qw; + qwid->setObjectName (to_qstring (name)); + } break; + + case tabs_widget: { + typedef array T1; + typedef pair T; + T x = open_box (load); + T1 tabs = x.x1; + T1 bodies= x.x2; + + QTMTabWidget* tw= new QTMTabWidget (); + + int i; + for (i= 0; i < N (tabs); i++) { + if (is_nil (tabs[i])) break; + QWidget* prelabel= concrete (tabs[i])->as_qwidget (); + QLabel* label = qobject_cast (prelabel); + QWidget* body = concrete (bodies[i])->as_qwidget (); + tw->addTab (body, label ? label->text () : ""); + delete prelabel; } - break; - - case scrollable_widget: - { - typedef pair T; - T x = open_box (load); - qt_widget wid = concrete (x.x1); - int style = x.x2; - - QTMScrollArea* w = new QTMScrollArea(); - w->setWidgetAndConnect (wid->as_qwidget()); - w->setWidgetResizable (true); - - qt_apply_tm_style (w, style); - // FIXME???? - // "Note that You must add the layout of widget before you call this function; - // if you add it later, the widget will not be visible - regardless of when - // you show() the scroll area. In this case, you can also not show() the widget - // later." - qwid = w; + if (i > 0) tw->resizeOthers (0); // Force the automatic resizing + + qwid= tw; + } break; + + case icon_tabs_widget: { + typedef array U1; + typedef array T1; + typedef triple T; + T x = open_box (load); + U1 icons = x.x1; + T1 tabs = x.x2; + T1 bodies= x.x3; + + QTMTabWidget* tw= new QTMTabWidget (); + int i; + for (i= 0; i < N (tabs); i++) { + if (is_nil (tabs[i])) break; + QImage* img = xpm_image (icons[i]); + QWidget* prelabel= concrete (tabs[i])->as_qwidget (); + QLabel* label = qobject_cast (prelabel); + QWidget* body = concrete (bodies[i])->as_qwidget (); + tw->addTab (body, QIcon (as_pixmap (*img)), label ? label->text () : ""); + delete prelabel; } - break; - - case hsplit_widget: - case vsplit_widget: - { - typedef pair T; - T x = open_box(load); - qt_widget w1 = concrete(x.x1); - qt_widget w2 = concrete(x.x2); - - QWidget* qw1 = w1->as_qwidget(); - QWidget* qw2 = w2->as_qwidget(); - QSplitter* split = new QSplitter(); - split->setOrientation(type == hsplit_widget ? Qt::Horizontal - : Qt::Vertical); - split->addWidget (qw1); - split->addWidget (qw2); - - qwid = split; - } - break; - case division_widget: - { - typedef pair T; - T x = open_box(load); - string name = x.x1; - qt_widget w = concrete(x.x2); - - /* NOTE: we might wish to wrap the widget in something else, - but there does not semm to be any easy Qt widget constructor - that allows us to do so. A splitter with one child comes close, - but adds a bit of padding. - - QWidget* qw = w->as_qwidget(); - QSplitter* split = new QSplitter(); - split->setOrientation (Qt::Horizontal); - split->addWidget (qw); - - qwid = split; - qwid->setObjectName (to_qstring (name)); - */ - - QWidget* qw = w->as_qwidget(); - qwid = qw; - qwid->setObjectName (to_qstring (name)); - } - break; - - case tabs_widget: - { - typedef array T1; - typedef pair T; - T x = open_box(load); - T1 tabs = x.x1; - T1 bodies = x.x2; - - QTMTabWidget* tw = new QTMTabWidget (); - - int i; - for (i = 0; i < N(tabs); i++) { - if (is_nil (tabs[i])) break; - QWidget* prelabel = concrete (tabs[i])->as_qwidget(); - QLabel* label = qobject_cast (prelabel); - QWidget* body = concrete (bodies[i])->as_qwidget(); - tw->addTab (body, label ? label->text() : ""); - delete prelabel; - } + if (i > 0) tw->resizeOthers (0); // Force the automatic resizing - if (i>0) tw->resizeOthers(0); // Force the automatic resizing + qwid= tw; + } break; - qwid = tw; - } - break; - - case icon_tabs_widget: - { - typedef array U1; - typedef array T1; - typedef triple T; - T x = open_box(load); - U1 icons = x.x1; - T1 tabs = x.x2; - T1 bodies = x.x3; - - QTMTabWidget* tw = new QTMTabWidget (); - int i; - for (i = 0; i < N(tabs); i++) { - if (is_nil (tabs[i])) break; - QImage* img = xpm_image (icons[i]); - QWidget* prelabel = concrete (tabs[i])->as_qwidget(); - QLabel* label = qobject_cast (prelabel); - QWidget* body = concrete (bodies[i])->as_qwidget(); - tw->addTab (body, QIcon (as_pixmap (*img)), label ? label->text() : ""); - delete prelabel; - } + case refresh_widget: { + typedef pair T; + T x= open_box (load); + qwid = new QTMRefreshWidget (this, x.x1, x.x2); + } break; - if (i>0) tw->resizeOthers(0); // Force the automatic resizing + case refreshable_widget: { + typedef pair T; + T x= open_box (load); + qwid = new QTMRefreshableWidget (this, x.x1, x.x2); + } break; - qwid = tw; - } - break; - - case refresh_widget: - { - typedef pair T; - T x = open_box (load); - qwid = new QTMRefreshWidget (this, x.x1, x.x2); - } - break; - - case refreshable_widget: - { - typedef pair T; - T x = open_box (load); - qwid = new QTMRefreshableWidget (this, x.x1, x.x2); - } - break; - - default: - qwid = NULL; + default: + qwid= NULL; } - - //qwid->setFocusPolicy (Qt::StrongFocus); // Bad idea: containers get focus - if (qwid->objectName().isEmpty()) - qwid->setObjectName (to_qstring (type_as_string())); + + // qwid->setFocusPolicy (Qt::StrongFocus); // Bad idea: containers get focus + if (qwid->objectName ().isEmpty ()) + qwid->setObjectName (to_qstring (type_as_string ())); return qwid; } diff --git a/src/Plugins/Qt/qt_ui_element.hpp b/src/Plugins/Qt/qt_ui_element.hpp index dc7e8b82ed..a9d2e437dd 100644 --- a/src/Plugins/Qt/qt_ui_element.hpp +++ b/src/Plugins/Qt/qt_ui_element.hpp @@ -12,15 +12,15 @@ #ifndef QT_UI_ELEMENT_HPP #define QT_UI_ELEMENT_HPP +#include "hashmap.hpp" #include "ntuple.hpp" #include "promise.hpp" -#include "url.hpp" #include "scheme.hpp" -#include "hashmap.hpp" +#include "url.hpp" -#include "qt_widget.hpp" #include "QTMMenuHelper.hpp" #include "QTMPixmapOrImage.hpp" +#include "qt_widget.hpp" #include #include @@ -28,168 +28,168 @@ class QMenu; class QAction; - /*! Construction of UI elements / widgets. Most of the items in the UI are constructed by this class, although in fact, the actual QWidgets and layout items aren't instantiated ("compiled") until one of as_qwidget(), as_qaction(), get_qmenu() or as_qlayoutmenu() is called. - + A UI element is first created using the factory methods create(), these store the parameters for the widget until they are needed upon creation. as_*() is typically called by another instance of qt_ui_element_rep or sometimes qt_plain_window_widget_rep and qt_refresh_widget_rep, who then gets ownership of the QObjects returned. - + See the documentation of qt_widget_rep for the rationale behind the four methods as_qaction(), get_qmenu(), as_qlayoutmenu(), as_qwidget() - - NOTE: although we store the QWidgets in qt_widget_rep::qwid after creating + + NOTE: although we store the QWidgets in qt_widget_rep::qwid after creating them, this caching achieves nothing for the current infrastructure, because TeXmacs always discards widgets which are not menus or toolbars. */ -class qt_ui_element_rep: public qt_widget_rep { - - // NOTE: automatic deletion of the blackbox upon destruction will trigger - // deletion of all the nested widgets within. - blackbox load; +class qt_ui_element_rep : public qt_widget_rep { + + // NOTE: automatic deletion of the blackbox upon destruction will trigger + // deletion of all the nested widgets within. + blackbox load; QPointer cachedAction; - QList* cachedActionList; - -public: + QList* cachedActionList; + +public: qt_ui_element_rep (types _type, blackbox _load); - virtual ~qt_ui_element_rep(); + virtual ~qt_ui_element_rep (); virtual widget make_popup_widget (); - + virtual QAction* as_qaction (); virtual QWidget* as_qwidget (); virtual QLayoutItem* as_qlayoutitem (); - virtual QList* get_qactionlist(); + virtual QList* get_qactionlist (); operator tree (); - template static qt_widget create (types _type, X1 x1) { - return tm_new (_type, close_box(x1)); + template static qt_widget create (types _type, X1 x1) { + return tm_new (_type, close_box (x1)); } - - template + + template static qt_widget create (types _type, X1 x1, X2 x2) { - typedef pair T; - return tm_new (_type, close_box (T (x1,x2))); + typedef pair T; + return tm_new (_type, close_box (T (x1, x2))); } - - template + + template static qt_widget create (types _type, X1 x1, X2 x2, X3 x3) { - typedef triple T; - return tm_new (_type, close_box (T (x1,x2,x3))); + typedef triple T; + return tm_new (_type, close_box (T (x1, x2, x3))); } - - template + + template static qt_widget create (types _type, X1 x1, X2 x2, X3 x3, X4 x4) { - typedef quartet T; - return tm_new (_type, close_box (T (x1,x2,x3,x4))); + typedef quartet T; + return tm_new (_type, close_box (T (x1, x2, x3, x4))); } - - template + + template static qt_widget create (types _type, X1 x1, X2 x2, X3 x3, X4 x4, X5 x5) { - typedef quintuple T; - return tm_new (_type, close_box (T (x1,x2,x3,x4,x5))); + typedef quintuple T; + return tm_new (_type, + close_box (T (x1, x2, x3, x4, x5))); } - + protected: - static blackbox get_payload (qt_widget qtw, types check_type = none); + static blackbox get_payload (qt_widget qtw, types check_type= none); }; - /*! A rectangular separator widget with a colored background. */ -class qt_glue_widget_rep: public qt_widget_rep { +class qt_glue_widget_rep : public qt_widget_rep { public: tree col; bool hx, vx; - SI w,h; - + SI w, h; + qt_glue_widget_rep (tree _col, bool _hx, bool _vx, SI _w, SI _h) - : col (_col), hx (_hx), vx (_vx), w (_w), h (_h) { } - - qt_glue_widget_rep () { } - + : col (_col), hx (_hx), vx (_vx), w (_w), h (_h) {} + + qt_glue_widget_rep () {} + QTMPixmapOrImage render (); - + virtual QAction* as_qaction (); virtual QWidget* as_qwidget (); }; /*! A wrapper widget executing a quit command upon SLOT_DESTROY. */ class qt_wrapped_widget_rep : public qt_widget_rep { - widget tmwid; + widget tmwid; command quit; + public: qt_wrapped_widget_rep (widget _tmwid, command _quit) - : tmwid (_tmwid), quit (_quit) { + : tmwid (_tmwid), quit (_quit) { add_child (tmwid); } - QWidget* as_qwidget () { return concrete(tmwid)->as_qwidget(); } - void send (slot s, blackbox val) { + QWidget* as_qwidget () { return concrete (tmwid)->as_qwidget (); } + void send (slot s, blackbox val) { switch (s) { - case SLOT_DESTROY: - if (! is_nil (quit)) quit (); - quit = command(); - break; - default: - return; + case SLOT_DESTROY: + if (!is_nil (quit)) quit (); + quit= command (); + break; + default: + return; } qt_widget_rep::send (s, val); if (DEBUG_QT_WIDGETS) cout << "qt_wrapped_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + << "\t\tto widget\t" << type_as_string () << LF; } - }; /*! Ad-hoc command to be used with choice widgets. - + The command associated with a qt_ui_element::choice_widget has one parameter (a list of selected items). For the reason to be of this class, see \sa qt_toggle_command_rep. - \sa qt_ui_element, , qt_ui_element_rep::as_qwidget, qt_ui_element_rep::choice_widget + \sa qt_ui_element, , qt_ui_element_rep::as_qwidget, + qt_ui_element_rep::choice_widget */ -class qt_choice_command_rep: public command_rep { +class qt_choice_command_rep : public command_rep { QPointer qwid; - command cmd; - bool multiple; //selectionModel()->selectedIndexes()) - selected << qwid->model()->data(item).toString(); - + foreach (QModelIndex item, qwid->selectionModel ()->selectedIndexes ()) + selected << qwid->model ()->data (item).toString (); + object l= null_object (); if (multiple) - for (int i = selected.size() - 1; i >= 0; --i) - l = cons (from_qstring (selected[i]), l); - else if (selected.size() > 0) - l = from_qstring (selected[0]); - else - l = ""; - + for (int i= selected.size () - 1; i >= 0; --i) + l= cons (from_qstring (selected[i]), l); + else if (selected.size () > 0) l= from_qstring (selected[0]); + else l= ""; + if (filtered) -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - cmd (list_object (l, from_qstring (qwid->filter()->filterRegExp().pattern()))); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + cmd (list_object ( + l, from_qstring (qwid->filter ()->filterRegExp ().pattern ()))); #else - cmd (list_object (l, from_qstring (qwid->filter()->filterRegularExpression().pattern()))); + cmd (list_object ( + l, from_qstring ( + qwid->filter ()->filterRegularExpression ().pattern ()))); #endif - else - cmd (list_object (l)); + else cmd (list_object (l)); } } - + tm_ostream& print (tm_ostream& out) { return out << "Choice"; } }; #endif // defined QT_UI_ELEMENT_HPP diff --git a/src/Plugins/Qt/qt_utilities.cpp b/src/Plugins/Qt/qt_utilities.cpp index 1d481565d0..93d77c39aa 100644 --- a/src/Plugins/Qt/qt_utilities.cpp +++ b/src/Plugins/Qt/qt_utilities.cpp @@ -1,49 +1,49 @@ /****************************************************************************** -* MODULE : qt_utilities.cpp -* DESCRIPTION: Utilities for QT -* COPYRIGHT : (C) 2007 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_utilities.cpp + * DESCRIPTION: Utilities for QT + * COPYRIGHT : (C) 2007 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ -#include "QTMStyle.hpp" #include "qt_utilities.hpp" +#include "QTMStyle.hpp" #include -#include -#include #include -#include #include -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#include +#include +#include +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include #endif #include -#include #include +#include #ifdef USE_QT_PRINTER -#include #include +#include #endif -#include #include +#include #include "colors.hpp" -#include "dictionary.hpp" #include "converter.hpp" +#include "dictionary.hpp" #include "locale.hpp" #include "scheme.hpp" #include "wencoding.hpp" -#include "qt_gui.hpp" // gui_maximal_extents() #include "editor.hpp" -#include "new_view.hpp" // get_current_editor() +#include "new_view.hpp" // get_current_editor() +#include "qt_gui.hpp" // gui_maximal_extents() #ifdef USE_PLUGIN_GS #include "Ghostscript/gs_utilities.hpp" @@ -57,18 +57,22 @@ void qt_dump (QObject* obj, int indent) { - if (obj == NULL) { cout << "NULL\n"; return; } - for (int j = 0;j < indent; ++j) cout << " "; - cout << from_qstring (obj->metaObject()->className()) << ":\n"; - foreach (QObject* child , obj->children()) { - qt_dump (child, indent+1); + if (obj == NULL) { + cout << "NULL\n"; + return; + } + for (int j= 0; j < indent; ++j) + cout << " "; + cout << from_qstring (obj->metaObject ()->className ()) << ":\n"; + foreach (QObject* child, obj->children ()) { + qt_dump (child, indent + 1); } } tm_ostream& -operator << (tm_ostream& out, QRect rect) { - return out << "(" << rect.x() << "," << rect.y() << "," - << rect.width() << "," << rect.height() << ")"; +operator<< (tm_ostream& out, QRect rect) { + return out << "(" << rect.x () << "," << rect.y () << "," << rect.width () + << "," << rect.height () << ")"; } /****************************************************************************** @@ -79,23 +83,25 @@ QFont to_qfont (int style, QFont font) { if ((style & WIDGET_STYLE_MINI) && tm_style_sheet == "" && use_mini_bars) { // Use smaller text font - int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); + int fs= as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); font.setPointSize (qt_zoom (fs > 0 ? fs : QTM_MINI_FONTSIZE)); } - if (style & WIDGET_STYLE_MONOSPACED) { // Use monospaced font - font.setFixedPitch (true); //FIXME: ignored for fonts in QActions + if (style & WIDGET_STYLE_MONOSPACED) { // Use monospaced font + font.setFixedPitch (true); // FIXME: ignored for fonts in QActions font.setStyleHint (QFont::Monospace); } - if (style & WIDGET_STYLE_GREY) // use grey text font - font.setWeight (QFont::Light); // FIXME: this is only an approximation - if (style & WIDGET_STYLE_PRESSED) // Button is currently pressed - {} - if (style & WIDGET_STYLE_INERT) // Only render, don't associate any action - {} - if (style & WIDGET_STYLE_BUTTON) // Render button as standard button - {} - if (style & WIDGET_STYLE_BOLD) - font.setBold(true); + if (style & WIDGET_STYLE_GREY) // use grey text font + font.setWeight (QFont::Light); // FIXME: this is only an approximation + if (style & WIDGET_STYLE_PRESSED) // Button is currently pressed + { + } + if (style & WIDGET_STYLE_INERT) // Only render, don't associate any action + { + } + if (style & WIDGET_STYLE_BUTTON) // Render button as standard button + { + } + if (style & WIDGET_STYLE_BOLD) font.setBold (true); return font; } @@ -105,16 +111,16 @@ em_factor () { } /*! Try to convert a TeXmacs length (em, px, w, h) into a QSize. - + This uses the widget's current size to compute relative sizes as specified with "FFw", where FF is the string representation of a double. A value of "1w" should not affect the widget size. - + FIXME: does 1w mean 100% of the contents' size or 100% of the available size? */ QSize -qt_decode_length (string width, string height, - const QSize& ref, const QFontMetrics& fm) { +qt_decode_length (string width, string height, const QSize& ref, + const QFontMetrics& fm) { QSize size= ref; string w_unit, h_unit; @@ -122,39 +128,39 @@ qt_decode_length (string width, string height, parse_length (width, w_len, w_unit); parse_length (height, h_len, h_unit); - // Width as a function of the default width - if (w_unit == "w") size.rwidth() *= w_len; - // Width as a function of the default height - else if (w_unit == "h") size.rwidth() = w_len * size.height(); - // Absolute EM units (temporarily fixed to 14px) + // Width as a function of the default width + if (w_unit == "w") size.rwidth ()*= w_len; + // Width as a function of the default height + else if (w_unit == "h") size.rwidth ()= w_len * size.height (); + // Absolute EM units (temporarily fixed to 14px) else if (w_unit == "em") { - //size.setWidth (em_factor()* w_len * fm.width("M")); - if (tm_style_sheet != "") w_len *= 14 * retina_scale; - else if (retina_zoom == 2) w_len *= 21; - else w_len *= 14; + // size.setWidth (em_factor()* w_len * fm.width("M")); + if (tm_style_sheet != "") w_len*= 14 * retina_scale; + else if (retina_zoom == 2) w_len*= 21; + else w_len*= 14; size.setWidth (w_len); } - // Absolute pixel units + // Absolute pixel units else if (w_unit == "px") { - if (tm_style_sheet != "") w_len *= retina_scale; - else if (retina_zoom == 2) w_len *= 1.5; + if (tm_style_sheet != "") w_len*= retina_scale; + else if (retina_zoom == 2) w_len*= 1.5; size.setWidth (w_len); } - // Height as a function of the default width - if (h_unit == "w") size.rheight() = h_len * size.width(); - // Height as a function of the default height - else if (h_unit == "h") size.rheight() *= h_len; + // Height as a function of the default width + if (h_unit == "w") size.rheight ()= h_len * size.width (); + // Height as a function of the default height + else if (h_unit == "h") size.rheight ()*= h_len; else if (h_unit == "em") { - //size.setHeight (em_factor()* h_len * fm.width("M")); - if (tm_style_sheet != "") h_len *= 14 * retina_scale; - else if (retina_zoom == 2) h_len *= 21; - else w_len *= 14; + // size.setHeight (em_factor()* h_len * fm.width("M")); + if (tm_style_sheet != "") h_len*= 14 * retina_scale; + else if (retina_zoom == 2) h_len*= 21; + else w_len*= 14; size.setHeight (h_len); } else if (h_unit == "px") { - if (tm_style_sheet != "") h_len *= retina_scale; - else if (retina_zoom == 2) h_len *= 1.5; + if (tm_style_sheet != "") h_len*= retina_scale; + else if (retina_zoom == 2) h_len*= 1.5; size.setHeight (h_len); } return size; @@ -163,33 +169,32 @@ qt_decode_length (string width, string height, // used only by to_qkeysequence static string conv_sub (const string& ks) { - string r(ks); - r = replace (r, "pageup", "pgup"); - r = replace (r, "pagedown", "pgdown"); - r = replace (r, "S-", "Shift+"); - r = replace (r, "A-", "Alt+"); - //r = replace (r, "K-", ""); + string r (ks); + r= replace (r, "pageup", "pgup"); + r= replace (r, "pagedown", "pgdown"); + r= replace (r, "S-", "Shift+"); + r= replace (r, "A-", "Alt+"); + // r = replace (r, "K-", ""); #ifdef Q_OS_MAC - r = replace (r, "C-", "Meta+"); - r = replace (r, "M-", "Ctrl+"); + r= replace (r, "C-", "Meta+"); + r= replace (r, "M-", "Ctrl+"); #else - r = replace (r, "C-", "Ctrl+"); - r = replace (r, "M-", "Meta+"); + r= replace (r, "C-", "Ctrl+"); + r= replace (r, "M-", "Meta+"); #endif - array a = tokenize (r, " "); - for (int i = 0; i < N(a); ++i) { - int pos = -1, tmp = 0, n = N(a[i]); - while (tmp < n && (tmp = search_forwards ("+", tmp, a[i])) != -1) - pos = tmp++; - if (n > pos+1) { - if (is_locase (a[i][pos+1])) - a[i] = a[i](0, pos) * upcase_all (a[i] (pos, n)); - else if (is_upcase (a[i][pos+1])) { + array a= tokenize (r, " "); + for (int i= 0; i < N (a); ++i) { + int pos= -1, tmp= 0, n= N (a[i]); + while (tmp < n && (tmp= search_forwards ("+", tmp, a[i])) != -1) + pos= tmp++; + if (n > pos + 1) { + if (is_locase (a[i][pos + 1])) + a[i]= a[i](0, pos) * upcase_all (a[i](pos, n)); + else if (is_upcase (a[i][pos + 1])) { // HACK: don't prepend Shift for function keys F1, F2... - if (n>pos+2 && a[i][pos+1] == 'F' && as_int (a[i][pos+2]) > 0) + if (n > pos + 2 && a[i][pos + 1] == 'F' && as_int (a[i][pos + 2]) > 0) ; - else - a[i] = a[i](0, pos+1) * "Shift+" * upcase_all (a[i] (pos+1, n)); + else a[i]= a[i](0, pos + 1) * "Shift+" * upcase_all (a[i](pos + 1, n)); } } } @@ -199,93 +204,94 @@ conv_sub (const string& ks) { QKeySequence to_qkeysequence (string ks) { string r (conv_sub (ks)); - if (DEBUG_QT && N(r) > 0) { + if (DEBUG_QT && N (r) > 0) { QKeySequence qks (to_qstring (r)); debug_qt << "ks: " << ks << " --> " << r << " --> " - << qks.toString (QKeySequence::NativeText).toLatin1().data() << LF; + << qks.toString (QKeySequence::NativeText).toLatin1 ().data () + << LF; return qks; } if (ends (r, "&")) { // HACK: because Qt menu can not show the key & - r= r(0, N(r)-1) * "Shift+7"; + r= r (0, N (r) - 1) * "Shift+7"; } return QKeySequence (to_qstring (r)); } - -tm_ostream& operator << (tm_ostream& out, coord4 c) { - out << "[" << c.x1 << "," << c.x2 << "," - << c.x3 << "," << c.x4 << "]"; - return out; +tm_ostream& +operator<< (tm_ostream& out, coord4 c) { + out << "[" << c.x1 << "," << c.x2 << "," << c.x3 << "," << c.x4 << "]"; + return out; } -tm_ostream& operator << (tm_ostream& out, coord2 c) { - out << "[" << c.x1 << "," << c.x2 << "]"; - return out; +tm_ostream& +operator<< (tm_ostream& out, coord2 c) { + out << "[" << c.x1 << "," << c.x2 << "]"; + return out; } coord4 -from_qrect (const QRect & rect) { +from_qrect (const QRect& rect) { SI c1, c2, c3, c4; - c1= rect.x() * SCREEN_PIXEL; - c2= -(rect.y() + rect.height()) * SCREEN_PIXEL; - c3= (rect.x() + rect.width()) * SCREEN_PIXEL; - c4= -rect.y() * SCREEN_PIXEL; + c1= rect.x () * SCREEN_PIXEL; + c2= -(rect.y () + rect.height ()) * SCREEN_PIXEL; + c3= (rect.x () + rect.width ()) * SCREEN_PIXEL; + c4= -rect.y () * SCREEN_PIXEL; return coord4 (c1, c2, c3, c4); } /*! Transforms a rectangle given by its lower left and upper right corners into one given by its upper left and width/height */ QRect -to_qrect (const coord4 & p) { - float c= 1.0/SCREEN_PIXEL; - return QRect (p.x1*c, -p.x4*c, - (p.x3-p.x1+SCREEN_PIXEL-1)*c, (p.x4-p.x2+SCREEN_PIXEL-1)*c); +to_qrect (const coord4& p) { + float c= 1.0 / SCREEN_PIXEL; + return QRect (p.x1 * c, -p.x4 * c, (p.x3 - p.x1 + SCREEN_PIXEL - 1) * c, + (p.x4 - p.x2 + SCREEN_PIXEL - 1) * c); } coord2 -from_qsize (const QSize & s) { - return coord2 (s.width() * SCREEN_PIXEL, s.height() * SCREEN_PIXEL); +from_qsize (const QSize& s) { + return coord2 (s.width () * SCREEN_PIXEL, s.height () * SCREEN_PIXEL); } QSize -to_qsize (const coord2 & p) { - float c= 1.0/SCREEN_PIXEL; - return QSize (p.x1*c, p.x2*c); +to_qsize (const coord2& p) { + float c= 1.0 / SCREEN_PIXEL; + return QSize (p.x1 * c, p.x2 * c); } QSize to_qsize (const SI& w, const SI& h) { - float c= 1.0/SCREEN_PIXEL; - return QSize (w*c, h*c); + float c= 1.0 / SCREEN_PIXEL; + return QSize (w * c, h * c); } coord2 -from_qpoint (const QPoint & pt) { - return coord2 (pt.x() * SCREEN_PIXEL, -pt.y() * SCREEN_PIXEL); +from_qpoint (const QPoint& pt) { + return coord2 (pt.x () * SCREEN_PIXEL, -pt.y () * SCREEN_PIXEL); } /*! Transforms texmacs coordinates, with origin at the lower left corner, into Qt coordinates, with origin at the upper left corner */ QPoint -to_qpoint (const coord2 & p) { - float c= 1.0/SCREEN_PIXEL; - return QPoint (p.x1*c, -p.x2*c); +to_qpoint (const coord2& p) { + float c= 1.0 / SCREEN_PIXEL; + return QPoint (p.x1 * c, -p.x2 * c); } array -from_qstringlist(const QStringList& l) { - array tl (l.size()); - for(QStringList::const_iterator it = l.begin(); it != l.end(); ++it) - tl << from_qstring(*it); +from_qstringlist (const QStringList& l) { + array tl (l.size ()); + for (QStringList::const_iterator it= l.begin (); it != l.end (); ++it) + tl << from_qstring (*it); return tl; } QStringList to_qstringlist (array l) { QStringList ql; - for(int i=0; i l) { it's cork, but often it's utf8. For instance when the title is built in a tmfs title handler in scheme, it is sent to us as an utf8 string. Should we convert before? Another example are items in the go-menu: file names are internally - stored using the os 8-bit encoding (UTF-8 on linux/Mac OS locale code page on windows), - but we assume that strings are sent to us for display in - widgets as cork and thus display the wrong encoding. - + stored using the os 8-bit encoding (UTF-8 on linux/Mac OS locale code page on + windows), but we assume that strings are sent to us for display in widgets as + cork and thus display the wrong encoding. + It gets tricky soon, so for the time being we use this hack. */ -QString //uses heuristics +QString // uses heuristics to_qstring (const string& s) { if (looks_utf8 (s) && !(looks_ascii (s) || looks_universal (s))) return utf8_to_qstring (s); - else - return utf8_to_qstring (cork_to_utf8 (s)); + else return utf8_to_qstring (cork_to_utf8 (s)); } string -from_qstring (const QString &s) { +from_qstring (const QString& s) { return utf8_to_cork (from_qstring_utf8 (s)); } QString latin1_to_qstring (const string& s) { c_string p (s); - QString nss= QString::fromLatin1 (p, N(s)); + QString nss= QString::fromLatin1 (p, N (s)); return nss; } QString utf8_to_qstring (const string& s) { c_string p (s); - QString nss= QString::fromUtf8 (p, N(s)); + QString nss= QString::fromUtf8 (p, N (s)); return nss; } string -from_qstring_utf8 (const QString &s) { - QByteArray arr= s.toUtf8 (); +from_qstring_utf8 (const QString& s) { + QByteArray arr = s.toUtf8 (); const char* cstr= arr.constData (); return string ((char*) cstr); } @@ -342,23 +347,22 @@ static QHash _NamedColors; */ QColor to_qcolor (const string& col) { - QString _col = to_qstring(col); - if (_NamedColors.contains (_col)) - return _NamedColors[_col]; + QString _col= to_qstring (col); + if (_NamedColors.contains (_col)) return _NamedColors[_col]; color c= named_color (col); if (c == 0 && locase_all (col) != "black") { - if(DEBUG_QT_WIDGETS) + if (DEBUG_QT_WIDGETS) debug_widgets << "to_qcolor(" << col << "): " - << "name is not defined.\n"; - return QColor(100,100,100); // FIXME? + << "name is not defined.\n"; + return QColor (100, 100, 100); // FIXME? } QColor _c= to_qcolor (c); - _NamedColors.insert(_col, _c); + _NamedColors.insert (_col, _c); return _c; } -/*! Returns a color encoded as a string with hexadecimal RGB values, - as in #e3a1ff +/*! Returns a color encoded as a string with hexadecimal RGB values, + as in #e3a1ff */ string from_qcolor (const QColor& col) { @@ -366,7 +370,7 @@ from_qcolor (const QColor& col) { } QColor -to_qcolor(color c) { +to_qcolor (color c) { int r, g, b, a; get_rgb_color (c, r, g, b, a); if (get_reverse_colors ()) reverse (r, g, b); @@ -381,64 +385,63 @@ to_color (const QColor& c) { return rgb_color (r, g, b, a); } - - - /****************************************************************************** * Image conversion ******************************************************************************/ bool qt_supports (url u) { - static QList formats= QImageReader::supportedImageFormats(); -/* if (DEBUG_CONVERT) { - debug_convert <<"QT valid formats:"; - foreach (QString _format, formats) debug_convert <<", "<< from_qstring(_format); - debug_convert < formats= QImageReader::supportedImageFormats (); + /* if (DEBUG_CONVERT) { + debug_convert <<"QT valid formats:"; + foreach (QString _format, formats) debug_convert <<", "<< + from_qstring(_format); debug_convert <as_length ("1pt"); - SI px = get_current_editor()->as_length ("1px"); - w= (int) im.width () * px * 1.0 / pt; - h= (int) im.height () * px * 1.0 / pt; - if (DEBUG_CONVERT) debug_convert <<"QT image_size (pt): " - <as_length ("1pt"); + SI px= get_current_editor ()->as_length ("1px"); + w = (int) im.width () * px * 1.0 / pt; + h = (int) im.height () * px * 1.0 / pt; + if (DEBUG_CONVERT) + debug_convert << "QT image_size (pt): " << w << " x " << h << LF; + return true; } } bool qt_native_image_size (url image, int& w, int& h) { - if (DEBUG_CONVERT) debug_convert << "qt_image_size :" <as_length ("1pt"); - SI par= get_current_editor()->as_length ("1par"); + SI pt = get_current_editor ()->as_length ("1pt"); + SI par= get_current_editor ()->as_length ("1par"); if (ww <= 0 || hh <= 0 || ww * pt > par) { w= "1par"; h= ""; @@ -451,26 +454,26 @@ qt_pretty_image_size (int ww, int hh, string& w, string& h) { bool qt_pretty_image_size (url image, string& w, string& h) { - if (suffix (image) == "pdf" || - suffix (image) == "ps" || + if (suffix (image) == "pdf" || suffix (image) == "ps" || suffix (image) == "eps") { w= ""; h= ""; return false; } - int ww, hh; + int ww, hh; bool r= qt_image_size (image, ww, hh); qt_pretty_image_size (ww, hh, w, h); return r; } void -qt_convert_image (url image, url dest, int w, int h) {// w, h in pixels - if (DEBUG_CONVERT) debug_convert << "qt_convert_image " << image << " -> "< " << dest << LF; QImage im (utf8_to_qstring (concretize (image))); if (im.isNull ()) convert_error << "Cannot read image file '" << image << "'" - << " in qt_convert_image" << LF; + << " in qt_convert_image" << LF; else { if (w > 0 && h > 0) im= im.scaled (w, h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); @@ -481,87 +484,102 @@ qt_convert_image (url image, url dest, int w, int h) {// w, h in pixels #ifdef USE_QT_PRINTER void qt_image_to_pdf (url image, url outfile, int w_pt, int h_pt, int dpi) { -// use a QPrinter to output raster images to eps or pdf -// dpi is the maximum dpi : the image will either be dowsampled to that dpi -// or the actual dpi will be lower - if (DEBUG_CONVERT) debug_convert << "qt_image_to_eps_or_pdf " << image << " -> "< " << outfile + << LF; QPrinter printer; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - printer.setOrientation(QPrinter::Portrait); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + printer.setOrientation (QPrinter::Portrait); #else - printer.setPageOrientation(QPageLayout::Portrait); + printer.setPageOrientation (QPageLayout::Portrait); #endif - if (suffix(outfile)=="eps") { - //note that PostScriptFormat is gone in Qt5. a substitute?: http://soft.proindependent.com/eps/ + if (suffix (outfile) == "eps") { + // note that PostScriptFormat is gone in Qt5. a substitute?: + // http://soft.proindependent.com/eps/ cout << "TeXmacs] warning: PostScript format no longer supported in Qt5\n"; - printer.setOutputFormat(QPrinter::PdfFormat); + printer.setOutputFormat (QPrinter::PdfFormat); } - else printer.setOutputFormat(QPrinter::PdfFormat); - printer.setFullPage(true); - if (!dpi) dpi=96; - printer.setResolution(dpi); - printer.setOutputFileName(utf8_to_qstring (concretize (outfile))); + else printer.setOutputFormat (QPrinter::PdfFormat); + printer.setFullPage (true); + if (!dpi) dpi= 96; + printer.setResolution (dpi); + printer.setOutputFileName (utf8_to_qstring (concretize (outfile))); QImage im (utf8_to_qstring (concretize (image))); if (im.isNull ()) { convert_error << "Cannot read image file '" << image << "'" - << " in qt_image_to_pdf" << LF; - // load the "?" image? + << " in qt_image_to_pdf" << LF; + // load the "?" image? } else { -/* if (DEBUG_CONVERT) debug_convert << "size asked " << w_pt << "x"< 0 && w_pt > 0 && h_pt > 0) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - printer.setPaperSize(QSizeF(w_pt, h_pt), QPrinter::Point); // in points +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + printer.setPaperSize (QSizeF (w_pt, h_pt), QPrinter::Point); // in points #else // see https://doc.qt.io/qt-5/qprinter-obsolete.html#setPaperSize - printer.setPageSize(QPageSize(QSizeF(w_pt, h_pt), QPageSize::Point)); + printer.setPageSize (QPageSize (QSizeF (w_pt, h_pt), QPageSize::Point)); #endif - // w_pt and h_pt are dimensions in points (and there are 72 points per inch) - int ww = w_pt * dpi / 72; - int hh = h_pt * dpi / 72; - if ((ww < im.width ()) ||( hh < im.height ())) //downsample if possible to reduce file size - im= im.scaled (ww, hh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - else // image was too small, reduce dpi accordingly to fill page - printer.setResolution((int) (dpi*im.width())/(double)ww); - if (DEBUG_CONVERT) debug_convert << "dpi asked: "<< dpi <<" ; actual dpi set: " << printer.resolution() < "< " + << outfile << LF; } #endif // defined(USE_QT_PRINTER) -void qt_image_to_eps(url image, url outfile, int w_pt, int h_pt, int dpi) { - qt_image_to_pdf(image, outfile, w_pt, h_pt, dpi);}; +void +qt_image_to_eps (url image, url outfile, int w_pt, int h_pt, int dpi) { + qt_image_to_pdf (image, outfile, w_pt, h_pt, dpi); +}; /* not in use anymore : now use a Qt printer that outputs ps. void qt_image_to_eps (url image, url eps, int w_pt, int h_pt, int dpi) { - if (DEBUG_CONVERT) debug_convert << "qt_image_to_eps " << image << " -> "< +"<>\n\t/ReusableStreamDecode\n\tfilter\n"; - + int v, i= 0, j= 0, k= 0, l= 0; string mask; for (j= 0; j < im.height (); j++) { @@ -631,7 +649,7 @@ qt_image_to_eps (url image, int w_pt, int h_pt, int dpi) { } } r << ">\ndef\n\n"; - + if (alpha) { r << "/MaskDatas\n\tcurrentfile\n\t<< /Filter /ASCIIHexDecode >>\n" << "\t/ReusableStreamDecode\n\tfilter\n" @@ -668,7 +686,6 @@ as_pixmap (const QImage& im) { return pm; } - /****************************************************************************** * Stuff related to widgets ******************************************************************************/ @@ -678,189 +695,199 @@ parse_tm_style (int style) { QString sheet; if ((style & WIDGET_STYLE_MINI) && tm_style_sheet == "" && use_mini_bars) { // Use smaller text font - int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); - sheet += QString("font-size: %1pt;").arg (fs > 0 ? fs : QTM_MINI_FONTSIZE); - sheet += QString("padding: 1px;"); + int fs= as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE)); + sheet+= QString ("font-size: %1pt;").arg (fs > 0 ? fs : QTM_MINI_FONTSIZE); + sheet+= QString ("padding: 1px;"); } - if (style & WIDGET_STYLE_MONOSPACED) // Use monospaced font - sheet += "font-family: \"monospace\";"; - if (style & WIDGET_STYLE_GREY) // Use grey text font - sheet += "color: #414141;"; - if (style & WIDGET_STYLE_PRESSED) // Button is currently pressed - sheet += ""; - if (style & WIDGET_STYLE_INERT) // Only render, don't associate any action - sheet += "color: #414141;"; - if (style & WIDGET_STYLE_BUTTON) // Render button as standard button - sheet += ""; - if (style & WIDGET_STYLE_CENTERED) // Use centered text - sheet += "text-align: center;"; - if (style & WIDGET_STYLE_BOLD) - sheet += "font-weight: bold;"; - if (DEBUG_QT_WIDGETS) - sheet += "border:1px solid rgb(255, 0, 0);"; + if (style & WIDGET_STYLE_MONOSPACED) // Use monospaced font + sheet+= "font-family: \"monospace\";"; + if (style & WIDGET_STYLE_GREY) // Use grey text font + sheet+= "color: #414141;"; + if (style & WIDGET_STYLE_PRESSED) // Button is currently pressed + sheet+= ""; + if (style & WIDGET_STYLE_INERT) // Only render, don't associate any action + sheet+= "color: #414141;"; + if (style & WIDGET_STYLE_BUTTON) // Render button as standard button + sheet+= ""; + if (style & WIDGET_STYLE_CENTERED) // Use centered text + sheet+= "text-align: center;"; + if (style & WIDGET_STYLE_BOLD) sheet+= "font-weight: bold;"; + if (DEBUG_QT_WIDGETS) sheet+= "border:1px solid rgb(255, 0, 0);"; if (occurs ("dark", tm_style_sheet)) { - if (style & WIDGET_STYLE_GREY) sheet += "color: #a0a0a0;"; - if (style & WIDGET_STYLE_INERT) sheet += "color: #a0a0a0;"; + if (style & WIDGET_STYLE_GREY) sheet+= "color: #a0a0a0;"; + if (style & WIDGET_STYLE_INERT) sheet+= "color: #a0a0a0;"; } return sheet; } void qt_apply_tm_style (QWidget* qwid, int style) { - QString sheet = "* {" + parse_tm_style (style) + "}"; + QString sheet= "* {" + parse_tm_style (style) + "}"; qwid->setStyleSheet (sheet); - qwid->setEnabled (! (style & WIDGET_STYLE_INERT)); + qwid->setEnabled (!(style & WIDGET_STYLE_INERT)); } void qt_apply_tm_style (QWidget* qwid, int style, color c) { - int r,g,b,a; + int r, g, b, a; get_rgb_color (c, r, g, b, a); - a = a*100/255; - if (occurs ("dark", tm_style_sheet)) { r= g= b= 224; a= 100; } - QString sheet = "* {" + parse_tm_style (style) - + QString("color: rgba(%1, %2, %3, %4%);").arg(r).arg(g).arg(b).arg(a) - + "} "; + a= a * 100 / 255; + if (occurs ("dark", tm_style_sheet)) { + r= g= b= 224; + a = 100; + } + QString sheet= "* {" + parse_tm_style (style) + + QString ("color: rgba(%1, %2, %3, %4%);") + .arg (r) + .arg (g) + .arg (b) + .arg (a) + + "} "; #ifdef Q_OS_MAC - /* Disabled QLabels are not greyed out (at least in MacOS, since Qt 4.7.2), - see: https://bugreports.qt-project.org/browse/QTBUG-19008 - For consistency we set the disabled color for all widgets. - */ - sheet += " :disabled { color: #7F7F7F; }"; + /* Disabled QLabels are not greyed out (at least in MacOS, since Qt 4.7.2), + see: https://bugreports.qt-project.org/browse/QTBUG-19008 + For consistency we set the disabled color for all widgets. + */ + sheet+= " :disabled { color: #7F7F7F; }"; #endif - qwid->setEnabled (! (style & WIDGET_STYLE_INERT)); + qwid->setEnabled (!(style & WIDGET_STYLE_INERT)); qwid->setStyleSheet (sheet); } - QString qt_translate (const string& s) { - string in_lan= get_input_language (); + string in_lan = get_input_language (); string out_lan= get_output_language (); - return to_qstring(tm_var_encode (translate (s, in_lan, out_lan))); + return to_qstring (tm_var_encode (translate (s, in_lan, out_lan))); } string qt_application_directory () { - return string (QCoreApplication::applicationDirPath().toLatin1().constData()); + return string ( + QCoreApplication::applicationDirPath ().toLatin1 ().constData ()); // This is used to set $TEXMACS_PATH // in Windows TeXmacs cannot run if this path contains unicode characters - // apparently because Guile uses standard narrow char api to load its modules => patch Guile?. - // return from_qstring (QCoreApplication::applicationDirPath ()); + // apparently because Guile uses standard narrow char api to load its modules + // => patch Guile?. return from_qstring (QCoreApplication::applicationDirPath + // ()); } string qt_get_date (string lan, string fm) { - QDateTime localtime = QDateTime::currentDateTime(); + QDateTime localtime= QDateTime::currentDateTime (); if (fm == "") { if ((lan == "british") || (lan == "english") || (lan == "american")) - fm = "MMMM d, yyyy"; - else if (lan == "german") - fm = "d. MMMM yyyy"; - else if (lan == "chinese" || lan == "japanese" || - lan == "korean" || lan == "taiwanese") - { - string y = as_string(localtime.date().year()); - string m = as_string(localtime.date().month()); - string d = as_string(localtime.date().day()); + fm= "MMMM d, yyyy"; + else if (lan == "german") fm= "d. MMMM yyyy"; + else if (lan == "chinese" || lan == "japanese" || lan == "korean" || + lan == "taiwanese") { + string y= as_string (localtime.date ().year ()); + string m= as_string (localtime.date ().month ()); + string d= as_string (localtime.date ().day ()); if (lan == "korean") return y * "<#b144> " * m * "<#c6d4> " * d * "<#c77c>"; return y * "<#5e74>" * m * "<#6708>" * d * "<#65e5>"; } - else fm = "d MMMM yyyy"; + else fm= "d MMMM yyyy"; } else if (fm[0] == '%') { - char buf[64]; + char buf[64]; time_t ti; time (&ti); - strftime (buf, sizeof(buf), as_charp(fm), ::localtime(&ti)); + strftime (buf, sizeof (buf), as_charp (fm), ::localtime (&ti)); return buf; } - QLocale loc = QLocale (to_qstring (language_to_locale(lan))); - QString date = loc.toString (localtime, to_qstring (fm)); + QLocale loc = QLocale (to_qstring (language_to_locale (lan))); + QString date= loc.toString (localtime, to_qstring (fm)); return from_qstring (date); } string qt_pretty_time (int t) { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QDateTime dt= QDateTime::fromTime_t (t); #else - QDateTime dt= QDateTime::fromSecsSinceEpoch(t); + QDateTime dt= QDateTime::fromSecsSinceEpoch (t); #endif QString s= dt.toString (); return from_qstring (s); } #ifdef USE_QT_PRINTER -#ifndef _MBD_EXPERIMENTAL_PRINTER_WIDGET // this is in qt_printer_widget -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) -#define PAPER(fmt) case QPrinter::fmt : return "fmt" +#ifndef _MBD_EXPERIMENTAL_PRINTER_WIDGET // this is in qt_printer_widget +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#define PAPER(fmt) \ + case QPrinter::fmt: \ + return "fmt" #else -#define PAPER(fmt) case QPageSize::fmt : return "fmt" +#define PAPER(fmt) \ + case QPageSize::fmt: \ + return "fmt" #endif static string -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) qt_papersize_to_string (QPrinter::PaperSize sz) { #else qt_papersize_to_string (QPageSize::PageSizeId sz) { #endif switch (sz) { - PAPER (A0) ; - PAPER (A1) ; - PAPER (A2) ; - PAPER (A3) ; - PAPER (A4) ; - PAPER (A5) ; - PAPER (A6) ; - PAPER (A7) ; - PAPER (A8) ; - PAPER (A9) ; - PAPER (B0) ; - PAPER (B1) ; - PAPER (B2) ; - PAPER (B3) ; - PAPER (B4) ; - PAPER (B5) ; - PAPER (B6) ; - PAPER (B7) ; - PAPER (B8) ; - PAPER (B9) ; - PAPER (B10) ; - PAPER (Letter) ; - default: - return "A4"; + PAPER (A0); + PAPER (A1); + PAPER (A2); + PAPER (A3); + PAPER (A4); + PAPER (A5); + PAPER (A6); + PAPER (A7); + PAPER (A8); + PAPER (A9); + PAPER (B0); + PAPER (B1); + PAPER (B2); + PAPER (B3); + PAPER (B4); + PAPER (B5); + PAPER (B6); + PAPER (B7); + PAPER (B8); + PAPER (B9); + PAPER (B10); + PAPER (Letter); + default: + return "A4"; } } #undef PAPER -bool -qt_print (bool& to_file, bool& landscape, string& pname, url& filename, +bool +qt_print (bool& to_file, bool& landscape, string& pname, url& filename, string& first, string& last, string& paper_type) { - static QPrinter *qprinter = NULL; + static QPrinter* qprinter= NULL; if (!qprinter) { - qprinter = new QPrinter; + qprinter= new QPrinter; } - QPrintDialog pdialog(qprinter); - if (pdialog.exec() == QDialog::Accepted) { - to_file = !(qprinter->outputFileName().isNull()); - pname = from_qstring( qprinter->printerName() ); - filename = from_qstring( qprinter->outputFileName() ); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - landscape = (qprinter->orientation() == QPrinter::Landscape); - paper_type = qt_papersize_to_string(qprinter->paperSize()); + QPrintDialog pdialog (qprinter); + if (pdialog.exec () == QDialog::Accepted) { + to_file = !(qprinter->outputFileName ().isNull ()); + pname = from_qstring (qprinter->printerName ()); + filename= from_qstring (qprinter->outputFileName ()); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + landscape = (qprinter->orientation () == QPrinter::Landscape); + paper_type= qt_papersize_to_string (qprinter->paperSize ()); #else - landscape = (qprinter->pageLayout().orientation() == QPageLayout::Landscape); - paper_type = qt_papersize_to_string(qprinter->pageLayout().pageSize().id()); + landscape= + (qprinter->pageLayout ().orientation () == QPageLayout::Landscape); + paper_type= + qt_papersize_to_string (qprinter->pageLayout ().pageSize ().id ()); #endif - if (qprinter->printRange() == QPrinter::PageRange) { - first = qprinter->fromPage(); - last = qprinter->toPage(); + if (qprinter->printRange () == QPrinter::PageRange) { + first= qprinter->fromPage (); + last = qprinter->toPage (); } - //cout << "Printer :" << pname << LF; - //cout << "File :" << filename << LF; + // cout << "Printer :" << pname << LF; + // cout << "File :" << filename << LF; return true; } return false; @@ -875,70 +902,64 @@ qt_print (bool& to_file, bool& landscape, string& pname, url& filename, } #endif // defined(USE_QT_PRINTER) - #ifdef OS_MACOS // Additional utilities for MACOS // this part has to be at the end because it imports CoreFoundation definitions // which interfere with TeXmacs and QT types... -#define extend CFextend // avoid name clashes... +#define extend CFextend // avoid name clashes... #define outline CFoutline // avoid name clashes... #include #undef extend - // HACK: this function is needed on MacOS when dropping URLS // which could not correspond to standard Unix paths -QString fromNSUrl(const QUrl &url) { - QString localFileQString = url.toLocalFile(); +QString +fromNSUrl (const QUrl& url) { + QString localFileQString= url.toLocalFile (); // [pzion 20150805] Work around // https://bugreports.qt.io/browse/QTBUG-40449 - if ( localFileQString.startsWith("/.file/id=") ) - { - CFStringRef relCFStringRef = - CFStringCreateWithCString(kCFAllocatorDefault, - localFileQString.toUtf8().constData(), - kCFStringEncodingUTF8); - CFURLRef relCFURL = - CFURLCreateWithFileSystemPath(kCFAllocatorDefault, - relCFStringRef, - kCFURLPOSIXPathStyle, - false); // isDirectory - CFErrorRef error = 0; - CFURLRef absCFURL = - CFURLCreateFilePathURL(kCFAllocatorDefault, relCFURL, &error); - if ( !error ) - { - static const CFIndex maxAbsPathCStrBufLen = 4096; - char absPathCStr[maxAbsPathCStrBufLen]; - if ( CFURLGetFileSystemRepresentation(absCFURL, - true, // resolveAgainstBase - reinterpret_cast( &absPathCStr[0] ), - maxAbsPathCStrBufLen)) - { - localFileQString = QString( absPathCStr ); + if (localFileQString.startsWith ("/.file/id=")) { + CFStringRef relCFStringRef= CFStringCreateWithCString ( + kCFAllocatorDefault, localFileQString.toUtf8 ().constData (), + kCFStringEncodingUTF8); + CFURLRef relCFURL= CFURLCreateWithFileSystemPath ( + kCFAllocatorDefault, relCFStringRef, kCFURLPOSIXPathStyle, + false); // isDirectory + CFErrorRef error= 0; + CFURLRef absCFURL= + CFURLCreateFilePathURL (kCFAllocatorDefault, relCFURL, &error); + if (!error) { + static const CFIndex maxAbsPathCStrBufLen= 4096; + char absPathCStr[maxAbsPathCStrBufLen]; + if (CFURLGetFileSystemRepresentation ( + absCFURL, + true, // resolveAgainstBase + reinterpret_cast (&absPathCStr[0]), + maxAbsPathCStrBufLen)) { + localFileQString= QString (absPathCStr); } } - CFRelease( absCFURL ); - CFRelease( relCFURL ); - CFRelease( relCFStringRef ); + CFRelease (absCFURL); + CFRelease (relCFURL); + CFRelease (relCFStringRef); } return localFileQString; } #endif // OS_MACOS /****************************************************************************** -* Style sheets -******************************************************************************/ + * Style sheets + ******************************************************************************/ static string current_style_sheet; void init_palette (QApplication* app) { if (occurs ("dark", tm_style_sheet)) { - QPalette pal= app -> style () -> standardPalette (); + QPalette pal= app->style ()->standardPalette (); pal.setColor (QPalette::Window, QColor (64, 64, 64)); pal.setColor (QPalette::WindowText, QColor (224, 224, 224)); pal.setColor (QPalette::Base, QColor (96, 96, 96)); @@ -953,7 +974,7 @@ init_palette (QApplication* app) { app->setPalette (pal); } else if (tm_style_sheet != "" && !occurs ("native", tm_style_sheet)) { - QPalette pal= app -> style () -> standardPalette (); + QPalette pal= app->style ()->standardPalette (); pal.setColor (QPalette::Window, QColor (232, 232, 232)); pal.setColor (QPalette::WindowText, QColor (0, 0, 0)); pal.setColor (QPalette::Base, QColor (255, 255, 255)); @@ -967,31 +988,31 @@ init_palette (QApplication* app) { pal.setColor (QPalette::HighlightedText, QColor (255, 255, 255)); app->setPalette (pal); } - - if (occurs ("dark", tm_style_sheet)) - tm_background= rgb_color (32, 32, 32); + + if (occurs ("dark", tm_style_sheet)) tm_background= rgb_color (32, 32, 32); else if (occurs ("native", tm_style_sheet)) { - QPalette pal = app -> palette (); + QPalette pal = app->palette (); QColor col = pal.color (QPalette::Mid); tm_background= rgb_color (col.red (), col.green (), col.blue ()); } - else if (tm_style_sheet != "") - tm_background= rgb_color (160, 160, 160); + else if (tm_style_sheet != "") tm_background= rgb_color (160, 160, 160); } string scale_px (string s) { string r; - for (int i=0; isetStyleSheet (to_qstring (current_style_sheet)); } diff --git a/src/Plugins/Qt/qt_utilities.hpp b/src/Plugins/Qt/qt_utilities.hpp index 393302d30d..1ec11ffe60 100644 --- a/src/Plugins/Qt/qt_utilities.hpp +++ b/src/Plugins/Qt/qt_utilities.hpp @@ -1,25 +1,25 @@ /****************************************************************************** -* MODULE : qt_utilities.hpp -* DESCRIPTION: Utilities for QT -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_utilities.hpp + * DESCRIPTION: Utilities for QT + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_UTILITIES_HPP #define QT_UTILITIES_HPP #include "message.hpp" #include "tm_debug.hpp" +#include +#include +#include #include #include -#include #include -#include -#include #include #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) @@ -27,54 +27,54 @@ class QStringList; #endif class QKeySequence; -typedef quartet coord4; -typedef pair coord2; +typedef quartet coord4; +typedef pair coord2; -void qt_dump (QObject* obj, int indent=0); +void qt_dump (QObject* obj, int indent= 0); /****************************************************************************** * Conversion of data types ******************************************************************************/ -QColor to_qcolor (const string& ); -QColor to_qcolor (color c); -string from_qcolor (const QColor& ); -color to_color (const QColor& ); +QColor to_qcolor (const string&); +QColor to_qcolor (color c); +string from_qcolor (const QColor&); +color to_color (const QColor&); -QRect to_qrect (const coord4 & p); -coord4 from_qrect (const QRect & rect); +QRect to_qrect (const coord4& p); +coord4 from_qrect (const QRect& rect); -QPoint to_qpoint (const coord2 & p); -coord2 from_qpoint (const QPoint & pt); +QPoint to_qpoint (const coord2& p); +coord2 from_qpoint (const QPoint& pt); -QSize to_qsize (const coord2 & p); -QSize to_qsize (const SI& w, const SI& h); -coord2 from_qsize (const QSize & s); +QSize to_qsize (const coord2& p); +QSize to_qsize (const SI& w, const SI& h); +coord2 from_qsize (const QSize& s); -QFont to_qfont (int style, QFont font); -void qt_apply_tm_style (QWidget* qwid, int style); -void qt_apply_tm_style (QWidget* qwid, int style, color c); +QFont to_qfont (int style, QFont font); +void qt_apply_tm_style (QWidget* qwid, int style); +void qt_apply_tm_style (QWidget* qwid, int style, color c); -QSize qt_decode_length (string width, string height, - const QSize& ref, const QFontMetrics& fm); +QSize qt_decode_length (string width, string height, const QSize& ref, + const QFontMetrics& fm); QKeySequence to_qkeysequence (string s); -QStringList to_qstringlist (array l); +QStringList to_qstringlist (array l); array from_qstringlist (const QStringList& l); ///// String conversion: Assumes UTF8 encodings both in QT and TeXmacs. -QString to_qstring (const string& s); -string from_qstring (const QString & s); -QString utf8_to_qstring (const string& s); +QString to_qstring (const string& s); +string from_qstring (const QString& s); +QString utf8_to_qstring (const string& s); QString latin1_to_qstring (const string& s); -string from_qstring_utf8 (const QString & s); +string from_qstring_utf8 (const QString& s); /*! Returns a QString with the translation of the argument to the current language. - - NOTE: translations of gui items are always done in the scheme side using + + NOTE: translations of gui items are always done in the scheme side using (translate stuff-to-translate), and this is enabled by default for most widgets displaying text. We need not and must not use Qt's mechanism for translations nor even this function, unless the strings to be translated are hardcoded in @@ -83,9 +83,8 @@ string from_qstring_utf8 (const QString & s); */ QString qt_translate (const string& s); - #ifdef OS_MACOS -QString fromNSUrl(const QUrl &url); +QString fromNSUrl (const QUrl& url); #endif /****************************************************************************** @@ -97,10 +96,10 @@ bool qt_image_size (url image, int& w, int& h); bool qt_native_image_size (url image, int& w, int& h); void qt_pretty_image_size (int ww, int hh, string& w, string& h); bool qt_pretty_image_size (url image, string& w, string& h); -void qt_convert_image (url image, url dest, int w =0, int h =0); -void qt_image_to_eps (url image, url eps, int w_pt =0, int h_pt =0, int dpi= 0); -string qt_image_to_eps (url image, int w_pt =0, int h_pt =0, int dpi= 0); -void qt_image_to_pdf (url image, url pdf, int w_pt =0, int h_pt =0, int dpi =0); +void qt_convert_image (url image, url dest, int w= 0, int h= 0); +void qt_image_to_eps (url image, url eps, int w_pt= 0, int h_pt= 0, int dpi= 0); +string qt_image_to_eps (url image, int w_pt= 0, int h_pt= 0, int dpi= 0); +void qt_image_to_pdf (url image, url pdf, int w_pt= 0, int h_pt= 0, int dpi= 0); string qt_application_directory (); string qt_get_date (string lan, string fm); @@ -117,48 +116,53 @@ QPixmap as_pixmap (const QImage& im); inline void check_type_void (blackbox bb, slot s) { if (!is_nil (bb)) { - failed_error << "slot type= " << as_string(s) << LF; + failed_error << "slot type= " << as_string (s) << LF; TM_FAILED ("type mismatch"); } } -template inline void +template +inline void check_type_id (int type_id, slot s) { if (type_id != type_helper::id) { - failed_error << "slot type= " << as_string(s) << LF; + failed_error << "slot type= " << as_string (s) << LF; TM_FAILED ("type mismatch"); } } -template void +template +void check_type (blackbox bb, slot s) { if (type_box (bb) != type_helper::id) { - failed_error << "slot type= " << as_string(s) << LF; + failed_error << "slot type= " << as_string (s) << LF; TM_FAILED ("type mismatch"); } } -template inline void +template +inline void check_type (blackbox bb, string s) { - check_type > (bb, s); + check_type> (bb, s); } /*! the run-loop should exit when the number of windows is zero */ -extern int nr_windows; +extern int nr_windows; /****************************************************************************** * Some debugging infrastucture ******************************************************************************/ -extern tm_ostream& operator << (tm_ostream& out, QRect rect); -extern tm_ostream& operator << (tm_ostream& out, QSize size); +extern tm_ostream& operator<< (tm_ostream& out, QRect rect); +extern tm_ostream& operator<< (tm_ostream& out, QSize size); -tm_ostream& operator << (tm_ostream& out, coord4 c); -tm_ostream& operator << (tm_ostream& out, coord2 c); +tm_ostream& operator<< (tm_ostream& out, coord4 c); +tm_ostream& operator<< (tm_ostream& out, coord2 c); // deprecated, use check_type(bb, slot) instead -//#define TYPE_CHECK(b) ASSERT (b, "type mismatch") +// #define TYPE_CHECK(b) ASSERT (b, "type mismatch") -#define NOT_IMPLEMENTED(x) \ -{ if (DEBUG_QT) debug_qt << x << " not implemented yet.\n"; } +#define NOT_IMPLEMENTED(x) \ + { \ + if (DEBUG_QT) debug_qt << x << " not implemented yet.\n"; \ + } -#endif // QT_UTILITIES_HPP +#endif // QT_UTILITIES_HPP diff --git a/src/Plugins/Qt/qt_widget.cpp b/src/Plugins/Qt/qt_widget.cpp index f8b2d65810..b115298b73 100644 --- a/src/Plugins/Qt/qt_widget.cpp +++ b/src/Plugins/Qt/qt_widget.cpp @@ -1,63 +1,62 @@ /****************************************************************************** -* MODULE : qt_widget.cpp -* DESCRIPTION: QT widget class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_widget.cpp + * DESCRIPTION: QT widget class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ -#include "qt_utilities.hpp" #include "qt_renderer.hpp" +#include "qt_utilities.hpp" -#include "qt_widget.hpp" -#include "qt_ui_element.hpp" -#include "qt_simple_widget.hpp" -#include "qt_tm_widget.hpp" -#include "qt_window_widget.hpp" #include "qt_chooser_widget.hpp" #include "qt_color_picker_widget.hpp" #include "qt_printer_widget.hpp" +#include "qt_simple_widget.hpp" +#include "qt_tm_widget.hpp" +#include "qt_ui_element.hpp" +#include "qt_widget.hpp" +#include "qt_window_widget.hpp" +#include "QTMMenuHelper.hpp" +#include "QTMWindow.hpp" #include "preferences.hpp" #include "tm_window.hpp" #include #include -#include "QTMMenuHelper.hpp" -#include "QTMWindow.hpp" - /****************************************************************************** * qt_widget_rep: the base widget for the Qt port. ******************************************************************************/ -template<> void +template <> +void tm_delete (qt_widget_rep* ptr) { if (ptr == NULL) return; - void *mem= ptr->derived_this (); - ptr -> ~qt_widget_rep (); + void* mem= ptr->derived_this (); + ptr->~qt_widget_rep (); fast_delete (mem); } -static long widget_counter = 0; +static long widget_counter= 0; -qt_widget_rep::qt_widget_rep(types _type, QWidget* _qwid) - : widget_rep (), id (widget_counter++), qwid (_qwid), type (_type) -{ +qt_widget_rep::qt_widget_rep (types _type, QWidget* _qwid) + : widget_rep (), id (widget_counter++), qwid (_qwid), type (_type) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_widget_rep: created a " << type_as_string() << LF; + debug_widgets << "qt_widget_rep: created a " << type_as_string () << LF; } -qt_widget_rep::~qt_widget_rep() { +qt_widget_rep::~qt_widget_rep () { if (DEBUG_QT_WIDGETS) - debug_widgets << "~qt_widget_rep: deleted a " << type_as_string() << LF; + debug_widgets << "~qt_widget_rep: deleted a " << type_as_string () << LF; // DON'T DO THIS! (several qt_widget_rep may have the same underlying QWidget) // UPD: really? when? And it wouldn't matter since we are using a guarded // pointer -// delete qwid; + // delete qwid; } void @@ -73,62 +72,54 @@ qt_widget_rep::add_children (array a) { void qt_widget_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_KEYBOARD_FOCUS: - { - check_type (val, s); - bool focus = open_box (val); - if (focus && qwid && !qwid->hasFocus()) { - qwid->activateWindow (); - qwid->setFocus (Qt::OtherFocusReason); - } - } - break; - case SLOT_KEYBOARD_FOCUS_ON: - { - string field = open_box(val); - if (qwid) { - QWidget* target = qwid->findChild (to_qstring (field)); - if (target == NULL) - target = qwid->findChild ("default focus target"); - if (target) target->setFocus(Qt::OtherFocusReason); - } - /* FIXME: This would be better than using QObject::findChild but it won't - work because the array of children is only sloppily used at best - (meaning some objects are not assigned as children of others...) - If this is ever made to work, we'll want to handle SLOT_KEYBOARD_FOCUS_ON - inside qt_input_text_widget_rep and possibly others - - for (int i = 0; i < N(children); ++i) - if (!is_nil(children[i])) children[i]->send (s, val); - */ + case SLOT_KEYBOARD_FOCUS: { + check_type (val, s); + bool focus= open_box (val); + if (focus && qwid && !qwid->hasFocus ()) { + qwid->activateWindow (); + qwid->setFocus (Qt::OtherFocusReason); } - break; - case SLOT_NAME: - { - // CHECK ME! - widget win = qt_window_widget_rep::widget_from_qwidget (qwid); - if (! is_nil (win)) win->send (SLOT_NAME, val); + } break; + case SLOT_KEYBOARD_FOCUS_ON: { + string field= open_box (val); + if (qwid) { + QWidget* target= qwid->findChild (to_qstring (field)); + if (target == NULL) + target= qwid->findChild ("default focus target"); + if (target) target->setFocus (Qt::OtherFocusReason); } - break; - case SLOT_DESTROY: - { - if (DEBUG_QT_WIDGETS) - debug_widgets << "Resending to " << N(children) << " children" << LF; - for (int i = 0; i < N(children); ++i) - if (!is_nil(children[i])) children[i]->send (s, val); - } - break; - default: - if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_widget_rep::send(), unhandled " << slot_name (s) - << " for widget of type: " << type_as_string() << ".\n"; + /* FIXME: This would be better than using QObject::findChild but it won't + work because the array of children is only sloppily used at best + (meaning some objects are not assigned as children of others...) + If this is ever made to work, we'll want to handle SLOT_KEYBOARD_FOCUS_ON + inside qt_input_text_widget_rep and possibly others + + for (int i = 0; i < N(children); ++i) + if (!is_nil(children[i])) children[i]->send (s, val); + */ + } break; + case SLOT_NAME: { + // CHECK ME! + widget win= qt_window_widget_rep::widget_from_qwidget (qwid); + if (!is_nil (win)) win->send (SLOT_NAME, val); + } break; + case SLOT_DESTROY: { + if (DEBUG_QT_WIDGETS) + debug_widgets << "Resending to " << N (children) << " children" << LF; + for (int i= 0; i < N (children); ++i) + if (!is_nil (children[i])) children[i]->send (s, val); + } break; + default: + if (DEBUG_QT_WIDGETS) + debug_widgets << "qt_widget_rep::send(), unhandled " << slot_name (s) + << " for widget of type: " << type_as_string () << ".\n"; } } /*! Returns the actual QWidget underlying this qt_widget_rep. - + Implementations of this method must comply with the following: - + * The policy is to give ownership of the object to the caller. * The pointer qt_widget_rep::qwid must be set to the returned object. * A new QWidget is built on each call. @@ -137,20 +128,20 @@ qt_widget_rep::send (slot s, blackbox val) { inline QWidget* qt_widget_rep::as_qwidget () { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_widget_rep::as_qwidget() for " - << type_as_string() << LF; + debug_widgets << "qt_widget_rep::as_qwidget() for " << type_as_string () + << LF; return qwid; } /*! Returns the QAction associated to this qt_widget_rep. - + The default action is of type QTMAction, does nothing and is disabled. See the remarks about memory management and menu instantiation and insertion in the comments to class qt_menu_rep. */ QAction* -qt_widget_rep::as_qaction() { - QAction* a = new QTMAction (NULL); +qt_widget_rep::as_qaction () { + QAction* a= new QTMAction (NULL); a->setEnabled (false); return a; } @@ -161,27 +152,25 @@ qt_widget_rep::as_qaction() { */ inline QLayoutItem* qt_widget_rep::as_qlayoutitem () { - return new QWidgetItem (as_qwidget ()); + return new QWidgetItem (as_qwidget ()); } - QList* -qt_widget_rep::get_qactionlist() { +qt_widget_rep::get_qactionlist () { return NULL; } - /*! Returns the widget as a window. - + Each TeXmacs widget can at some point be asked to present itself into a window. The scheme-originating function window_create () expects this method in every - widget. + widget. - This default implementation constructs a wrapper qt_window_widget for the + This default implementation constructs a wrapper qt_window_widget for the widget and returns it. This wrapper will hold a new QTMPlainWindow object which will manage close events and take ownership of the original QWidget. qt_window_widget owns the QTMPlainWindow and is responsible for its deletion. - + The default implementation should suffice in most cases. \param name A unique identifier for the window. This is *not* the window title. @@ -192,34 +181,38 @@ widget qt_widget_rep::plain_window_widget (string name, command quit, int border) { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_widget_rep::plain_window_widget() around a " - << type_as_string() << LF; + << type_as_string () << LF; - QTMPlainWindow* win = new QTMPlainWindow (0); - QLayoutItem* li = as_qlayoutitem(); + QTMPlainWindow* win= new QTMPlainWindow (0); + QLayoutItem* li = as_qlayoutitem (); if (li) { - QLayout* l = li->layout(); - if (! l) { - l = new QVBoxLayout (win); + QLayout* l= li->layout (); + if (!l) { + l= new QVBoxLayout (win); l->addItem (li); // Layout owns the QLayoutItem } - win->setLayout (l);// Transfers ownership of QWidgets in QLayoutItems to win - } else { - QWidget* qw = as_qwidget(); + win->setLayout ( + l); // Transfers ownership of QWidgets in QLayoutItems to win + } + else { + QWidget* qw= as_qwidget (); if (qw) { - QLayout* l = new QVBoxLayout (win); + QLayout* l= new QVBoxLayout (win); win->setLayout (l); // And the QLayout to the QTMPlainWindow. l->addWidget (qw); // qw now belongs to the QWidget with the layout (win) - } else { + } + else { TM_FAILED ("attempt to create a window around a nil QWidget"); } } - - int l,t,r,b; - win->layout()->getContentsMargins (&l, &t, &r, &b); - win->layout()->setContentsMargins (l+border, t+border, r+border, b+border); - win->setWindowTitle (to_qstring (name)); // HACK: remove me (see bug#40837) - - qt_window_widget_rep* wid = tm_new (win, name, quit); + + int l, t, r, b; + win->layout ()->getContentsMargins (&l, &t, &r, &b); + win->layout ()->setContentsMargins (l + border, t + border, r + border, + b + border); + win->setWindowTitle (to_qstring (name)); // HACK: remove me (see bug#40837) + + qt_window_widget_rep* wid= tm_new (win, name, quit); wid->add_child (this); return widget (wid); @@ -233,7 +226,7 @@ qt_widget_rep::plain_window_widget (string name, command quit, int border) { */ widget qt_widget_rep::make_popup_widget () { - return tm_new ((widget_rep*)this, command()); + return tm_new ((widget_rep*) this, command ()); } /*! Interface for the creation of popups. @@ -241,29 +234,30 @@ qt_widget_rep::make_popup_widget () { */ widget qt_widget_rep::popup_window_widget (string s) { - widget wid= make_popup_widget(); - ASSERT(concrete(wid) != this, "Loop in call to popup_window_widget()"); - return concrete(wid)->popup_window_widget(s); + widget wid= make_popup_widget (); + ASSERT (concrete (wid) != this, "Loop in call to popup_window_widget()"); + return concrete (wid)->popup_window_widget (s); } widget qt_widget_rep::tooltip_window_widget (string s) { - widget wid= make_popup_widget(); - ASSERT(concrete(wid) != this, "Loop in call to tooltip_window_widget()"); - return concrete(wid)->tooltip_window_widget(s); + widget wid= make_popup_widget (); + ASSERT (concrete (wid) != this, "Loop in call to tooltip_window_widget()"); + return concrete (wid)->tooltip_window_widget (s); } -tm_ostream& operator << (tm_ostream& out, qt_widget w) { - return out << "qt_widget of type: " << w.rep->type_as_string(); +tm_ostream& +operator<< (tm_ostream& out, qt_widget w) { + return out << "qt_widget of type: " << w.rep->type_as_string (); } - + /****************************************************************************** -* Global functions we export for the creation of windowed widgets by TeXmacs -******************************************************************************/ + * Global functions we export for the creation of windowed widgets by TeXmacs + ******************************************************************************/ /*! Creates a decorated window using the given widget. - Each widget type may choose how to present itself as a window, by + Each widget type may choose how to present itself as a window, by reimplementing qt_widget_rep::plain_window_widget(), although the base class qt_widget_rep provides a default implementation which suffices in most cases. See its documentation. @@ -275,16 +269,14 @@ tm_ostream& operator << (tm_ostream& out, qt_widget w) { widget plain_window_widget (widget w, string name, command q) { if (headless_mode) return headless_widget (); - widget win= concrete(w)->plain_window_widget (name, q); + widget win= concrete (w)->plain_window_widget (name, q); if (name != "popup") { int xx, yy, ww, hh; - xx = yy = ww = hh = -1; + xx= yy= ww= hh= -1; get_preferred_position (name, xx, yy); get_preferred_size (name, ww, hh); - if (xx != -1) - set_position (win, xx, yy); - if (ww != -1) - set_size (win, ww, hh); + if (xx != -1) set_position (win, xx, yy); + if (ww != -1) set_size (win, ww, hh); } return win; } @@ -294,24 +286,24 @@ plain_window_widget (widget w, string name, command q) { widget popup_window_widget (widget w, string s) { if (headless_mode) return headless_widget (); - return concrete(w)->popup_window_widget (s); + return concrete (w)->popup_window_widget (s); } widget tooltip_window_widget (widget w, string s) { if (headless_mode) return headless_widget (); - return concrete(w)->tooltip_window_widget (s); + return concrete (w)->tooltip_window_widget (s); } -/*! A factory for a popup widget container whose contents are to be unmapped as - soon as the mouse exits the widget. - +/*! A factory for a popup widget container whose contents are to be unmapped as + soon as the mouse exits the widget. + There are currently two kinds of popup widgets: those whose underlying QWidget is a QMenu, and those that hold any sort of QWidget. The former are used in edit_mouse.cpp to implement a contextual menu in the canvas and are implemented using qt_menu_rep; the latter are used for help-balloons and are implemented using qt_popup_widget_rep. - + \param w The widget to be placed in the popup. It will be deleted after the mouse leaves the popup. \return The popup widget. @@ -319,7 +311,7 @@ tooltip_window_widget (widget w, string s) { widget popup_widget (widget w) { if (headless_mode) return headless_widget (); - return concrete(w)->make_popup_widget(); + return concrete (w)->make_popup_widget (); } /*! Destroys a window as created via qt_window_widget. @@ -334,277 +326,330 @@ destroy_window_widget (widget w) { if (headless_mode) return; if (DEBUG_QT_WIDGETS) debug_widgets << "destroy_window_widget() on " - << static_cast(w.rep)->type_as_string() << LF; + << static_cast (w.rep)->type_as_string () + << LF; } - /****************************************************************************** - * TeXmacs interface for the creation of widgets. - * See Graphics/Gui/widget.hpp for comments. + * TeXmacs interface for the creation of widgets. + * See Graphics/Gui/widget.hpp for comments. ******************************************************************************/ -widget horizontal_menu (array a) { +widget +horizontal_menu (array a) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::horizontal_menu, a); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::horizontal_menu, a); wid->add_children (a); return abstract (wid); } -widget vertical_menu (array a) { +widget +vertical_menu (array a) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::vertical_menu, a); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::vertical_menu, a); wid->add_children (a); return abstract (wid); } -widget horizontal_list (array a) { +widget +horizontal_list (array a) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::horizontal_list, a); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::horizontal_list, a); wid->add_children (a); return abstract (wid); } -widget vertical_list (array a) { +widget +vertical_list (array a) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::vertical_list, a); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::vertical_list, a); wid->add_children (a); return abstract (wid); } -widget division_widget (string name, widget w) { +widget +division_widget (string name, widget w) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::division_widget, - name, w); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::division_widget, name, w); wid->add_child (w); return abstract (wid); } -widget aligned_widget (array lhs, array rhs, SI hsep, SI vsep, - SI lpad, SI rpad) { +widget +aligned_widget (array lhs, array rhs, SI hsep, SI vsep, SI lpad, + SI rpad) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::aligned_widget, - lhs, rhs, coord4 (hsep, vsep, lpad, rpad)); + qt_widget wid= qt_ui_element_rep::create ( + qt_widget_rep::aligned_widget, lhs, rhs, coord4 (hsep, vsep, lpad, rpad)); wid->add_children (lhs); wid->add_children (rhs); return abstract (wid); } -widget tabs_widget (array tabs, array bodies) { +widget +tabs_widget (array tabs, array bodies) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::tabs_widget, - tabs, bodies); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::tabs_widget, tabs, bodies); wid->add_children (tabs); wid->add_children (bodies); return abstract (wid); } -widget icon_tabs_widget (array us, array ts, array bs) { +widget +icon_tabs_widget (array us, array ts, array bs) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::icon_tabs_widget, - us, ts, bs); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::icon_tabs_widget, us, ts, bs); wid->add_children (ts); wid->add_children (bs); return abstract (wid); } -widget wrapped_widget (widget w, command cmd) { +widget +wrapped_widget (widget w, command cmd) { if (headless_mode) return headless_widget (); return tm_new (w, cmd); } -widget tile_menu (array a, int cols) { +widget +tile_menu (array a, int cols) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::tile_menu, a, cols); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::tile_menu, a, cols); wid->add_children (a); return abstract (wid); } -widget minibar_menu (array a) { +widget +minibar_menu (array a) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::minibar_menu, a); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::minibar_menu, a); wid->add_children (a); return abstract (wid); } -widget menu_separator (bool vertical) { +widget +menu_separator (bool vertical) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::menu_separator, - vertical); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::menu_separator, vertical); return abstract (wid); } -widget menu_group (string name, int style) { +widget +menu_group (string name, int style) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::menu_group, - name, style); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::menu_group, name, style); return abstract (wid); } -widget pulldown_button (widget w, promise pw) { +widget +pulldown_button (widget w, promise pw) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::pulldown_button, - w, pw); - // FIXME: the promise widget isn't added to the children when it's evaluated - // wid->add_child (??); - return abstract(wid); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::pulldown_button, w, pw); + // FIXME: the promise widget isn't added to the children when it's evaluated + // wid->add_child (??); + return abstract (wid); } -widget pullright_button (widget w, promise pw) { +widget +pullright_button (widget w, promise pw) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::pullright_button, - w, pw); - // FIXME: the promise widget isn't added to the children when it's evaluated - // wid->add_child (??); - return abstract(wid); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::pullright_button, w, pw); + // FIXME: the promise widget isn't added to the children when it's evaluated + // wid->add_child (??); + return abstract (wid); } -widget menu_button (widget w, command cmd, string pre, string ks, int style) { +widget +menu_button (widget w, command cmd, string pre, string ks, int style) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::menu_button, - w, cmd, pre, ks, style); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::menu_button, w, cmd, + pre, ks, style); wid->add_child (w); return abstract (wid); } -widget balloon_widget (widget w, widget help) { +widget +balloon_widget (widget w, widget help) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::balloon_widget, - w, help); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::balloon_widget, w, help); wid->add_child (w); return abstract (wid); } -widget text_widget (string s, int style, color col, bool tsp) { +widget +text_widget (string s, int style, color col, bool tsp) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::text_widget, - s, style, col, tsp); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::text_widget, s, + style, col, tsp); return abstract (wid); } -widget xpm_widget (url file_name) { +widget +xpm_widget (url file_name) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::xpm_widget, - file_name); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::xpm_widget, file_name); return abstract (wid); } -widget toggle_widget (command cmd, bool on, int style) { +widget +toggle_widget (command cmd, bool on, int style) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::toggle_widget, - cmd, on, style); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::toggle_widget, cmd, on, style); return abstract (wid); } -widget enum_widget (command cmd, array vals, string val, int style, - string width) { +widget +enum_widget (command cmd, array vals, string val, int style, + string width) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::enum_widget, - cmd, vals, val, style, width); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::enum_widget, cmd, + vals, val, style, width); return abstract (wid); } -widget choice_widget (command cmd, array vals, array chosen) { +widget +choice_widget (command cmd, array vals, array chosen) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::choice_widget, - cmd, vals, chosen, true); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::choice_widget, cmd, + vals, chosen, true); return abstract (wid); } -widget choice_widget (command cmd, array vals, string cur) { +widget +choice_widget (command cmd, array vals, string cur) { if (headless_mode) return headless_widget (); array chosen (1); - chosen[0]= cur; - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::choice_widget, - cmd, vals, chosen, false); + chosen[0] = cur; + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::choice_widget, cmd, + vals, chosen, false); return abstract (wid); } -widget choice_widget (command cmd, array vals, string cur, string filter) { +widget +choice_widget (command cmd, array vals, string cur, string filter) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::filtered_choice_widget, - cmd, vals, cur, filter); + qt_widget wid= qt_ui_element_rep::create ( + qt_widget_rep::filtered_choice_widget, cmd, vals, cur, filter); return abstract (wid); } -widget user_canvas_widget (widget w, int style) { +widget +user_canvas_widget (widget w, int style) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::scrollable_widget, - w, style); + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::scrollable_widget, w, style); wid->add_child (w); return abstract (wid); } -widget resize_widget (widget w, int style, string w1, string h1, - string w2, string h2, string w3, string h3, - string hpos, string vpos) { +widget +resize_widget (widget w, int style, string w1, string h1, string w2, string h2, + string w3, string h3, string hpos, string vpos) { typedef triple T1; if (headless_mode) return headless_widget (); - (void) hpos; (void) vpos; - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::resize_widget, - w, style, T1(w1, w2, w3), - T1(h1, h2, h3)); + (void) hpos; + (void) vpos; + qt_widget wid= qt_ui_element_rep::create ( + qt_widget_rep::resize_widget, w, style, T1 (w1, w2, w3), T1 (h1, h2, h3)); wid->add_child (w); return abstract (wid); } -widget hsplit_widget (widget l, widget r) { +widget +hsplit_widget (widget l, widget r) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::hsplit_widget, l, r); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::hsplit_widget, l, r); wid->add_children (array (l, r)); return abstract (wid); } -widget vsplit_widget (widget t, widget b) { +widget +vsplit_widget (widget t, widget b) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::vsplit_widget, t, b); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::vsplit_widget, t, b); wid->add_children (array (t, b)); return abstract (wid); } -widget refresh_widget (string tmwid, string kind) { +widget +refresh_widget (string tmwid, string kind) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::refresh_widget, - tmwid, kind); - // FIXME: decide what to do with children in QTMRefresh::recompute() + qt_widget wid= + qt_ui_element_rep::create (qt_widget_rep::refresh_widget, tmwid, kind); + // FIXME: decide what to do with children in QTMRefresh::recompute() return abstract (wid); } -widget refreshable_widget (object promise, string kind) { +widget +refreshable_widget (object promise, string kind) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::refreshable_widget, - promise, kind); - // FIXME: decide what to do with children in QTMRefreshable::recompute() + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::refreshable_widget, + promise, kind); + // FIXME: decide what to do with children in QTMRefreshable::recompute() return abstract (wid); } -widget glue_widget (bool hx, bool vx, SI w, SI h) { +widget +glue_widget (bool hx, bool vx, SI w, SI h) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_ui_element_rep::glue_widget, - hx, vx, w/PIXEL, h/PIXEL); + qt_widget wid= qt_ui_element_rep::create (qt_ui_element_rep::glue_widget, hx, + vx, w / PIXEL, h / PIXEL); return abstract (wid); } -widget glue_widget (tree col, bool hx, bool vx, SI w, SI h) { +widget +glue_widget (tree col, bool hx, bool vx, SI w, SI h) { return tm_new (col, hx, vx, w, h); } -widget inputs_list_widget (command call_back, array prompts) { +widget +inputs_list_widget (command call_back, array prompts) { if (headless_mode) return headless_widget (); return tm_new (call_back, prompts); } -widget input_text_widget (command call_back, string type, array def, - int style, string width) { +widget +input_text_widget (command call_back, string type, array def, int style, + string width) { if (headless_mode) return headless_widget (); return tm_new (call_back, type, def, style, width); } -widget color_picker_widget (command call_back, bool bg, array proposals) { +widget +color_picker_widget (command call_back, bool bg, array proposals) { if (headless_mode) return headless_widget (); return tm_new (call_back, bg, proposals); } -widget file_chooser_widget (command cmd, string type, string prompt) { +widget +file_chooser_widget (command cmd, string type, string prompt) { if (headless_mode) return headless_widget (); return tm_new (cmd, type, prompt); } -#if !defined (USE_QT_PRINTER) -widget printer_widget (command cmd, url ps_pdf_file){ - return widget(); +#if !defined(USE_QT_PRINTER) +widget +printer_widget (command cmd, url ps_pdf_file) { + return widget (); } #else -widget printer_widget (command cmd, url ps_pdf_file) { +widget +printer_widget (command cmd, url ps_pdf_file) { if (headless_mode) return headless_widget (); return tm_new (cmd, ps_pdf_file); } #endif -widget texmacs_widget (int mask, command quit) { +widget +texmacs_widget (int mask, command quit) { if (headless_mode) return headless_widget (); if (mask) return tm_new (mask, quit); - else return tm_new (quit); + else return tm_new (quit); } -widget ink_widget (command cb) { - NOT_IMPLEMENTED("Ink widget"); - (void) cb; return widget(); +widget +ink_widget (command cb) { + NOT_IMPLEMENTED ("Ink widget"); + (void) cb; + return widget (); } -widget tree_view_widget (command cmd, tree data, tree actions) { +widget +tree_view_widget (command cmd, tree data, tree actions) { if (headless_mode) return headless_widget (); - qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::tree_view_widget, - cmd, data, actions); + qt_widget wid= qt_ui_element_rep::create (qt_widget_rep::tree_view_widget, + cmd, data, actions); return abstract (wid); - } - //// Widgets which are not strictly required by TeXmacs have void implementations +//// Widgets which are not strictly required by TeXmacs have void +/// implementations -widget empty_widget () { NOT_IMPLEMENTED("empty_widget"); return widget(); } -widget extend_widget (widget w, array a) { (void) a; return w; } -widget wait_widget (SI width, SI height, string message) { - (void) width; (void) height; (void) message; return widget(); +widget +empty_widget () { + NOT_IMPLEMENTED ("empty_widget"); + return widget (); +} +widget +extend_widget (widget w, array a) { + (void) a; + return w; +} +widget +wait_widget (SI width, SI height, string message) { + (void) width; + (void) height; + (void) message; + return widget (); } diff --git a/src/Plugins/Qt/qt_widget.hpp b/src/Plugins/Qt/qt_widget.hpp index 36e6a2d51d..de310dba47 100644 --- a/src/Plugins/Qt/qt_widget.hpp +++ b/src/Plugins/Qt/qt_widget.hpp @@ -1,21 +1,21 @@ /****************************************************************************** -* MODULE : qt_widget.hpp -* DESCRIPTION: QT widget class -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_widget.hpp + * DESCRIPTION: QT widget class + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_WIDGET_HPP #define QT_WIDGET_HPP #include "fast_alloc.hpp" -#include "widget.hpp" #include "message.hpp" #include "qt_utilities.hpp" +#include "widget.hpp" #include class QWidget; @@ -29,9 +29,9 @@ class qt_widget; Every TeXmacs Widget is an entity which can be manipulated from within scheme. The interface to this is provided by widget_rep, which we extend. The methods here declared must be implemented by the QT wrappers. - + We must distinguish between three stages of widget creation: - + 1) Scheme widgets: these are scheme trees describing the widgets. These trees are the result of several macro expansions on the code given by the user in scheme (see under progs/kernel/gui) and are wholly handled by the TeXmacs @@ -51,33 +51,33 @@ class qt_widget; the four methods as_qaction(), as_qlayoutitem(), as_qwidget() and get_qmenu(). Reimplementations of these should cope with the basic differences these concepts have in QT: - - * as_qaction() returns a QAction, mainly to be inserted into a QMenuBar. + + * as_qaction() returns a QAction, mainly to be inserted into a QMenuBar. QWidgets should render themselves in an adequate fashion (i.e. with small font, using popup buttons where appropriate, etc.) - + * as_qlayoutitem() usually does one of two things: either embedding a QWidget in a QLayouttItem, so as to add it to some QLayout, or creating a "pure" QLayoutItem. - + * as_qwidget() returns a regular QWidget, for example to be embedded in a standalone window. - + get_qmenu() returns the QMenu owned by the QAction returned by as_qaction(). This method also promotes the object upon which it was invoked to owner of the QMenu. Again: calling wid->get_qmenu() creates the QMenu and leaves ownership of it to wid. - + In the first three cases a new instance of the QObject is created if neede and ownership is transferred to the caller. One reason why the underlying QWidget is NOT owned by the qt_widget is that several qt_widgets may have the same underlying QWidget (UPD: which?). Another are the problems due to delayed deletion of TeXmacs objects. The only exception to this rule are those qt_widgets whose compiled widgets are windows to whom we leave the - responsibility of deletion. They are the outmost widget, typically a + responsibility of deletion. They are the outmost widget, typically a QTMPlainWindow or a QTMWindow, who should be the parent of all the related QWidgets. - + Most of the UI items are implemented by qt_ui_element_rep, with some exceptions. Creation from the TeXmacs side is done using the global functions declared in Graphics/Gui/widget.hpp. @@ -87,37 +87,68 @@ class qt_widget; class qt_widget_rep : public widget_rep { protected: array children; + public: - long id; + long id; QPointer qwid; /*! A list of all supported widget types. - FIXME: This enum breaks the basic inheritance rules, since we have to + FIXME: This enum breaks the basic inheritance rules, since we have to update the base class each time we implement a new subclass. It's also some sort of bastardic and lame RTTI, which might be proof of bad design... But it comes handy in a few places right now ;) NOTE: please modify qt_widget_type_strings[] in type_as_string() accordingly! */ enum types { - none = 0, - input_widget, file_chooser, window_widget, view_widget, - horizontal_menu, vertical_menu, horizontal_list, vertical_list, - tile_menu, minibar_menu, menu_separator, menu_group, - pulldown_button, pullright_button, menu_button, balloon_widget, - text_widget, xpm_widget, toggle_widget, enum_widget, - choice_widget, scrollable_widget, hsplit_widget, vsplit_widget, - aligned_widget, tabs_widget, icon_tabs_widget, wrapped_widget, - refresh_widget, refreshable_widget, glue_widget, resize_widget, - texmacs_widget, simple_widget, embedded_tm_widget, popup_widget, - field_widget, filtered_choice_widget,tree_view_widget, division_widget - } ; - + none= 0, + input_widget, + file_chooser, + window_widget, + view_widget, + horizontal_menu, + vertical_menu, + horizontal_list, + vertical_list, + tile_menu, + minibar_menu, + menu_separator, + menu_group, + pulldown_button, + pullright_button, + menu_button, + balloon_widget, + text_widget, + xpm_widget, + toggle_widget, + enum_widget, + choice_widget, + scrollable_widget, + hsplit_widget, + vsplit_widget, + aligned_widget, + tabs_widget, + icon_tabs_widget, + wrapped_widget, + refresh_widget, + refreshable_widget, + glue_widget, + resize_widget, + texmacs_widget, + simple_widget, + embedded_tm_widget, + popup_widget, + field_widget, + filtered_choice_widget, + tree_view_widget, + division_widget + }; + types type; - - qt_widget_rep (types _type=none, QWidget* _qwid=0); + + qt_widget_rep (types _type= none, QWidget* _qwid= 0); virtual ~qt_widget_rep (); virtual inline string get_nickname () { return "popup"; } - + virtual widget plain_window_widget (string name, command quit, int b= 3); virtual widget make_popup_widget (); virtual widget popup_window_widget (string s); @@ -125,104 +156,133 @@ class qt_widget_rep : public widget_rep { void add_child (widget a); void add_children (array a); - - ////////////////////// Qt semantics of abstract texmacs widgets - + + ////////////////////// Qt semantics of abstract texmacs widgets + virtual QAction* as_qaction (); virtual QWidget* as_qwidget (); virtual QLayoutItem* as_qlayoutitem (); - virtual QList* get_qactionlist(); - + virtual QList* get_qactionlist (); ////////////////////// Debugging - - string type_as_string() { - static const char* qt_widget_type_strings[] = { - "none", - "input_widget", "file_chooser", "window_widget", - "view_widget", "horizontal_menu", "vertical_menu", - "horizontal_list", "vertical_list", "tile_menu", - "minibar_menu", "menu_separator", "menu_group", - "pulldown_button", "pullright_button", "menu_button", - "balloon_widget", "text_widget", "xpm_widget", - "toggle_widget", "enum_widget", "choice_widget", - "scrollable_widget", "hsplit_widget", "vsplit_widget", - "aligned_widget", "tabs_widget", "icon_tabs_widget", - "wrapped_widget", "refresh_widget", "refreshable_widget", - "glue_widget", "resize_widget", "texmacs_widget", - "simple_widget", "embedded_tm_widget", "popup_widget", - "field_widget", "filtered_choice_widget", "tree_view_widget", - "division_widget" - }; + + string type_as_string () { + static const char* qt_widget_type_strings[]= {"none", + "input_widget", + "file_chooser", + "window_widget", + "view_widget", + "horizontal_menu", + "vertical_menu", + "horizontal_list", + "vertical_list", + "tile_menu", + "minibar_menu", + "menu_separator", + "menu_group", + "pulldown_button", + "pullright_button", + "menu_button", + "balloon_widget", + "text_widget", + "xpm_widget", + "toggle_widget", + "enum_widget", + "choice_widget", + "scrollable_widget", + "hsplit_widget", + "vsplit_widget", + "aligned_widget", + "tabs_widget", + "icon_tabs_widget", + "wrapped_widget", + "refresh_widget", + "refreshable_widget", + "glue_widget", + "resize_widget", + "texmacs_widget", + "simple_widget", + "embedded_tm_widget", + "popup_widget", + "field_widget", + "filtered_choice_widget", + "tree_view_widget", + "division_widget"}; return string (qt_widget_type_strings[type]) * "\t id: " * as_string (id); } - + ////////////////////// Handling of TeXmacs' messages - /// See widkit_wrapper.cpp for the reference list of slots. Based on the - /// handlers invoked by wk_widget_rep::send(), query() etc. we can decide - /// what slots must implement each qt_widget. + /// See widkit_wrapper.cpp for the reference list of slots. Based on the + /// handlers invoked by wk_widget_rep::send(), query() etc. we can decide + /// what slots must implement each qt_widget. virtual void send (slot s, blackbox val); - + virtual blackbox query (slot s, int type_id) { (void) type_id; if (DEBUG_QT) - debug_qt << "qt_widget_rep::query(), unhandled " << slot_name (s) - << " for widget of type: " << type_as_string() << LF; + debug_qt << "qt_widget_rep::query(), unhandled " << slot_name (s) + << " for widget of type: " << type_as_string () << LF; return blackbox (); } - + virtual widget read (slot s, blackbox index) { (void) index; if (DEBUG_QT) - debug_qt << "qt_widget_rep::read(), unhandled " << slot_name (s) - << " for widget of type: " << type_as_string() << LF; + debug_qt << "qt_widget_rep::read(), unhandled " << slot_name (s) + << " for widget of type: " << type_as_string () << LF; return widget (); } - + virtual void write (slot s, blackbox index, widget w) { - (void) index; (void) w; + (void) index; + (void) w; if (DEBUG_QT) - debug_qt << "qt_widget_rep::write(), unhandled " << slot_name (s) - << " for widget of type: " << type_as_string() << LF; + debug_qt << "qt_widget_rep::write(), unhandled " << slot_name (s) + << " for widget of type: " << type_as_string () << LF; } - + virtual void notify (slot s, blackbox new_val) { (void) new_val; if (DEBUG_QT) debug_qt << "qt_widget_rep::notify(), unhandled " << slot_name (s) - << " for widget of type: " << type_as_string() << LF; + << " for widget of type: " << type_as_string () << LF; } }; -template <> void tm_delete(qt_widget_rep *); +template <> void tm_delete (qt_widget_rep*); /*! Reference counting mechanism. - Like elsewhere in TeXmacs, this is a wrapper around its corresponding + Like elsewhere in TeXmacs, this is a wrapper around its corresponding qt_widget_rep which implements reference counting. See src/Kernel/Abstractions/basic.hpp */ class qt_widget { public: - ABSTRACT_NULL(qt_widget); // Automagically declared constructor, methods, etc. + ABSTRACT_NULL ( + qt_widget); // Automagically declared constructor, methods, etc. - inline bool operator == (qt_widget w) { return rep == w.rep; } - inline bool operator != (qt_widget w) { return rep != w.rep; } + inline bool operator== (qt_widget w) { return rep == w.rep; } + inline bool operator!= (qt_widget w) { return rep != w.rep; } }; // Automagically create definitions for the stuff declared inside qt_widget with // the macro ABSTRACT_NULL(). See src/Kernel/Abstractions/basic.hpp -ABSTRACT_NULL_CODE(qt_widget); +ABSTRACT_NULL_CODE (qt_widget); - // Needed for the ntuples (see ntuple.h) -tm_ostream& operator << (tm_ostream& out, qt_widget w); +// Needed for the ntuples (see ntuple.h) +tm_ostream& operator<< (tm_ostream& out, qt_widget w); /*! Casting form qt_widget to widget */ -inline widget abstract (qt_widget w) { return widget (w.rep); } +inline widget +abstract (qt_widget w) { + return widget (w.rep); +} /*! Casting from widget to qt_widget */ -inline qt_widget concrete (widget w) { +inline qt_widget +concrete (widget w) { return qt_widget (static_cast (w.rep)); } @@ -231,20 +291,19 @@ inline widget headless_widget (); class qt_headless_widget_rep : public qt_widget_rep { public: - qt_headless_widget_rep () {}; + qt_headless_widget_rep (){}; virtual ~qt_headless_widget_rep () { - if (DEBUG_QT_WIDGETS) - debug_widgets << "~qt_headless_widget_rep" << LF; + if (DEBUG_QT_WIDGETS) debug_widgets << "~qt_headless_widget_rep" << LF; } virtual inline string get_nickname () { return "headless"; } virtual widget plain_window_widget (string name, command quit, int b= 3) { - (void) name; (void) quit; (void) b; - return headless_widget (); - } - virtual widget make_popup_widget () { + (void) name; + (void) quit; + (void) b; return headless_widget (); } + virtual widget make_popup_widget () { return headless_widget (); } virtual widget popup_window_widget (string s) { (void) s; return headless_widget (); @@ -257,16 +316,13 @@ class qt_headless_widget_rep : public qt_widget_rep { virtual QAction* as_qaction () { return NULL; } virtual QWidget* as_qwidget () { return NULL; } virtual QLayoutItem* as_qlayoutitem () { return NULL; } - virtual QList* get_qactionlist() { return NULL; } + virtual QList* get_qactionlist () { return NULL; } - virtual void send (slot s, blackbox val) { - qt_widget_rep::send (s, val); - } + virtual void send (slot s, blackbox val) { qt_widget_rep::send (s, val); } virtual blackbox query (slot s, int type_id) { static int id= 1; switch (s) { - case SLOT_IDENTIFIER: - { + case SLOT_IDENTIFIER: { check_type_id (type_id, s); return close_box (id++); } @@ -275,22 +331,26 @@ class qt_headless_widget_rep : public qt_widget_rep { } } virtual widget read (slot s, blackbox index) { - (void) s; (void) index; - return headless_widget ();; + (void) s; + (void) index; + return headless_widget (); + ; } virtual void write (slot s, blackbox index, widget w) { - (void) s; (void) index; (void) w; + (void) s; + (void) index; + (void) w; qt_widget_rep::write (s, index, w); - } virtual void notify (slot s, blackbox new_val) { - (void) s; (void) new_val; + (void) s; + (void) new_val; qt_widget_rep::notify (s, new_val); - } }; -inline widget headless_widget () { +inline widget +headless_widget () { return widget ((widget_rep*) tm_new ()); } diff --git a/src/Plugins/Qt/qt_window_widget.cpp b/src/Plugins/Qt/qt_window_widget.cpp index a107f0a650..365e20cb82 100644 --- a/src/Plugins/Qt/qt_window_widget.cpp +++ b/src/Plugins/Qt/qt_window_widget.cpp @@ -10,66 +10,65 @@ ******************************************************************************/ #include "qt_window_widget.hpp" -#include "qt_tm_widget.hpp" -#include "qt_utilities.hpp" -#include "qt_gui.hpp" -#include "QTMWindow.hpp" #include "QTMGuiHelper.hpp" #include "QTMMenuHelper.hpp" +#include "QTMWindow.hpp" +#include "qt_gui.hpp" +#include "qt_tm_widget.hpp" +#include "qt_utilities.hpp" -#include "message.hpp" #include "analyze.hpp" +#include "message.hpp" #include "tm_window.hpp" -#include -#include #include +#include +#include /*! Construct a qt_window_widget_rep around an already compiled widget. - - This means that the QWidget passed as an argument already represents a fully + + This means that the QWidget passed as an argument already represents a fully parsed and compiled scheme widget. We use this fact to decide whether we must be resizable or not, for instance. - + The parameter "fake" means this qt_window_widget_rep is not part of the window list, so the nr_windows global variable must not be updated. */ qt_window_widget_rep::qt_window_widget_rep (QWidget* _wid, string name, command _quit, bool _fake) -: qt_widget_rep (window_widget, _wid), orig_name(name), quit(_quit), fake(_fake) -{ + : qt_widget_rep (window_widget, _wid), orig_name (name), quit (_quit), + fake (_fake) { qwid->setProperty ("texmacs_window_widget", QVariant::fromValue ((void*) this)); - - // Try to connect only if the QWidget has a closed() signal - // We need this for the QDockWidgets we use in side tools (see qt_tm_widget_rep) - if (qwid->metaObject() -> - indexOfSignal (QMetaObject::normalizedSignature ("closed()").constData ()) != -1) { - QTMCommand* qtmcmd = new QTMCommand (qwid, quit); - QObject::connect(qwid, SIGNAL (closed()), qtmcmd, SLOT (apply())); + + // Try to connect only if the QWidget has a closed() signal + // We need this for the QDockWidgets we use in side tools (see + // qt_tm_widget_rep) + if (qwid->metaObject ()->indexOfSignal ( + QMetaObject::normalizedSignature ("closed()").constData ()) != -1) { + QTMCommand* qtmcmd= new QTMCommand (qwid, quit); + QObject::connect (qwid, SIGNAL (closed ()), qtmcmd, SLOT (apply ())); } - if (!has_resizable_children (_wid)) - qwid->setFixedSize (qwid->sizeHint()); - - // HACK: don't increment window count for side tools or any other fake windows - if (!fake) win_id = ++nr_windows; - - if (DEBUG_QT) - debug_qt << "Creating qt_window_widget " << id << "\n"; + if (!has_resizable_children (_wid)) qwid->setFixedSize (qwid->sizeHint ()); + + // HACK: don't increment window count for side tools or any other fake windows + if (!fake) win_id= ++nr_windows; + + if (DEBUG_QT) debug_qt << "Creating qt_window_widget " << id << "\n"; if (tm_style_sheet == "") { QPalette pal; -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // QPalette::Background. This value is obsolete. Use Window instead. QColor winbg= pal.color (QPalette::Background); - if (winbg.red() + winbg.green() + winbg.blue () < 255) + if (winbg.red () + winbg.green () + winbg.blue () < 255) pal.setColor (QPalette::Background, QColor (240, 240, 240)); _wid->setPalette (pal); } #else QColor winbg= pal.color (QPalette::Window); - if (winbg.red() + winbg.green() + winbg.blue () < 255) + if (winbg.red () + winbg.green () + winbg.blue () < 255) pal.setColor (QPalette::Window, QColor (240, 240, 240)); _wid->setPalette (pal); } @@ -79,12 +78,10 @@ qt_window_widget_rep::qt_window_widget_rep (QWidget* _wid, string name, /*! WARNING! This should be the only place were QWidgets are destroyed! */ -qt_window_widget_rep::~qt_window_widget_rep () -{ +qt_window_widget_rep::~qt_window_widget_rep () { if (!fake) nr_windows--; - if (DEBUG_QT) - debug_qt << "Deleting qt_window_widget " << id << "\n"; - //if (qwid) qwid->deleteLater(); // this caused bug 61844 + if (DEBUG_QT) debug_qt << "Deleting qt_window_widget " << id << "\n"; + // if (qwid) qwid->deleteLater(); // this caused bug 61844 if (qwid) { notify_window_destroy (get_nickname ()); delete qwid; @@ -92,8 +89,7 @@ qt_window_widget_rep::~qt_window_widget_rep () } widget -qt_window_widget_rep::popup_window_widget (string s) -{ +qt_window_widget_rep::popup_window_widget (string s) { qwid->setWindowTitle (to_qstring (s)); qwid->setWindowModality (Qt::NonModal); qwid->setWindowFlags (Qt::Popup); @@ -102,15 +98,13 @@ qt_window_widget_rep::popup_window_widget (string s) /*! Looks among the widget's parents for the containing texmacs window */ -widget_rep* -qt_window_widget_rep::widget_from_qwidget (QWidget* q) -{ +widget_rep* +qt_window_widget_rep::widget_from_qwidget (QWidget* q) { while (q != NULL) { - QVariant v = q->property ("texmacs_window_widget"); + QVariant v= q->property ("texmacs_window_widget"); if (v.canConvert ()) return static_cast (v.value ()); - else - q = q->parentWidget(); + else q= q->parentWidget (); } return NULL; } @@ -120,21 +114,21 @@ qt_window_widget_rep::widget_from_qwidget (QWidget* q) */ bool qt_window_widget_rep::has_resizable_children (QWidget* w, bool ret) { - // Ignore any non QWidgets + // Ignore any non QWidgets if (!w) return false; - - // Hack: these must always be resizable + + // Hack: these must always be resizable if (qobject_cast (w) || qobject_cast (w)) return true; - ret = (w->minimumSize() != QSize (0,0) && - w->maximumSize() != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX) && - w->minimumSize() != w->maximumSize()); - - QObjectList ch = w->children(); - for (int i=0; i (ch[i]), ret); - + ret= (w->minimumSize () != QSize (0, 0) && + w->maximumSize () != QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX) && + w->minimumSize () != w->maximumSize ()); + + QObjectList ch= w->children (); + for (int i= 0; i < ch.size (); ++i) + ret= ret || has_resizable_children (qobject_cast (ch[i]), ret); + return ret; } @@ -142,162 +136,145 @@ void qt_window_widget_rep::send (slot s, blackbox val) { if (DEBUG_QT_WIDGETS) debug_widgets << "qt_window_widget_rep::send " << slot_name (s) << LF; - + switch (s) { - case SLOT_SIZE: - { - check_type(val, s); - coord2 p = open_box (val); - if (qwid) { - QSize size = to_qsize (p); - qwid->resize (size); - } + case SLOT_SIZE: { + check_type (val, s); + coord2 p= open_box (val); + if (qwid) { + QSize size= to_qsize (p); + qwid->resize (size); } - break; - case SLOT_POSITION: - { - check_type(val, s); - coord2 p = open_box (val); - if (qwid) { - QPoint pt = to_qpoint (p); + } break; + case SLOT_POSITION: { + check_type (val, s); + coord2 p= open_box (val); + if (qwid) { + QPoint pt= to_qpoint (p); #ifdef OS_MACOS - pt.ry() = (pt.y() <= 40) ? 40 : pt.y(); - // to avoid window under menu bar on MAC when moving at (0,0) - // FIXME: use the real menu bar height. + pt.ry ()= (pt.y () <= 40) ? 40 : pt.y (); + // to avoid window under menu bar on MAC when moving at (0,0) + // FIXME: use the real menu bar height. #endif - qwid->move (pt); - } + qwid->move (pt); } - break; - case SLOT_VISIBILITY: - { - check_type (val, s); - bool flag = open_box (val); - if (qwid) { - if (flag) { - //QWidget* master = QApplication::activeWindow (); - qwid->show(); - //qwid->activateWindow(); - //WEIRD: in Ubuntu uncommenting the above line causes the main window - //to be opened in the background. - qwid->raise(); - //QApplication::setActiveWindow (master); - } - else qwid->hide(); + } break; + case SLOT_VISIBILITY: { + check_type (val, s); + bool flag= open_box (val); + if (qwid) { + if (flag) { + // QWidget* master = QApplication::activeWindow (); + qwid->show (); + // qwid->activateWindow(); + // WEIRD: in Ubuntu uncommenting the above line causes the main window + // to be opened in the background. + qwid->raise (); + // QApplication::setActiveWindow (master); } + else qwid->hide (); } - break; - case SLOT_MOUSE_GRAB: - { - check_type (val, s); - bool flag = open_box (val); // true= get grab, false= release grab - if (flag && qwid) { - qwid->setWindowFlags (Qt::Window); // ok? - qwid->setWindowModality (Qt::WindowModal); //ok? - qwid->show(); - } - } - break; - case SLOT_NAME: // sets window *title* not the name - { - check_type (val, s); - string name = open_box (val); - // The [*] is for QWidget::setWindowModified() - if (qwid) qwid->setWindowTitle (to_qstring (name * "[*]")); - } - break; - case SLOT_MODIFIED: - { - check_type (val, s); - bool flag = open_box (val); - if (qwid) qwid->setWindowModified (flag); - } - break; - case SLOT_REFRESH: - { - check_type (val, s); - string kind = open_box (val); - the_gui->gui_helper->emitTmSlotRefresh (kind); + } break; + case SLOT_MOUSE_GRAB: { + check_type (val, s); + bool flag= open_box (val); // true= get grab, false= release grab + if (flag && qwid) { + qwid->setWindowFlags (Qt::Window); // ok? + qwid->setWindowModality (Qt::WindowModal); // ok? + qwid->show (); } - break; - default: - qt_widget_rep::send(s, val); + } break; + case SLOT_NAME: // sets window *title* not the name + { + check_type (val, s); + string name= open_box (val); + // The [*] is for QWidget::setWindowModified() + if (qwid) qwid->setWindowTitle (to_qstring (name * "[*]")); + } break; + case SLOT_MODIFIED: { + check_type (val, s); + bool flag= open_box (val); + if (qwid) qwid->setWindowModified (flag); + } break; + case SLOT_REFRESH: { + check_type (val, s); + string kind= open_box (val); + the_gui->gui_helper->emitTmSlotRefresh (kind); + } break; + default: + qt_widget_rep::send (s, val); } } blackbox qt_window_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_window_widget_rep::query " << slot_name(s) << LF; + debug_widgets << "qt_window_widget_rep::query " << slot_name (s) << LF; switch (s) { - case SLOT_IDENTIFIER: - { - check_type_id (type_id, s); - return close_box (win_id); - } + case SLOT_IDENTIFIER: { + check_type_id (type_id, s); + return close_box (win_id); + } - case SLOT_POSITION: - { - check_type_id (type_id, s); - QRect g; - // FIXME: dock widgets are embedded into qt_window_widget_reps as a temporary hack - // because of this the underlying widget is not always a top level window - if (qwid->isWindow()) g = qwid->frameGeometry(); - else g = qwid->window()->frameGeometry(); - //cout << "wpos: " << pt.x() << ", " << pt.y() << LF; - return close_box (from_qpoint (QPoint (g.x(), g.y()))); - } + case SLOT_POSITION: { + check_type_id (type_id, s); + QRect g; + // FIXME: dock widgets are embedded into qt_window_widget_reps as a + // temporary hack because of this the underlying widget is not always a top + // level window + if (qwid->isWindow ()) g= qwid->frameGeometry (); + else g= qwid->window ()->frameGeometry (); + // cout << "wpos: " << pt.x() << ", " << pt.y() << LF; + return close_box (from_qpoint (QPoint (g.x (), g.y ()))); + } - case SLOT_SIZE: - { - check_type_id (type_id, s); - QSize sz = qwid->frameSize(); - return close_box (from_qsize (sz)); - } + case SLOT_SIZE: { + check_type_id (type_id, s); + QSize sz= qwid->frameSize (); + return close_box (from_qsize (sz)); + } - default: - return qt_widget_rep::query (s, type_id); + default: + return qt_widget_rep::query (s, type_id); } } widget qt_window_widget_rep::read (slot s, blackbox index) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_window_widget_rep::read " << slot_name(s) + debug_widgets << "qt_window_widget_rep::read " << slot_name (s) << "\tWidget id: " << id << LF; - + switch (s) { - case SLOT_WINDOW: // We use this in qt_gui_rep::show_help_balloon() - check_type_void (index, s); - return this; + case SLOT_WINDOW: // We use this in qt_gui_rep::show_help_balloon() + check_type_void (index, s); + return this; - default: - return qt_widget_rep::read (s, index); + default: + return qt_widget_rep::read (s, index); } } void qt_window_widget_rep::notify (slot s, blackbox new_val) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_window_widget_rep::notify " << slot_name(s) << LF; + debug_widgets << "qt_window_widget_rep::notify " << slot_name (s) << LF; widget_rep::notify (s, new_val); } - /****************************************************************************** * popup widget ******************************************************************************/ - qt_popup_widget_rep::qt_popup_widget_rep (widget wid, command _quit) -: qt_widget_rep(qt_widget_rep::popup_widget, 0), quit(_quit) { - - qwid = new QTMPopupWidget(concrete(wid)->as_qwidget()); - - if (qwid->metaObject() -> - indexOfSignal (QMetaObject::normalizedSignature ("closed()").constData ()) != -1) { - QTMCommand* qtmcmd = new QTMCommand(qwid, quit); - QObject::connect(qwid, SIGNAL (closed()), qtmcmd, SLOT (apply())); + : qt_widget_rep (qt_widget_rep::popup_widget, 0), quit (_quit) { + + qwid= new QTMPopupWidget (concrete (wid)->as_qwidget ()); + + if (qwid->metaObject ()->indexOfSignal ( + QMetaObject::normalizedSignature ("closed()").constData ()) != -1) { + QTMCommand* qtmcmd= new QTMCommand (qwid, quit); + QObject::connect (qwid, SIGNAL (closed ()), qtmcmd, SLOT (apply ())); } } @@ -305,11 +282,11 @@ qt_popup_widget_rep::qt_popup_widget_rep (widget wid, command _quit) WARNING! This should be the only place were QWidgets are destroyed! */ qt_popup_widget_rep::~qt_popup_widget_rep () { - if (qwid) qwid->deleteLater(); + if (qwid) qwid->deleteLater (); } widget -qt_popup_widget_rep::popup_window_widget(string s) { +qt_popup_widget_rep::popup_window_widget (string s) { qwid->setWindowTitle (to_qstring (s)); // useless for Qt::Popup return this; @@ -323,71 +300,59 @@ qt_popup_widget_rep::tooltip_window_widget (string s) { return this; } - - void qt_popup_widget_rep::send (slot s, blackbox val) { switch (s) { - case SLOT_SIZE: - { - check_type(val, s); - qwid->resize (to_qsize (open_box (val))); - } - break; - - case SLOT_POSITION: - { - check_type(val, s); - qwid->move (to_qpoint (open_box (val))); - } - break; - - case SLOT_VISIBILITY: - { - check_type (val, s); - qwid->setVisible(open_box (val)); - } - break; - - //FIXME: what's this? - case SLOT_MOUSE_GRAB: - { - check_type (val, s); - bool flag = open_box (val); // true= get grab, false= release grab - - qwid->hide(); - if (flag) qwid->setWindowModality(Qt::WindowModal); //ok? - else qwid->setWindowModality(Qt::NonModal); //ok? - qwid->show(); - } - break; - - default: - qt_widget_rep::send(s, val); + case SLOT_SIZE: { + check_type (val, s); + qwid->resize (to_qsize (open_box (val))); + } break; + + case SLOT_POSITION: { + check_type (val, s); + qwid->move (to_qpoint (open_box (val))); + } break; + + case SLOT_VISIBILITY: { + check_type (val, s); + qwid->setVisible (open_box (val)); + } break; + + // FIXME: what's this? + case SLOT_MOUSE_GRAB: { + check_type (val, s); + bool flag= open_box (val); // true= get grab, false= release grab + + qwid->hide (); + if (flag) qwid->setWindowModality (Qt::WindowModal); // ok? + else qwid->setWindowModality (Qt::NonModal); // ok? + qwid->show (); + } break; + + default: + qt_widget_rep::send (s, val); } - + if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_popup_widget_rep: sent " << slot_name (s) - << "\t\tto widget\t" << type_as_string() << LF; + debug_widgets << "qt_popup_widget_rep: sent " << slot_name (s) + << "\t\tto widget\t" << type_as_string () << LF; } blackbox qt_popup_widget_rep::query (slot s, int type_id) { if (DEBUG_QT_WIDGETS) - debug_widgets << "qt_popup_widget_rep::query " << slot_name(s) << LF; + debug_widgets << "qt_popup_widget_rep::query " << slot_name (s) << LF; switch (s) { - case SLOT_POSITION: - { - check_type_id (type_id, s); - return close_box (from_qpoint (qwid->pos())); - } - case SLOT_SIZE: - { - check_type_id (type_id, s); - return close_box (from_qsize (qwid->size())); - } - default: - return qt_widget_rep::query (s, type_id); + case SLOT_POSITION: { + check_type_id (type_id, s); + return close_box (from_qpoint (qwid->pos ())); + } + case SLOT_SIZE: { + check_type_id (type_id, s); + return close_box (from_qsize (qwid->size ())); + } + default: + return qt_widget_rep::query (s, type_id); } } diff --git a/src/Plugins/Qt/qt_window_widget.hpp b/src/Plugins/Qt/qt_window_widget.hpp index f108822292..1cfb9322aa 100644 --- a/src/Plugins/Qt/qt_window_widget.hpp +++ b/src/Plugins/Qt/qt_window_widget.hpp @@ -1,13 +1,13 @@ /****************************************************************************** -* MODULE : qt_window_widget.hpp -* DESCRIPTION: QT window widget. -* COPYRIGHT : (C) 2008 Massimiliano Gubinelli -******************************************************************************* -* This software falls under the GNU general public license version 3 or later. -* It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE -* in the root directory or . -******************************************************************************/ + * MODULE : qt_window_widget.hpp + * DESCRIPTION: QT window widget. + * COPYRIGHT : (C) 2008 Massimiliano Gubinelli + ******************************************************************************* + * This software falls under the GNU general public license version 3 or later. + * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE + * in the root directory or . + ******************************************************************************/ #ifndef QT_WINDOW_WIDGET_HPP #define QT_WINDOW_WIDGET_HPP @@ -17,64 +17,64 @@ class QWidget; /*! Models the simplest top-level window possible - + When any TeXmacs widget needs promotion into a TeXmacs window, the method - qt_widget_rep::plain_window_widget() or any reimplementation thereof - encapsulates it into a qt_window_widget. This class handles the necessary + qt_widget_rep::plain_window_widget() or any reimplementation thereof + encapsulates it into a qt_window_widget. This class handles the necessary slots, in particular all those already handled by qt_widget_rep. - - This qt_widget takes ownership of the enclosed QWidget and marks it as a + + This qt_widget takes ownership of the enclosed QWidget and marks it as a "texmacs_window_widget" using QObject::property(). The value of the property is set to this qt_window_widget_rep. - Later, the handling of some texmacs messages (SLOT_WINDOW in qt_simple_widget_rep - for instance) will require access to an instance of qt_window_widget which they - retrieve using the static member widget_from_qwidget(), who in turn uses the - mentioned property. - + Later, the handling of some texmacs messages (SLOT_WINDOW in + qt_simple_widget_rep for instance) will require access to an instance of + qt_window_widget which they retrieve using the static member + widget_from_qwidget(), who in turn uses the mentioned property. + qt_window_widget_rep is the *sole responsible* for the deletion of QWidgets. This makes sense in as much as all QWidgets are owned by some texmacs widget - which is inside some texmacs window: the method plain_window_widget must ALWAYS + which is inside some texmacs window: the method plain_window_widget must ALWAYS return a qt_window_widget_rep or we'll leak. */ -class qt_window_widget_rep: public qt_widget_rep { +class qt_window_widget_rep : public qt_widget_rep { protected: - int win_id; //!< Unique integer identifier, returned by SLOT_IDENTIFIER. - string orig_name; //!< Unique name assigned to the window. + int win_id; //!< Unique integer identifier, returned by SLOT_IDENTIFIER. + string orig_name; //!< Unique name assigned to the window. command quit; //!< Command to be executed when the window is closed. - bool fake; //!< Whether this truly is a window (or a docked widget). + bool fake; //!< Whether this truly is a window (or a docked widget). public: - - qt_window_widget_rep (QWidget* _wid, string name, command q, bool fake=false); + qt_window_widget_rep (QWidget* _wid, string name, command q, + bool fake= false); ~qt_window_widget_rep (); virtual inline string get_nickname () { return orig_name; } - virtual widget popup_window_widget (string s); + virtual widget popup_window_widget (string s); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); - virtual widget read (slot s, blackbox index); - virtual void notify (slot s, blackbox new_val); - + virtual widget read (slot s, blackbox index); + virtual void notify (slot s, blackbox new_val); + static widget_rep* widget_from_qwidget (QWidget* qwid); - static bool has_resizable_children (QWidget* w, bool ret=false); + static bool has_resizable_children (QWidget* w, bool ret= false); }; /*! */ -class qt_popup_widget_rep: public qt_widget_rep { +class qt_popup_widget_rep : public qt_widget_rep { public: command quit; - + qt_popup_widget_rep (widget wid, command q); ~qt_popup_widget_rep (); - + virtual widget popup_window_widget (string s); virtual widget tooltip_window_widget (string s); - virtual void send (slot s, blackbox val); + virtual void send (slot s, blackbox val); virtual blackbox query (slot s, int type_id); };