diff --git a/docs/CODING-STYLE.md b/docs/CODING-STYLE.md index 3f72414..8ee2170 100644 --- a/docs/CODING-STYLE.md +++ b/docs/CODING-STYLE.md @@ -57,7 +57,38 @@ information. - Never use parens in return statements when not necessary. -File Organization +Naming +------ + +### Type Names + +- Start with a capital letter. +- Each new word is capitalized. +- No underscores. + + +### Variable Names + +- Start each variable name with a lowercase letter. +- Each subsequent word is capitalized. +- No underscores. +- Data members start with a lowercase "m" with the 2nd letter capitalized. +- Use "i" prefix for indexes and "n" prefix for total number of indexes. + + +### Function names + +- Start each function name with a lowercase letter. +- Each subsequent word is capitalized. +- No underscores. + + +### Constant Names + +- TBD (currently not uniform) + + +Code Organization ----------------- Generally code is organized into modules. Usually a module defines a single @@ -87,6 +118,7 @@ All header files should have an ifndef guard to prevent multiple inclusion. #endif // ns_Module_h ``` + ### Include Directives Header files should be included in the following order. @@ -111,3 +143,8 @@ glabels header files. Do not use forward declarations to any external entities. Use the appropriate include directives instead. + +### Namespaces + +- Private definitions are placed in unnamed namespaces to limit scope to the current translation unit. +- All other glabels code is placed in the top-level "glabels" namespace. diff --git a/glabels/AboutDialog.cpp b/glabels/AboutDialog.cpp index cdeca04..e2ce2c0 100644 --- a/glabels/AboutDialog.cpp +++ b/glabels/AboutDialog.cpp @@ -28,56 +28,61 @@ #include "Version.h" -/// -/// Constructor -/// -AboutDialog::AboutDialog( QWidget *parent ) - : QDialog(parent) +namespace glabels { - setupUi( this ); - QString version = tr("Version") + " " + Version::STRING; - - QString description = tr("A program to create labels and business cards."); - - QString copyright = "Copyright © 2017 Jim Evins "; - - QString licenseParagraph1 = - tr( "gLabels is free software: you can redistribute it and/or modify " - "it under the terms of the GNU General Public License as published by " - "the Free Software Foundation, either version 3 of the License, or " - "(at your option) any later version." ); + /// + /// Constructor + /// + AboutDialog::AboutDialog( QWidget *parent ) + : QDialog(parent) + { + setupUi( this ); - QString licenseParagraph2 = - tr( "gLabels is distributed in the hope that it will be useful, " - "but WITHOUT ANY WARRANTY; without even the implied warranty of " - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " - "GNU General Public License for more details." ); + QString version = tr("Version") + " " + Version::STRING; - QString markup = - "

" + version + "

" + - "

" + description + "

" + - "

" + copyright + "

" + - "

" + licenseParagraph1 + "

" + - "

" + licenseParagraph2 + "

"; + QString description = tr("A program to create labels and business cards."); + + QString copyright = "Copyright © 2017 Jim Evins "; + + QString licenseParagraph1 = + tr( "gLabels is free software: you can redistribute it and/or modify " + "it under the terms of the GNU General Public License as published by " + "the Free Software Foundation, either version 3 of the License, or " + "(at your option) any later version." ); + + QString licenseParagraph2 = + tr( "gLabels is distributed in the hope that it will be useful, " + "but WITHOUT ANY WARRANTY; without even the implied warranty of " + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " + "GNU General Public License for more details." ); + + QString markup = + "

" + version + "

" + + "

" + description + "

" + + "

" + copyright + "

" + + "

" + licenseParagraph1 + "

" + + "

" + licenseParagraph2 + "

"; + + aboutLabel->setText( markup ); + } + + + /// + /// "License" Button Clicked Slot + /// + void AboutDialog::onLicenseButtonClicked() + { + QDesktopServices::openUrl( QUrl("http://www.gnu.org/licenses/gpl-3.0.txt") ); + } + + + /// + /// "Website" Button Clicked Slot + /// + void AboutDialog::onWebsiteButtonClicked() + { + QDesktopServices::openUrl( QUrl(Version::WEBSITE) ); + } - aboutLabel->setText( markup ); -} - - -/// -/// "License" Button Clicked Slot -/// -void AboutDialog::onLicenseButtonClicked() -{ - QDesktopServices::openUrl( QUrl("http://www.gnu.org/licenses/gpl-3.0.txt") ); -} - - -/// -/// "Website" Button Clicked Slot -/// -void AboutDialog::onWebsiteButtonClicked() -{ - QDesktopServices::openUrl( QUrl(Version::WEBSITE) ); } diff --git a/glabels/AboutDialog.h b/glabels/AboutDialog.h index ab6d7af..7ecb4fd 100644 --- a/glabels/AboutDialog.h +++ b/glabels/AboutDialog.h @@ -25,29 +25,34 @@ #include "ui_AboutDialog.h" -/// -/// About Dialog Widget -/// -class AboutDialog : public QDialog, public Ui_AboutDialog +namespace glabels { - Q_OBJECT + + /// + /// About Dialog Widget + /// + class AboutDialog : public QDialog, public Ui_AboutDialog + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - AboutDialog( QWidget *parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + AboutDialog( QWidget *parent = 0 ); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onLicenseButtonClicked(); - void onWebsiteButtonClicked(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onLicenseButtonClicked(); + void onWebsiteButtonClicked(); -}; + }; + +} #endif // AboutDialog_h diff --git a/glabels/BarcodeBackends.cpp b/glabels/BarcodeBackends.cpp index 4811a17..6f87be1 100644 --- a/glabels/BarcodeBackends.cpp +++ b/glabels/BarcodeBackends.cpp @@ -21,159 +21,163 @@ #include "BarcodeBackends.h" -namespace +namespace glabels { - const std::string default_id = "code39"; -} + + // + // Static data + // + BarcodeBackends::BackendMap BarcodeBackends::mBackendIdMap; + BarcodeBackends::BackendMap BarcodeBackends::mBackendNameMap; -BarcodeBackends::BackendMap BarcodeBackends::mBackendIdMap; -BarcodeBackends::BackendMap BarcodeBackends::mBackendNameMap; + BarcodeBackends::StyleMap BarcodeBackends::mStyleIdMap; + BarcodeBackends::StyleMap BarcodeBackends::mStyleNameMap; -BarcodeBackends::StyleMap BarcodeBackends::mStyleIdMap; -BarcodeBackends::StyleMap BarcodeBackends::mStyleNameMap; - -QList BarcodeBackends::mBackendNameList; -QList BarcodeBackends::mNameList; + QList BarcodeBackends::mBackendNameList; + QList BarcodeBackends::mNameList; -BarcodeBackends::BarcodeBackends() -{ - registerStyle( "postnet", "", tr("POSTNET (any)"), - false, false, true, false, "12345-6789-12", false, 11 ); + BarcodeBackends::BarcodeBackends() + { + registerStyle( "postnet", "", tr("POSTNET (any)"), + false, false, true, false, "12345-6789-12", false, 11 ); - registerStyle( "postnet-5", "", tr("POSTNET-5 (ZIP only)"), - false, false, true, false, "12345", false, 5 ); + registerStyle( "postnet-5", "", tr("POSTNET-5 (ZIP only)"), + false, false, true, false, "12345", false, 5 ); - registerStyle( "postnet-9", "", tr("POSTNET-9 (ZIP+4)"), - false, false, true, false, "12345-6789", false, 9 ); + registerStyle( "postnet-9", "", tr("POSTNET-9 (ZIP+4)"), + false, false, true, false, "12345-6789", false, 9 ); - registerStyle( "postnet-11", "", tr("POSTNET-11 (DPBC)"), - false, false, true, false, "12345-6789-12", false, 11 ); + registerStyle( "postnet-11", "", tr("POSTNET-11 (DPBC)"), + false, false, true, false, "12345-6789-12", false, 11 ); - registerStyle( "cepnet", "", tr("CEPNET"), - false, false, true, false, "12345-678", false, 8 ); + registerStyle( "cepnet", "", tr("CEPNET"), + false, false, true, false, "12345-678", false, 8 ); - registerStyle( "onecode", "", tr("USPS Intelligent Mail"), - false, false, true, false, "12345678901234567890", false, 20 ); + registerStyle( "onecode", "", tr("USPS Intelligent Mail"), + false, false, true, false, "12345678901234567890", false, 20 ); - registerStyle( "code39", "", tr("Code 39"), - true, true, true, true, "1234567890", true, 10 ); + registerStyle( "code39", "", tr("Code 39"), + true, true, true, true, "1234567890", true, 10 ); - registerStyle( "code39ext", "", tr("Code 39 Extended"), - true, true, true, true, "1234567890", true, 10 ); + registerStyle( "code39ext", "", tr("Code 39 Extended"), + true, true, true, true, "1234567890", true, 10 ); - registerStyle( "upc-A", "", tr("UPC-A"), - true, false, true, false, "12345678901", false, 11 ); + registerStyle( "upc-A", "", tr("UPC-A"), + true, false, true, false, "12345678901", false, 11 ); - registerStyle( "ean-13", "", tr("EAN-13"), - true, false, true, false, "123456789012", false, 12 ); + registerStyle( "ean-13", "", tr("EAN-13"), + true, false, true, false, "123456789012", false, 12 ); - registerStyle( "datamatrix", "", tr("DataMatrix"), - false, false, true, false, "1234567890AB", false, 12 ); + registerStyle( "datamatrix", "", tr("DataMatrix"), + false, false, true, false, "1234567890AB", false, 12 ); - registerStyle( "qrcode", "", tr("QRCode"), - false, false, true, false, "1234567890AB", false, 12 ); -} + registerStyle( "qrcode", "", tr("QRCode"), + false, false, true, false, "1234567890AB", false, 12 ); + } -void BarcodeBackends::init( void ) -{ - static BarcodeBackends* singletonInstance = NULL; + void BarcodeBackends::init( void ) + { + static BarcodeBackends* singletonInstance = NULL; - if ( singletonInstance == NULL ) - { - singletonInstance = new BarcodeBackends(); + if ( singletonInstance == NULL ) + { + singletonInstance = new BarcodeBackends(); + } } -} -QString BarcodeBackends::BackendIdToName( const QString& backendId ) -{ - BackendMap::iterator i = mBackendIdMap.find( backendId ); - if ( i != mBackendIdMap.end() ) + QString BarcodeBackends::BackendIdToName( const QString& backendId ) { - return i.value(); - } + BackendMap::iterator i = mBackendIdMap.find( backendId ); + if ( i != mBackendIdMap.end() ) + { + return i.value(); + } - return ""; -} - - -QString BarcodeBackends::BackendNameToId( const QString& backendName ) -{ - BackendMap::iterator i = mBackendNameMap.find( backendName ); - if ( i != mBackendNameMap.end() ) - { - return i.value(); + return ""; } - - return ""; -} -const QList& BarcodeBackends::getBackendNameList() -{ - return mBackendNameList; -} - - -const QList& BarcodeBackends::getNameList() -{ - return mNameList; -} - - -const BarcodeStyle* BarcodeBackends::lookupStyleFromId( const QString& id ) -{ - StyleMap::iterator i = mStyleIdMap.find( id ); - if ( i != mStyleIdMap.end() ) + QString BarcodeBackends::BackendNameToId( const QString& backendName ) { - return i.value(); - } + BackendMap::iterator i = mBackendNameMap.find( backendName ); + if ( i != mBackendNameMap.end() ) + { + return i.value(); + } - return 0; -} + return ""; + } -const BarcodeStyle* BarcodeBackends::lookupStyleFromName( const QString& name ) -{ - StyleMap::iterator i = mStyleNameMap.find( name ); - if ( i != mStyleNameMap.end() ) + const QList& BarcodeBackends::getBackendNameList() { - return i.value(); + return mBackendNameList; } + + + const QList& BarcodeBackends::getNameList() + { + return mNameList; + } + + + const BarcodeStyle* BarcodeBackends::lookupStyleFromId( const QString& id ) + { + StyleMap::iterator i = mStyleIdMap.find( id ); + if ( i != mStyleIdMap.end() ) + { + return i.value(); + } - return 0; -} - - -void BarcodeBackends::registerBackend( QString& id, QString& name) -{ - mBackendNameList.append( name ); - mBackendIdMap.insert( id, name ); - mBackendNameMap.insert( name, id ); -} - - -void BarcodeBackends::registerStyle( const char* id, - const char* backendId, - const QString& name, - bool canText, - bool textOptional, - bool canChecksum, - bool checksumOptional, - const char* defaultDigits, - bool canFreeForm, - int preferedN ) -{ - BarcodeStyle* style = new BarcodeStyle( QString(id), QString(backendId), name, - canText, textOptional, - canChecksum, checksumOptional, - QString(defaultDigits), canFreeForm, preferedN ); - - QString fqName = QString(backendId) + QString(".") + name; // Name may not be unique - - mNameList.append( name ); - mStyleIdMap.insert( id, style ); - mStyleNameMap.insert( fqName, style ); + return 0; + } + + + const BarcodeStyle* BarcodeBackends::lookupStyleFromName( const QString& name ) + { + StyleMap::iterator i = mStyleNameMap.find( name ); + if ( i != mStyleNameMap.end() ) + { + return i.value(); + } + + return 0; + } + + + void BarcodeBackends::registerBackend( QString& id, QString& name) + { + mBackendNameList.append( name ); + mBackendIdMap.insert( id, name ); + mBackendNameMap.insert( name, id ); + } + + + void BarcodeBackends::registerStyle( const char* id, + const char* backendId, + const QString& name, + bool canText, + bool textOptional, + bool canChecksum, + bool checksumOptional, + const char* defaultDigits, + bool canFreeForm, + int preferedN ) + { + BarcodeStyle* style = new BarcodeStyle( QString(id), QString(backendId), name, + canText, textOptional, + canChecksum, checksumOptional, + QString(defaultDigits), + canFreeForm, preferedN ); + + QString fqName = QString(backendId) + QString(".") + name; // Name may not be unique + + mNameList.append( name ); + mStyleIdMap.insert( id, style ); + mStyleNameMap.insert( fqName, style ); + } + } diff --git a/glabels/BarcodeBackends.h b/glabels/BarcodeBackends.h index 1057a72..6e63ab2 100644 --- a/glabels/BarcodeBackends.h +++ b/glabels/BarcodeBackends.h @@ -30,68 +30,73 @@ #include "BarcodeStyle.h" -/// -/// Barcode Backends Database -/// -class BarcodeBackends : public QObject +namespace glabels { + + /// + /// Barcode Backends Database + /// + class BarcodeBackends : public QObject + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -private: - BarcodeBackends(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + BarcodeBackends(); -public: - static void init( void ); + public: + static void init( void ); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - static QString BackendIdToName( const QString& backendId ); - static QString BackendNameToId( const QString& backendName ); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + static QString BackendIdToName( const QString& backendId ); + static QString BackendNameToId( const QString& backendName ); - static const QList& getBackendNameList(); - static const QList& getNameList(); + static const QList& getBackendNameList(); + static const QList& getNameList(); - static const BarcodeStyle* lookupStyleFromId( const QString& id ); - static const BarcodeStyle* lookupStyleFromName( const QString& name ); + static const BarcodeStyle* lookupStyleFromId( const QString& id ); + static const BarcodeStyle* lookupStyleFromName( const QString& name ); - ///////////////////////////////// - // Private Methods - ///////////////////////////////// -private: - static void registerBackend( QString &id, QString &name); + ///////////////////////////////// + // Private Methods + ///////////////////////////////// + private: + static void registerBackend( QString &id, QString &name); - static void registerStyle( const char* id, - const char* backendId, - const QString& name, - bool canText, - bool textOptional, - bool canChecksum, - bool checksumOptional, - const char* defaultDigits, - bool canFreeForm, - int preferedN ); + static void registerStyle( const char* id, + const char* backendId, + const QString& name, + bool canText, + bool textOptional, + bool canChecksum, + bool checksumOptional, + const char* defaultDigits, + bool canFreeForm, + int preferedN ); - ///////////////////////////////// - // Private Members - ///////////////////////////////// - typedef QMap BackendMap; - static BackendMap mBackendIdMap; - static BackendMap mBackendNameMap; + ///////////////////////////////// + // Private Members + ///////////////////////////////// + typedef QMap BackendMap; + static BackendMap mBackendIdMap; + static BackendMap mBackendNameMap; - typedef QMap StyleMap; - static StyleMap mStyleIdMap; - static StyleMap mStyleNameMap; + typedef QMap StyleMap; + static StyleMap mStyleIdMap; + static StyleMap mStyleNameMap; - static QList mBackendNameList; - static QList mNameList; + static QList mBackendNameList; + static QList mNameList; -}; + }; + +} #endif // BarcodeBackends_h diff --git a/glabels/BarcodeMenu.cpp b/glabels/BarcodeMenu.cpp index 9b226ec..83a64f0 100644 --- a/glabels/BarcodeMenu.cpp +++ b/glabels/BarcodeMenu.cpp @@ -25,38 +25,43 @@ #include "BarcodeMenuItem.h" -/// -/// Constructor -/// -BarcodeMenu::BarcodeMenu() +namespace glabels { - foreach ( QString name, BarcodeBackends::getNameList() ) + + /// + /// Constructor + /// + BarcodeMenu::BarcodeMenu() { - const BarcodeStyle* bcStyle = BarcodeBackends::lookupStyleFromName( name ); + foreach ( QString name, BarcodeBackends::getNameList() ) + { + const BarcodeStyle* bcStyle = BarcodeBackends::lookupStyleFromName( name ); - BarcodeMenuItem* bcMenuItem = new BarcodeMenuItem( bcStyle ); - connect( bcMenuItem, SIGNAL(activated()), this, SLOT(onMenuItemActivated) ); + BarcodeMenuItem* bcMenuItem = new BarcodeMenuItem( bcStyle ); + connect( bcMenuItem, SIGNAL(activated()), this, SLOT(onMenuItemActivated) ); - addAction( bcMenuItem ); + addAction( bcMenuItem ); + } } -} - - -/// -/// bcStyle getter -/// -const BarcodeStyle* BarcodeMenu::bcStyle() const -{ - return mBcStyle; -} - - -/// -/// onMenuItemActivated slot -/// -void BarcodeMenu::onMenuItemActivated( BarcodeStyle *bcStyle ) -{ - mBcStyle = bcStyle; - - emit styleChanged(); + + + /// + /// bcStyle getter + /// + const BarcodeStyle* BarcodeMenu::bcStyle() const + { + return mBcStyle; + } + + + /// + /// onMenuItemActivated slot + /// + void BarcodeMenu::onMenuItemActivated( BarcodeStyle *bcStyle ) + { + mBcStyle = bcStyle; + + emit styleChanged(); + } + } diff --git a/glabels/BarcodeMenu.h b/glabels/BarcodeMenu.h index 4e92ebe..3d13adc 100644 --- a/glabels/BarcodeMenu.h +++ b/glabels/BarcodeMenu.h @@ -27,48 +27,53 @@ #include "BarcodeStyle.h" -/// -/// Barcode Menu -/// -class BarcodeMenu : public QMenu +namespace glabels { - Q_OBJECT + + /// + /// Barcode Menu + /// + class BarcodeMenu : public QMenu + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - BarcodeMenu(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + BarcodeMenu(); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void styleChanged(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void styleChanged(); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - const BarcodeStyle* bcStyle() const; + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + const BarcodeStyle* bcStyle() const; - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onMenuItemActivated( BarcodeStyle *bcStyle ); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onMenuItemActivated( BarcodeStyle *bcStyle ); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - BarcodeStyle* mBcStyle; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + BarcodeStyle* mBcStyle; -}; + }; + +} #endif // BarcodeMenu_h diff --git a/glabels/BarcodeMenuButton.cpp b/glabels/BarcodeMenuButton.cpp index 04700c9..8ccddf2 100644 --- a/glabels/BarcodeMenuButton.cpp +++ b/glabels/BarcodeMenuButton.cpp @@ -25,38 +25,43 @@ #include "BarcodeMenuItem.h" -/// -/// Constructor -/// -BarcodeMenuButton::BarcodeMenuButton( QWidget* parent ) - : QPushButton(parent) +namespace glabels { - mMenu = new BarcodeMenu(); - setMenu( mMenu ); + + /// + /// Constructor + /// + BarcodeMenuButton::BarcodeMenuButton( QWidget* parent ) + : QPushButton(parent) + { + mMenu = new BarcodeMenu(); + setMenu( mMenu ); - mBcStyle = BarcodeBackends::lookupStyleFromId( "" ); // Default style - setText( mBcStyle->name() ); + mBcStyle = BarcodeBackends::lookupStyleFromId( "" ); // Default style + setText( mBcStyle->name() ); + + connect( mMenu, SIGNAL(styleChanged()), this, SLOT(onMenuStyleChanged()) ); + } + + + /// + /// bcStyle getter + /// + const BarcodeStyle* BarcodeMenuButton::bcStyle() const + { + return mBcStyle; + } + + + /// + /// onMenuStyleChanged slot + /// + void BarcodeMenuButton::onMenuStyleChanged() + { + mBcStyle = mMenu->bcStyle(); + setText( mBcStyle->name() ); + + emit styleChanged(); + } - connect( mMenu, SIGNAL(styleChanged()), this, SLOT(onMenuStyleChanged()) ); -} - - -/// -/// bcStyle getter -/// -const BarcodeStyle* BarcodeMenuButton::bcStyle() const -{ - return mBcStyle; -} - - -/// -/// onMenuStyleChanged slot -/// -void BarcodeMenuButton::onMenuStyleChanged() -{ - mBcStyle = mMenu->bcStyle(); - setText( mBcStyle->name() ); - - emit styleChanged(); } diff --git a/glabels/BarcodeMenuButton.h b/glabels/BarcodeMenuButton.h index 07c9b24..5edeeb7 100644 --- a/glabels/BarcodeMenuButton.h +++ b/glabels/BarcodeMenuButton.h @@ -28,49 +28,54 @@ #include "BarcodeStyle.h" -/// -/// Barcode Menu Button -/// -class BarcodeMenuButton : public QPushButton +namespace glabels { - Q_OBJECT + + /// + /// Barcode Menu Button + /// + class BarcodeMenuButton : public QPushButton + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - BarcodeMenuButton( QWidget* parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + BarcodeMenuButton( QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void styleChanged(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void styleChanged(); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - const BarcodeStyle* bcStyle() const; + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + const BarcodeStyle* bcStyle() const; - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onMenuStyleChanged(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onMenuStyleChanged(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - BarcodeMenu* mMenu; - const BarcodeStyle* mBcStyle; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + BarcodeMenu* mMenu; + const BarcodeStyle* mBcStyle; -}; + }; + +} #endif // BarcodeMenuButton_h diff --git a/glabels/BarcodeMenuItem.cpp b/glabels/BarcodeMenuItem.cpp index 99dfd54..a54c4ce 100644 --- a/glabels/BarcodeMenuItem.cpp +++ b/glabels/BarcodeMenuItem.cpp @@ -21,31 +21,36 @@ #include "BarcodeMenuItem.h" -/// -/// Constructor From Data -/// -BarcodeMenuItem::BarcodeMenuItem( const BarcodeStyle* bcStyle, QObject* parent ) - : QAction(parent), mBcStyle(bcStyle) +namespace glabels { - setText( bcStyle->name() ); - connect( this, SIGNAL(triggered()), this, SLOT(onTriggered()) ); -} - - -/// -/// bcStyle Property Getter -/// -const BarcodeStyle* BarcodeMenuItem::bcStyle() const -{ - return mBcStyle; -} - - -/// -/// onTriggered slot -/// -void BarcodeMenuItem::onTriggered() -{ - emit activated( mBcStyle ); + /// + /// Constructor From Data + /// + BarcodeMenuItem::BarcodeMenuItem( const BarcodeStyle* bcStyle, QObject* parent ) + : QAction(parent), mBcStyle(bcStyle) + { + setText( bcStyle->name() ); + + connect( this, SIGNAL(triggered()), this, SLOT(onTriggered()) ); + } + + + /// + /// bcStyle Property Getter + /// + const BarcodeStyle* BarcodeMenuItem::bcStyle() const + { + return mBcStyle; + } + + + /// + /// onTriggered slot + /// + void BarcodeMenuItem::onTriggered() + { + emit activated( mBcStyle ); + } + } diff --git a/glabels/BarcodeMenuItem.h b/glabels/BarcodeMenuItem.h index 13be99d..369919f 100644 --- a/glabels/BarcodeMenuItem.h +++ b/glabels/BarcodeMenuItem.h @@ -27,48 +27,53 @@ #include "BarcodeStyle.h" -/// -/// Barcode Menu Item -/// -class BarcodeMenuItem : public QAction +namespace glabels { - Q_OBJECT + + /// + /// Barcode Menu Item + /// + class BarcodeMenuItem : public QAction + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - BarcodeMenuItem( const BarcodeStyle* bcStyle, QObject* parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + BarcodeMenuItem( const BarcodeStyle* bcStyle, QObject* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void activated( const BarcodeStyle* bcStyle ); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void activated( const BarcodeStyle* bcStyle ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - const BarcodeStyle* bcStyle() const; + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + const BarcodeStyle* bcStyle() const; - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onTriggered(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onTriggered(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - const BarcodeStyle* mBcStyle; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + const BarcodeStyle* mBcStyle; -}; + }; + +} #endif // BarcodeMenuItem_h diff --git a/glabels/BarcodeStyle.cpp b/glabels/BarcodeStyle.cpp index d9f91a2..8c47399 100644 --- a/glabels/BarcodeStyle.cpp +++ b/glabels/BarcodeStyle.cpp @@ -21,37 +21,41 @@ #include "BarcodeStyle.h" -/// -/// Default Constructor -/// -BarcodeStyle::BarcodeStyle () - : mId( "" ), - mBackendId( "" ), - mName( "" ), - mCanText( false ), - mTextOptional( false ), - mCanChecksum( false ), - mChecksumOptional( false ), - mDefaultDigits( "" ), - mCanFreeform( false ), - mPreferedN( 0 ) +namespace glabels { -} + + /// + /// Default Constructor + /// + BarcodeStyle::BarcodeStyle () + : mId( "" ), + mBackendId( "" ), + mName( "" ), + mCanText( false ), + mTextOptional( false ), + mCanChecksum( false ), + mChecksumOptional( false ), + mDefaultDigits( "" ), + mCanFreeform( false ), + mPreferedN( 0 ) + { + // empty + } -/// -/// Constructor From Data -/// -BarcodeStyle::BarcodeStyle ( const QString& id, - const QString& backendId, - const QString& name, - bool canText, - bool textOptional, - bool canChecksum, - bool checksumOptional, - const QString& defaultDigits, - bool canFreeform, - int preferedN ) + /// + /// Constructor From Data + /// + BarcodeStyle::BarcodeStyle ( const QString& id, + const QString& backendId, + const QString& name, + bool canText, + bool textOptional, + bool canChecksum, + bool checksumOptional, + const QString& defaultDigits, + bool canFreeform, + int preferedN ) : mId( id ), mBackendId( backendId ), mName( name ), @@ -62,111 +66,114 @@ BarcodeStyle::BarcodeStyle ( const QString& id, mDefaultDigits( defaultDigits ), mCanFreeform( canFreeform ), mPreferedN( preferedN ) -{ -} - - -/// -/// ID Property Getter -/// -const QString& BarcodeStyle::id() const -{ - return mId; -} - - -/// -/// Backend ID Property Getter -/// -const QString& BarcodeStyle::backendId() const -{ - return mBackendId; -} - - -/// -/// Name Property Getter -/// -const QString& BarcodeStyle::name() const -{ - return mName; -} - - -/// -/// Can Text Property Getter -/// -bool BarcodeStyle::canText() const -{ - return mCanText; -} - - -/// -/// Text Optional Property Getter -/// -bool BarcodeStyle::textOptional() const -{ - return mTextOptional; -} - - -/// -/// Can Checksum Property Getter -/// -bool BarcodeStyle::canChecksum() const -{ - return mCanChecksum; -} - - -/// -/// Checksum Optional Property Getter -/// -bool BarcodeStyle::checksumOptional() const -{ - return mChecksumOptional; -} - - -/// -/// Default Digits Property Getter -/// -const QString& BarcodeStyle::defaultDigits() const -{ - return mDefaultDigits; -} - - -/// -/// Can Freeform Property Getter -/// -bool BarcodeStyle::canFreeform() const -{ - return mCanFreeform; -} - - -/// -/// Prefered N Property Getter -/// -int BarcodeStyle::preferedN() const -{ - return mPreferedN; -} - - -/// -/// Generate Example Digits -/// -QString BarcodeStyle::exampleDigits( int n ) const -{ - if ( mCanFreeform ) { - return QString( qMax( n, 1 ), QChar('0') ); + // empty } - else + + + /// + /// ID Property Getter + /// + const QString& BarcodeStyle::id() const + { + return mId; + } + + + /// + /// Backend ID Property Getter + /// + const QString& BarcodeStyle::backendId() const + { + return mBackendId; + } + + + /// + /// Name Property Getter + /// + const QString& BarcodeStyle::name() const + { + return mName; + } + + + /// + /// Can Text Property Getter + /// + bool BarcodeStyle::canText() const + { + return mCanText; + } + + + /// + /// Text Optional Property Getter + /// + bool BarcodeStyle::textOptional() const + { + return mTextOptional; + } + + + /// + /// Can Checksum Property Getter + /// + bool BarcodeStyle::canChecksum() const + { + return mCanChecksum; + } + + + /// + /// Checksum Optional Property Getter + /// + bool BarcodeStyle::checksumOptional() const + { + return mChecksumOptional; + } + + + /// + /// Default Digits Property Getter + /// + const QString& BarcodeStyle::defaultDigits() const { return mDefaultDigits; } + + + /// + /// Can Freeform Property Getter + /// + bool BarcodeStyle::canFreeform() const + { + return mCanFreeform; + } + + + /// + /// Prefered N Property Getter + /// + int BarcodeStyle::preferedN() const + { + return mPreferedN; + } + + + /// + /// Generate Example Digits + /// + QString BarcodeStyle::exampleDigits( int n ) const + { + if ( mCanFreeform ) + { + return QString( qMax( n, 1 ), QChar('0') ); + } + else + { + return mDefaultDigits; + } + } + } diff --git a/glabels/BarcodeStyle.h b/glabels/BarcodeStyle.h index a290b3f..bf8e68d 100644 --- a/glabels/BarcodeStyle.h +++ b/glabels/BarcodeStyle.h @@ -24,77 +24,82 @@ #include -/// -/// Barcode Style Type -/// -struct BarcodeStyle +namespace glabels { + + /// + /// Barcode Style Type + /// + struct BarcodeStyle + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - BarcodeStyle (); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + BarcodeStyle (); - BarcodeStyle ( const QString& id, - const QString& backendId, - const QString& name, - bool canText, - bool textOptional, - bool canChecksum, - bool checksumOptional, - const QString& defaultDigits, - bool canFreeform, - int preferedN ); + BarcodeStyle ( const QString& id, + const QString& backendId, + const QString& name, + bool canText, + bool textOptional, + bool canChecksum, + bool checksumOptional, + const QString& defaultDigits, + bool canFreeform, + int preferedN ); - ///////////////////////////////// - // Properties - ///////////////////////////////// - const QString& id() const; + ///////////////////////////////// + // Properties + ///////////////////////////////// + const QString& id() const; - const QString& backendId() const; + const QString& backendId() const; - const QString& name() const; + const QString& name() const; - bool canText() const; + bool canText() const; - bool textOptional() const; + bool textOptional() const; - bool canChecksum() const; + bool canChecksum() const; - bool checksumOptional() const; + bool checksumOptional() const; - const QString& defaultDigits() const; + const QString& defaultDigits() const; - bool canFreeform() const; + bool canFreeform() const; - int preferedN() const; + int preferedN() const; - ///////////////////////////////// - // Methods - ///////////////////////////////// -public: - QString exampleDigits( int n ) const; + ///////////////////////////////// + // Methods + ///////////////////////////////// + public: + QString exampleDigits( int n ) const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - QString mId; - QString mBackendId; - QString mName; - bool mCanText; - bool mTextOptional; - bool mCanChecksum; - bool mChecksumOptional; - QString mDefaultDigits; - bool mCanFreeform; - int mPreferedN; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + QString mId; + QString mBackendId; + QString mName; + bool mCanText; + bool mTextOptional; + bool mCanChecksum; + bool mChecksumOptional; + QString mDefaultDigits; + bool mCanFreeform; + int mPreferedN; -}; + }; + +} #endif // BarcodeStyle_h diff --git a/glabels/Category.cpp b/glabels/Category.cpp index e396021..6f81337 100644 --- a/glabels/Category.cpp +++ b/glabels/Category.cpp @@ -27,6 +27,7 @@ namespace glabels Category::Category( const QString &id, const QString &name ) : mId(id), mName(name) { + // empty } diff --git a/glabels/ColorButton.cpp b/glabels/ColorButton.cpp index 668a6f1..afa81c6 100644 --- a/glabels/ColorButton.cpp +++ b/glabels/ColorButton.cpp @@ -28,148 +28,159 @@ #include "ColorSwatch.h" -namespace +namespace glabels { - const int SWATCH_W = 64; - const int SWATCH_H = 24; -} - - -ColorButton::ColorButton( QWidget* parent ) - : QPushButton( parent ) -{ -} - - -void ColorButton::init( const QString& defaultLabel, const QColor& defaultColor, const QColor& color ) -{ - mDefaultColor = defaultColor; - mColorNode = ColorNode( color ); - - setMinimumSize( QSize( 85, 34 ) ); - setIconSize( QSize(SWATCH_W, SWATCH_H) ); - - setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, color ) ) ); - setText( "" ); - setCheckable( true ); - - mDialog = new ColorPaletteDialog( defaultLabel, defaultColor, color ); - - connect( this, SIGNAL(toggled(bool)), this, SLOT(onButtonToggled(bool)) ); - connect( mDialog, SIGNAL(colorChanged(ColorNode,bool)), - this, SLOT(onPaletteDialogChanged(ColorNode,bool)) ); - connect( mDialog, SIGNAL(accepted()), this, SLOT(onPaletteDialogAccepted()) ); - connect( mDialog, SIGNAL(rejected()), this, SLOT(onPaletteDialogRejected()) ); -} - - -void ColorButton::setColorNode( ColorNode colorNode ) -{ - mIsDefault = false; - - mColorNode = colorNode; - - if ( colorNode.isField() ) + + // + // Private + // + namespace { - setIcon( QIcon() ); - setText( QString("${%1}").arg( colorNode.key() ) ); + const int SWATCH_W = 64; + const int SWATCH_H = 24; } - else + + + ColorButton::ColorButton( QWidget* parent ) + : QPushButton( parent ) { - setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, colorNode.color() ) ) ); + // empty + } + + + void ColorButton::init( const QString& defaultLabel, + const QColor& defaultColor, + const QColor& color ) + { + mDefaultColor = defaultColor; + mColorNode = ColorNode( color ); + + setMinimumSize( QSize( 85, 34 ) ); + setIconSize( QSize(SWATCH_W, SWATCH_H) ); + + setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, color ) ) ); + setText( "" ); + setCheckable( true ); + + mDialog = new ColorPaletteDialog( defaultLabel, defaultColor, color ); + + connect( this, SIGNAL(toggled(bool)), this, SLOT(onButtonToggled(bool)) ); + connect( mDialog, SIGNAL(colorChanged(ColorNode,bool)), + this, SLOT(onPaletteDialogChanged(ColorNode,bool)) ); + connect( mDialog, SIGNAL(accepted()), this, SLOT(onPaletteDialogAccepted()) ); + connect( mDialog, SIGNAL(rejected()), this, SLOT(onPaletteDialogRejected()) ); + } + + + void ColorButton::setColorNode( ColorNode colorNode ) + { + mIsDefault = false; + + mColorNode = colorNode; + + if ( colorNode.isField() ) + { + setIcon( QIcon() ); + setText( QString("${%1}").arg( colorNode.key() ) ); + } + else + { + setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, colorNode.color() ) ) ); + setText( "" ); + } + + mDialog->setColorNode( colorNode ); + } + + + void ColorButton::setColor( QColor color ) + { + mIsDefault = false; + + mColorNode.setField( false ); + mColorNode.setColor( color ); + mColorNode.setKey( "" ); + + setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, color ) ) ); setText( "" ); } - mDialog->setColorNode( colorNode ); -} - -void ColorButton::setColor( QColor color ) -{ - mIsDefault = false; - - mColorNode.setField( false ); - mColorNode.setColor( color ); - mColorNode.setKey( "" ); - - setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, color ) ) ); - setText( "" ); -} - - -void ColorButton::setToDefault() -{ - mIsDefault = true; - - mColorNode.setField( false ); - mColorNode.setColor( mDefaultColor ); - mColorNode.setKey( "" ); - - setIcon( QIcon(ColorSwatch( SWATCH_W, SWATCH_H, mDefaultColor ) ) ); - setText( "" ); -} - - -ColorNode ColorButton::colorNode() -{ - return mColorNode; -} - - -void ColorButton::setKeys( const QList keyList ) -{ - mDialog->setKeys( keyList ); -} - - -void ColorButton::clearKeys() -{ - mDialog->clearKeys(); -} - - -void ColorButton::onButtonToggled( bool checked ) -{ - if ( checked ) + void ColorButton::setToDefault() { - /// - /// @TODO: improve positioning of dialog -- near edges of screen. - /// - QPoint dialogPos( 0, height() ); - mDialog->move( mapToGlobal(dialogPos) ); + mIsDefault = true; - mDialog->show(); - } -} + mColorNode.setField( false ); + mColorNode.setColor( mDefaultColor ); + mColorNode.setKey( "" ); - -void ColorButton::onPaletteDialogAccepted() -{ - setChecked( false ); -} - - -void ColorButton::onPaletteDialogRejected() -{ - setChecked( false ); -} - - -void ColorButton::onPaletteDialogChanged( ColorNode colorNode, bool isDefault ) -{ - mColorNode = colorNode; - mIsDefault = isDefault; - - if ( colorNode.isField() ) - { - setIcon( QIcon() ); - setText( QString("${%1}").arg( colorNode.key() ) ); - } - else - { - setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, colorNode.color() ) ) ); + setIcon( QIcon(ColorSwatch( SWATCH_W, SWATCH_H, mDefaultColor ) ) ); setText( "" ); } + + + ColorNode ColorButton::colorNode() + { + return mColorNode; + } + + + void ColorButton::setKeys( const QList keyList ) + { + mDialog->setKeys( keyList ); + } + + + void ColorButton::clearKeys() + { + mDialog->clearKeys(); + } + + + void ColorButton::onButtonToggled( bool checked ) + { + if ( checked ) + { + /// + /// @TODO: improve positioning of dialog -- near edges of screen. + /// + QPoint dialogPos( 0, height() ); + mDialog->move( mapToGlobal(dialogPos) ); + + mDialog->show(); + } + } + + + void ColorButton::onPaletteDialogAccepted() + { + setChecked( false ); + } + + + void ColorButton::onPaletteDialogRejected() + { + setChecked( false ); + } + + + void ColorButton::onPaletteDialogChanged( ColorNode colorNode, bool isDefault ) + { + mColorNode = colorNode; + mIsDefault = isDefault; + + if ( colorNode.isField() ) + { + setIcon( QIcon() ); + setText( QString("${%1}").arg( colorNode.key() ) ); + } + else + { + setIcon( QIcon( ColorSwatch( SWATCH_W, SWATCH_H, colorNode.color() ) ) ); + setText( "" ); + } - emit colorChanged(); + emit colorChanged(); + } + } diff --git a/glabels/ColorButton.h b/glabels/ColorButton.h index 1719eed..3e0b386 100644 --- a/glabels/ColorButton.h +++ b/glabels/ColorButton.h @@ -28,67 +28,72 @@ #include "ColorPaletteDialog.h" -/// -/// Color Button -/// -class ColorButton : public QPushButton +namespace glabels { - Q_OBJECT + + /// + /// Color Button + /// + class ColorButton : public QPushButton + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorButton( QWidget* parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorButton( QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void colorChanged(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void colorChanged(); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void init( const QString& defaultLabel, const QColor& defaultColor, const QColor& color ); - void setColorNode( ColorNode colorNode ); - void setColor( QColor color ); - void setToDefault(); - ColorNode colorNode(); - void setKeys( const QList keyList ); - void clearKeys(); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void init( const QString& defaultLabel, const QColor& defaultColor, const QColor& color ); + void setColorNode( ColorNode colorNode ); + void setColor( QColor color ); + void setToDefault(); + ColorNode colorNode(); + void setKeys( const QList keyList ); + void clearKeys(); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onButtonToggled( bool checked ); - void onPaletteDialogAccepted(); - void onPaletteDialogRejected(); - void onPaletteDialogChanged( ColorNode colorNode, bool isDefault ); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onButtonToggled( bool checked ); + void onPaletteDialogAccepted(); + void onPaletteDialogRejected(); + void onPaletteDialogChanged( ColorNode colorNode, bool isDefault ); - ///////////////////////////////// - // Private Methods - ///////////////////////////////// -private: + ///////////////////////////////// + // Private Methods + ///////////////////////////////// + private: - ///////////////////////////////// - // Private Members - ///////////////////////////////// -private: - QColor mDefaultColor; - bool mIsDefault; - ColorNode mColorNode; + ///////////////////////////////// + // Private Members + ///////////////////////////////// + private: + QColor mDefaultColor; + bool mIsDefault; + ColorNode mColorNode; - ColorPaletteDialog* mDialog; -}; + ColorPaletteDialog* mDialog; + }; + +} #endif // ColorButton_h diff --git a/glabels/ColorHistory.cpp b/glabels/ColorHistory.cpp index 00c8a28..6227416 100644 --- a/glabels/ColorHistory.cpp +++ b/glabels/ColorHistory.cpp @@ -25,89 +25,95 @@ #include -ColorHistory::ColorHistory() +namespace glabels { -} - -ColorHistory* ColorHistory::instance() -{ - static ColorHistory* singletonInstance = 0; - - if ( singletonInstance == 0 ) + ColorHistory::ColorHistory() { - singletonInstance = new ColorHistory(); + // empty } - return singletonInstance; -} - -void ColorHistory::addColor( const QColor &color ) -{ - QList colorList = readColorList(); - - // Remove any occurances of this color already in list - colorList.removeAll( color ); - - // Now add to list - colorList.append( color ); - - // Remove oldest colors, if size exceeds current max - while ( colorList.size() > MAX_COLORS ) + ColorHistory* ColorHistory::instance() { - colorList.removeFirst(); + static ColorHistory* singletonInstance = 0; + + if ( singletonInstance == 0 ) + { + singletonInstance = new ColorHistory(); + } + + return singletonInstance; } - writeColorList( colorList ); + + void ColorHistory::addColor( const QColor &color ) + { + QList colorList = readColorList(); + + // Remove any occurances of this color already in list + colorList.removeAll( color ); + + // Now add to list + colorList.append( color ); + + // Remove oldest colors, if size exceeds current max + while ( colorList.size() > MAX_COLORS ) + { + colorList.removeFirst(); + } + + writeColorList( colorList ); - emit changed(); -} - - -QList ColorHistory::getColors() -{ - return readColorList(); -} - - -QList ColorHistory::readColorList() -{ - QStringList defaultList; - QSettings settings; - - settings.beginGroup( "ColorHistory" ); - QStringList colorNameList = settings.value( "colors", defaultList ).toStringList(); - settings.endGroup(); - - QList colorList; - foreach ( QString colorName, colorNameList ) - { - colorList << QColor( colorName ); + emit changed(); } - // Remove oldest colors, if size exceeds current max - while ( colorList.size() > MAX_COLORS ) + + QList ColorHistory::getColors() { - colorList.removeFirst(); + return readColorList(); } - return colorList; -} - -void ColorHistory::writeColorList( const QList& colorList ) -{ - // Build name list - QStringList colorNameList; - foreach ( QColor color, colorList ) + QList ColorHistory::readColorList() { - colorNameList << color.name(); + QStringList defaultList; + QSettings settings; + + settings.beginGroup( "ColorHistory" ); + QStringList colorNameList = settings.value( "colors", defaultList ).toStringList(); + settings.endGroup(); + + QList colorList; + foreach ( QString colorName, colorNameList ) + { + colorList << QColor( colorName ); + } + + // Remove oldest colors, if size exceeds current max + while ( colorList.size() > MAX_COLORS ) + { + colorList.removeFirst(); + } + + return colorList; + } + + + void ColorHistory::writeColorList( const QList& colorList ) + { + // Build name list + QStringList colorNameList; + foreach ( QColor color, colorList ) + { + colorNameList << color.name(); + } + + // Save + QSettings settings; + settings.beginGroup( "ColorHistory" ); + settings.setValue( "colors", colorNameList ); + settings.endGroup(); } - // Save - QSettings settings; - settings.beginGroup( "ColorHistory" ); - settings.setValue( "colors", colorNameList ); - settings.endGroup(); } diff --git a/glabels/ColorHistory.h b/glabels/ColorHistory.h index 845cd78..db3f013 100644 --- a/glabels/ColorHistory.h +++ b/glabels/ColorHistory.h @@ -26,55 +26,60 @@ #include -/// -/// Color History -/// -class ColorHistory : public QObject +namespace glabels { - Q_OBJECT -public: - static const int MAX_COLORS = 9; + /// + /// Color History + /// + class ColorHistory : public QObject + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -private: - ColorHistory(); + public: + static const int MAX_COLORS = 9; -public: - static ColorHistory* instance(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + ColorHistory(); + + public: + static ColorHistory* instance(); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void changed(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void changed(); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void addColor( const QColor &color ); - QList getColors(); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void addColor( const QColor &color ); + QList getColors(); - ///////////////////////////////// - // Private Methods - ///////////////////////////////// -private: - QList readColorList(); - void writeColorList( const QList& colorList ); + ///////////////////////////////// + // Private Methods + ///////////////////////////////// + private: + QList readColorList(); + void writeColorList( const QList& colorList ); - ///////////////////////////////// - // Private Members - ///////////////////////////////// -private: + ///////////////////////////////// + // Private Members + ///////////////////////////////// + private: -}; + }; + +} #endif // ColorHistory_h diff --git a/glabels/ColorNode.cpp b/glabels/ColorNode.cpp index 08e1229..1a71b51 100644 --- a/glabels/ColorNode.cpp +++ b/glabels/ColorNode.cpp @@ -24,171 +24,180 @@ #include "Merge/Record.h" -/// -/// Default Constructor -/// -ColorNode::ColorNode() - : mIsField(false), mColor(QColor::fromRgba(0x00000000)), mKey("") +namespace glabels { -} - -/// -/// Constructor From Data -/// -ColorNode::ColorNode( bool isField, const QColor& color, const QString& key ) - : mIsField(isField), mColor(color), mKey(key) -{ -} - - -/// -/// Constructor From Data -/// -ColorNode::ColorNode( bool isField, uint32_t rgba, const QString& key ) - : mIsField(isField), mKey(key) -{ - mColor = QColor( (rgba >> 24) & 0xFF, - (rgba >> 16) & 0xFF, - (rgba >> 8) & 0xFF, - (rgba ) & 0xFF ); -} - - -/// -/// Constructor From Color -/// -ColorNode::ColorNode( const QColor& color ) - : mIsField(false), mColor(color), mKey("") -{ -} - - -/// -/// Constructor From Key -/// -ColorNode::ColorNode( const QString& key ) - : mIsField(true), mColor(QColor::fromRgba(0x00000000)), mKey(key) -{ -} - - -/// -/// == Operator -/// -bool ColorNode::operator==( const ColorNode& cn ) -{ - return (mIsField == cn.mIsField) && - (mColor == cn.mColor) && - (mKey == cn.mKey); -} - - -/// -/// != Operator -/// -bool ColorNode::operator!=( const ColorNode& cn ) -{ - return (mIsField != cn.mIsField) || - (mColor != cn.mColor) || - (mKey != cn.mKey); -} - - -/// -/// Field Flag Property Getter -/// -bool ColorNode::isField() const -{ - return mIsField; -} - - -/// -/// Field Flag Property Setter -/// -void ColorNode::setField( bool isField ) -{ - mIsField = isField; -} - - -/// -/// Color Property Getter -/// -const QColor& ColorNode::color() const -{ - return mColor; -} - - -/// -/// Color Property Setter -/// -void ColorNode::setColor( const QColor& color ) -{ - mColor = color; -} - - -/// -/// Key Property Getter -/// -const QString& ColorNode::key() const -{ - return mKey; -} - - -/// -/// Key Property Setter -/// -void ColorNode::setKey( const QString& key ) -{ - mKey = key; -} - - -/// -/// Get color encoded as an RGBA 32-bit number -/// -uint32_t ColorNode::rgba() const -{ - uint32_t c = - mColor.red() << 24 | - mColor.green() << 16 | - mColor.blue() << 8 | - mColor.alpha(); - - return c; -} - - -/// -/// Get color, expand if necessary -/// -QColor ColorNode::color( merge::Record* record ) const -{ - if ( mIsField ) + /// + /// Default Constructor + /// + ColorNode::ColorNode() + : mIsField(false), mColor(QColor::fromRgba(0x00000000)), mKey("") { - if ( record == 0 ) - { - return mColor; - } - else - { - if ( record->contains( mKey ) ) - { - return QColor( (*record)[ mKey ] ); - } - else - { - return mColor; - } - } + // empty } - else + + + /// + /// Constructor From Data + /// + ColorNode::ColorNode( bool isField, const QColor& color, const QString& key ) + : mIsField(isField), mColor(color), mKey(key) + { + // empty + } + + + /// + /// Constructor From Data + /// + ColorNode::ColorNode( bool isField, uint32_t rgba, const QString& key ) + : mIsField(isField), mKey(key) + { + mColor = QColor( (rgba >> 24) & 0xFF, + (rgba >> 16) & 0xFF, + (rgba >> 8) & 0xFF, + (rgba ) & 0xFF ); + } + + + /// + /// Constructor From Color + /// + ColorNode::ColorNode( const QColor& color ) + : mIsField(false), mColor(color), mKey("") + { + // empty + } + + + /// + /// Constructor From Key + /// + ColorNode::ColorNode( const QString& key ) + : mIsField(true), mColor(QColor::fromRgba(0x00000000)), mKey(key) + { + // empty + } + + + /// + /// == Operator + /// + bool ColorNode::operator==( const ColorNode& cn ) + { + return (mIsField == cn.mIsField) && + (mColor == cn.mColor) && + (mKey == cn.mKey); + } + + + /// + /// != Operator + /// + bool ColorNode::operator!=( const ColorNode& cn ) + { + return (mIsField != cn.mIsField) || + (mColor != cn.mColor) || + (mKey != cn.mKey); + } + + + /// + /// Field Flag Property Getter + /// + bool ColorNode::isField() const + { + return mIsField; + } + + + /// + /// Field Flag Property Setter + /// + void ColorNode::setField( bool isField ) + { + mIsField = isField; + } + + + /// + /// Color Property Getter + /// + const QColor& ColorNode::color() const { return mColor; } + + + /// + /// Color Property Setter + /// + void ColorNode::setColor( const QColor& color ) + { + mColor = color; + } + + + /// + /// Key Property Getter + /// + const QString& ColorNode::key() const + { + return mKey; + } + + + /// + /// Key Property Setter + /// + void ColorNode::setKey( const QString& key ) + { + mKey = key; + } + + + /// + /// Get color encoded as an RGBA 32-bit number + /// + uint32_t ColorNode::rgba() const + { + uint32_t c = + mColor.red() << 24 | + mColor.green() << 16 | + mColor.blue() << 8 | + mColor.alpha(); + + return c; + } + + + /// + /// Get color, expand if necessary + /// + QColor ColorNode::color( merge::Record* record ) const + { + if ( mIsField ) + { + if ( record == 0 ) + { + return mColor; + } + else + { + if ( record->contains( mKey ) ) + { + return QColor( (*record)[ mKey ] ); + } + else + { + return mColor; + } + } + } + else + { + return mColor; + } + } + } diff --git a/glabels/ColorNode.h b/glabels/ColorNode.h index 3350c7d..69bf002 100644 --- a/glabels/ColorNode.h +++ b/glabels/ColorNode.h @@ -30,78 +30,83 @@ #include "Merge/Record.h" -/// -/// Color Node Type -/// -struct ColorNode +namespace glabels { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorNode(); + /// + /// Color Node Type + /// + struct ColorNode + { - ColorNode( bool isField, const QColor& color, const QString& key ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorNode(); - ColorNode( bool isField, uint32_t rgba, const QString& key ); + ColorNode( bool isField, const QColor& color, const QString& key ); - ColorNode( const QColor& color ); + ColorNode( bool isField, uint32_t rgba, const QString& key ); - ColorNode( const QString& key ); + ColorNode( const QColor& color ); + + ColorNode( const QString& key ); - ///////////////////////////////// - // Operators - ///////////////////////////////// -public: - bool operator==( const ColorNode& cn ); + ///////////////////////////////// + // Operators + ///////////////////////////////// + public: + bool operator==( const ColorNode& cn ); - bool operator!=( const ColorNode& cn ); + bool operator!=( const ColorNode& cn ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - // - // Field Flag Property - // - bool isField() const; - void setField( bool isField ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + // + // Field Flag Property + // + bool isField() const; + void setField( bool isField ); - // - // Color Property - // - const QColor& color() const; - void setColor( const QColor& color ); + // + // Color Property + // + const QColor& color() const; + void setColor( const QColor& color ); - // - // Key Property - // - const QString& key() const; - void setKey( const QString& key ); + // + // Key Property + // + const QString& key() const; + void setKey( const QString& key ); - ///////////////////////////////// - // Misc. Methods - ///////////////////////////////// -public: - uint32_t rgba() const; - QColor color( merge::Record* record ) const; + ///////////////////////////////// + // Misc. Methods + ///////////////////////////////// + public: + uint32_t rgba() const; + QColor color( merge::Record* record ) const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - bool mIsField; - QColor mColor; - QString mKey; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + bool mIsField; + QColor mColor; + QString mKey; -}; + }; + +} #endif // ColorNode_h diff --git a/glabels/ColorPaletteButtonItem.cpp b/glabels/ColorPaletteButtonItem.cpp index fd0f324..e7438b2 100644 --- a/glabels/ColorPaletteButtonItem.cpp +++ b/glabels/ColorPaletteButtonItem.cpp @@ -25,96 +25,101 @@ #include -// -// Private Configuration Data -// -namespace +namespace glabels { - const int border = 4; - const int hBox = 25; - const int outlineWidthPixels = 1; -} - - -/// -/// Constructor From Data -/// -ColorPaletteButtonItem::ColorPaletteButtonItem( const QString& text, QWidget* parent ) - : QWidget(parent), mText(text), mHover(false) -{ - setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) ); - setMinimumSize( hBox+2*border+1, hBox+2*border+1 ); -} - - -/// -/// Paint Event -/// -void ColorPaletteButtonItem::paintEvent( QPaintEvent* event ) -{ - QPainter painter(this); // - // Draw background + // Private // - if ( isEnabled() && mHover ) + namespace { - QLinearGradient gradient( 0, 0, 0, height() ); - gradient.setColorAt( 0, palette().color( QPalette::Highlight ).lighter() ); - gradient.setColorAt( 1, palette().color( QPalette::Highlight ) ); - painter.setBrush( QBrush( gradient ) ); + const int border = 4; + const int hBox = 25; + const int outlineWidthPixels = 1; + } + + + /// + /// Constructor From Data + /// + ColorPaletteButtonItem::ColorPaletteButtonItem( const QString& text, QWidget* parent ) + : QWidget(parent), mText(text), mHover(false) + { + setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) ); + setMinimumSize( hBox+2*border+1, hBox+2*border+1 ); + } + + + /// + /// Paint Event + /// + void ColorPaletteButtonItem::paintEvent( QPaintEvent* event ) + { + QPainter painter(this); + + // + // Draw background + // + if ( isEnabled() && mHover ) + { + QLinearGradient gradient( 0, 0, 0, height() ); + gradient.setColorAt( 0, palette().color( QPalette::Highlight ).lighter() ); + gradient.setColorAt( 1, palette().color( QPalette::Highlight ) ); + painter.setBrush( QBrush( gradient ) ); - QPen pen( palette().color( QPalette::Text ) ); - pen.setWidth( outlineWidthPixels ); - painter.setPen( pen ); + QPen pen( palette().color( QPalette::Text ) ); + pen.setWidth( outlineWidthPixels ); + painter.setPen( pen ); - painter.drawRect( 0, 0, width()-1, height()-1 ); + painter.drawRect( 0, 0, width()-1, height()-1 ); + } + + // + // Draw text + // + painter.setBrush( QBrush( Qt::NoBrush ) ); + + if ( isEnabled() && mHover ) + { + painter.setPen( QPen( palette().color( QPalette::HighlightedText ) ) ); + } + else + { + painter.setPen( QPen( palette().color( QPalette::Text ) ) ); + } + + QRect textRect( border, border, width()-2*border, hBox ); + + painter.drawText( textRect, Qt::AlignLeft|Qt::AlignVCenter, mText ); } - // - // Draw text - // - painter.setBrush( QBrush( Qt::NoBrush ) ); - if ( isEnabled() && mHover ) + /// + /// Enter Event + /// + void ColorPaletteButtonItem::enterEvent( QEvent* event ) { - painter.setPen( QPen( palette().color( QPalette::HighlightedText ) ) ); + mHover = true; + update(); } - else + + + /// + /// Leave Event + /// + void ColorPaletteButtonItem::leaveEvent( QEvent* event ) { - painter.setPen( QPen( palette().color( QPalette::Text ) ) ); + mHover = false; + update(); } - QRect textRect( border, border, width()-2*border, hBox ); - - painter.drawText( textRect, Qt::AlignLeft|Qt::AlignVCenter, mText ); -} - - -/// -/// Enter Event -/// -void ColorPaletteButtonItem::enterEvent( QEvent* event ) -{ - mHover = true; - update(); -} - - -/// -/// Leave Event -/// -void ColorPaletteButtonItem::leaveEvent( QEvent* event ) -{ - mHover = false; - update(); -} - -/// -/// Mouse Press Event -/// -void ColorPaletteButtonItem::mousePressEvent( QMouseEvent* event ) -{ - emit activated(); + /// + /// Mouse Press Event + /// + void ColorPaletteButtonItem::mousePressEvent( QMouseEvent* event ) + { + emit activated(); + } + } diff --git a/glabels/ColorPaletteButtonItem.h b/glabels/ColorPaletteButtonItem.h index 640c04f..9a2788c 100644 --- a/glabels/ColorPaletteButtonItem.h +++ b/glabels/ColorPaletteButtonItem.h @@ -26,45 +26,50 @@ #include -/// -/// Color Palette Item -/// -class ColorPaletteButtonItem : public QWidget +namespace glabels { - Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorPaletteButtonItem( const QString& text, QWidget* parent = 0 ); + /// + /// Color Palette Item + /// + class ColorPaletteButtonItem : public QWidget + { + Q_OBJECT + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorPaletteButtonItem( const QString& text, QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void activated(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void activated(); - ///////////////////////////////// - // Event handlers - ///////////////////////////////// -protected: - void paintEvent( QPaintEvent* event ); - void enterEvent( QEvent* event ); - void leaveEvent( QEvent* event ); - void mousePressEvent( QMouseEvent* event ); + ///////////////////////////////// + // Event handlers + ///////////////////////////////// + protected: + void paintEvent( QPaintEvent* event ); + void enterEvent( QEvent* event ); + void leaveEvent( QEvent* event ); + void mousePressEvent( QMouseEvent* event ); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - QString mText; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + QString mText; - bool mHover; -}; + bool mHover; + }; + +} #endif // ColorPaletteButtonItem_h diff --git a/glabels/ColorPaletteDialog.cpp b/glabels/ColorPaletteDialog.cpp index 5773bad..27d3729 100644 --- a/glabels/ColorPaletteDialog.cpp +++ b/glabels/ColorPaletteDialog.cpp @@ -30,289 +30,298 @@ #include -ColorPaletteDialog::ColorTableEntry ColorPaletteDialog::mColorTable[] = { - - { "#ef2929", tr("Light Scarlet Red", "Color name") }, - { "#fcaf3e", tr("Light Orange", "Color name") }, - { "#fce94f", tr("Light Butter", "Color name") }, - { "#8ae234", tr("Light Chameleon", "Color name") }, - { "#729fcf", tr("Light Sky Blue", "Color name") }, - { "#ad7fa8", tr("Light Plum", "Color name") }, - { "#e9b96e", tr("Light Chocolate", "Color name") }, - { "#888a85", tr("Light Aluminum 1", "Color name") }, - { "#eeeeec", tr("Light Aluminum 2", "Color name") }, - - { "#cc0000", tr("Scarlet Red", "Color name") }, - { "#f57900", tr("Orange", "Color name") }, - { "#edd400", tr("Butter", "Color name") }, - { "#73d216", tr("Chameleon", "Color name") }, - { "#3465a4", tr("Sky Blue", "Color name") }, - { "#75507b", tr("Plum", "Color name") }, - { "#c17d11", tr("Chocolate", "Color name") }, - { "#555753", tr("Aluminum 1", "Color name") }, - { "#d3d7cf", tr("Aluminum 2", "Color name") }, - - { "#a40000", tr("Dark Scarlet Red", "Color name") }, - { "#ce5c00", tr("Dark Orange", "Color name") }, - { "#c4a000", tr("Dark Butter", "Color name") }, - { "#4e9a06", tr("Dark Chameleon", "Color name") }, - { "#204a87", tr("Dark Sky Blue", "Color name") }, - { "#5c3566", tr("Dark Plum", "Color name") }, - { "#8f5902", tr("Dark Chocolate", "Color name") }, - { "#2e3436", tr("Dark Aluminum 1", "Color name") }, - { "#babdb6", tr("Dark Aluminum 2", "Color name") }, - - { "#000000", tr("Black", "Color name") }, - { "#2e3436", tr("Very Dark Gray", "Color name") }, - { "#555753", tr("Darker Gray", "Color name") }, - { "#888a85", tr("Dark Gray", "Color name") }, - { "#babdb6", tr("Medium Gray", "Color name") }, - { "#d3d7cf", tr("Light Gray", "Color name") }, - { "#eeeeec", tr("Lighter Gray", "Color name") }, - { "#f3f3f3", tr("Very Light Gray", "Color name") }, - { "#ffffff", tr("White", "Color name") } -}; - - -ColorPaletteDialog::ColorPaletteDialog( const QString& defaultLabel, - const QColor& defaultColor, - const QColor& color, - QWidget* parent ) - : QDialog( parent ) +namespace glabels { - mColorHistory = ColorHistory::instance(); - connect( mColorHistory, SIGNAL(changed()), this, SLOT(onColorHistoryChanged()) ); - mDefaultColor = defaultColor; - mColorNode = ColorNode( color ); + // + // Static data + // + ColorPaletteDialog::ColorTableEntry ColorPaletteDialog::mColorTable[] = { - setStyleSheet( ".glabels--ColorPaletteDialog {background: white; border: 1px solid black}" ); - setWindowFlags( Qt::Popup | Qt::FramelessWindowHint ); + { "#ef2929", tr("Light Scarlet Red", "Color name") }, + { "#fcaf3e", tr("Light Orange", "Color name") }, + { "#fce94f", tr("Light Butter", "Color name") }, + { "#8ae234", tr("Light Chameleon", "Color name") }, + { "#729fcf", tr("Light Sky Blue", "Color name") }, + { "#ad7fa8", tr("Light Plum", "Color name") }, + { "#e9b96e", tr("Light Chocolate", "Color name") }, + { "#888a85", tr("Light Aluminum 1", "Color name") }, + { "#eeeeec", tr("Light Aluminum 2", "Color name") }, - QVBoxLayout* vLayout = new QVBoxLayout(); - vLayout->setContentsMargins( 0, 0, 0, 0 ); - vLayout->setSpacing( 0 ); + { "#cc0000", tr("Scarlet Red", "Color name") }, + { "#f57900", tr("Orange", "Color name") }, + { "#edd400", tr("Butter", "Color name") }, + { "#73d216", tr("Chameleon", "Color name") }, + { "#3465a4", tr("Sky Blue", "Color name") }, + { "#75507b", tr("Plum", "Color name") }, + { "#c17d11", tr("Chocolate", "Color name") }, + { "#555753", tr("Aluminum 1", "Color name") }, + { "#d3d7cf", tr("Aluminum 2", "Color name") }, - ColorPaletteButtonItem* defaultButton = new ColorPaletteButtonItem( defaultLabel ); - connect( defaultButton, SIGNAL(activated()), this, SLOT(onDefaultItemActivated()) ); - vLayout->addWidget( defaultButton ); - - QFrame* hline1 = new QFrame; - hline1->setFrameStyle( QFrame::HLine | QFrame::Plain ); - hline1->setLineWidth( 1 ); - vLayout->addWidget( hline1 ); + { "#a40000", tr("Dark Scarlet Red", "Color name") }, + { "#ce5c00", tr("Dark Orange", "Color name") }, + { "#c4a000", tr("Dark Butter", "Color name") }, + { "#4e9a06", tr("Dark Chameleon", "Color name") }, + { "#204a87", tr("Dark Sky Blue", "Color name") }, + { "#5c3566", tr("Dark Plum", "Color name") }, + { "#8f5902", tr("Dark Chocolate", "Color name") }, + { "#2e3436", tr("Dark Aluminum 1", "Color name") }, + { "#babdb6", tr("Dark Aluminum 2", "Color name") }, - QGridLayout* mainPaletteLayout = new QGridLayout(); - mainPaletteLayout->setSpacing( 0 ); - for ( int iRow = 0; iRow < PALETTE_ROWS; iRow++ ) + { "#000000", tr("Black", "Color name") }, + { "#2e3436", tr("Very Dark Gray", "Color name") }, + { "#555753", tr("Darker Gray", "Color name") }, + { "#888a85", tr("Dark Gray", "Color name") }, + { "#babdb6", tr("Medium Gray", "Color name") }, + { "#d3d7cf", tr("Light Gray", "Color name") }, + { "#eeeeec", tr("Lighter Gray", "Color name") }, + { "#f3f3f3", tr("Very Light Gray", "Color name") }, + { "#ffffff", tr("White", "Color name") } + + }; + + + ColorPaletteDialog::ColorPaletteDialog( const QString& defaultLabel, + const QColor& defaultColor, + const QColor& color, + QWidget* parent ) + : QDialog( parent ) { + mColorHistory = ColorHistory::instance(); + connect( mColorHistory, SIGNAL(changed()), this, SLOT(onColorHistoryChanged()) ); + + mDefaultColor = defaultColor; + mColorNode = ColorNode( color ); + + setStyleSheet( ".glabels--ColorPaletteDialog {background: white; border: 1px solid black}" ); + setWindowFlags( Qt::Popup | Qt::FramelessWindowHint ); + + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setContentsMargins( 0, 0, 0, 0 ); + vLayout->setSpacing( 0 ); + + ColorPaletteButtonItem* defaultButton = new ColorPaletteButtonItem( defaultLabel ); + connect( defaultButton, SIGNAL(activated()), this, SLOT(onDefaultItemActivated()) ); + vLayout->addWidget( defaultButton ); + + QFrame* hline1 = new QFrame; + hline1->setFrameStyle( QFrame::HLine | QFrame::Plain ); + hline1->setLineWidth( 1 ); + vLayout->addWidget( hline1 ); + + QGridLayout* mainPaletteLayout = new QGridLayout(); + mainPaletteLayout->setSpacing( 0 ); + for ( int iRow = 0; iRow < PALETTE_ROWS; iRow++ ) + { + for ( int iCol = 0; iCol < PALETTE_COLS; iCol++ ) + { + int i = iRow*PALETTE_COLS + iCol; + + ColorPaletteItem* item = new ColorPaletteItem( i, + QColor( mColorTable[i].colorSpec ), + mColorTable[i].name ); + connect( item, SIGNAL(activated(int)), this, SLOT(onPaletteItemActivated(int)) ); + + mainPaletteLayout->addWidget( item, iRow, iCol ); + } + } + vLayout->addLayout( mainPaletteLayout ); + + QFrame* hline2 = new QFrame; + hline2->setFrameStyle( QFrame::HLine | QFrame::Plain ); + hline2->setLineWidth( 1 ); + vLayout->addWidget( hline2 ); + + QHBoxLayout* customPaletteLayout = new QHBoxLayout(); + customPaletteLayout->setSpacing( 0 ); for ( int iCol = 0; iCol < PALETTE_COLS; iCol++ ) { - int i = iRow*PALETTE_COLS + iCol; + mHistoryItem[iCol] = new ColorPaletteItem( iCol, QColor(0,0,0,0), "" ); + mHistoryItem[iCol]->setEnabled( false ); + connect( mHistoryItem[iCol], SIGNAL(activated(int)), this, SLOT(onHistoryItemActivated(int)) ); - ColorPaletteItem* item = new ColorPaletteItem( i, - QColor( mColorTable[i].colorSpec ), - mColorTable[i].name ); - connect( item, SIGNAL(activated(int)), this, SLOT(onPaletteItemActivated(int)) ); + customPaletteLayout->addWidget( mHistoryItem[iCol] ); + } + vLayout->addLayout( customPaletteLayout ); - mainPaletteLayout->addWidget( item, iRow, iCol ); + + QFrame* hline3 = new QFrame; + hline3->setFrameStyle( QFrame::HLine | QFrame::Plain ); + hline3->setLineWidth( 1 ); + vLayout->addWidget( hline3 ); + + ColorPaletteButtonItem* customColorButton = new ColorPaletteButtonItem( tr("Custom color...") ); + connect( customColorButton, SIGNAL(activated()), this, SLOT(onCustomColorItemActivated()) ); + vLayout->addWidget( customColorButton ); + + QFrame* hline4 = new QFrame; + hline4->setFrameStyle( QFrame::HLine | QFrame::Plain ); + hline4->setLineWidth( 1 ); + vLayout->addWidget( hline4 ); + + mMergeFieldCombo = new QComboBox(); + mMergeFieldCombo->addItem( tr("Merge key...") ); + mMergeFieldCombo->setMinimumSize( 34, 34 ); + mMergeFieldCombo->setFrame( false ); + mMergeFieldCombo->setEnabled( false ); + connect( mMergeFieldCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboIndexChanged(int)) ); + vLayout->addWidget( mMergeFieldCombo ); + + // Item 0 is the ComboBox title, not an item intended for selection. So disable it. + const QStandardItemModel* model = qobject_cast(mMergeFieldCombo->model()); + QStandardItem* item = model->item(0); + item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); + + setLayout( vLayout ); + + loadCustomColorHistory(); + } + + + void ColorPaletteDialog::setColorNode( const ColorNode& colorNode ) + { + mColorNode = colorNode; + } + + + void ColorPaletteDialog::setKeys( const QStringList& keyList ) + { + mKeys = keyList; + + // Clear old keys, (all entries, except item 0) + for ( int index = mMergeFieldCombo->count()-1; index > 0; index-- ) + { + mMergeFieldCombo->removeItem( index ); + } + + // Add new keys + if ( keyList.size() > 0 ) + { + mMergeFieldCombo->addItems( keyList ); + mMergeFieldCombo->setEnabled( true ); + } + else + { + mMergeFieldCombo->setEnabled( false ); } } - vLayout->addLayout( mainPaletteLayout ); - QFrame* hline2 = new QFrame; - hline2->setFrameStyle( QFrame::HLine | QFrame::Plain ); - hline2->setLineWidth( 1 ); - vLayout->addWidget( hline2 ); - QHBoxLayout* customPaletteLayout = new QHBoxLayout(); - customPaletteLayout->setSpacing( 0 ); - for ( int iCol = 0; iCol < PALETTE_COLS; iCol++ ) + void ColorPaletteDialog::clearKeys() { - mHistoryItem[iCol] = new ColorPaletteItem( iCol, QColor(0,0,0,0), "" ); - mHistoryItem[iCol]->setEnabled( false ); - connect( mHistoryItem[iCol], SIGNAL(activated(int)), this, SLOT(onHistoryItemActivated(int)) ); - - customPaletteLayout->addWidget( mHistoryItem[iCol] ); - } - vLayout->addLayout( customPaletteLayout ); - - - QFrame* hline3 = new QFrame; - hline3->setFrameStyle( QFrame::HLine | QFrame::Plain ); - hline3->setLineWidth( 1 ); - vLayout->addWidget( hline3 ); - - ColorPaletteButtonItem* customColorButton = new ColorPaletteButtonItem( tr("Custom color...") ); - connect( customColorButton, SIGNAL(activated()), this, SLOT(onCustomColorItemActivated()) ); - vLayout->addWidget( customColorButton ); - - QFrame* hline4 = new QFrame; - hline4->setFrameStyle( QFrame::HLine | QFrame::Plain ); - hline4->setLineWidth( 1 ); - vLayout->addWidget( hline4 ); - - mMergeFieldCombo = new QComboBox(); - mMergeFieldCombo->addItem( tr("Merge key...") ); - mMergeFieldCombo->setMinimumSize( 34, 34 ); - mMergeFieldCombo->setFrame( false ); - mMergeFieldCombo->setEnabled( false ); - connect( mMergeFieldCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboIndexChanged(int)) ); - vLayout->addWidget( mMergeFieldCombo ); - - // Item 0 is the ComboBox title, not an item intended for selection. So disable it. - const QStandardItemModel* model = qobject_cast(mMergeFieldCombo->model()); - QStandardItem* item = model->item(0); - item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); - setLayout( vLayout ); - - loadCustomColorHistory(); -} - - -void ColorPaletteDialog::setColorNode( const ColorNode& colorNode ) -{ - mColorNode = colorNode; -} - - -void ColorPaletteDialog::setKeys( const QStringList& keyList ) -{ - mKeys = keyList; - - // Clear old keys, (all entries, except item 0) - for ( int index = mMergeFieldCombo->count()-1; index > 0; index-- ) - { - mMergeFieldCombo->removeItem( index ); - } - - // Add new keys - if ( keyList.size() > 0 ) - { - mMergeFieldCombo->addItems( keyList ); - mMergeFieldCombo->setEnabled( true ); - } - else - { + for ( int index = mMergeFieldCombo->count()-1; index > 0; index-- ) + { + mMergeFieldCombo->removeItem( index ); + } mMergeFieldCombo->setEnabled( false ); } -} -void ColorPaletteDialog::clearKeys() -{ - - for ( int index = mMergeFieldCombo->count()-1; index > 0; index-- ) + void ColorPaletteDialog::onDefaultItemActivated() { - mMergeFieldCombo->removeItem( index ); + mColorNode.setField( false ); + mColorNode.setColor( mDefaultColor ); + mColorNode.setKey( "" ); + + emit colorChanged( mColorNode, true ); + accept(); } - mMergeFieldCombo->setEnabled( false ); -} -void ColorPaletteDialog::onDefaultItemActivated() -{ - mColorNode.setField( false ); - mColorNode.setColor( mDefaultColor ); - mColorNode.setKey( "" ); - - emit colorChanged( mColorNode, true ); - accept(); -} - - -void ColorPaletteDialog::onPaletteItemActivated( int id ) -{ - mColorNode.setField( false ); - mColorNode.setColor( QColor( mColorTable[id].colorSpec ) ); - mColorNode.setKey( "" ); - - emit colorChanged( mColorNode, false ); - accept(); -} - - -void ColorPaletteDialog::onHistoryItemActivated( int id ) -{ - mColorNode.setField( false ); - mColorNode.setColor( mColorHistory->getColors()[id] ); - mColorNode.setKey( "" ); - - emit colorChanged( mColorNode, false ); - accept(); -} - - -void ColorPaletteDialog::onCustomColorItemActivated() -{ - QColorDialog dlg( mColorNode.color(), this ); - dlg.setWindowTitle( tr("Custom Color") ); - - if ( dlg.exec() ) + void ColorPaletteDialog::onPaletteItemActivated( int id ) { - ColorNode newColorNode; + mColorNode.setField( false ); + mColorNode.setColor( QColor( mColorTable[id].colorSpec ) ); + mColorNode.setKey( "" ); - newColorNode.setField( false ); - newColorNode.setColor( dlg.currentColor() ); - newColorNode.setKey( "" ); + emit colorChanged( mColorNode, false ); + accept(); + } - if ( newColorNode != mColorNode ) + + void ColorPaletteDialog::onHistoryItemActivated( int id ) + { + mColorNode.setField( false ); + mColorNode.setColor( mColorHistory->getColors()[id] ); + mColorNode.setKey( "" ); + + emit colorChanged( mColorNode, false ); + accept(); + } + + + void ColorPaletteDialog::onCustomColorItemActivated() + { + QColorDialog dlg( mColorNode.color(), this ); + dlg.setWindowTitle( tr("Custom Color") ); + + if ( dlg.exec() ) { - mColorNode = newColorNode; + ColorNode newColorNode; + + newColorNode.setField( false ); + newColorNode.setColor( dlg.currentColor() ); + newColorNode.setKey( "" ); + + if ( newColorNode != mColorNode ) + { + mColorNode = newColorNode; - mColorHistory->addColor( mColorNode.color() ); + mColorHistory->addColor( mColorNode.color() ); + + emit colorChanged( mColorNode, false ); + accept(); + } + } + } + + + void ColorPaletteDialog::onColorHistoryChanged() + { + loadCustomColorHistory(); + } + + + void ColorPaletteDialog::loadCustomColorHistory() + { + QList colorList = mColorHistory->getColors(); + + int id = 0; + foreach ( QColor color, colorList ) + { + mHistoryItem[id]->setColor( id, color, QString(tr("Custom color #%1").arg(id+1) ) ); + mHistoryItem[id]->setEnabled( true ); + id++; + } + + while ( id < PALETTE_ROWS ) + { + mHistoryItem[id]->setEnabled( false ); + id++; + } + } + + + void ColorPaletteDialog::onComboIndexChanged( int index ) + { + if ( index != 0 ) + { + mColorNode.setField( true ); + mColorNode.setColor( QColor("#eeeeec") ); + mColorNode.setKey( mKeys[index-1] ); emit colorChanged( mColorNode, false ); accept(); } } -} -void ColorPaletteDialog::onColorHistoryChanged() -{ - loadCustomColorHistory(); -} - - -void ColorPaletteDialog::loadCustomColorHistory() -{ - QList colorList = mColorHistory->getColors(); - - int id = 0; - foreach ( QColor color, colorList ) + void ColorPaletteDialog::showEvent( QShowEvent* event ) { - mHistoryItem[id]->setColor( id, color, QString(tr("Custom color #%1").arg(id+1) ) ); - mHistoryItem[id]->setEnabled( true ); - id++; + mMergeFieldCombo->setCurrentIndex( 0 ); + + QDialog::showEvent( event ); } - while ( id < PALETTE_ROWS ) - { - mHistoryItem[id]->setEnabled( false ); - id++; - } -} - - -void ColorPaletteDialog::onComboIndexChanged( int index ) -{ - if ( index != 0 ) - { - mColorNode.setField( true ); - mColorNode.setColor( QColor("#eeeeec") ); - mColorNode.setKey( mKeys[index-1] ); - - emit colorChanged( mColorNode, false ); - accept(); - } -} - - -void ColorPaletteDialog::showEvent( QShowEvent* event ) -{ - mMergeFieldCombo->setCurrentIndex( 0 ); - - QDialog::showEvent( event ); } diff --git a/glabels/ColorPaletteDialog.h b/glabels/ColorPaletteDialog.h index 012b953..3c56e36 100644 --- a/glabels/ColorPaletteDialog.h +++ b/glabels/ColorPaletteDialog.h @@ -31,86 +31,91 @@ #include "ColorPaletteButtonItem.h" -/// -/// Color Palette Dialog -/// -class ColorPaletteDialog : public QDialog +namespace glabels { - Q_OBJECT + + /// + /// Color Palette Dialog + /// + class ColorPaletteDialog : public QDialog + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorPaletteDialog( const QString& defaultLabel, - const QColor& defaultColor, - const QColor& color, - QWidget* parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorPaletteDialog( const QString& defaultLabel, + const QColor& defaultColor, + const QColor& color, + QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void colorChanged( ColorNode colorNode, bool isDefault ); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void colorChanged( ColorNode colorNode, bool isDefault ); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void setColorNode( const ColorNode& colorNode ); - void setKeys( const QStringList& keyList ); - void clearKeys(); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void setColorNode( const ColorNode& colorNode ); + void setKeys( const QStringList& keyList ); + void clearKeys(); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onDefaultItemActivated(); - void onPaletteItemActivated( int id ); - void onHistoryItemActivated( int id ); - void onCustomColorItemActivated(); - void onColorHistoryChanged(); - void onComboIndexChanged( int index ); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onDefaultItemActivated(); + void onPaletteItemActivated( int id ); + void onHistoryItemActivated( int id ); + void onCustomColorItemActivated(); + void onColorHistoryChanged(); + void onComboIndexChanged( int index ); -protected: - void showEvent( QShowEvent* event ); + protected: + void showEvent( QShowEvent* event ); - ///////////////////////////////// - // Private Methods - ///////////////////////////////// -private: - void loadCustomColorHistory(); + ///////////////////////////////// + // Private Methods + ///////////////////////////////// + private: + void loadCustomColorHistory(); - ///////////////////////////////// - // Private Members - ///////////////////////////////// -private: - QColor mDefaultColor; - ColorNode mColorNode; + ///////////////////////////////// + // Private Members + ///////////////////////////////// + private: + QColor mDefaultColor; + ColorNode mColorNode; - static const int PALETTE_COLS = ColorHistory::MAX_COLORS; - static const int PALETTE_ROWS = 4; + static const int PALETTE_COLS = ColorHistory::MAX_COLORS; + static const int PALETTE_ROWS = 4; - typedef struct { - QString colorSpec; - QString name; - } ColorTableEntry; + typedef struct { + QString colorSpec; + QString name; + } ColorTableEntry; - static ColorTableEntry mColorTable[]; + static ColorTableEntry mColorTable[]; - ColorHistory* mColorHistory; - ColorPaletteItem* mHistoryItem[PALETTE_COLS]; + ColorHistory* mColorHistory; + ColorPaletteItem* mHistoryItem[PALETTE_COLS]; - QComboBox* mMergeFieldCombo; - QStringList mKeys; + QComboBox* mMergeFieldCombo; + QStringList mKeys; -}; + }; + +} #endif // ColorPaletteDialog_h diff --git a/glabels/ColorPaletteItem.cpp b/glabels/ColorPaletteItem.cpp index c2c518a..d53f8fa 100644 --- a/glabels/ColorPaletteItem.cpp +++ b/glabels/ColorPaletteItem.cpp @@ -25,120 +25,125 @@ #include -// -// Private Configuration Data -// -namespace +namespace glabels { - const int border = 4; - const int wSwatch = 25; - const int hSwatch = 25; - - const int hoverBgOutlineWidthPixels = 1; - - const int outlineWidthPixels = 1; -} - - -/// -/// Constructor From Data -/// -ColorPaletteItem::ColorPaletteItem( int id, - const QColor& color, - const QString& tip, - QWidget* parent ) - : QWidget(parent), mId(id), mColor(color), mTip(tip), mHover(false) -{ - setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) ); - setMinimumSize( wSwatch+2*border+1, hSwatch+2*border+1 ); - setToolTip( tip ); -} - - -/// -/// Color Property Setter -/// -void ColorPaletteItem::setColor( int id, - const QColor& color, - const QString& tip ) -{ - mId = id; - mColor = color; - mTip = tip; - - setToolTip( tip ); - update(); -} - - -/// -/// Paint Event -/// -void ColorPaletteItem::paintEvent( QPaintEvent* event ) -{ - QPainter painter(this); // - // Draw swatch + // Private // - if ( isEnabled() ) + namespace { - if ( mHover ) + const int border = 4; + const int wSwatch = 25; + const int hSwatch = 25; + + const int hoverBgOutlineWidthPixels = 1; + + const int outlineWidthPixels = 1; + } + + + /// + /// Constructor From Data + /// + ColorPaletteItem::ColorPaletteItem( int id, + const QColor& color, + const QString& tip, + QWidget* parent ) + : QWidget(parent), mId(id), mColor(color), mTip(tip), mHover(false) + { + setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) ); + setMinimumSize( wSwatch+2*border+1, hSwatch+2*border+1 ); + setToolTip( tip ); + } + + + /// + /// Color Property Setter + /// + void ColorPaletteItem::setColor( int id, + const QColor& color, + const QString& tip ) + { + mId = id; + mColor = color; + mTip = tip; + + setToolTip( tip ); + update(); + } + + + /// + /// Paint Event + /// + void ColorPaletteItem::paintEvent( QPaintEvent* event ) + { + QPainter painter(this); + + // + // Draw swatch + // + if ( isEnabled() ) { - QPen pen( palette().color( QPalette::Text ) ); - pen.setWidth( 2*outlineWidthPixels ); - pen.setJoinStyle( Qt::MiterJoin ); - painter.setPen( pen ); - painter.setBrush( QBrush( mColor ) ); - painter.drawRect( 1, 1, width()-2, height()-2 ); + if ( mHover ) + { + QPen pen( palette().color( QPalette::Text ) ); + pen.setWidth( 2*outlineWidthPixels ); + pen.setJoinStyle( Qt::MiterJoin ); + painter.setPen( pen ); + painter.setBrush( QBrush( mColor ) ); + painter.drawRect( 1, 1, width()-2, height()-2 ); + } + else + { + QPen pen( palette().color( QPalette::Text ) ); + pen.setWidth( outlineWidthPixels ); + painter.setPen( pen ); + painter.setBrush( QBrush( mColor ) ); + painter.drawRect( border, border, wSwatch, hSwatch ); + } + + } else { - QPen pen( palette().color( QPalette::Text ) ); + QPen pen( palette().color( QPalette::Disabled, QPalette::Text ) ); pen.setWidth( outlineWidthPixels ); painter.setPen( pen ); painter.setBrush( QBrush( mColor ) ); painter.drawRect( border, border, wSwatch, hSwatch ); } - } - else + + + /// + /// Enter Event + /// + void ColorPaletteItem::enterEvent( QEvent* event ) { - QPen pen( palette().color( QPalette::Disabled, QPalette::Text ) ); - pen.setWidth( outlineWidthPixels ); - painter.setPen( pen ); - painter.setBrush( QBrush( mColor ) ); - painter.drawRect( border, border, wSwatch, hSwatch ); + mHover = true; + update(); } -} - -/// -/// Enter Event -/// -void ColorPaletteItem::enterEvent( QEvent* event ) -{ - mHover = true; - update(); -} - - -/// -/// Leave Event -/// -void ColorPaletteItem::leaveEvent( QEvent* event ) -{ - mHover = false; - update(); -} + /// + /// Leave Event + /// + void ColorPaletteItem::leaveEvent( QEvent* event ) + { + mHover = false; + update(); + } -/// -/// Mouse Press Event -/// -void ColorPaletteItem::mousePressEvent( QMouseEvent* event ) -{ - emit activated( mId ); + /// + /// Mouse Press Event + /// + void ColorPaletteItem::mousePressEvent( QMouseEvent* event ) + { + emit activated( mId ); + } + } diff --git a/glabels/ColorPaletteItem.h b/glabels/ColorPaletteItem.h index b61e0d4..9cd4ab4 100644 --- a/glabels/ColorPaletteItem.h +++ b/glabels/ColorPaletteItem.h @@ -26,59 +26,64 @@ #include -/// -/// Color Palette Item -/// -class ColorPaletteItem : public QWidget +namespace glabels { - Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorPaletteItem( int id, - const QColor& color, - const QString& tip, - QWidget* parent = 0 ); + /// + /// Color Palette Item + /// + class ColorPaletteItem : public QWidget + { + Q_OBJECT + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorPaletteItem( int id, + const QColor& color, + const QString& tip, + QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void activated( int id ); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void activated( int id ); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void setColor( int id, - const QColor& color, - const QString& tip ); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void setColor( int id, + const QColor& color, + const QString& tip ); - ///////////////////////////////// - // Event handlers - ///////////////////////////////// -protected: - void paintEvent( QPaintEvent* event ); - void enterEvent( QEvent* event ); - void leaveEvent( QEvent* event ); - void mousePressEvent( QMouseEvent* event ); + ///////////////////////////////// + // Event handlers + ///////////////////////////////// + protected: + void paintEvent( QPaintEvent* event ); + void enterEvent( QEvent* event ); + void leaveEvent( QEvent* event ); + void mousePressEvent( QMouseEvent* event ); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - int mId; - QColor mColor; - QString mTip; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + int mId; + QColor mColor; + QString mTip; - bool mHover; -}; + bool mHover; + }; + +} #endif // ColorPaletteItem_h diff --git a/glabels/ColorSwatch.cpp b/glabels/ColorSwatch.cpp index 64a38d2..0b97a2d 100644 --- a/glabels/ColorSwatch.cpp +++ b/glabels/ColorSwatch.cpp @@ -24,33 +24,38 @@ #include -// -// Private Configuration Data -// -namespace +namespace glabels { - const QColor outlineColor( 0, 0, 0 ); - const double outlineWidthPixels = 1; -} - - -/// -/// Constructor -/// -ColorSwatch::ColorSwatch( int w, int h, const QColor& color ) - : QPixmap( w, h ) -{ - fill( Qt::transparent ); - - QPainter painter(this ); - - painter.setBackgroundMode( Qt::TransparentMode ); - - QBrush brush( color ); - QPen pen( outlineColor ); - pen.setWidth( outlineWidthPixels ); - - painter.setBrush( brush ); - painter.setPen( pen ); - painter.drawRect( 1, 1, w-2, h-2 ); + + // + // Private + // + namespace + { + const QColor outlineColor( 0, 0, 0 ); + const double outlineWidthPixels = 1; + } + + + /// + /// Constructor + /// + ColorSwatch::ColorSwatch( int w, int h, const QColor& color ) + : QPixmap( w, h ) + { + fill( Qt::transparent ); + + QPainter painter(this ); + + painter.setBackgroundMode( Qt::TransparentMode ); + + QBrush brush( color ); + QPen pen( outlineColor ); + pen.setWidth( outlineWidthPixels ); + + painter.setBrush( brush ); + painter.setPen( pen ); + painter.drawRect( 1, 1, w-2, h-2 ); + } + } diff --git a/glabels/ColorSwatch.h b/glabels/ColorSwatch.h index 03e51f2..173b2a1 100644 --- a/glabels/ColorSwatch.h +++ b/glabels/ColorSwatch.h @@ -25,19 +25,24 @@ #include -/// -/// Simple Preview Widget -/// -class ColorSwatch : public QPixmap +namespace glabels { + + /// + /// Simple Preview Widget + /// + class ColorSwatch : public QPixmap + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ColorSwatch( int w, int h, const QColor& color ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ColorSwatch( int w, int h, const QColor& color ); -}; + }; + +} #endif // ColorSwatch_h diff --git a/glabels/Constants.h b/glabels/Constants.h index eddf5fe..5fb4917 100644 --- a/glabels/Constants.h +++ b/glabels/Constants.h @@ -31,6 +31,7 @@ namespace glabels const double PTS_PER_CM = (10.0*PTS_PER_MM); const double PTS_PER_PICA = 12.0; + const Distance EPSILON( 0.5, Units::PT ); } #endif // glabels_Constants_h diff --git a/glabels/Cursors.cpp b/glabels/Cursors.cpp index d4a4783..a54703a 100644 --- a/glabels/Cursors.cpp +++ b/glabels/Cursors.cpp @@ -23,37 +23,48 @@ #include -Cursors::Barcode::Barcode() - : QCursor( QPixmap(":cursors/32x32/cursor_barcode.png"), 7, 7 ) -{ -} - - -Cursors::Box::Box() - : QCursor( QPixmap(":cursors/32x32/cursor_box.png"), 7, 7 ) -{ -} - - -Cursors::Ellipse::Ellipse() - : QCursor( QPixmap(":cursors/32x32/cursor_ellipse.png"), 7, 7 ) -{ -} - - -Cursors::Image::Image() - : QCursor( QPixmap(":cursors/32x32/cursor_image.png"), 7, 7 ) -{ -} - - -Cursors::Line::Line() - : QCursor( QPixmap(":cursors/32x32/cursor_line.png"), 7, 7 ) -{ -} - - -Cursors::Text::Text() - : QCursor( QPixmap(":cursors/32x32/cursor_text.png"), 7, 7 ) +namespace glabels { + + Cursors::Barcode::Barcode() + : QCursor( QPixmap(":cursors/32x32/cursor_barcode.png"), 7, 7 ) + { + // empty + } + + + Cursors::Box::Box() + : QCursor( QPixmap(":cursors/32x32/cursor_box.png"), 7, 7 ) + { + // empty + } + + + Cursors::Ellipse::Ellipse() + : QCursor( QPixmap(":cursors/32x32/cursor_ellipse.png"), 7, 7 ) + { + // empty + } + + + Cursors::Image::Image() + : QCursor( QPixmap(":cursors/32x32/cursor_image.png"), 7, 7 ) + { + // empty + } + + + Cursors::Line::Line() + : QCursor( QPixmap(":cursors/32x32/cursor_line.png"), 7, 7 ) + { + // empty + } + + + Cursors::Text::Text() + : QCursor( QPixmap(":cursors/32x32/cursor_text.png"), 7, 7 ) + { + // empty + } + } diff --git a/glabels/Cursors.h b/glabels/Cursors.h index 512159b..479a33e 100644 --- a/glabels/Cursors.h +++ b/glabels/Cursors.h @@ -25,53 +25,58 @@ #include -/// -/// Glabels Cursors -/// -namespace Cursors +namespace glabels { + /// + /// Glabels Cursors + /// + namespace Cursors + { + - class Barcode : public QCursor - { - public: - Barcode(); - }; + class Barcode : public QCursor + { + public: + Barcode(); + }; - class Box : public QCursor - { - public: - Box(); - }; + class Box : public QCursor + { + public: + Box(); + }; - class Ellipse : public QCursor - { - public: - Ellipse(); - }; + class Ellipse : public QCursor + { + public: + Ellipse(); + }; - class Image : public QCursor - { - public: - Image(); - }; + class Image : public QCursor + { + public: + Image(); + }; - class Line : public QCursor - { - public: - Line(); - }; + class Line : public QCursor + { + public: + Line(); + }; - class Text : public QCursor - { - public: - Text(); - }; + class Text : public QCursor + { + public: + Text(); + }; + + } } diff --git a/glabels/Db.cpp b/glabels/Db.cpp index 3d166a6..422d63b 100644 --- a/glabels/Db.cpp +++ b/glabels/Db.cpp @@ -32,18 +32,26 @@ #include "XmlVendorParser.h" -namespace -{ - bool partNameLessThan( const glabels::Template *a, const glabels::Template *b ) - { - return glabels::StrUtil::comparePartNames( a->name(), b->name() ) < 0; - } -} - - namespace glabels { + + // + // Private + // + namespace + { + const QString empty = ""; + + bool partNameLessThan( const Template *a, const Template *b ) + { + return StrUtil::comparePartNames( a->name(), b->name() ) < 0; + } + } + + // + // Static data + // QList Db::mPapers; QStringList Db::mPaperIds; QStringList Db::mPaperNames; @@ -53,10 +61,9 @@ namespace glabels QList Db::mVendors; QStringList Db::mVendorNames; QList Db::mTemplates; + QString Db::mPaperNameOther; - QString Db::mPaperNameOther; - QString Db::mEmpty = ""; - + Db::Db() { mPaperNameOther = tr("Other"); @@ -204,7 +211,7 @@ namespace glabels } qWarning() << "Unknown paper name: " << name; - return mEmpty; + return empty; } @@ -225,7 +232,7 @@ namespace glabels } qWarning() << "Unknown paper id: " << id; - return mEmpty; + return empty; } @@ -318,7 +325,7 @@ namespace glabels } qWarning() << "Unknown category name: " << name; - return mEmpty; + return empty; } @@ -334,7 +341,7 @@ namespace glabels } qWarning() << "Unknown category id: " << id; - return mEmpty; + return empty; } @@ -399,7 +406,7 @@ namespace glabels } qWarning() << "Unknown vendor name: " << name; - return mEmpty; + return empty; } diff --git a/glabels/Db.h b/glabels/Db.h index 1c2947a..99313a9 100644 --- a/glabels/Db.h +++ b/glabels/Db.h @@ -131,8 +131,8 @@ namespace glabels static QList mTemplates; - static QString mPaperNameOther; - static QString mEmpty; + static QString mPaperNameOther; + }; } diff --git a/glabels/EnumUtil.cpp b/glabels/EnumUtil.cpp index 80c0ec8..69d1979 100644 --- a/glabels/EnumUtil.cpp +++ b/glabels/EnumUtil.cpp @@ -21,101 +21,106 @@ #include "EnumUtil.h" -namespace EnumUtil +namespace glabels { - - QString weightToString( QFont::Weight weight ) + + namespace EnumUtil { - switch (weight) + + QString weightToString( QFont::Weight weight ) { - case QFont::Bold: - return "bold"; - break; - default: - return "normal"; - break; + switch (weight) + { + case QFont::Bold: + return "bold"; + break; + default: + return "normal"; + break; + } } - } - QFont::Weight stringToWeight( const QString& string ) - { - if ( string == "bold" ) + QFont::Weight stringToWeight( const QString& string ) { - return QFont::Bold; + if ( string == "bold" ) + { + return QFont::Bold; + } + else + { + return QFont::Normal; + } } - else - { - return QFont::Normal; - } - } - QString hAlignToString( Qt::Alignment align ) - { - switch (align) + QString hAlignToString( Qt::Alignment align ) { - case Qt::AlignRight: - return "right"; - break; - case Qt::AlignHCenter: - return "center"; - break; - default: - return "left"; - break; + switch (align) + { + case Qt::AlignRight: + return "right"; + break; + case Qt::AlignHCenter: + return "center"; + break; + default: + return "left"; + break; + } } - } - Qt::Alignment stringToHAlign( const QString& string ) - { - if ( string == "right" ) + Qt::Alignment stringToHAlign( const QString& string ) { - return Qt::AlignRight; + if ( string == "right" ) + { + return Qt::AlignRight; + } + else if ( string == "center" ) + { + return Qt::AlignHCenter; + } + else + { + return Qt::AlignLeft; + } } - else if ( string == "center" ) - { - return Qt::AlignHCenter; - } - else - { - return Qt::AlignLeft; - } - } - QString vAlignToString( Qt::Alignment align ) - { - switch (align) + QString vAlignToString( Qt::Alignment align ) { - case Qt::AlignBottom: - return "bottom"; - break; - case Qt::AlignVCenter: - return "center"; - break; - default: - return "top"; - break; + switch (align) + { + case Qt::AlignBottom: + return "bottom"; + break; + case Qt::AlignVCenter: + return "center"; + break; + default: + return "top"; + break; + } } - } - Qt::Alignment stringToVAlign( const QString& string ) - { - if ( string == "bottom" ) + Qt::Alignment stringToVAlign( const QString& string ) { - return Qt::AlignBottom; - } - else if ( string == "center" ) - { - return Qt::AlignVCenter; - } - else - { - return Qt::AlignTop; + if ( string == "bottom" ) + { + return Qt::AlignBottom; + } + else if ( string == "center" ) + { + return Qt::AlignVCenter; + } + else + { + return Qt::AlignTop; + } } + } } diff --git a/glabels/EnumUtil.h b/glabels/EnumUtil.h index 8d78513..2d40926 100644 --- a/glabels/EnumUtil.h +++ b/glabels/EnumUtil.h @@ -27,17 +27,22 @@ #include -namespace EnumUtil +namespace glabels { - QString weightToString( QFont::Weight weight ); - QFont::Weight stringToWeight( const QString& string ); + namespace EnumUtil + { - QString hAlignToString( Qt::Alignment align ); - Qt::Alignment stringToHAlign( const QString& string ); + QString weightToString( QFont::Weight weight ); + QFont::Weight stringToWeight( const QString& string ); - QString vAlignToString( Qt::Alignment align ); - Qt::Alignment stringToVAlign( const QString& string ); + QString hAlignToString( Qt::Alignment align ); + Qt::Alignment stringToHAlign( const QString& string ); + + QString vAlignToString( Qt::Alignment align ); + Qt::Alignment stringToVAlign( const QString& string ); + + } } diff --git a/glabels/FieldButton.cpp b/glabels/FieldButton.cpp index 5a89c52..b897cb7 100644 --- a/glabels/FieldButton.cpp +++ b/glabels/FieldButton.cpp @@ -25,80 +25,85 @@ #include -/// -/// Constructor -/// -FieldButton::FieldButton( QWidget* parent ) - : QComboBox(parent) +namespace glabels { - setEnabled( false ); - connect( this, SIGNAL(currentIndexChanged(int)), this, SLOT(onIndexChanged(int)) ); -} - - -void FieldButton::setName( const QString& name ) -{ - mName = name; - if ( count() == 0 ) + /// + /// Constructor + /// + FieldButton::FieldButton( QWidget* parent ) + : QComboBox(parent) { + setEnabled( false ); + + connect( this, SIGNAL(currentIndexChanged(int)), this, SLOT(onIndexChanged(int)) ); + } + + + void FieldButton::setName( const QString& name ) + { + mName = name; + if ( count() == 0 ) + { + addItem( mName ); + } + else + { + setItemText( 0, mName ); + } + + // Item 0 is the ComboBox title, not an item intended for selection. So disable it. + const QStandardItemModel* itemModel = qobject_cast(model()); + QStandardItem* item = itemModel->item(0); + item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); + } + + + void FieldButton::setKeys( const QStringList& keyList ) + { + // Clear old keys + clear(); addItem( mName ); - } - else - { - setItemText( 0, mName ); - } - // Item 0 is the ComboBox title, not an item intended for selection. So disable it. - const QStandardItemModel* itemModel = qobject_cast(model()); - QStandardItem* item = itemModel->item(0); - item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); -} - - -void FieldButton::setKeys( const QStringList& keyList ) -{ - // Clear old keys - clear(); - addItem( mName ); - - // Item 0 is the ComboBox title, not an item intended for selection. So disable it. - const QStandardItemModel* itemModel = qobject_cast(model()); - QStandardItem* item = itemModel->item(0); - item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); + // Item 0 is the ComboBox title, not an item intended for selection. So disable it. + const QStandardItemModel* itemModel = qobject_cast(model()); + QStandardItem* item = itemModel->item(0); + item->setFlags( item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled) ); - // Add new keys - if ( keyList.size() > 0 ) - { - addItems( keyList ); - setEnabled( true ); - } - else - { - setEnabled( false ); - } -} - - -void FieldButton::clearKeys() -{ - clear(); - addItem( mName ); - - setEnabled( false ); -} - - - -/// -/// onMenuKeySelected slot -/// -void FieldButton::onIndexChanged( int index ) -{ - if ( index > 0 ) - { - emit keySelected( itemText(index) ); - - setCurrentIndex( 0 ); + // Add new keys + if ( keyList.size() > 0 ) + { + addItems( keyList ); + setEnabled( true ); + } + else + { + setEnabled( false ); + } } + + + void FieldButton::clearKeys() + { + clear(); + addItem( mName ); + + setEnabled( false ); + } + + + + /// + /// onMenuKeySelected slot + /// + void FieldButton::onIndexChanged( int index ) + { + if ( index > 0 ) + { + emit keySelected( itemText(index) ); + + setCurrentIndex( 0 ); + } + } + } diff --git a/glabels/FieldButton.h b/glabels/FieldButton.h index 7de9a20..9bbf278 100644 --- a/glabels/FieldButton.h +++ b/glabels/FieldButton.h @@ -26,50 +26,55 @@ #include -/// -/// Field Button -/// -class FieldButton : public QComboBox +namespace glabels { - Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - FieldButton( QWidget* parent = 0 ); + /// + /// Field Button + /// + class FieldButton : public QComboBox + { + Q_OBJECT + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + FieldButton( QWidget* parent = 0 ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void keySelected( QString key ); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void keySelected( QString key ); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void setName( const QString& name = "" ); - void setKeys( const QStringList& keyList ); - void clearKeys(); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void setName( const QString& name = "" ); + void setKeys( const QStringList& keyList ); + void clearKeys(); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onIndexChanged( int index ); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onIndexChanged( int index ); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - QString mName; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + QString mName; -}; + }; + +} #endif // FieldButton_h diff --git a/glabels/File.cpp b/glabels/File.cpp index b9dfac7..47c0c27 100644 --- a/glabels/File.cpp +++ b/glabels/File.cpp @@ -33,81 +33,34 @@ #include "XmlLabelCreator.h" -/// -/// Static data -/// -QString File::mCwd = "."; - - -/// -/// New Label Dialog -/// -bool File::newLabel( MainWindow *window ) +namespace glabels { - SelectProductDialog dialog( window ); - dialog.exec(); - const glabels::Template* tmplate = dialog.tmplate(); - if ( tmplate ) + // + // Static data + // + QString File::mCwd = "."; + + + /// + /// New Label Dialog + /// + bool File::newLabel( MainWindow *window ) { - LabelModel* label = new LabelModel(); - label->setTmplate( tmplate ); - label->clearModified(); + SelectProductDialog dialog( window ); + dialog.exec(); - // Intelligently decide to rotate label by default - const glabels::Frame* frame = tmplate->frames().first(); - label->setRotate( frame->h() > frame->w() ); - - // Either apply to current window or open a new one - if ( window->isEmpty() ) + const Template* tmplate = dialog.tmplate(); + if ( tmplate ) { - window->setModel( label ); - } - else - { - MainWindow *newWindow = new MainWindow(); - newWindow->setModel( label ); - newWindow->show(); - } + LabelModel* label = new LabelModel(); + label->setTmplate( tmplate ); + label->clearModified(); - return true; - } - else - { - return false; - } -} + // Intelligently decide to rotate label by default + const Frame* frame = tmplate->frames().first(); + label->setRotate( frame->h() > frame->w() ); - -/// -/// Open File Dialog -/// -void File::open( MainWindow *window ) -{ - // Either use the saved CWD from a previous open/save or grab it from the path of the current file - QString cwd = mCwd; - if ( window->model() && !window->model()->fileName().isEmpty() ) - { - QFileInfo fileInfo( window->model()->fileName() ); - if ( fileInfo.isFile() ) - { - cwd = fileInfo.absolutePath(); - } - } - - QString fileName = - QFileDialog::getOpenFileName( window, - tr("gLabels - Open Project"), - cwd, - tr("glabels files (*.glabels);;All files (*)") - ); - if ( !fileName.isEmpty() ) - { - LabelModel *label = XmlLabelParser::readFile( fileName ); - if ( label ) - { - label->setFileName( fileName ); - // Either apply to current window or open a new one if ( window->isEmpty() ) { @@ -120,123 +73,175 @@ void File::open( MainWindow *window ) newWindow->show(); } - // Save CWD - mCwd = QFileInfo( fileName ).absolutePath(); + return true; } else { - QMessageBox msgBox; - msgBox.setText( tr("Unable to open \"") + fileName + tr("\".") ); - msgBox.setStandardButtons( QMessageBox::Ok ); - msgBox.setDefaultButton( QMessageBox::Ok ); - msgBox.exec(); + return false; } } -} -/// -/// Save file -/// -bool File::save( MainWindow *window ) -{ - if ( window->model()->fileName().isEmpty() ) + /// + /// Open File Dialog + /// + void File::open( MainWindow *window ) { - return saveAs( window ); - } - - if ( !window->model()->isModified() ) - { - return true; - } - - XmlLabelCreator::writeFile( window->model(), window->model()->fileName() ); - window->model()->clearModified(); - - // Save CWD - mCwd = QFileInfo( window->model()->fileName() ).absolutePath(); - - return true; -} - - -/// -/// Save file as -/// -bool File::saveAs( MainWindow *window ) -{ - // Either use the saved CWD from a previous open/save or grab it from the path of the current file - QString cwd = mCwd; - if ( window->model() && !window->model()->fileName().isEmpty() ) - { - QFileInfo fileInfo( window->model()->fileName() ); - if ( fileInfo.isFile() ) + // Either use the saved CWD from a previous open/save or grab it from the path of the current file + QString cwd = mCwd; + if ( window->model() && !window->model()->fileName().isEmpty() ) { - cwd = fileInfo.filePath(); - } - } - - QString rawFileName = - QFileDialog::getSaveFileName( window, - tr("gLabels - Save Project As"), - cwd, - tr("glabels files (*.glabels);;All files (*)"), - 0, - QFileDialog::DontConfirmOverwrite ); - if ( !rawFileName.isEmpty() ) - { - QString fileName = FileUtil::addExtension( rawFileName, ".glabels" ); - - - if ( QFileInfo(fileName).exists() ) - { - QMessageBox msgBox( window ); - msgBox.setWindowTitle( tr("Save Label As") ); - msgBox.setIcon( QMessageBox::Warning ); - msgBox.setText( tr("%1 already exists.").arg(fileName) ); - msgBox.setInformativeText( tr("Do you want to replace it?") ); - msgBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No ); - msgBox.setDefaultButton( QMessageBox::No ); - - if ( msgBox.exec() == QMessageBox::No ) + QFileInfo fileInfo( window->model()->fileName() ); + if ( fileInfo.isFile() ) { - return saveAs( window ); + cwd = fileInfo.absolutePath(); } } - - XmlLabelCreator::writeFile( window->model(), fileName ); - window->model()->setFileName( fileName ); + + QString fileName = + QFileDialog::getOpenFileName( window, + tr("gLabels - Open Project"), + cwd, + tr("glabels files (*.glabels);;All files (*)") + ); + if ( !fileName.isEmpty() ) + { + LabelModel *label = XmlLabelParser::readFile( fileName ); + if ( label ) + { + label->setFileName( fileName ); + + // Either apply to current window or open a new one + if ( window->isEmpty() ) + { + window->setModel( label ); + } + else + { + MainWindow *newWindow = new MainWindow(); + newWindow->setModel( label ); + newWindow->show(); + } + + // Save CWD + mCwd = QFileInfo( fileName ).absolutePath(); + } + else + { + QMessageBox msgBox; + msgBox.setText( tr("Unable to open \"") + fileName + tr("\".") ); + msgBox.setStandardButtons( QMessageBox::Ok ); + msgBox.setDefaultButton( QMessageBox::Ok ); + msgBox.exec(); + } + } + } + + + /// + /// Save file + /// + bool File::save( MainWindow *window ) + { + if ( window->model()->fileName().isEmpty() ) + { + return saveAs( window ); + } + + if ( !window->model()->isModified() ) + { + return true; + } + + XmlLabelCreator::writeFile( window->model(), window->model()->fileName() ); window->model()->clearModified(); - + // Save CWD - mCwd = QFileInfo( fileName ).absolutePath(); + mCwd = QFileInfo( window->model()->fileName() ).absolutePath(); return true; } - return false; -} - -/// -/// Close file -/// -void File::close( MainWindow *window ) -{ - window->close(); -} - - -/// -/// Exit, closing all windows -/// -void File::exit() -{ - foreach ( QWidget* qwidget, QApplication::topLevelWidgets() ) + /// + /// Save file as + /// + bool File::saveAs( MainWindow *window ) { - if ( MainWindow* window = qobject_cast(qwidget) ) + // Either use the saved CWD from a previous open/save or grab it from the path of the current file + QString cwd = mCwd; + if ( window->model() && !window->model()->fileName().isEmpty() ) { - window->close(); + QFileInfo fileInfo( window->model()->fileName() ); + if ( fileInfo.isFile() ) + { + cwd = fileInfo.filePath(); + } + } + + QString rawFileName = + QFileDialog::getSaveFileName( window, + tr("gLabels - Save Project As"), + cwd, + tr("glabels files (*.glabels);;All files (*)"), + 0, + QFileDialog::DontConfirmOverwrite ); + if ( !rawFileName.isEmpty() ) + { + QString fileName = FileUtil::addExtension( rawFileName, ".glabels" ); + + + if ( QFileInfo(fileName).exists() ) + { + QMessageBox msgBox( window ); + msgBox.setWindowTitle( tr("Save Label As") ); + msgBox.setIcon( QMessageBox::Warning ); + msgBox.setText( tr("%1 already exists.").arg(fileName) ); + msgBox.setInformativeText( tr("Do you want to replace it?") ); + msgBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No ); + msgBox.setDefaultButton( QMessageBox::No ); + + if ( msgBox.exec() == QMessageBox::No ) + { + return saveAs( window ); + } + } + + XmlLabelCreator::writeFile( window->model(), fileName ); + window->model()->setFileName( fileName ); + window->model()->clearModified(); + + // Save CWD + mCwd = QFileInfo( fileName ).absolutePath(); + + return true; + } + + return false; + } + + + /// + /// Close file + /// + void File::close( MainWindow *window ) + { + window->close(); + } + + + /// + /// Exit, closing all windows + /// + void File::exit() + { + foreach ( QWidget* qwidget, QApplication::topLevelWidgets() ) + { + if ( MainWindow* window = qobject_cast(qwidget) ) + { + window->close(); + } } } + } diff --git a/glabels/File.h b/glabels/File.h index aa2ce3b..6b9ba70 100644 --- a/glabels/File.h +++ b/glabels/File.h @@ -24,31 +24,37 @@ #include -// Forward References -class MainWindow; - -/// -/// File Actions -/// -/// Note: class provides a translation context for these static functions. -/// -class File : public QObject +namespace glabels { - Q_OBJECT -public: - static bool newLabel( MainWindow *window = 0 ); - static void open( MainWindow *window ); - static bool save( MainWindow *window ); - static bool saveAs( MainWindow *window ); - static void close( MainWindow *window ); - static void exit(); + // Forward References + class MainWindow; -private: - static QString mCwd; + + /// + /// File Actions + /// + /// Note: class provides a translation context for these static functions. + /// + class File : public QObject + { + Q_OBJECT + + public: + static bool newLabel( MainWindow *window = 0 ); + static void open( MainWindow *window ); + static bool save( MainWindow *window ); + static bool saveAs( MainWindow *window ); + static void close( MainWindow *window ); + static void exit(); + + private: + static QString mCwd; -}; + }; + +} #endif // File_h diff --git a/glabels/FileUtil.cpp b/glabels/FileUtil.cpp index 21d0dc1..3347ad8 100644 --- a/glabels/FileUtil.cpp +++ b/glabels/FileUtil.cpp @@ -21,17 +21,22 @@ #include "FileUtil.h" -namespace FileUtil +namespace glabels { - QString addExtension( const QString& rawFilename, const QString& extension ) + namespace FileUtil { - if ( rawFilename.endsWith( extension ) ) + + QString addExtension( const QString& rawFilename, const QString& extension ) { - return rawFilename; + if ( rawFilename.endsWith( extension ) ) + { + return rawFilename; + } + + return rawFilename + extension; } - return rawFilename + extension; } } diff --git a/glabels/FileUtil.h b/glabels/FileUtil.h index 236eacb..cea32d9 100644 --- a/glabels/FileUtil.h +++ b/glabels/FileUtil.h @@ -25,10 +25,15 @@ #include -namespace FileUtil +namespace glabels { - QString addExtension( const QString& rawFilename, const QString& extension ); + namespace FileUtil + { + + QString addExtension( const QString& rawFilename, const QString& extension ); + + } } diff --git a/glabels/Frame.cpp b/glabels/Frame.cpp index 609e744..20a62d0 100644 --- a/glabels/Frame.cpp +++ b/glabels/Frame.cpp @@ -30,6 +30,7 @@ namespace glabels Frame::Frame( const QString& id ) : mId(id), mNLabels(0), mLayoutDescription("") { + // empty } diff --git a/glabels/FrameCd.cpp b/glabels/FrameCd.cpp index 0e1b915..c585252 100644 --- a/glabels/FrameCd.cpp +++ b/glabels/FrameCd.cpp @@ -23,7 +23,7 @@ #include -#include "privateConstants.h" +#include "Constants.h" #include "StrUtil.h" @@ -96,6 +96,7 @@ namespace glabels : mR1(other.mR1), mR2(other.mR2), mW(other.mW), mH(other.mH), mWaste(other.mWaste), mPath(other.mPath), Frame(other) { + // empty } @@ -160,10 +161,10 @@ namespace glabels { if ( FrameCd *otherCd = dynamic_cast(other) ) { - if ( (fabs( mW - otherCd->mW ) <= Constants::EPSILON) && - (fabs( mH - otherCd->mH ) <= Constants::EPSILON) && - (fabs( mR1 - otherCd->mR1 ) <= Constants::EPSILON) && - (fabs( mR2 - otherCd->mR2 ) <= Constants::EPSILON) ) + if ( (fabs( mW - otherCd->mW ) <= EPSILON) && + (fabs( mH - otherCd->mH ) <= EPSILON) && + (fabs( mR1 - otherCd->mR1 ) <= EPSILON) && + (fabs( mR2 - otherCd->mR2 ) <= EPSILON) ) { return true; } diff --git a/glabels/FrameEllipse.cpp b/glabels/FrameEllipse.cpp index 74c0113..55be6a3 100644 --- a/glabels/FrameEllipse.cpp +++ b/glabels/FrameEllipse.cpp @@ -21,7 +21,7 @@ #include "FrameEllipse.h" -#include "privateConstants.h" +#include "Constants.h" #include "StrUtil.h" @@ -41,6 +41,7 @@ namespace glabels FrameEllipse::FrameEllipse( const FrameEllipse& other ) : mW(other.mW), mH(other.mH), mWaste(other.mWaste), mPath(other.mPath), Frame(other) { + // empty } @@ -94,8 +95,8 @@ namespace glabels { if ( FrameEllipse* otherEllipse = dynamic_cast(other) ) { - if ( (fabs( mW - otherEllipse->mW ) <= Constants::EPSILON) && - (fabs( mH - otherEllipse->mH ) <= Constants::EPSILON) ) + if ( (fabs( mW - otherEllipse->mW ) <= EPSILON) && + (fabs( mH - otherEllipse->mH ) <= EPSILON) ) { return true; } diff --git a/glabels/FrameRect.cpp b/glabels/FrameRect.cpp index da8bf0a..207df40 100644 --- a/glabels/FrameRect.cpp +++ b/glabels/FrameRect.cpp @@ -21,7 +21,7 @@ #include "FrameRect.h" -#include "privateConstants.h" +#include "Constants.h" #include "StrUtil.h" @@ -48,6 +48,7 @@ namespace glabels : mW(other.mW), mH(other.mH), mR(other.mR), mXWaste(other.mXWaste), mYWaste(other.mYWaste), mPath(other.mPath), Frame(other) { + // empty } @@ -113,8 +114,8 @@ namespace glabels { if ( FrameRect *otherRect = dynamic_cast(other) ) { - if ( (fabs( mW - otherRect->mW ) <= Constants::EPSILON) && - (fabs( mH - otherRect->mH ) <= Constants::EPSILON) ) + if ( (fabs( mW - otherRect->mW ) <= EPSILON) && + (fabs( mH - otherRect->mH ) <= EPSILON) ) { return true; } diff --git a/glabels/FrameRound.cpp b/glabels/FrameRound.cpp index 6f8ac67..86f9dde 100644 --- a/glabels/FrameRound.cpp +++ b/glabels/FrameRound.cpp @@ -21,7 +21,7 @@ #include "FrameRound.h" -#include "privateConstants.h" +#include "Constants.h" #include "StrUtil.h" @@ -34,13 +34,15 @@ namespace glabels : mR(r), mWaste(waste), Frame(id) { mPath.addEllipse( 0, 0, 2*mR.pt(), 2*mR.pt() ); - mClipPath.addEllipse( -mWaste.pt(), -mWaste.pt(), 2*(mR+mWaste).pt(), 2*(mR+mWaste).pt() ); + mClipPath.addEllipse( -mWaste.pt(), -mWaste.pt(), + 2*(mR+mWaste).pt(), 2*(mR+mWaste).pt() ); } FrameRound::FrameRound( const FrameRound& other ) : mR(other.mR), mWaste(other.mWaste), mPath(other.mPath), Frame(other) { + // empty } @@ -99,7 +101,7 @@ namespace glabels { if ( FrameRound *otherRound = dynamic_cast(other) ) { - if ( fabs( mR - otherRound->mR ) <= Constants::EPSILON ) + if ( fabs( mR - otherRound->mR ) <= EPSILON ) { return true; } diff --git a/glabels/Handles.cpp b/glabels/Handles.cpp index 2746154..ab8a392 100644 --- a/glabels/Handles.cpp +++ b/glabels/Handles.cpp @@ -27,532 +27,563 @@ #include "LabelModelObject.h" -namespace +namespace glabels { - const double handlePixels = 7; - const double handleOutlineWidthPixels = 1; - const QColor handleFillColor( 0, 192, 0, 96 ); - const QColor originHandleFillColor( 192, 0, 0, 96 ); - const QColor handleOutlineColor( 0, 0, 0, 192 ); -} + // + // Private + // + namespace + { + const double handlePixels = 7; + const double handleOutlineWidthPixels = 1; + + const QColor handleFillColor( 0, 192, 0, 96 ); + const QColor originHandleFillColor( 192, 0, 0, 96 ); + const QColor handleOutlineColor( 0, 0, 0, 192 ); + } -/// -/// Handle Constructor -/// -Handle::Handle( LabelModelObject* owner, Location location ) - : mOwner(owner), mLocation(location) -{ -} + /// + /// Handle Constructor + /// + Handle::Handle( LabelModelObject* owner, Location location ) + : mOwner(owner), mLocation(location) + { + // empty + } -/// -/// Handle Destructor -/// -Handle::~Handle() -{ -} + /// + /// Handle Destructor + /// + Handle::~Handle() + { + // empty + } -/// -/// Handle owner -/// -LabelModelObject* Handle::owner() const -{ - return mOwner; -} + /// + /// Handle owner + /// + LabelModelObject* Handle::owner() const + { + return mOwner; + } -/// -/// Handle location -/// -Handle::Location Handle::location() const -{ - return mLocation; -} + /// + /// Handle location + /// + Handle::Location Handle::location() const + { + return mLocation; + } -/// -/// Draw Handle at x,y -/// -void Handle::drawAt( QPainter* painter, - double scale, - const glabels::Distance& x, - const glabels::Distance& y, - QColor color ) const -{ - painter->save(); + /// + /// Draw Handle at x,y + /// + void Handle::drawAt( QPainter* painter, + double scale, + const Distance& x, + const Distance& y, + QColor color ) const + { + painter->save(); - painter->translate( x.pt(), y.pt() ); + painter->translate( x.pt(), y.pt() ); - double s = 1.0 / scale; + double s = 1.0 / scale; - QPen pen( handleOutlineColor ); - pen.setCosmetic( true ); - pen.setWidth( handleOutlineWidthPixels ); + QPen pen( handleOutlineColor ); + pen.setCosmetic( true ); + pen.setWidth( handleOutlineWidthPixels ); - painter->setPen( pen ); - painter->setBrush( color ); + painter->setPen( pen ); + painter->setBrush( color ); - painter->drawRect( QRectF( -s*handlePixels/2.0, -s*handlePixels/2.0, s*handlePixels, s*handlePixels ) ); + painter->drawRect( QRectF( -s*handlePixels/2.0, -s*handlePixels/2.0, + s*handlePixels, s*handlePixels ) ); - painter->restore(); -} + painter->restore(); + } -/// -/// Create Handle path at x,y -/// -QPainterPath Handle::pathAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const -{ - QPainterPath path; + /// + /// Create Handle path at x,y + /// + QPainterPath Handle::pathAt( double scale, + const Distance& x, + const Distance& y ) const + { + QPainterPath path; - double s = 1/scale; + double s = 1/scale; - path.addRect( -s*handlePixels/2, -s*handlePixels/2, s*handlePixels, s*handlePixels ); - path.translate( x.pt(), y.pt() ); + path.addRect( -s*handlePixels/2, -s*handlePixels/2, s*handlePixels, s*handlePixels ); + path.translate( x.pt(), y.pt() ); - return path; -} - - -/// -/// HandleNorth Constructor -/// -HandleNorth::HandleNorth( LabelModelObject* owner ) - : Handle( owner, N ) -{ -} - - -/// -/// HandleNorth Destructor -/// -HandleNorth::~HandleNorth() -{ -} - - -/// -/// HandleNorth Clone -/// -HandleNorth* HandleNorth::clone( LabelModelObject* newOwner ) const -{ - return new HandleNorth( newOwner ); -} - - -/// -/// Draw HandleNorth -/// -void HandleNorth::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w()/2, 0, handleFillColor ); -} - - -/// -/// HandleNorth Path -/// -QPainterPath HandleNorth::path( double scale ) const -{ - return pathAt( scale, mOwner->w()/2, 0 ); -} - - -/// -/// HandleNorthEast Constructor -/// -HandleNorthEast::HandleNorthEast( LabelModelObject* owner ) - : Handle( owner, NE ) -{ -} - - -/// -/// HandleNorthEast Destructor -/// -HandleNorthEast::~HandleNorthEast() -{ -} - - -/// -/// HandleNorthEast Clone -/// -HandleNorthEast* HandleNorthEast::clone( LabelModelObject* newOwner ) const -{ - return new HandleNorthEast( newOwner ); -} - - -/// -/// Draw HandleNorthEast -/// -void HandleNorthEast::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w(), 0, handleFillColor ); -} - - -/// -/// HandleNorthEast Path -/// -QPainterPath HandleNorthEast::path( double scale ) const -{ - return pathAt( scale, mOwner->w(), 0 ); -} - - -/// -/// HandleEast Constructor -/// -HandleEast::HandleEast( LabelModelObject* owner ) - : Handle( owner, E ) -{ -} - - -/// -/// HandleEast Destructor -/// -HandleEast::~HandleEast() -{ -} - - -/// -/// HandleEast Clone -/// -HandleEast* HandleEast::clone( LabelModelObject* newOwner ) const -{ - return new HandleEast( newOwner ); -} - - -/// -/// Draw HandleEast -/// -void HandleEast::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w(), mOwner->h()/2, handleFillColor ); -} - - -/// -/// HandleEast Path -/// -QPainterPath HandleEast::path( double scale ) const -{ - return pathAt( scale, mOwner->w(), mOwner->h()/2 ); -} - - -/// -/// HandleSouthEast Constructor -/// -HandleSouthEast::HandleSouthEast( LabelModelObject* owner ) - : Handle( owner, SE ) -{ -} - - -/// -/// HandleSouthEast Destructor -/// -HandleSouthEast::~HandleSouthEast() -{ -} - - -/// -/// HandleSouthEast Clone -/// -HandleSouthEast* HandleSouthEast::clone( LabelModelObject* newOwner ) const -{ - return new HandleSouthEast( newOwner ); -} - - -/// -/// Draw HandleSouthEast -/// -void HandleSouthEast::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w(), mOwner->h(), handleFillColor ); -} - - -/// -/// HandleSouthEast Path -/// -QPainterPath HandleSouthEast::path( double scale ) const -{ - return pathAt( scale, mOwner->w(), mOwner->h() ); -} - - -/// -/// HandleSouth Constructor -/// -HandleSouth::HandleSouth( LabelModelObject* owner ) - : Handle( owner, S ) -{ -} - - -/// -/// HandleSouth Destructor -/// -HandleSouth::~HandleSouth() -{ -} - - -/// -/// HandleSouth Clone -/// -HandleSouth* HandleSouth::clone( LabelModelObject* newOwner ) const -{ - return new HandleSouth( newOwner ); -} - - -/// -/// Draw HandleSouth -/// -void HandleSouth::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w()/2, mOwner->h(), handleFillColor ); -} - - -/// -/// HandleSouth Path -/// -QPainterPath HandleSouth::path( double scale ) const -{ - return pathAt( scale, mOwner->w()/2, mOwner->h() ); -} - - -/// -/// HandleSouthWest Constructor -/// -HandleSouthWest::HandleSouthWest( LabelModelObject* owner ) - : Handle( owner, SW ) -{ -} - - -/// -/// HandleSouthWest Destructor -/// -HandleSouthWest::~HandleSouthWest() -{ -} - - -/// -/// HandleSouthWest Clone -/// -HandleSouthWest* HandleSouthWest::clone( LabelModelObject* newOwner ) const -{ - return new HandleSouthWest( newOwner ); -} - - -/// -/// Draw HandleSouthWest -/// -void HandleSouthWest::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, 0, mOwner->h(), handleFillColor ); -} - - -/// -/// HandleSouthWest Path -/// -QPainterPath HandleSouthWest::path( double scale ) const -{ - return pathAt( scale, 0, mOwner->h() ); -} - - -/// -/// HandleWest Constructor -/// -HandleWest::HandleWest( LabelModelObject* owner ) - : Handle( owner, W ) -{ -} - - -/// -/// HandleWest Destructor -/// -HandleWest::~HandleWest() -{ -} - - -/// -/// HandleWest Clone -/// -HandleWest* HandleWest::clone( LabelModelObject* newOwner ) const -{ - return new HandleWest( newOwner ); -} - - -/// -/// Draw HandleWest -/// -void HandleWest::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, 0, mOwner->h()/2, handleFillColor ); -} - - -/// -/// HandleWest Path -/// -QPainterPath HandleWest::path( double scale ) const -{ - return pathAt( scale, 0, mOwner->h()/2 ); -} - - -/// -/// HandleNorthWest Constructor -/// -HandleNorthWest::HandleNorthWest( LabelModelObject* owner ) - : Handle( owner, NW ) -{ -} - - -/// -/// HandleNorthWest Destructor -/// -HandleNorthWest::~HandleNorthWest() -{ -} - -/// -/// HandleNorthWest Clone -/// -HandleNorthWest* HandleNorthWest::clone( LabelModelObject* newOwner ) const -{ - return new HandleNorthWest( newOwner ); -} - - -/// -/// Draw HandleNorthWest -/// -void HandleNorthWest::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, 0, 0, originHandleFillColor ); -} - - -/// -/// HandleNorthWest Path -/// -QPainterPath HandleNorthWest::path( double scale ) const -{ - return pathAt( scale, 0, 0 ); -} - - -/// -/// HandleP1 Constructor -/// -HandleP1::HandleP1( LabelModelObject* owner ) - : Handle( owner, P1 ) -{ -} - - -/// -/// HandleP1 Destructor -/// -HandleP1::~HandleP1() -{ -} - - -/// -/// HandleP1 Clone -/// -HandleP1* HandleP1::clone( LabelModelObject* newOwner ) const -{ - return new HandleP1( newOwner ); -} - - -/// -/// Draw HandleP1 -/// -void HandleP1::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, 0, 0, originHandleFillColor ); -} - - -/// -/// HandleP1 Path -/// -QPainterPath HandleP1::path( double scale ) const -{ - return pathAt( scale, 0, 0 ); -} - - -/// -/// HandleP2 Constructor -/// -HandleP2::HandleP2( LabelModelObject* owner ) - : Handle( owner, P2 ) -{ -} - - -/// -/// HandleP2 Destructor -/// -HandleP2::~HandleP2() -{ -} - - -/// -/// HandleP2 Clone -/// -HandleP2* HandleP2::clone( LabelModelObject* newOwner ) const -{ - return new HandleP2( newOwner ); -} - - -/// -/// Draw HandleP2 -/// -void HandleP2::draw( QPainter* painter, double scale ) const -{ - drawAt( painter, scale, mOwner->w(), mOwner->h(), handleFillColor ); -} - - -/// -/// HandleP2 Path -/// -QPainterPath HandleP2::path( double scale ) const -{ - return pathAt( scale, mOwner->w(), mOwner->h() ); + return path; + } + + + /// + /// HandleNorth Constructor + /// + HandleNorth::HandleNorth( LabelModelObject* owner ) + : Handle( owner, N ) + { + // empty + } + + + /// + /// HandleNorth Destructor + /// + HandleNorth::~HandleNorth() + { + // empty + } + + + /// + /// HandleNorth Clone + /// + HandleNorth* HandleNorth::clone( LabelModelObject* newOwner ) const + { + return new HandleNorth( newOwner ); + } + + + /// + /// Draw HandleNorth + /// + void HandleNorth::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w()/2, 0, handleFillColor ); + } + + + /// + /// HandleNorth Path + /// + QPainterPath HandleNorth::path( double scale ) const + { + return pathAt( scale, mOwner->w()/2, 0 ); + } + + + /// + /// HandleNorthEast Constructor + /// + HandleNorthEast::HandleNorthEast( LabelModelObject* owner ) + : Handle( owner, NE ) + { + // empty + } + + + /// + /// HandleNorthEast Destructor + /// + HandleNorthEast::~HandleNorthEast() + { + // empty + } + + + /// + /// HandleNorthEast Clone + /// + HandleNorthEast* HandleNorthEast::clone( LabelModelObject* newOwner ) const + { + return new HandleNorthEast( newOwner ); + } + + + /// + /// Draw HandleNorthEast + /// + void HandleNorthEast::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w(), 0, handleFillColor ); + } + + + /// + /// HandleNorthEast Path + /// + QPainterPath HandleNorthEast::path( double scale ) const + { + return pathAt( scale, mOwner->w(), 0 ); + } + + + /// + /// HandleEast Constructor + /// + HandleEast::HandleEast( LabelModelObject* owner ) + : Handle( owner, E ) + { + // empty + } + + + /// + /// HandleEast Destructor + /// + HandleEast::~HandleEast() + { + // empty + } + + + /// + /// HandleEast Clone + /// + HandleEast* HandleEast::clone( LabelModelObject* newOwner ) const + { + return new HandleEast( newOwner ); + } + + + /// + /// Draw HandleEast + /// + void HandleEast::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w(), mOwner->h()/2, handleFillColor ); + } + + + /// + /// HandleEast Path + /// + QPainterPath HandleEast::path( double scale ) const + { + return pathAt( scale, mOwner->w(), mOwner->h()/2 ); + } + + + /// + /// HandleSouthEast Constructor + /// + HandleSouthEast::HandleSouthEast( LabelModelObject* owner ) + : Handle( owner, SE ) + { + // empty + } + + + /// + /// HandleSouthEast Destructor + /// + HandleSouthEast::~HandleSouthEast() + { + // empty + } + + + /// + /// HandleSouthEast Clone + /// + HandleSouthEast* HandleSouthEast::clone( LabelModelObject* newOwner ) const + { + return new HandleSouthEast( newOwner ); + } + + + /// + /// Draw HandleSouthEast + /// + void HandleSouthEast::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w(), mOwner->h(), handleFillColor ); + } + + + /// + /// HandleSouthEast Path + /// + QPainterPath HandleSouthEast::path( double scale ) const + { + return pathAt( scale, mOwner->w(), mOwner->h() ); + } + + + /// + /// HandleSouth Constructor + /// + HandleSouth::HandleSouth( LabelModelObject* owner ) + : Handle( owner, S ) + { + // empty + } + + + /// + /// HandleSouth Destructor + /// + HandleSouth::~HandleSouth() + { + // empty + } + + + /// + /// HandleSouth Clone + /// + HandleSouth* HandleSouth::clone( LabelModelObject* newOwner ) const + { + return new HandleSouth( newOwner ); + } + + + /// + /// Draw HandleSouth + /// + void HandleSouth::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w()/2, mOwner->h(), handleFillColor ); + } + + + /// + /// HandleSouth Path + /// + QPainterPath HandleSouth::path( double scale ) const + { + return pathAt( scale, mOwner->w()/2, mOwner->h() ); + } + + + /// + /// HandleSouthWest Constructor + /// + HandleSouthWest::HandleSouthWest( LabelModelObject* owner ) + : Handle( owner, SW ) + { + // empty + } + + + /// + /// HandleSouthWest Destructor + /// + HandleSouthWest::~HandleSouthWest() + { + // empty + } + + + /// + /// HandleSouthWest Clone + /// + HandleSouthWest* HandleSouthWest::clone( LabelModelObject* newOwner ) const + { + return new HandleSouthWest( newOwner ); + } + + + /// + /// Draw HandleSouthWest + /// + void HandleSouthWest::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, 0, mOwner->h(), handleFillColor ); + } + + + /// + /// HandleSouthWest Path + /// + QPainterPath HandleSouthWest::path( double scale ) const + { + return pathAt( scale, 0, mOwner->h() ); + } + + + /// + /// HandleWest Constructor + /// + HandleWest::HandleWest( LabelModelObject* owner ) + : Handle( owner, W ) + { + // empty + } + + + /// + /// HandleWest Destructor + /// + HandleWest::~HandleWest() + { + // empty + } + + + /// + /// HandleWest Clone + /// + HandleWest* HandleWest::clone( LabelModelObject* newOwner ) const + { + return new HandleWest( newOwner ); + } + + + /// + /// Draw HandleWest + /// + void HandleWest::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, 0, mOwner->h()/2, handleFillColor ); + } + + + /// + /// HandleWest Path + /// + QPainterPath HandleWest::path( double scale ) const + { + return pathAt( scale, 0, mOwner->h()/2 ); + } + + + /// + /// HandleNorthWest Constructor + /// + HandleNorthWest::HandleNorthWest( LabelModelObject* owner ) + : Handle( owner, NW ) + { + // empty + } + + + /// + /// HandleNorthWest Destructor + /// + HandleNorthWest::~HandleNorthWest() + { + // empty + } + + /// + /// HandleNorthWest Clone + /// + HandleNorthWest* HandleNorthWest::clone( LabelModelObject* newOwner ) const + { + return new HandleNorthWest( newOwner ); + } + + + /// + /// Draw HandleNorthWest + /// + void HandleNorthWest::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, 0, 0, originHandleFillColor ); + } + + + /// + /// HandleNorthWest Path + /// + QPainterPath HandleNorthWest::path( double scale ) const + { + return pathAt( scale, 0, 0 ); + } + + + /// + /// HandleP1 Constructor + /// + HandleP1::HandleP1( LabelModelObject* owner ) + : Handle( owner, P1 ) + { + // empty + } + + + /// + /// HandleP1 Destructor + /// + HandleP1::~HandleP1() + { + // empty + } + + + /// + /// HandleP1 Clone + /// + HandleP1* HandleP1::clone( LabelModelObject* newOwner ) const + { + return new HandleP1( newOwner ); + } + + + /// + /// Draw HandleP1 + /// + void HandleP1::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, 0, 0, originHandleFillColor ); + } + + + /// + /// HandleP1 Path + /// + QPainterPath HandleP1::path( double scale ) const + { + return pathAt( scale, 0, 0 ); + } + + + /// + /// HandleP2 Constructor + /// + HandleP2::HandleP2( LabelModelObject* owner ) + : Handle( owner, P2 ) + { + // empty + } + + + /// + /// HandleP2 Destructor + /// + HandleP2::~HandleP2() + { + // empty + } + + + /// + /// HandleP2 Clone + /// + HandleP2* HandleP2::clone( LabelModelObject* newOwner ) const + { + return new HandleP2( newOwner ); + } + + + /// + /// Draw HandleP2 + /// + void HandleP2::draw( QPainter* painter, double scale ) const + { + drawAt( painter, scale, mOwner->w(), mOwner->h(), handleFillColor ); + } + + + /// + /// HandleP2 Path + /// + QPainterPath HandleP2::path( double scale ) const + { + return pathAt( scale, mOwner->w(), mOwner->h() ); + } + } diff --git a/glabels/Handles.h b/glabels/Handles.h index 9b8710c..b0f18e3 100644 --- a/glabels/Handles.h +++ b/glabels/Handles.h @@ -27,304 +27,310 @@ #include "Distance.h" -// Forward References -class LabelModelObject; - -/// -/// Handle Base Class -/// -class Handle +namespace glabels { - //////////////////////////// - // Location enumeration - //////////////////////////// -public: - enum Location { NW, N, NE, E, SE, S, SW, W, P1, P2 }; - - - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -protected: - Handle( LabelModelObject* owner, Location location ); -public: - virtual ~Handle(); + + // Forward References + class LabelModelObject; - //////////////////////////// - // Duplication - //////////////////////////// - virtual Handle* clone( LabelModelObject* newOwner ) const = 0; + /// + /// Handle Base Class + /// + class Handle + { + //////////////////////////// + // Location enumeration + //////////////////////////// + public: + enum Location { NW, N, NE, E, SE, S, SW, W, P1, P2 }; + + + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + protected: + Handle( LabelModelObject* owner, Location location ); + public: + virtual ~Handle(); + + + //////////////////////////// + // Duplication + //////////////////////////// + virtual Handle* clone( LabelModelObject* newOwner ) const = 0; - //////////////////////////// - // Attribue Methods - //////////////////////////// - LabelModelObject* owner() const; - Location location() const; + //////////////////////////// + // Attribue Methods + //////////////////////////// + LabelModelObject* owner() const; + Location location() const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const = 0; - virtual QPainterPath path( double scale ) const = 0; -protected: - void drawAt( QPainter* painter, - double scale, - const glabels::Distance& x, - const glabels::Distance& y, - QColor color ) const; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const = 0; + virtual QPainterPath path( double scale ) const = 0; + protected: + void drawAt( QPainter* painter, + double scale, + const Distance& x, + const Distance& y, + QColor color ) const; - QPainterPath pathAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const; + QPainterPath pathAt( double scale, + const Distance& x, + const Distance& y ) const; - //////////////////////////// - // Protected Data - //////////////////////////// -protected: - LabelModelObject* mOwner; - Location mLocation; + //////////////////////////// + // Protected Data + //////////////////////////// + protected: + LabelModelObject* mOwner; + Location mLocation; -}; + }; -/// -/// HandleNorth Class -/// -class HandleNorth : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleNorth( LabelModelObject* owner ); - virtual ~HandleNorth(); - virtual HandleNorth* clone( LabelModelObject* newOwner ) const; + /// + /// HandleNorth Class + /// + class HandleNorth : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleNorth( LabelModelObject* owner ); + virtual ~HandleNorth(); + virtual HandleNorth* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleNorthEast Class -/// -class HandleNorthEast : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleNorthEast( LabelModelObject* owner ); - virtual ~HandleNorthEast(); - virtual HandleNorthEast* clone( LabelModelObject* newOwner ) const; + /// + /// HandleNorthEast Class + /// + class HandleNorthEast : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleNorthEast( LabelModelObject* owner ); + virtual ~HandleNorthEast(); + virtual HandleNorthEast* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleEast Class -/// -class HandleEast : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleEast( LabelModelObject* owner ); - virtual ~HandleEast(); - virtual HandleEast* clone( LabelModelObject* newOwner ) const; + /// + /// HandleEast Class + /// + class HandleEast : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleEast( LabelModelObject* owner ); + virtual ~HandleEast(); + virtual HandleEast* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleSouthEast Class -/// -class HandleSouthEast : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleSouthEast( LabelModelObject* owner ); - virtual ~HandleSouthEast(); - virtual HandleSouthEast* clone( LabelModelObject* newOwner ) const; + /// + /// HandleSouthEast Class + /// + class HandleSouthEast : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleSouthEast( LabelModelObject* owner ); + virtual ~HandleSouthEast(); + virtual HandleSouthEast* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleSouth Class -/// -class HandleSouth : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleSouth( LabelModelObject* owner ); - virtual ~HandleSouth(); - virtual HandleSouth* clone( LabelModelObject* newOwner ) const; + /// + /// HandleSouth Class + /// + class HandleSouth : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleSouth( LabelModelObject* owner ); + virtual ~HandleSouth(); + virtual HandleSouth* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleSouthWest Class -/// -class HandleSouthWest : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleSouthWest( LabelModelObject* owner ); - virtual ~HandleSouthWest(); - virtual HandleSouthWest* clone( LabelModelObject* newOwner ) const; + /// + /// HandleSouthWest Class + /// + class HandleSouthWest : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleSouthWest( LabelModelObject* owner ); + virtual ~HandleSouthWest(); + virtual HandleSouthWest* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleWest Class -/// -class HandleWest : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleWest( LabelModelObject* owner ); - virtual ~HandleWest(); - virtual HandleWest* clone( LabelModelObject* newOwner ) const; + /// + /// HandleWest Class + /// + class HandleWest : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleWest( LabelModelObject* owner ); + virtual ~HandleWest(); + virtual HandleWest* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleNorthWest Class -/// -class HandleNorthWest : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleNorthWest( LabelModelObject* owner ); - virtual ~HandleNorthWest(); - virtual HandleNorthWest* clone( LabelModelObject* newOwner ) const; + /// + /// HandleNorthWest Class + /// + class HandleNorthWest : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleNorthWest( LabelModelObject* owner ); + virtual ~HandleNorthWest(); + virtual HandleNorthWest* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleP1 Class -/// -class HandleP1 : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleP1( LabelModelObject* owner ); - virtual ~HandleP1(); - virtual HandleP1* clone( LabelModelObject* newOwner ) const; + /// + /// HandleP1 Class + /// + class HandleP1 : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleP1( LabelModelObject* owner ); + virtual ~HandleP1(); + virtual HandleP1* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; -/// -/// HandleP2 Class -/// -class HandleP2 : public Handle -{ - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - HandleP2( LabelModelObject* owner ); - virtual ~HandleP2(); + /// + /// HandleP2 Class + /// + class HandleP2 : public Handle + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + HandleP2( LabelModelObject* owner ); + virtual ~HandleP2(); - //////////////////////////// - // Duplication - //////////////////////////// - virtual HandleP2* clone( LabelModelObject* newOwner ) const; + //////////////////////////// + // Duplication + //////////////////////////// + virtual HandleP2* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - virtual void draw( QPainter* painter, double scale ) const; - virtual QPainterPath path( double scale ) const; -}; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + virtual void draw( QPainter* painter, double scale ) const; + virtual QPainterPath path( double scale ) const; + }; + +} #endif // Handles_h diff --git a/glabels/Help.cpp b/glabels/Help.cpp index f418066..9cf8b87 100644 --- a/glabels/Help.cpp +++ b/glabels/Help.cpp @@ -26,20 +26,25 @@ #include "AboutDialog.h" -/// -/// Display Help Contents -/// -void Help::displayContents( QWidget *parent ) +namespace glabels { - qDebug() << "TODO: Help::displayContents"; -} + + /// + /// Display Help Contents + /// + void Help::displayContents( QWidget *parent ) + { + qDebug() << "TODO: Help::displayContents"; + } -/// -/// Display Help->About Dialog -/// -void Help::displayAbout( QWidget *parent ) -{ - AboutDialog dialog( parent ); - dialog.exec(); + /// + /// Display Help->About Dialog + /// + void Help::displayAbout( QWidget *parent ) + { + AboutDialog dialog( parent ); + dialog.exec(); + } + } diff --git a/glabels/Help.h b/glabels/Help.h index db41330..21779ad 100644 --- a/glabels/Help.h +++ b/glabels/Help.h @@ -25,16 +25,20 @@ #include -/// -/// Help Actions -/// -namespace Help +namespace glabels { - void displayContents( QWidget *parent ); - void displayAbout( QWidget *parent ); + /// + /// Help Actions + /// + namespace Help + { + + void displayContents( QWidget *parent ); + void displayAbout( QWidget *parent ); + + } } - #endif // Help_h diff --git a/glabels/Icons.h b/glabels/Icons.h index be9561d..9c9d995 100644 --- a/glabels/Icons.h +++ b/glabels/Icons.h @@ -25,324 +25,320 @@ #include -/// -/// Glabels Icons -/// -namespace Icons +namespace glabels { - class Arrow : public QIcon - { - public: - Arrow() - { - addFile( ":icons/16x16/actions/glabels-arrow.png" ); - addFile( ":icons/24x24/actions/glabels-arrow.png" ); - } - }; - - - class Barcode : public QIcon - { - public: - Barcode() - { - addFile( ":icons/16x16/actions/glabels-barcode.png" ); - addFile( ":icons/24x24/actions/glabels-barcode.png" ); - } - }; - - - class Box : public QIcon - { - public: - Box() - { - addFile( ":icons/16x16/actions/glabels-box.png" ); - addFile( ":icons/24x24/actions/glabels-box.png" ); - } - }; - - - class Ellipse : public QIcon - { - public: - Ellipse() - { - addFile( ":icons/16x16/actions/glabels-ellipse.png" ); - addFile( ":icons/24x24/actions/glabels-ellipse.png" ); - } - }; - - - class Image : public QIcon - { - public: - Image() - { - addFile( ":icons/16x16/actions/glabels-image.png" ); - addFile( ":icons/24x24/actions/glabels-image.png" ); - } - }; - - - class Line : public QIcon - { - public: - Line() - { - addFile( ":icons/16x16/actions/glabels-line.png" ); - addFile( ":icons/24x24/actions/glabels-line.png" ); - } - }; - - - class Text : public QIcon - { - public: - Text() - { - addFile( ":icons/16x16/actions/glabels-text.png" ); - addFile( ":icons/24x24/actions/glabels-text.png" ); - } - }; - - - class Merge : public QIcon - { - public: - Merge() - { - addFile( ":icons/16x16/actions/glabels-merge.png" ); - addFile( ":icons/24x24/actions/glabels-merge.png" ); - } - }; - - - class ObjectProperties : public QIcon - { - public: - ObjectProperties() - { - addFile( ":icons/16x16/actions/glabels-object-properties.png" ); - addFile( ":icons/24x24/actions/glabels-object-properties.png" ); - } - }; - - - class AlignLeft : public QIcon - { - public: - AlignLeft() - { - addFile( ":icons/16x16/actions/glabels-align-left.png" ); - } - }; - - - class AlignHCenter : public QIcon - { - public: - AlignHCenter() - { - addFile( ":icons/16x16/actions/glabels-align-hcenter.png" ); - } - }; - - - class AlignRight : public QIcon - { - public: - AlignRight() - { - addFile( ":icons/16x16/actions/glabels-align-right.png" ); - } - }; - - - class AlignBottom : public QIcon - { - public: - AlignBottom() - { - addFile( ":icons/16x16/actions/glabels-align-bottom.png" ); - } - }; - - - class AlignVCenter : public QIcon - { - public: - AlignVCenter() - { - addFile( ":icons/16x16/actions/glabels-align-vcenter.png" ); - } - }; - - - class AlignTop : public QIcon - { - public: - AlignTop() - { - addFile( ":icons/16x16/actions/glabels-align-top.png" ); - } - }; - - - class CenterHoriz : public QIcon - { - public: - CenterHoriz() - { - addFile( ":icons/16x16/actions/glabels-center-horiz.png" ); - } - }; - - - class CenterVert : public QIcon - { - public: - CenterVert() - { - addFile( ":icons/16x16/actions/glabels-center-vert.png" ); - } - }; - - - class FlipHoriz : public QIcon - { - public: - FlipHoriz() - { - addFile( ":icons/16x16/actions/glabels-flip-horiz.png" ); - } - }; - - - class FlipVert : public QIcon - { - public: - FlipVert() - { - addFile( ":icons/16x16/actions/glabels-flip-vert.png" ); - } - }; - - - class RotateLeft : public QIcon - { - public: - RotateLeft() - { - addFile( ":icons/16x16/actions/glabels-rotate-left.png" ); - } - }; - - - class RotateRight : public QIcon - { - public: - RotateRight() - { - addFile( ":icons/16x16/actions/glabels-rotate-right.png" ); - } - }; - - - class OrderBottom : public QIcon - { - public: - OrderBottom() - { - addFile( ":icons/16x16/actions/glabels-order-bottom.png" ); - } - }; - - - class OrderTop : public QIcon - { - public: - OrderTop() - { - addFile( ":icons/16x16/actions/glabels-order-top.png" ); - } - }; - - - class AlignTextBottom : public QIcon - { - public: - AlignTextBottom() - { - addFile( ":icons/24x24/actions/glabels-align-text-bottom.png" ); - } - }; - - - class AlignTextMiddle : public QIcon - { - public: - AlignTextMiddle() - { - addFile( ":icons/24x24/actions/glabels-align-text-middle.png" ); - } - }; - - - class AlignTextTop : public QIcon - { - public: - AlignTextTop() - { - addFile( ":icons/24x24/actions/glabels-align-text-top.png" ); - } - }; - - - class BucketFill : public QIcon - { - public: - BucketFill() - { - addFile( ":icons/16x16/actions/glabels-bucket-fill.png" ); - addFile( ":icons/24x24/actions/glabels-bucket-fill.png" ); - } - }; - - - class Pencil : public QIcon - { - public: - Pencil() - { - addFile( ":icons/16x16/actions/glabels-pencil.png" ); - addFile( ":icons/24x24/actions/glabels-pencil.png" ); - } - }; - - - class Glabels : public QIcon - { - public: - Glabels() - { - addFile( ":icons/16x16/apps/glabels.png" ); - addFile( ":icons/24x24/apps/glabels.png" ); - addFile( ":icons/32x32/apps/glabels.png" ); - addFile( ":icons/48x48/apps/glabels.png" ); - addFile( ":icons/scalable/apps/glabels.svg" ); - } - }; - - /// - /// Fallback Icons. These are fallbacks for icons that would normally come from the current theme, - /// if supported. These icons are copied from the mate-icon-theme (GPL-v3 or CC-BY-SA-v3). + /// Glabels Icons /// - namespace Fallback + namespace Icons { + class Arrow : public QIcon + { + public: + Arrow() + { + addFile( ":icons/16x16/actions/glabels-arrow.png" ); + addFile( ":icons/24x24/actions/glabels-arrow.png" ); + } + }; + + + class Barcode : public QIcon + { + public: + Barcode() + { + addFile( ":icons/16x16/actions/glabels-barcode.png" ); + addFile( ":icons/24x24/actions/glabels-barcode.png" ); + } + }; + + + class Box : public QIcon + { + public: + Box() + { + addFile( ":icons/16x16/actions/glabels-box.png" ); + addFile( ":icons/24x24/actions/glabels-box.png" ); + } + }; + + + class Ellipse : public QIcon + { + public: + Ellipse() + { + addFile( ":icons/16x16/actions/glabels-ellipse.png" ); + addFile( ":icons/24x24/actions/glabels-ellipse.png" ); + } + }; + + + class Image : public QIcon + { + public: + Image() + { + addFile( ":icons/16x16/actions/glabels-image.png" ); + addFile( ":icons/24x24/actions/glabels-image.png" ); + } + }; + + + class Line : public QIcon + { + public: + Line() + { + addFile( ":icons/16x16/actions/glabels-line.png" ); + addFile( ":icons/24x24/actions/glabels-line.png" ); + } + }; + + + class Text : public QIcon + { + public: + Text() + { + addFile( ":icons/16x16/actions/glabels-text.png" ); + addFile( ":icons/24x24/actions/glabels-text.png" ); + } + }; + + + class Merge : public QIcon + { + public: + Merge() + { + addFile( ":icons/16x16/actions/glabels-merge.png" ); + addFile( ":icons/24x24/actions/glabels-merge.png" ); + } + }; + + + class ObjectProperties : public QIcon + { + public: + ObjectProperties() + { + addFile( ":icons/16x16/actions/glabels-object-properties.png" ); + addFile( ":icons/24x24/actions/glabels-object-properties.png" ); + } + }; + + + class AlignLeft : public QIcon + { + public: + AlignLeft() + { + addFile( ":icons/16x16/actions/glabels-align-left.png" ); + } + }; + + + class AlignHCenter : public QIcon + { + public: + AlignHCenter() + { + addFile( ":icons/16x16/actions/glabels-align-hcenter.png" ); + } + }; + + + class AlignRight : public QIcon + { + public: + AlignRight() + { + addFile( ":icons/16x16/actions/glabels-align-right.png" ); + } + }; + + + class AlignBottom : public QIcon + { + public: + AlignBottom() + { + addFile( ":icons/16x16/actions/glabels-align-bottom.png" ); + } + }; + + + class AlignVCenter : public QIcon + { + public: + AlignVCenter() + { + addFile( ":icons/16x16/actions/glabels-align-vcenter.png" ); + } + }; + + + class AlignTop : public QIcon + { + public: + AlignTop() + { + addFile( ":icons/16x16/actions/glabels-align-top.png" ); + } + }; + + + class CenterHoriz : public QIcon + { + public: + CenterHoriz() + { + addFile( ":icons/16x16/actions/glabels-center-horiz.png" ); + } + }; + + + class CenterVert : public QIcon + { + public: + CenterVert() + { + addFile( ":icons/16x16/actions/glabels-center-vert.png" ); + } + }; + + + class FlipHoriz : public QIcon + { + public: + FlipHoriz() + { + addFile( ":icons/16x16/actions/glabels-flip-horiz.png" ); + } + }; + + + class FlipVert : public QIcon + { + public: + FlipVert() + { + addFile( ":icons/16x16/actions/glabels-flip-vert.png" ); + } + }; + + + class RotateLeft : public QIcon + { + public: + RotateLeft() + { + addFile( ":icons/16x16/actions/glabels-rotate-left.png" ); + } + }; + + + class RotateRight : public QIcon + { + public: + RotateRight() + { + addFile( ":icons/16x16/actions/glabels-rotate-right.png" ); + } + }; + + + class OrderBottom : public QIcon + { + public: + OrderBottom() + { + addFile( ":icons/16x16/actions/glabels-order-bottom.png" ); + } + }; + + + class OrderTop : public QIcon + { + public: + OrderTop() + { + addFile( ":icons/16x16/actions/glabels-order-top.png" ); + } + }; + + + class AlignTextBottom : public QIcon + { + public: + AlignTextBottom() + { + addFile( ":icons/24x24/actions/glabels-align-text-bottom.png" ); + } + }; + + + class AlignTextMiddle : public QIcon + { + public: + AlignTextMiddle() + { + addFile( ":icons/24x24/actions/glabels-align-text-middle.png" ); + } + }; + + + class AlignTextTop : public QIcon + { + public: + AlignTextTop() + { + addFile( ":icons/24x24/actions/glabels-align-text-top.png" ); + } + }; + + + class BucketFill : public QIcon + { + public: + BucketFill() + { + addFile( ":icons/16x16/actions/glabels-bucket-fill.png" ); + addFile( ":icons/24x24/actions/glabels-bucket-fill.png" ); + } + }; + + + class Pencil : public QIcon + { + public: + Pencil() + { + addFile( ":icons/16x16/actions/glabels-pencil.png" ); + addFile( ":icons/24x24/actions/glabels-pencil.png" ); + } + }; + + + class Glabels : public QIcon + { + public: + Glabels() + { + addFile( ":icons/16x16/apps/glabels.png" ); + addFile( ":icons/24x24/apps/glabels.png" ); + addFile( ":icons/32x32/apps/glabels.png" ); + addFile( ":icons/48x48/apps/glabels.png" ); + addFile( ":icons/scalable/apps/glabels.svg" ); + } + }; + + class EditCopy : public QIcon { public: diff --git a/glabels/LabelEditor.cpp b/glabels/LabelEditor.cpp index b22e7be..fb7c844 100644 --- a/glabels/LabelEditor.cpp +++ b/glabels/LabelEditor.cpp @@ -42,1183 +42,204 @@ #include "UndoRedoModel.h" -// -// Private Configuration Data -// -namespace +namespace glabels { - const int nZoomLevels = 11; - const double zoomLevels[nZoomLevels] = { 8, 6, 4, 3, 2, 1.5, 1, 0.75, 0.67, 0.50, 0.33 }; - const double PTS_PER_INCH = 72.0; - const double ZOOM_TO_FIT_PAD = 16.0; - - const QColor backgroundColor( 192, 192, 192 ); - - const QColor shadowColor( 64, 64, 64, 128 ); - const double shadowOffsetPixels = 4; - - const QColor labelColor( 255, 255, 255 ); - const QColor labelOutlineColor( 0, 0, 0 ); - const double labelOutlineWidthPixels = 1; - - const QColor gridLineColor( 192, 192, 192 ); - const double gridLineWidthPixels = 1; - const glabels::Distance gridSpacing = glabels::Distance::pt(9); // TODO: determine from locale. - - const QColor markupLineColor( 240, 99, 99 ); - const double markupLineWidthPixels = 1; - - const QColor selectRegionFillColor( 192, 192, 255, 128 ); - const QColor selectRegionOutlineColor( 0, 0, 255, 128 ); - const double selectRegionOutlineWidthPixels = 3; -} - - - -/// -/// Constructor -/// -LabelEditor::LabelEditor( QScrollArea* scrollArea, QWidget* parent ) - : QWidget(parent), mScrollArea(scrollArea) -{ - mState = IdleState; - - mModel = 0; - mUndoRedoModel = 0; - mMarkupVisible = true; - mGridVisible = true; - mGridSpacing = 18; - - setMouseTracking( true ); - setFocusPolicy(Qt::StrongFocus); - - connect( Settings::instance(), SIGNAL(changed()), this, SLOT(onSettingsChanged()) ); - onSettingsChanged(); -} - - -/// -/// Zoom property -/// -double -LabelEditor::zoom() const -{ - return mZoom; -} - - -/// -/// Markup visible? property -/// -bool -LabelEditor::markupVisible() const -{ - return mMarkupVisible; -} - - -/// -/// Grid visible? property -/// -bool -LabelEditor::qridVisible() const -{ - return mGridVisible; -} - - -/// -/// Model Parameter Setter -/// -void -LabelEditor::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) -{ - mModel = model; - mUndoRedoModel = undoRedoModel; - - if ( model ) + // + // Private + // + namespace { - zoomToFit(); + const int nZoomLevels = 11; + const double zoomLevels[nZoomLevels] = { 8, 6, 4, 3, 2, 1.5, 1, 0.75, 0.67, 0.50, 0.33 }; - connect( model, SIGNAL(changed()), this, SLOT(update()) ); - connect( model, SIGNAL(selectionChanged()), this, SLOT(update()) ); - connect( model, SIGNAL(sizeChanged()), this, SLOT(onModelSizeChanged()) ); + const double ZOOM_TO_FIT_PAD = 16.0; - update(); - } -} + const QColor backgroundColor( 192, 192, 192 ); + const QColor shadowColor( 64, 64, 64, 128 ); + const double shadowOffsetPixels = 4; -/// -/// Grid Visibility Parameter Setter -/// -void -LabelEditor::setGridVisible( bool visibleFlag ) -{ - mGridVisible = visibleFlag; - update(); -} + const QColor labelColor( 255, 255, 255 ); + const QColor labelOutlineColor( 0, 0, 0 ); + const double labelOutlineWidthPixels = 1; + const QColor gridLineColor( 192, 192, 192 ); + const double gridLineWidthPixels = 1; + const Distance gridSpacing = Distance::pt(9); // TODO: determine from locale. -/// -/// Markup Visibility Parameter Setter -/// -void -LabelEditor::setMarkupVisible( bool visibleFlag ) -{ - mMarkupVisible = visibleFlag; - update(); -} + const QColor markupLineColor( 240, 99, 99 ); + const double markupLineWidthPixels = 1; - -/// -/// Zoom In "One Notch" -/// -void -LabelEditor::zoomIn() -{ - // Find closest standard zoom level to our current zoom - // Start with 2nd largest scale - int i_min = 1; - double dist_min = qFabs( zoomLevels[1] - mZoom ); - - for ( int i = 2; i < nZoomLevels; i++ ) - { - double dist = qFabs( zoomLevels[i] - mZoom ); - if ( dist < dist_min ) - { - i_min = i; - dist_min = dist; - } + const QColor selectRegionFillColor( 192, 192, 255, 128 ); + const QColor selectRegionOutlineColor( 0, 0, 255, 128 ); + const double selectRegionOutlineWidthPixels = 3; } - // Zoom in one notch - setZoomReal( zoomLevels[i_min-1], false ); -} - -/// -/// Zoom Out "One Notch" -/// -void -LabelEditor::zoomOut() -{ - // Find closest standard zoom level to our current zoom - // Start with largest scale, end on 2nd smallest - int i_min = 0; - double dist_min = qFabs( zoomLevels[0] - mZoom ); - - for ( int i = 1; i < (nZoomLevels-1); i++ ) + /// + /// Constructor + /// + LabelEditor::LabelEditor( QScrollArea* scrollArea, QWidget* parent ) + : QWidget(parent), mScrollArea(scrollArea) { - double dist = qFabs( zoomLevels[i] - mZoom ); - if ( dist < dist_min ) - { - i_min = i; - dist_min = dist; - } + mState = IdleState; + + mModel = 0; + mUndoRedoModel = 0; + mMarkupVisible = true; + mGridVisible = true; + mGridSpacing = 18; + + setMouseTracking( true ); + setFocusPolicy(Qt::StrongFocus); + + connect( Settings::instance(), SIGNAL(changed()), this, SLOT(onSettingsChanged()) ); + onSettingsChanged(); } - // Zoom out one notch - setZoomReal( zoomLevels[i_min+1], false ); -} - -/// -/// Zoom To 1:1 Scale -/// -void -LabelEditor::zoom1To1() -{ - setZoomReal( 1.0, false ); -} - - -/// -/// Zoom To Fit -/// -void -LabelEditor::zoomToFit() -{ - double wPixels = mScrollArea->maximumViewportSize().width(); - double hPixels = mScrollArea->maximumViewportSize().height(); - - double x_scale = ( wPixels - ZOOM_TO_FIT_PAD ) / mModel->w().pt(); - double y_scale = ( hPixels - ZOOM_TO_FIT_PAD ) / mModel->h().pt(); - double newZoom = qMin( x_scale, y_scale ) * PTS_PER_INCH / physicalDpiX(); - - // Limits - newZoom = qMin( newZoom, zoomLevels[0] ); - newZoom = qMax( newZoom, zoomLevels[nZoomLevels-1] ); - - setZoomReal( newZoom, true ); -} - - -/// -/// Is Zoom at Maximum? -/// -bool -LabelEditor::isZoomMax() const -{ - return mZoom >= zoomLevels[0]; -} - - -/// -/// Is Zoom at Minimum? -/// -bool -LabelEditor::isZoomMin() const -{ - return mZoom <= zoomLevels[nZoomLevels-1]; -} - - -/// -/// Set Zoom to Value -/// -void -LabelEditor::setZoomReal( double zoom, bool zoomToFitFlag ) -{ - mZoom = zoom; - mZoomToFitFlag = zoomToFitFlag; - - /* Actual scale depends on DPI of display (assume DpiX == DpiY). */ - mScale = zoom * physicalDpiX() / PTS_PER_INCH; - - setMinimumSize( mScale*mModel->w().pt() + ZOOM_TO_FIT_PAD, - mScale*mModel->h().pt() + ZOOM_TO_FIT_PAD ); - - /* Adjust origin to center label in widget. */ - mX0 = (width()/mScale - mModel->w()) / 2; - mY0 = (height()/mScale - mModel->h()) / 2; - - update(); - - emit zoomChanged(); -} - - -/// -/// Arrow mode (normal mode) -/// -void -LabelEditor::arrowMode() -{ - setCursor( Qt::ArrowCursor ); - - mState = IdleState; -} - - -/// -/// Create box mode -/// -void -LabelEditor::createBoxMode() -{ - setCursor( Cursors::Box() ); - - mCreateObjectType = Box; - mState = CreateIdle; -} - - -/// -/// Create ellipse mode -/// -void -LabelEditor::createEllipseMode() -{ - setCursor( Cursors::Ellipse() ); - - mCreateObjectType = Ellipse; - mState = CreateIdle; -} - - -/// -/// Create image mode -/// -void -LabelEditor::createImageMode() -{ - setCursor( Cursors::Image() ); - - mCreateObjectType = Image; - mState = CreateIdle; -} - - -/// -/// Create line mode -/// -void -LabelEditor::createLineMode() -{ - setCursor( Cursors::Line() ); - - mCreateObjectType = Line; - mState = CreateIdle; -} - - -/// -/// Create text mode -/// -void -LabelEditor::createTextMode() -{ - setCursor( Cursors::Text() ); - - mCreateObjectType = Text; - mState = CreateIdle; -} - - -/// -/// Resize Event Handler -/// -void -LabelEditor::resizeEvent( QResizeEvent *event ) -{ - if ( mModel ) + /// + /// Zoom property + /// + double + LabelEditor::zoom() const { - if ( mZoomToFitFlag ) + return mZoom; + } + + + /// + /// Markup visible? property + /// + bool + LabelEditor::markupVisible() const + { + return mMarkupVisible; + } + + + /// + /// Grid visible? property + /// + bool + LabelEditor::qridVisible() const + { + return mGridVisible; + } + + + /// + /// Model Parameter Setter + /// + void + LabelEditor::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) + { + mModel = model; + mUndoRedoModel = undoRedoModel; + + if ( model ) { zoomToFit(); - } - else - { - /* Re-adjust origin to center label in widget. */ - mX0 = (width()/mScale - mModel->w()) / 2; - mY0 = (height()/mScale - mModel->h()) / 2; + + connect( model, SIGNAL(changed()), this, SLOT(update()) ); + connect( model, SIGNAL(selectionChanged()), this, SLOT(update()) ); + connect( model, SIGNAL(sizeChanged()), this, SLOT(onModelSizeChanged()) ); update(); } } -} -/// -/// Mouse Button Press Event Handler -/// -void -LabelEditor::mousePressEvent( QMouseEvent* event ) -{ - if ( mModel ) + /// + /// Grid Visibility Parameter Setter + /// + void + LabelEditor::setGridVisible( bool visibleFlag ) { - /* - * Transform to label coordinates - */ - QTransform transform; + mGridVisible = visibleFlag; + update(); + } - transform.scale( mScale, mScale ); - transform.translate( mX0.pt(), mY0.pt() ); - QPointF pWorld = transform.inverted().map( event->pos() ); - glabels::Distance xWorld = glabels::Distance::pt( pWorld.x() ); - glabels::Distance yWorld = glabels::Distance::pt( pWorld.y() ); + /// + /// Markup Visibility Parameter Setter + /// + void + LabelEditor::setMarkupVisible( bool visibleFlag ) + { + mMarkupVisible = visibleFlag; + update(); + } - - if ( event->button() & Qt::LeftButton ) + + /// + /// Zoom In "One Notch" + /// + void + LabelEditor::zoomIn() + { + // Find closest standard zoom level to our current zoom + // Start with 2nd largest scale + int i_min = 1; + double dist_min = qFabs( zoomLevels[1] - mZoom ); + + for ( int i = 2; i < nZoomLevels; i++ ) { - // - // LEFT BUTTON - // - switch (mState) + double dist = qFabs( zoomLevels[i] - mZoom ); + if ( dist < dist_min ) { - - case IdleState: - { - LabelModelObject* object = 0; - Handle* handle = 0; - if ( mModel->isSelectionAtomic() && - (handle = mModel->handleAt( mScale, xWorld, yWorld )) != 0 ) - { - // - // Start an object resize - // - mResizeObject = handle->owner(); - mResizeHandle = handle; - mResizeHonorAspect = event->modifiers() & Qt::ControlModifier; - - mState = ArrowResize; - } - else if ( (object = mModel->objectAt( mScale, xWorld, yWorld )) != 0 ) - { - // - // Start a Move Selection (adjusting selection if necessary) - // - if ( event->modifiers() & Qt::ControlModifier ) - { - if ( object->isSelected() ) - { - // Un-selecting a selected item - mModel->unselectObject( object ); - } - else - { - // Add to current selection - mModel->selectObject( object ); - } - } - else - { - if ( !object->isSelected() ) - { - // Replace current selection with this object - mModel->unselectAll(); - mModel->selectObject( object ); - } - } - - mMoveLastX = xWorld; - mMoveLastY = yWorld; - - mState = ArrowMove; - } - else - { - // - // Start a Select Region - // - if ( !(event->modifiers() & Qt::ControlModifier) ) - { - mModel->unselectAll(); - } - - mSelectRegionVisible = true; - mSelectRegion.setX1( xWorld ); - mSelectRegion.setY1( yWorld ); - mSelectRegion.setX2( xWorld ); - mSelectRegion.setY2( yWorld ); - - mState = ArrowSelectRegion; - update(); - } - } - break; - - - case CreateIdle: - { - switch ( mCreateObjectType ) - { - case Box: - mCreateObject = new LabelModelBoxObject(); - break; - case Ellipse: - mCreateObject = new LabelModelEllipseObject(); - break; - case Line: - mCreateObject = new LabelModelLineObject(); - break; - case Image: - mCreateObject = new LabelModelImageObject(); - break; - case Text: - mCreateObject = new LabelModelTextObject(); - break; - case Barcode: - // mCreateObject = new LabelModelBarcodeObject(); - break; - default: - qDebug() << "LabelEditor::mousePressEvent: Invalid creation type. Should not happen!"; - break; - } - - mCreateObject->setPosition( xWorld, yWorld ); - mCreateObject->setSize( 0, 0 ); - mModel->addObject( mCreateObject ); - - mModel->unselectAll(); - mModel->selectObject( mCreateObject ); - - mCreateX0 = xWorld; - mCreateY0 = yWorld; - - mState = CreateDrag; - } - break; - - - default: - { - qDebug() << "LabelEditor::mousePressEvent: Invalid state. Should not happen!"; - } - break; - - } - - } - else if ( event->button() & Qt::RightButton ) - { - // - // RIGHT BUTTON - // - if ( mState == IdleState ) - { - emit contextMenuActivate(); + i_min = i; + dist_min = dist; } } + + // Zoom in one notch + setZoomReal( zoomLevels[i_min-1], false ); } -} -/// -/// Mouse Movement Event Handler -/// -void -LabelEditor::mouseMoveEvent( QMouseEvent* event ) -{ - if ( mModel ) + /// + /// Zoom Out "One Notch" + /// + void + LabelEditor::zoomOut() { - /* - * Transform to label coordinates - */ - QTransform transform; + // Find closest standard zoom level to our current zoom + // Start with largest scale, end on 2nd smallest + int i_min = 0; + double dist_min = qFabs( zoomLevels[0] - mZoom ); - transform.scale( mScale, mScale ); - transform.translate( mX0.pt(), mY0.pt() ); - - QPointF pWorld = transform.inverted().map( event->pos() ); - glabels::Distance xWorld = glabels::Distance::pt( pWorld.x() ); - glabels::Distance yWorld = glabels::Distance::pt( pWorld.y() ); - - - /* - * Emit signal regardless of mode - */ - emit pointerMoved( xWorld, yWorld ); - - - /* - * Handle event as appropriate for state - */ - switch (mState) + for ( int i = 1; i < (nZoomLevels-1); i++ ) { - - case IdleState: - if ( mModel->isSelectionAtomic() && - mModel->handleAt( mScale, xWorld, yWorld ) ) + double dist = qFabs( zoomLevels[i] - mZoom ); + if ( dist < dist_min ) { - setCursor( Qt::CrossCursor ); - } - else if ( mModel->objectAt( mScale, xWorld, yWorld ) ) - { - setCursor( Qt::SizeAllCursor ); - } - else - { - setCursor( Qt::ArrowCursor ); - } - break; - - case ArrowSelectRegion: - mSelectRegion.setX2( xWorld ); - mSelectRegion.setY2( yWorld ); - update(); - break; - - case ArrowMove: - mUndoRedoModel->checkpoint( tr("Move") ); - mModel->moveSelection( (xWorld - mMoveLastX), - (yWorld - mMoveLastY) ); - mMoveLastX = xWorld; - mMoveLastY = yWorld; - break; - - case ArrowResize: - handleResizeMotion( xWorld, yWorld ); - break; - - case CreateIdle: - break; - - case CreateDrag: - switch (mCreateObjectType) - { - case Box: - case Ellipse: - case Image: - case Text: - case Barcode: - mCreateObject->setPosition( min( xWorld, mCreateX0 ), - min( yWorld, mCreateY0 ) ); - mCreateObject->setSize( max(xWorld,mCreateX0) - min(xWorld,mCreateX0), - max(yWorld,mCreateY0) - min(yWorld,mCreateY0) ); - - break; - case Line: - mCreateObject->setSize( xWorld - mCreateX0, yWorld - mCreateY0 ); - break; - default: - qDebug() << "LabelEditor::mouseMoveEvent: Invalid creation mode. Should not happen!"; - break; - } - break; - - default: - qDebug() << "LabelEditor::mouseMoveEvent: Invalid state. Should not happen!"; - break; - - } - } -} - - -/// -/// Mouse Button Release Event Handler -/// -void -LabelEditor::mouseReleaseEvent( QMouseEvent* event ) -{ - if ( mModel ) - { - /* - * Transform to label coordinates - */ - QTransform transform; - - transform.scale( mScale, mScale ); - transform.translate( mX0.pt(), mY0.pt() ); - - QPointF pWorld = transform.inverted().map( event->pos() ); - glabels::Distance xWorld = glabels::Distance::pt( pWorld.x() ); - glabels::Distance yWorld = glabels::Distance::pt( pWorld.y() ); - - - if ( event->button() & Qt::LeftButton ) - { - // - // LEFT BUTTON Release - // - switch (mState) - { - - case ArrowResize: - mState = IdleState; - break; - - case ArrowSelectRegion: - mSelectRegionVisible = false; - mSelectRegion.setX2( xWorld ); - mSelectRegion.setY2( yWorld ); - - mModel->selectRegion( mSelectRegion ); - - mState = IdleState; - update(); - break; - - case CreateDrag: - if ( (fabs(mCreateObject->w()) < 4) && (fabs(mCreateObject->h()) < 4) ) - { - switch (mCreateObjectType) - { - case Text: - mCreateObject->setSize( 72, 36 ); - break; - case Line: - mCreateObject->setSize( 72, 0 ); - break; - default: - mCreateObject->setSize( 72, 72 ); - break; - } - } - - setCursor( Qt::ArrowCursor ); - mState = IdleState; - break; - - default: - mState = IdleState; - break; - - } - - } - } -} - - -/// -/// Leave Event Handler -/// -void -LabelEditor::leaveEvent( QEvent* event ) -{ - if ( mModel ) - { - emit pointerExited(); - } -} - - -/// -/// Handle resize motion -/// -void -LabelEditor::handleResizeMotion( const glabels::Distance& xWorld, - const glabels::Distance& yWorld ) -{ - QPointF p( xWorld.pt(), yWorld.pt() ); - Handle::Location location = mResizeHandle->location(); - - /* - * Change point to object relative coordinates - */ - p -= QPointF( mResizeObject->x0().pt(), mResizeObject->y0().pt() ); - p = mResizeObject->matrix().inverted().map( p ); - - /* - * Initialize origin and 2 corners in object relative coordinates. - */ - double x0 = 0.0; - double y0 = 0.0; - - double x1 = 0.0; - double y1 = 0.0; - - double x2 = mResizeObject->w().pt(); - double y2 = mResizeObject->h().pt(); - - /* - * Calculate new size - */ - double w, h; - switch ( location ) - { - case Handle::NW: - w = std::max( x2 - p.x(), 0.0 ); - h = std::max( y2 - p.y(), 0.0 ); - break; - case Handle::N: - w = x2 - x1; - h = std::max( y2 - p.y(), 0.0 ); - break; - case Handle::NE: - w = std::max( p.x() - x1, 0.0 ); - h = std::max( y2 - p.y(), 0.0 ); - break; - case Handle::E: - w = std::max( p.x() - x1, 0.0 ); - h = y2 - y1; - break; - case Handle::SE: - w = std::max( p.x() - x1, 0.0 ); - h = std::max( p.y() - y1, 0.0 ); - break; - case Handle::S: - w = x2 - x1; - h = std::max( p.y() - y1, 0.0 ); - break; - case Handle::SW: - w = std::max( x2 - p.x(), 0.0 ); - h = std::max( p.y() - y1, 0.0 ); - break; - case Handle::W: - w = std::max( x2 - p.x(), 0.0 ); - h = y2 - y1; - break; - case Handle::P1: - x1 = p.x(); - y1 = p.y(); - w = x2 - p.x(); - h = y2 - p.y(); - x0 = x0 + x1; - y0 = y0 + y1; - break; - case Handle::P2: - w = p.x() - x1; - h = p.y() - y1; - x0 = x0 + x1; - y0 = y0 + y1; - break; - default: - qDebug() << "LabelEditor::handleResizeMotion: Invalid Handle Location. Should not happen!"; - } - - /* - * Set size - */ - if ( !(location == Handle::P1) && !(location == Handle::P2) ) - { - if ( mResizeHonorAspect ) - { - switch ( location ) - { - case Handle::E: - case Handle::W: - mResizeObject->setWHonorAspect( glabels::Distance::pt(w) ); - break; - case Handle::N: - case Handle::S: - mResizeObject->setHHonorAspect( glabels::Distance::pt(h) ); - break; - default: - mResizeObject->setSizeHonorAspect( glabels::Distance::pt(w), - glabels::Distance::pt(h) ); - break; + i_min = i; + dist_min = dist; } } - else - { - mResizeObject->setSize( glabels::Distance::pt(w), - glabels::Distance::pt(h) ); - } - /* - * Adjust origin, if needed. - */ - switch ( location ) - { - case Handle::NW: - x0 += x2 - mResizeObject->w().pt(); - y0 += y2 - mResizeObject->h().pt(); - break; - case Handle::N: - case Handle::NE: - y0 += y2 - mResizeObject->h().pt(); - break; - case Handle::W: - case Handle::SW: - x0 += x2 - mResizeObject->w().pt(); - break; - defaule: - break; - } + // Zoom out one notch + setZoomReal( zoomLevels[i_min+1], false ); } - else + + + /// + /// Zoom To 1:1 Scale + /// + void + LabelEditor::zoom1To1() { - mResizeObject->setSize( glabels::Distance::pt(w), - glabels::Distance::pt(h) ); + setZoomReal( 1.0, false ); } - /* - * Put new origin back into world coordinates and set. - */ - QPointF p0( x0, y0 ); - p0 = mResizeObject->matrix().map( p0 ); - p0 += QPointF( mResizeObject->x0().pt(), mResizeObject->y0().pt() ); - mResizeObject->setPosition( glabels::Distance::pt(p0.x()), - glabels::Distance::pt(p0.y()) ); -} - -/// -/// Key Press Event Handler -void -LabelEditor::keyPressEvent( QKeyEvent* event ) -{ - if ( mState == IdleState ) - { - switch (event->key()) - { - - case Qt::Key_Left: - mUndoRedoModel->checkpoint( tr("Move") ); - mModel->moveSelection( -mStepSize, glabels::Distance(0) ); - break; - - case Qt::Key_Up: - mUndoRedoModel->checkpoint( tr("Move") ); - mModel->moveSelection( glabels::Distance(0), -mStepSize ); - break; - - case Qt::Key_Right: - mUndoRedoModel->checkpoint( tr("Move") ); - mModel->moveSelection( mStepSize, glabels::Distance(0) ); - break; - - case Qt::Key_Down: - mUndoRedoModel->checkpoint( tr("Move") ); - mModel->moveSelection( glabels::Distance(0), mStepSize ); - break; - - case Qt::Key_Delete: - mUndoRedoModel->checkpoint( tr("Delete") ); - mModel->deleteSelection(); - setCursor( Qt::ArrowCursor ); - break; - - default: - QWidget::keyPressEvent( event ); - break; - - } - } - else - { - QWidget::keyPressEvent( event ); - } -} - - -/// -/// Paint Event Handler -/// -void -LabelEditor::paintEvent( QPaintEvent* event ) -{ - if ( mModel ) - { - QPainter painter( this ); - - painter.setRenderHint( QPainter::Antialiasing, true ); - painter.setRenderHint( QPainter::TextAntialiasing, true ); - painter.setRenderHint( QPainter::SmoothPixmapTransform, true ); - - /* Fill background before any transformations */ - painter.setBrush( QBrush( backgroundColor ) ); - painter.setPen( Qt::NoPen ); - painter.drawRect( rect() ); - - /* Transform. */ - painter.scale( mScale, mScale ); - painter.translate( mX0.pt(), mY0.pt() ); - - /* Now draw from the bottom layer up. */ - drawBgLayer( &painter ); - drawGridLayer( &painter ); - drawMarkupLayer( &painter ); - drawObjectsLayer( &painter ); - drawFgLayer( &painter ); - drawHighlightLayer( &painter ); - drawSelectRegionLayer( &painter ); - } -} - - -/// -/// Draw Background Layer -/// -void -LabelEditor::drawBgLayer( QPainter* painter ) -{ - /* - * Draw shadow - */ - painter->save(); - - painter->setBrush( QBrush( shadowColor ) ); - painter->setPen( Qt::NoPen ); - - painter->translate( shadowOffsetPixels/mScale, shadowOffsetPixels/mScale ); - - if ( mModel->rotate() ) - { - painter->rotate( -90 ); - painter->translate( -mModel->frame()->w().pt(), 0 ); - } - painter->drawPath( mModel->frame()->path() ); - - painter->restore(); - - - /* - * Draw label - */ - painter->save(); - - painter->setBrush( QBrush( labelColor ) ); - painter->setPen( Qt::NoPen ); - - if ( mModel->rotate() ) - { - painter->rotate( -90 ); - painter->translate( -mModel->frame()->w().pt(), 0 ); - } - painter->drawPath( mModel->frame()->path() ); - - painter->restore(); -} - - -/// -/// Draw Grid Layer -/// -void -LabelEditor::drawGridLayer( QPainter* painter ) -{ - if ( mGridVisible ) - { - glabels::Distance w = mModel->frame()->w(); - glabels::Distance h = mModel->frame()->h(); - - glabels::Distance x0, y0; - if ( dynamic_cast( mModel->frame() ) ) - { - x0 = gridSpacing; - y0 = gridSpacing; - } - else - { - /* round labels, adjust grid to line up with center of label. */ - x0 = fmod( w/2, gridSpacing ); - y0 = fmod( h/2, gridSpacing ); - } - - painter->save(); - if ( mModel->rotate() ) - { - painter->rotate( -90 ); - painter->translate( -mModel->frame()->w().pt(), 0 ); - } - - painter->setClipPath( mModel->frame()->path() ); - - QPen pen( gridLineColor, gridLineWidthPixels ); - pen.setCosmetic( true ); - painter->setPen( pen ); - - for ( glabels::Distance x = x0; x < w; x += gridSpacing ) - { - painter->drawLine( x.pt(), 0, x.pt(), h.pt() ); - } - - for ( glabels::Distance y = y0; y < h; y += gridSpacing ) - { - painter->drawLine( 0, y.pt(), w.pt(), y.pt() ); - } - - painter->restore(); - } -} - - -/// -/// Draw Markup Layer -/// -void -LabelEditor::drawMarkupLayer( QPainter* painter ) -{ - if ( mMarkupVisible ) - { - painter->save(); - - QPen pen( markupLineColor, markupLineWidthPixels ); - pen.setCosmetic( true ); - - painter->setBrush( Qt::NoBrush ); - painter->setPen( pen ); - - if ( mModel->rotate() ) - { - painter->rotate( -90 ); - painter->translate( -mModel->frame()->w().pt(), 0 ); - } - - foreach( glabels::Markup* markup, mModel->frame()->markups() ) - { - painter->drawPath( markup->path() ); - } - - painter->restore(); - } -} - - -/// -/// Draw Objects Layer -/// -void -LabelEditor::drawObjectsLayer( QPainter* painter ) -{ - mModel->draw( painter ); -} - - -/// -/// Draw Foreground Layer -/// -void -LabelEditor::drawFgLayer( QPainter* painter ) -{ - /* - * Draw label outline - */ - painter->save(); - - QPen pen( labelOutlineColor, labelOutlineWidthPixels ); - pen.setCosmetic( true ); - painter->setBrush( QBrush( Qt::NoBrush ) ); - painter->setPen( pen ); - - if ( mModel->rotate() ) - { - painter->rotate( -90 ); - painter->translate( -mModel->frame()->w().pt(), 0 ); - } - painter->drawPath( mModel->frame()->path() ); - - painter->restore(); -} - - -/// -/// Draw Highlight Layer -/// -void -LabelEditor::drawHighlightLayer( QPainter* painter ) -{ - painter->save(); - - foreach ( LabelModelObject* object, mModel->objectList() ) - { - if ( object->isSelected() ) - { - object->drawSelectionHighlight( painter, mScale ); - } - } - - painter->restore(); -} - - -/// -/// Draw Select Region Layer -/// -void -LabelEditor::drawSelectRegionLayer( QPainter* painter ) -{ - if ( mSelectRegionVisible ) - { - painter->save(); - - QPen pen( selectRegionOutlineColor, selectRegionOutlineWidthPixels ); - pen.setCosmetic( true ); - painter->setBrush( selectRegionFillColor ); - painter->setPen( pen ); - - painter->drawRect( mSelectRegion.rect() ); - - painter->restore(); - } - -} - - -/// -/// Settings changed handler -/// -void LabelEditor::onSettingsChanged() -{ - glabels::Units units = Settings::units(); - - mStepSize = glabels::Distance( units.resolution(), units ); -} - - -/// -/// Model size changed handler -/// -void LabelEditor::onModelSizeChanged() -{ - if (mZoomToFitFlag) + /// + /// Zoom To Fit + /// + void + LabelEditor::zoomToFit() { double wPixels = mScrollArea->maximumViewportSize().width(); double hPixels = mScrollArea->maximumViewportSize().height(); @@ -1231,20 +252,1002 @@ void LabelEditor::onModelSizeChanged() newZoom = qMin( newZoom, zoomLevels[0] ); newZoom = qMax( newZoom, zoomLevels[nZoomLevels-1] ); - mZoom = newZoom; + setZoomReal( newZoom, true ); } - /* Actual scale depends on DPI of display (assume DpiX == DpiY). */ - mScale = mZoom * physicalDpiX() / PTS_PER_INCH; - setMinimumSize( mScale*mModel->w().pt() + ZOOM_TO_FIT_PAD, - mScale*mModel->h().pt() + ZOOM_TO_FIT_PAD ); + /// + /// Is Zoom at Maximum? + /// + bool + LabelEditor::isZoomMax() const + { + return mZoom >= zoomLevels[0]; + } - /* Adjust origin to center label in widget. */ - mX0 = (width()/mScale - mModel->w()) / 2; - mY0 = (height()/mScale - mModel->h()) / 2; - update(); + /// + /// Is Zoom at Minimum? + /// + bool + LabelEditor::isZoomMin() const + { + return mZoom <= zoomLevels[nZoomLevels-1]; + } + + + /// + /// Set Zoom to Value + /// + void + LabelEditor::setZoomReal( double zoom, bool zoomToFitFlag ) + { + mZoom = zoom; + mZoomToFitFlag = zoomToFitFlag; + + /* Actual scale depends on DPI of display (assume DpiX == DpiY). */ + mScale = zoom * physicalDpiX() / PTS_PER_INCH; + + setMinimumSize( mScale*mModel->w().pt() + ZOOM_TO_FIT_PAD, + mScale*mModel->h().pt() + ZOOM_TO_FIT_PAD ); + + /* Adjust origin to center label in widget. */ + mX0 = (width()/mScale - mModel->w()) / 2; + mY0 = (height()/mScale - mModel->h()) / 2; + + update(); + + emit zoomChanged(); + } + + + /// + /// Arrow mode (normal mode) + /// + void + LabelEditor::arrowMode() + { + setCursor( Qt::ArrowCursor ); + + mState = IdleState; + } + + + /// + /// Create box mode + /// + void + LabelEditor::createBoxMode() + { + setCursor( Cursors::Box() ); + + mCreateObjectType = Box; + mState = CreateIdle; + } + + + /// + /// Create ellipse mode + /// + void + LabelEditor::createEllipseMode() + { + setCursor( Cursors::Ellipse() ); + + mCreateObjectType = Ellipse; + mState = CreateIdle; + } + + + /// + /// Create image mode + /// + void + LabelEditor::createImageMode() + { + setCursor( Cursors::Image() ); + + mCreateObjectType = Image; + mState = CreateIdle; + } + + + /// + /// Create line mode + /// + void + LabelEditor::createLineMode() + { + setCursor( Cursors::Line() ); + + mCreateObjectType = Line; + mState = CreateIdle; + } + + + /// + /// Create text mode + /// + void + LabelEditor::createTextMode() + { + setCursor( Cursors::Text() ); + + mCreateObjectType = Text; + mState = CreateIdle; + } + + + /// + /// Resize Event Handler + /// + void + LabelEditor::resizeEvent( QResizeEvent *event ) + { + if ( mModel ) + { + if ( mZoomToFitFlag ) + { + zoomToFit(); + } + else + { + /* Re-adjust origin to center label in widget. */ + mX0 = (width()/mScale - mModel->w()) / 2; + mY0 = (height()/mScale - mModel->h()) / 2; + + update(); + } + } + } + + + /// + /// Mouse Button Press Event Handler + /// + void + LabelEditor::mousePressEvent( QMouseEvent* event ) + { + if ( mModel ) + { + /* + * Transform to label coordinates + */ + QTransform transform; + + transform.scale( mScale, mScale ); + transform.translate( mX0.pt(), mY0.pt() ); + + QPointF pWorld = transform.inverted().map( event->pos() ); + Distance xWorld = Distance::pt( pWorld.x() ); + Distance yWorld = Distance::pt( pWorld.y() ); + + + if ( event->button() & Qt::LeftButton ) + { + // + // LEFT BUTTON + // + switch (mState) + { + + case IdleState: + { + LabelModelObject* object = 0; + Handle* handle = 0; + if ( mModel->isSelectionAtomic() && + (handle = mModel->handleAt( mScale, xWorld, yWorld )) != 0 ) + { + // + // Start an object resize + // + mResizeObject = handle->owner(); + mResizeHandle = handle; + mResizeHonorAspect = event->modifiers() & Qt::ControlModifier; + + mState = ArrowResize; + } + else if ( (object = mModel->objectAt( mScale, xWorld, yWorld )) != 0 ) + { + // + // Start a Move Selection (adjusting selection if necessary) + // + if ( event->modifiers() & Qt::ControlModifier ) + { + if ( object->isSelected() ) + { + // Un-selecting a selected item + mModel->unselectObject( object ); + } + else + { + // Add to current selection + mModel->selectObject( object ); + } + } + else + { + if ( !object->isSelected() ) + { + // Replace current selection with this object + mModel->unselectAll(); + mModel->selectObject( object ); + } + } + + mMoveLastX = xWorld; + mMoveLastY = yWorld; + + mState = ArrowMove; + } + else + { + // + // Start a Select Region + // + if ( !(event->modifiers() & Qt::ControlModifier) ) + { + mModel->unselectAll(); + } + + mSelectRegionVisible = true; + mSelectRegion.setX1( xWorld ); + mSelectRegion.setY1( yWorld ); + mSelectRegion.setX2( xWorld ); + mSelectRegion.setY2( yWorld ); + + mState = ArrowSelectRegion; + update(); + } + } + break; + + + case CreateIdle: + { + switch ( mCreateObjectType ) + { + case Box: + mCreateObject = new LabelModelBoxObject(); + break; + case Ellipse: + mCreateObject = new LabelModelEllipseObject(); + break; + case Line: + mCreateObject = new LabelModelLineObject(); + break; + case Image: + mCreateObject = new LabelModelImageObject(); + break; + case Text: + mCreateObject = new LabelModelTextObject(); + break; + case Barcode: + // mCreateObject = new LabelModelBarcodeObject(); + break; + default: + qDebug() << "LabelEditor::mousePressEvent: Invalid creation type. Should not happen!"; + break; + } + + mCreateObject->setPosition( xWorld, yWorld ); + mCreateObject->setSize( 0, 0 ); + mModel->addObject( mCreateObject ); + + mModel->unselectAll(); + mModel->selectObject( mCreateObject ); + + mCreateX0 = xWorld; + mCreateY0 = yWorld; + + mState = CreateDrag; + } + break; + + + default: + { + qDebug() << "LabelEditor::mousePressEvent: Invalid state. Should not happen!"; + } + break; + + } + + } + else if ( event->button() & Qt::RightButton ) + { + // + // RIGHT BUTTON + // + if ( mState == IdleState ) + { + emit contextMenuActivate(); + } + } + } + } + + + /// + /// Mouse Movement Event Handler + /// + void + LabelEditor::mouseMoveEvent( QMouseEvent* event ) + { + if ( mModel ) + { + /* + * Transform to label coordinates + */ + QTransform transform; + + transform.scale( mScale, mScale ); + transform.translate( mX0.pt(), mY0.pt() ); + + QPointF pWorld = transform.inverted().map( event->pos() ); + Distance xWorld = Distance::pt( pWorld.x() ); + Distance yWorld = Distance::pt( pWorld.y() ); + + + /* + * Emit signal regardless of mode + */ + emit pointerMoved( xWorld, yWorld ); + + + /* + * Handle event as appropriate for state + */ + switch (mState) + { + + case IdleState: + if ( mModel->isSelectionAtomic() && + mModel->handleAt( mScale, xWorld, yWorld ) ) + { + setCursor( Qt::CrossCursor ); + } + else if ( mModel->objectAt( mScale, xWorld, yWorld ) ) + { + setCursor( Qt::SizeAllCursor ); + } + else + { + setCursor( Qt::ArrowCursor ); + } + break; + + case ArrowSelectRegion: + mSelectRegion.setX2( xWorld ); + mSelectRegion.setY2( yWorld ); + update(); + break; + + case ArrowMove: + mUndoRedoModel->checkpoint( tr("Move") ); + mModel->moveSelection( (xWorld - mMoveLastX), + (yWorld - mMoveLastY) ); + mMoveLastX = xWorld; + mMoveLastY = yWorld; + break; + + case ArrowResize: + handleResizeMotion( xWorld, yWorld ); + break; + + case CreateIdle: + break; + + case CreateDrag: + switch (mCreateObjectType) + { + case Box: + case Ellipse: + case Image: + case Text: + case Barcode: + mCreateObject->setPosition( min( xWorld, mCreateX0 ), + min( yWorld, mCreateY0 ) ); + mCreateObject->setSize( max(xWorld,mCreateX0) - min(xWorld,mCreateX0), + max(yWorld,mCreateY0) - min(yWorld,mCreateY0) ); + + break; + case Line: + mCreateObject->setSize( xWorld - mCreateX0, yWorld - mCreateY0 ); + break; + default: + qDebug() << "LabelEditor::mouseMoveEvent: Invalid creation mode. Should not happen!"; + break; + } + break; + + default: + qDebug() << "LabelEditor::mouseMoveEvent: Invalid state. Should not happen!"; + break; + + } + } + } + + + /// + /// Mouse Button Release Event Handler + /// + void + LabelEditor::mouseReleaseEvent( QMouseEvent* event ) + { + if ( mModel ) + { + /* + * Transform to label coordinates + */ + QTransform transform; + + transform.scale( mScale, mScale ); + transform.translate( mX0.pt(), mY0.pt() ); + + QPointF pWorld = transform.inverted().map( event->pos() ); + Distance xWorld = Distance::pt( pWorld.x() ); + Distance yWorld = Distance::pt( pWorld.y() ); + + + if ( event->button() & Qt::LeftButton ) + { + // + // LEFT BUTTON Release + // + switch (mState) + { + + case ArrowResize: + mState = IdleState; + break; + + case ArrowSelectRegion: + mSelectRegionVisible = false; + mSelectRegion.setX2( xWorld ); + mSelectRegion.setY2( yWorld ); + + mModel->selectRegion( mSelectRegion ); + + mState = IdleState; + update(); + break; + + case CreateDrag: + if ( (fabs(mCreateObject->w()) < 4) && (fabs(mCreateObject->h()) < 4) ) + { + switch (mCreateObjectType) + { + case Text: + mCreateObject->setSize( 72, 36 ); + break; + case Line: + mCreateObject->setSize( 72, 0 ); + break; + default: + mCreateObject->setSize( 72, 72 ); + break; + } + } + + setCursor( Qt::ArrowCursor ); + mState = IdleState; + break; + + default: + mState = IdleState; + break; + + } + + } + } + } + + + /// + /// Leave Event Handler + /// + void + LabelEditor::leaveEvent( QEvent* event ) + { + if ( mModel ) + { + emit pointerExited(); + } + } + + + /// + /// Handle resize motion + /// + void + LabelEditor::handleResizeMotion( const Distance& xWorld, + const Distance& yWorld ) + { + QPointF p( xWorld.pt(), yWorld.pt() ); + Handle::Location location = mResizeHandle->location(); + + /* + * Change point to object relative coordinates + */ + p -= QPointF( mResizeObject->x0().pt(), mResizeObject->y0().pt() ); + p = mResizeObject->matrix().inverted().map( p ); + + /* + * Initialize origin and 2 corners in object relative coordinates. + */ + double x0 = 0.0; + double y0 = 0.0; + + double x1 = 0.0; + double y1 = 0.0; + + double x2 = mResizeObject->w().pt(); + double y2 = mResizeObject->h().pt(); + + /* + * Calculate new size + */ + double w, h; + switch ( location ) + { + case Handle::NW: + w = std::max( x2 - p.x(), 0.0 ); + h = std::max( y2 - p.y(), 0.0 ); + break; + case Handle::N: + w = x2 - x1; + h = std::max( y2 - p.y(), 0.0 ); + break; + case Handle::NE: + w = std::max( p.x() - x1, 0.0 ); + h = std::max( y2 - p.y(), 0.0 ); + break; + case Handle::E: + w = std::max( p.x() - x1, 0.0 ); + h = y2 - y1; + break; + case Handle::SE: + w = std::max( p.x() - x1, 0.0 ); + h = std::max( p.y() - y1, 0.0 ); + break; + case Handle::S: + w = x2 - x1; + h = std::max( p.y() - y1, 0.0 ); + break; + case Handle::SW: + w = std::max( x2 - p.x(), 0.0 ); + h = std::max( p.y() - y1, 0.0 ); + break; + case Handle::W: + w = std::max( x2 - p.x(), 0.0 ); + h = y2 - y1; + break; + case Handle::P1: + x1 = p.x(); + y1 = p.y(); + w = x2 - p.x(); + h = y2 - p.y(); + x0 = x0 + x1; + y0 = y0 + y1; + break; + case Handle::P2: + w = p.x() - x1; + h = p.y() - y1; + x0 = x0 + x1; + y0 = y0 + y1; + break; + default: + qDebug() << "LabelEditor::handleResizeMotion: Invalid Handle Location. Should not happen!"; + } + + /* + * Set size + */ + if ( !(location == Handle::P1) && !(location == Handle::P2) ) + { + if ( mResizeHonorAspect ) + { + switch ( location ) + { + case Handle::E: + case Handle::W: + mResizeObject->setWHonorAspect( Distance::pt(w) ); + break; + case Handle::N: + case Handle::S: + mResizeObject->setHHonorAspect( Distance::pt(h) ); + break; + default: + mResizeObject->setSizeHonorAspect( Distance::pt(w), + Distance::pt(h) ); + break; + } + } + else + { + mResizeObject->setSize( Distance::pt(w), + Distance::pt(h) ); + } + + /* + * Adjust origin, if needed. + */ + switch ( location ) + { + case Handle::NW: + x0 += x2 - mResizeObject->w().pt(); + y0 += y2 - mResizeObject->h().pt(); + break; + case Handle::N: + case Handle::NE: + y0 += y2 - mResizeObject->h().pt(); + break; + case Handle::W: + case Handle::SW: + x0 += x2 - mResizeObject->w().pt(); + break; + defaule: + break; + } + } + else + { + mResizeObject->setSize( Distance::pt(w), + Distance::pt(h) ); + } + + /* + * Put new origin back into world coordinates and set. + */ + QPointF p0( x0, y0 ); + p0 = mResizeObject->matrix().map( p0 ); + p0 += QPointF( mResizeObject->x0().pt(), mResizeObject->y0().pt() ); + mResizeObject->setPosition( Distance::pt(p0.x()), + Distance::pt(p0.y()) ); + } + + + /// + /// Key Press Event Handler + void + LabelEditor::keyPressEvent( QKeyEvent* event ) + { + if ( mState == IdleState ) + { + switch (event->key()) + { + + case Qt::Key_Left: + mUndoRedoModel->checkpoint( tr("Move") ); + mModel->moveSelection( -mStepSize, Distance(0) ); + break; + + case Qt::Key_Up: + mUndoRedoModel->checkpoint( tr("Move") ); + mModel->moveSelection( Distance(0), -mStepSize ); + break; + + case Qt::Key_Right: + mUndoRedoModel->checkpoint( tr("Move") ); + mModel->moveSelection( mStepSize, Distance(0) ); + break; + + case Qt::Key_Down: + mUndoRedoModel->checkpoint( tr("Move") ); + mModel->moveSelection( Distance(0), mStepSize ); + break; + + case Qt::Key_Delete: + mUndoRedoModel->checkpoint( tr("Delete") ); + mModel->deleteSelection(); + setCursor( Qt::ArrowCursor ); + break; + + default: + QWidget::keyPressEvent( event ); + break; + + } + } + else + { + QWidget::keyPressEvent( event ); + } + } + + + /// + /// Paint Event Handler + /// + void + LabelEditor::paintEvent( QPaintEvent* event ) + { + if ( mModel ) + { + QPainter painter( this ); + + painter.setRenderHint( QPainter::Antialiasing, true ); + painter.setRenderHint( QPainter::TextAntialiasing, true ); + painter.setRenderHint( QPainter::SmoothPixmapTransform, true ); + + /* Fill background before any transformations */ + painter.setBrush( QBrush( backgroundColor ) ); + painter.setPen( Qt::NoPen ); + painter.drawRect( rect() ); + + /* Transform. */ + painter.scale( mScale, mScale ); + painter.translate( mX0.pt(), mY0.pt() ); + + /* Now draw from the bottom layer up. */ + drawBgLayer( &painter ); + drawGridLayer( &painter ); + drawMarkupLayer( &painter ); + drawObjectsLayer( &painter ); + drawFgLayer( &painter ); + drawHighlightLayer( &painter ); + drawSelectRegionLayer( &painter ); + } + } + + + /// + /// Draw Background Layer + /// + void + LabelEditor::drawBgLayer( QPainter* painter ) + { + /* + * Draw shadow + */ + painter->save(); + + painter->setBrush( QBrush( shadowColor ) ); + painter->setPen( Qt::NoPen ); + + painter->translate( shadowOffsetPixels/mScale, shadowOffsetPixels/mScale ); + + if ( mModel->rotate() ) + { + painter->rotate( -90 ); + painter->translate( -mModel->frame()->w().pt(), 0 ); + } + painter->drawPath( mModel->frame()->path() ); + + painter->restore(); + + + /* + * Draw label + */ + painter->save(); + + painter->setBrush( QBrush( labelColor ) ); + painter->setPen( Qt::NoPen ); + + if ( mModel->rotate() ) + { + painter->rotate( -90 ); + painter->translate( -mModel->frame()->w().pt(), 0 ); + } + painter->drawPath( mModel->frame()->path() ); + + painter->restore(); + } + + + /// + /// Draw Grid Layer + /// + void + LabelEditor::drawGridLayer( QPainter* painter ) + { + if ( mGridVisible ) + { + Distance w = mModel->frame()->w(); + Distance h = mModel->frame()->h(); + + Distance x0, y0; + if ( dynamic_cast( mModel->frame() ) ) + { + x0 = gridSpacing; + y0 = gridSpacing; + } + else + { + /* round labels, adjust grid to line up with center of label. */ + x0 = fmod( w/2, gridSpacing ); + y0 = fmod( h/2, gridSpacing ); + } + + painter->save(); + if ( mModel->rotate() ) + { + painter->rotate( -90 ); + painter->translate( -mModel->frame()->w().pt(), 0 ); + } + + painter->setClipPath( mModel->frame()->path() ); + + QPen pen( gridLineColor, gridLineWidthPixels ); + pen.setCosmetic( true ); + painter->setPen( pen ); + + for ( Distance x = x0; x < w; x += gridSpacing ) + { + painter->drawLine( x.pt(), 0, x.pt(), h.pt() ); + } + + for ( Distance y = y0; y < h; y += gridSpacing ) + { + painter->drawLine( 0, y.pt(), w.pt(), y.pt() ); + } + + painter->restore(); + } + } + + + /// + /// Draw Markup Layer + /// + void + LabelEditor::drawMarkupLayer( QPainter* painter ) + { + if ( mMarkupVisible ) + { + painter->save(); + + QPen pen( markupLineColor, markupLineWidthPixels ); + pen.setCosmetic( true ); + + painter->setBrush( Qt::NoBrush ); + painter->setPen( pen ); + + if ( mModel->rotate() ) + { + painter->rotate( -90 ); + painter->translate( -mModel->frame()->w().pt(), 0 ); + } + + foreach( Markup* markup, mModel->frame()->markups() ) + { + painter->drawPath( markup->path() ); + } + + painter->restore(); + } + } + + + /// + /// Draw Objects Layer + /// + void + LabelEditor::drawObjectsLayer( QPainter* painter ) + { + mModel->draw( painter ); + } + + + /// + /// Draw Foreground Layer + /// + void + LabelEditor::drawFgLayer( QPainter* painter ) + { + /* + * Draw label outline + */ + painter->save(); + + QPen pen( labelOutlineColor, labelOutlineWidthPixels ); + pen.setCosmetic( true ); + painter->setBrush( QBrush( Qt::NoBrush ) ); + painter->setPen( pen ); + + if ( mModel->rotate() ) + { + painter->rotate( -90 ); + painter->translate( -mModel->frame()->w().pt(), 0 ); + } + painter->drawPath( mModel->frame()->path() ); + + painter->restore(); + } + + + /// + /// Draw Highlight Layer + /// + void + LabelEditor::drawHighlightLayer( QPainter* painter ) + { + painter->save(); + + foreach ( LabelModelObject* object, mModel->objectList() ) + { + if ( object->isSelected() ) + { + object->drawSelectionHighlight( painter, mScale ); + } + } + + painter->restore(); + } + + + /// + /// Draw Select Region Layer + /// + void + LabelEditor::drawSelectRegionLayer( QPainter* painter ) + { + if ( mSelectRegionVisible ) + { + painter->save(); + + QPen pen( selectRegionOutlineColor, selectRegionOutlineWidthPixels ); + pen.setCosmetic( true ); + painter->setBrush( selectRegionFillColor ); + painter->setPen( pen ); + + painter->drawRect( mSelectRegion.rect() ); + + painter->restore(); + } + + } + + + /// + /// Settings changed handler + /// + void LabelEditor::onSettingsChanged() + { + Units units = Settings::units(); + + mStepSize = Distance( units.resolution(), units ); + } + + + /// + /// Model size changed handler + /// + void LabelEditor::onModelSizeChanged() + { + if (mZoomToFitFlag) + { + double wPixels = mScrollArea->maximumViewportSize().width(); + double hPixels = mScrollArea->maximumViewportSize().height(); + + double x_scale = ( wPixels - ZOOM_TO_FIT_PAD ) / mModel->w().pt(); + double y_scale = ( hPixels - ZOOM_TO_FIT_PAD ) / mModel->h().pt(); + double newZoom = qMin( x_scale, y_scale ) * PTS_PER_INCH / physicalDpiX(); + + // Limits + newZoom = qMin( newZoom, zoomLevels[0] ); + newZoom = qMax( newZoom, zoomLevels[nZoomLevels-1] ); + + mZoom = newZoom; + } + + /* Actual scale depends on DPI of display (assume DpiX == DpiY). */ + mScale = mZoom * physicalDpiX() / PTS_PER_INCH; + + setMinimumSize( mScale*mModel->w().pt() + ZOOM_TO_FIT_PAD, + mScale*mModel->h().pt() + ZOOM_TO_FIT_PAD ); + + /* Adjust origin to center label in widget. */ + mX0 = (width()/mScale - mModel->w()) / 2; + mY0 = (height()/mScale - mModel->h()) / 2; + + update(); + + emit zoomChanged(); + } - emit zoomChanged(); } diff --git a/glabels/LabelEditor.h b/glabels/LabelEditor.h index 28cb7cb..60d997b 100644 --- a/glabels/LabelEditor.h +++ b/glabels/LabelEditor.h @@ -28,188 +28,194 @@ #include "Region.h" -// Forward References -class LabelModel; -class LabelModelObject; -class UndoRedoModel; -class Handle; - -/// -/// LabelEditor Widget -/// -class LabelEditor : public QWidget +namespace glabels { - Q_OBJECT - ///////////////////////////////////// - // Lifecycle - ///////////////////////////////////// -public: - LabelEditor( QScrollArea* scrollArea, QWidget* parent = 0 ); + // Forward References + class LabelModel; + class LabelModelObject; + class UndoRedoModel; + class Handle; - ///////////////////////////////////// - // Signals - ///////////////////////////////////// -signals: - void contextMenuActivate(); - void zoomChanged(); - void pointerMoved( const glabels::Distance& x, const glabels::Distance& y ); - void pointerExited(); - void modeChanged(); + /// + /// LabelEditor Widget + /// + class LabelEditor : public QWidget + { + Q_OBJECT + + ///////////////////////////////////// + // Lifecycle + ///////////////////////////////////// + public: + LabelEditor( QScrollArea* scrollArea, QWidget* parent = 0 ); - ///////////////////////////////////// - // Parameters - ///////////////////////////////////// -public: - double zoom() const; - bool markupVisible() const; - bool qridVisible() const; + ///////////////////////////////////// + // Signals + ///////////////////////////////////// + signals: + void contextMenuActivate(); + void zoomChanged(); + void pointerMoved( const Distance& x, const Distance& y ); + void pointerExited(); + void modeChanged(); - ///////////////////////////////////// - // Model - ///////////////////////////////////// -public: - void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); + ///////////////////////////////////// + // Parameters + ///////////////////////////////////// + public: + double zoom() const; + bool markupVisible() const; + bool qridVisible() const; - ///////////////////////////////////// - // Visibility operations - ///////////////////////////////////// -public: - void setGridVisible( bool visibleFlag ); - void setMarkupVisible( bool visibleFlag ); + ///////////////////////////////////// + // Model + ///////////////////////////////////// + public: + void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); - ///////////////////////////////////// - // Zoom operations - ///////////////////////////////////// -public: - void zoomIn(); - void zoomOut(); - void zoom1To1(); - void zoomToFit(); - bool isZoomMax() const; - bool isZoomMin() const; -private: - void setZoomReal( double zoom, bool zoomToFitFlag ); + ///////////////////////////////////// + // Visibility operations + ///////////////////////////////////// + public: + void setGridVisible( bool visibleFlag ); + void setMarkupVisible( bool visibleFlag ); - ///////////////////////////////////// - // Mode operations - ///////////////////////////////////// -public: - void arrowMode(); - void createBoxMode(); - void createEllipseMode(); - void createLineMode(); - void createImageMode(); - void createTextMode(); - void createBarcodeMode(); + ///////////////////////////////////// + // Zoom operations + ///////////////////////////////////// + public: + void zoomIn(); + void zoomOut(); + void zoom1To1(); + void zoomToFit(); + bool isZoomMax() const; + bool isZoomMin() const; + private: + void setZoomReal( double zoom, bool zoomToFitFlag ); - ///////////////////////////////////// - // Event handlers - ///////////////////////////////////// -protected: - void resizeEvent( QResizeEvent* event ); - void mousePressEvent( QMouseEvent* event ); - void mouseMoveEvent( QMouseEvent* event ); - void mouseReleaseEvent( QMouseEvent* event ); - void leaveEvent( QEvent* event ); - void keyPressEvent( QKeyEvent* event ); - void paintEvent( QPaintEvent* event ); + ///////////////////////////////////// + // Mode operations + ///////////////////////////////////// + public: + void arrowMode(); + void createBoxMode(); + void createEllipseMode(); + void createLineMode(); + void createImageMode(); + void createTextMode(); + void createBarcodeMode(); - ///////////////////////////////////// - // Private methods - ///////////////////////////////////// -private: - void handleResizeMotion( const glabels::Distance& xWorld, - const glabels::Distance& yWorld ); - - void drawBgLayer( QPainter* painter ); - void drawGridLayer( QPainter* painter ); - void drawMarkupLayer( QPainter* painter ); - void drawObjectsLayer( QPainter* painter ); - void drawFgLayer( QPainter* painter ); - void drawHighlightLayer( QPainter* painter ); - void drawSelectRegionLayer( QPainter* painter ); + ///////////////////////////////////// + // Event handlers + ///////////////////////////////////// + protected: + void resizeEvent( QResizeEvent* event ); + void mousePressEvent( QMouseEvent* event ); + void mouseMoveEvent( QMouseEvent* event ); + void mouseReleaseEvent( QMouseEvent* event ); + void leaveEvent( QEvent* event ); + void keyPressEvent( QKeyEvent* event ); + void paintEvent( QPaintEvent* event ); - ///////////////////////////////////// - // Private slots - ///////////////////////////////////// -private slots: - void onSettingsChanged(); - void onModelSizeChanged(); + ///////////////////////////////////// + // Private methods + ///////////////////////////////////// + private: + void handleResizeMotion( const Distance& xWorld, + const Distance& yWorld ); + + void drawBgLayer( QPainter* painter ); + void drawGridLayer( QPainter* painter ); + void drawMarkupLayer( QPainter* painter ); + void drawObjectsLayer( QPainter* painter ); + void drawFgLayer( QPainter* painter ); + void drawHighlightLayer( QPainter* painter ); + void drawSelectRegionLayer( QPainter* painter ); + + + ///////////////////////////////////// + // Private slots + ///////////////////////////////////// + private slots: + void onSettingsChanged(); + void onModelSizeChanged(); + + + ///////////////////////////////////// + // Private data + ///////////////////////////////////// + private: + enum State { + IdleState, + ArrowSelectRegion, + ArrowMove, + ArrowResize, + CreateIdle, + CreateDrag + }; + + enum CreateType { + Box, + Ellipse, + Line, + Image, + Text, + Barcode + }; + + QScrollArea* mScrollArea; + + double mZoom; + bool mZoomToFitFlag; + double mScale; + Distance mX0; + Distance mY0; + + bool mMarkupVisible; + bool mGridVisible; + + double mGridSpacing; + Distance mStepSize; + + LabelModel* mModel; + UndoRedoModel* mUndoRedoModel; + + State mState; + + /* ArrowSelectRegion state */ + bool mSelectRegionVisible; + Region mSelectRegion; + + /* ArrowMove state */ + Distance mMoveLastX; + Distance mMoveLastY; + + /* ArrowResize state */ + LabelModelObject* mResizeObject; + Handle* mResizeHandle; + bool mResizeHonorAspect; + + /* CreateDrag state */ + CreateType mCreateObjectType; + LabelModelObject* mCreateObject; + Distance mCreateX0; + Distance mCreateY0; - ///////////////////////////////////// - // Private data - ///////////////////////////////////// -private: - enum State { - IdleState, - ArrowSelectRegion, - ArrowMove, - ArrowResize, - CreateIdle, - CreateDrag }; - enum CreateType { - Box, - Ellipse, - Line, - Image, - Text, - Barcode - }; - - QScrollArea* mScrollArea; - - double mZoom; - bool mZoomToFitFlag; - double mScale; - glabels::Distance mX0; - glabels::Distance mY0; - - bool mMarkupVisible; - bool mGridVisible; - - double mGridSpacing; - glabels::Distance mStepSize; - - LabelModel* mModel; - UndoRedoModel* mUndoRedoModel; - - State mState; - - /* ArrowSelectRegion state */ - bool mSelectRegionVisible; - Region mSelectRegion; - - /* ArrowMove state */ - glabels::Distance mMoveLastX; - glabels::Distance mMoveLastY; - - /* ArrowResize state */ - LabelModelObject* mResizeObject; - Handle* mResizeHandle; - bool mResizeHonorAspect; - - /* CreateDrag state */ - CreateType mCreateObjectType; - LabelModelObject* mCreateObject; - glabels::Distance mCreateX0; - glabels::Distance mCreateY0; - - -}; +} #endif // LabelEditor_h diff --git a/glabels/LabelModel.cpp b/glabels/LabelModel.cpp index 4c16711..68ca518 100644 --- a/glabels/LabelModel.cpp +++ b/glabels/LabelModel.cpp @@ -35,1383 +35,1391 @@ #include "Merge/None.h" -namespace +namespace glabels { - const QString MIME_TYPE = "application/x-glabels-objects"; -} - -/// -/// Default constructor. -/// -LabelModel::LabelModel() : mUntitledInstance(0), mModified(true), mTmplate(0), mRotate(false) -{ - mMerge = new merge::None(); -} - - -/// -/// Save model state -/// -LabelModel* LabelModel::save() const -{ - LabelModel* savedModel = new LabelModel; - savedModel->restore( this ); - - return savedModel; -} - - -/// -/// Restore model state -/// -void LabelModel::restore( const LabelModel *savedModel ) -{ - // Clear current object list - foreach ( LabelModelObject* object, mObjectList ) + // + // Private + // + namespace { - delete object; + const QString MIME_TYPE = "application/x-glabels-objects"; } - mObjectList.clear(); - // Now copy state - mUntitledInstance = savedModel->mUntitledInstance; - mModified = savedModel->mModified; - mFileName = savedModel->mFileName; - mCompressionLevel = savedModel->mCompressionLevel; - mTmplate = savedModel->mTmplate; - mFrame = savedModel->mFrame; - mRotate = savedModel->mRotate; - foreach ( LabelModelObject* savedObject, savedModel->mObjectList ) + /// + /// Default constructor. + /// + LabelModel::LabelModel() : mUntitledInstance(0), mModified(true), mTmplate(0), mRotate(false) { - LabelModelObject* object = savedObject->clone(); + mMerge = new merge::None(); + } + + + /// + /// Save model state + /// + LabelModel* LabelModel::save() const + { + LabelModel* savedModel = new LabelModel; + savedModel->restore( this ); + + return savedModel; + } + + + /// + /// Restore model state + /// + void LabelModel::restore( const LabelModel *savedModel ) + { + // Clear current object list + foreach ( LabelModelObject* object, mObjectList ) + { + delete object; + } + mObjectList.clear(); + + // Now copy state + mUntitledInstance = savedModel->mUntitledInstance; + mModified = savedModel->mModified; + mFileName = savedModel->mFileName; + mCompressionLevel = savedModel->mCompressionLevel; + mTmplate = savedModel->mTmplate; + mFrame = savedModel->mFrame; + mRotate = savedModel->mRotate; + + foreach ( LabelModelObject* savedObject, savedModel->mObjectList ) + { + LabelModelObject* object = savedObject->clone(); + object->setParent( this ); + mObjectList << object; + + connect( object, SIGNAL(changed()), this, SLOT(onObjectChanged()) ); + connect( object, SIGNAL(moved()), this, SLOT(onObjectMoved()) ); + } + + delete mMerge; + mMerge = savedModel->mMerge->clone(); + + // Emit signals based on potential changes + emit changed(); + emit selectionChanged(); + emit modifiedChanged(); + emit nameChanged(); + emit sizeChanged(); + emit mergeChanged(); + emit mergeSourceChanged(); + emit mergeSelectionChanged(); + } + + + /// + /// Is model modified? + /// + bool LabelModel::isModified() const + { + return mModified; + } + + + /// + /// Get filename + /// + const QString& LabelModel::fileName() const + { + return mFileName; + } + + + /// + /// Set filename + /// + void LabelModel::setFileName( const QString &fileName ) + { + if ( mFileName != fileName ) + { + mFileName = fileName; + emit nameChanged(); + } + } + + + /// + /// Get compression level + /// + int LabelModel::compressionLevel() const + { + return mCompressionLevel; + } + + + /// + /// Set compression level + /// + void LabelModel::setCompressionLevel( int compressionLevel ) + { + mCompressionLevel = compressionLevel; + } + + + /// + /// Get template + /// + const Template* LabelModel::tmplate() const + { + return mTmplate; + } + + + /// + /// Get frame + /// + const Frame* LabelModel::frame() const + { + return mFrame; + } + + + /// + /// Set template + /// + void LabelModel::setTmplate( const Template* tmplate ) + { + if (mTmplate != tmplate) + { + mTmplate = tmplate; + mFrame = tmplate->frames().first(); + + setModified(); + + emit changed(); + emit sizeChanged(); + + Settings::addToRecentTemplateList( tmplate->name() ); + } + } + + + /// + /// Get rotation + /// + bool LabelModel::rotate() const + { + return mRotate; + } + + + /// + /// Set rotation + /// + void LabelModel::setRotate( bool rotate ) + { + if (mRotate != rotate) + { + mRotate = rotate; + + setModified(); + + emit changed(); + emit sizeChanged(); + } + } + + + /// + /// Get width + /// + Distance LabelModel::w() const + { + return mRotate ? mFrame->h() : mFrame->w(); + } + + + /// + /// Get height + /// + Distance LabelModel::h() const + { + return mRotate ? mFrame->w() : mFrame->h(); + } + + + /// + /// Get object list + /// + const QList& LabelModel::objectList() const + { + return mObjectList; + } + + + /// + /// Get short name. + /// + QString LabelModel::shortName() + { + static int untitledCount = 0; + + if ( mFileName.isEmpty() ) + { + if ( mUntitledInstance == 0 ) + { + mUntitledInstance = ++untitledCount; + } + QString numString; + numString.setNum(mUntitledInstance);; + + return tr("Untitled") + numString; + } + else + { + QFileInfo fileInfo( mFileName ); + return fileInfo.baseName(); + } + } + + + /// + /// Get merge object + /// + merge::Merge* LabelModel::merge() const + { + return mMerge; + } + + + /// + /// Set merge object + /// + void LabelModel::setMerge( merge::Merge* merge ) + { + if ( merge != mMerge ) + { + delete mMerge; + mMerge = merge; + + connect( mMerge, SIGNAL(sourceChanged()), this, SLOT(onMergeSourceChanged()) ); + connect( mMerge, SIGNAL(selectionChanged()), this, SLOT(onMergeSelectionChanged()) ); + + setModified(); + + emit changed(); + emit mergeChanged(); + emit mergeSourceChanged(); + } + } + + + /// + /// Set modified status + /// + void LabelModel::setModified() + { + mModified = true; + emit modifiedChanged(); + } + + + /// + /// Clear modified status + /// + void LabelModel::clearModified() + { + mModified = false; + emit modifiedChanged(); + } + + + /// + /// Add object. + /// + void LabelModel::addObject( LabelModelObject* object ) + { object->setParent( this ); mObjectList << object; connect( object, SIGNAL(changed()), this, SLOT(onObjectChanged()) ); connect( object, SIGNAL(moved()), this, SLOT(onObjectMoved()) ); - } - - delete mMerge; - mMerge = savedModel->mMerge->clone(); - - // Emit signals based on potential changes - emit changed(); - emit selectionChanged(); - emit modifiedChanged(); - emit nameChanged(); - emit sizeChanged(); - emit mergeChanged(); - emit mergeSourceChanged(); - emit mergeSelectionChanged(); -} - - -/// -/// Is model modified? -/// -bool LabelModel::isModified() const -{ - return mModified; -} - - -/// -/// Get filename -/// -const QString& LabelModel::fileName() const -{ - return mFileName; -} - - -/// -/// Set filename -/// -void LabelModel::setFileName( const QString &fileName ) -{ - if ( mFileName != fileName ) - { - mFileName = fileName; - emit nameChanged(); - } -} - - -/// -/// Get compression level -/// -int LabelModel::compressionLevel() const -{ - return mCompressionLevel; -} - - -/// -/// Set compression level -/// -void LabelModel::setCompressionLevel( int compressionLevel ) -{ - mCompressionLevel = compressionLevel; -} - - -/// -/// Get template -/// -const glabels::Template* LabelModel::tmplate() const -{ - return mTmplate; -} - - -/// -/// Get frame -/// -const glabels::Frame* LabelModel::frame() const -{ - return mFrame; -} - - -/// -/// Set template -/// -void LabelModel::setTmplate( const glabels::Template* tmplate ) -{ - if (mTmplate != tmplate) - { - mTmplate = tmplate; - mFrame = tmplate->frames().first(); - - setModified(); - - emit changed(); - emit sizeChanged(); - - Settings::addToRecentTemplateList( tmplate->name() ); - } -} - - -/// -/// Get rotation -/// -bool LabelModel::rotate() const -{ - return mRotate; -} - - -/// -/// Set rotation -/// -void LabelModel::setRotate( bool rotate ) -{ - if (mRotate != rotate) - { - mRotate = rotate; setModified(); emit changed(); - emit sizeChanged(); - } -} - - -/// -/// Get width -/// -glabels::Distance LabelModel::w() const -{ - return mRotate ? mFrame->h() : mFrame->w(); -} - - -/// -/// Get height -/// -glabels::Distance LabelModel::h() const -{ - return mRotate ? mFrame->w() : mFrame->h(); -} - - -/// -/// Get object list -/// -const QList& LabelModel::objectList() const -{ - return mObjectList; -} - - -/// -/// Get short name. -/// -QString LabelModel::shortName() -{ - static int untitledCount = 0; - - if ( mFileName.isEmpty() ) - { - if ( mUntitledInstance == 0 ) - { - mUntitledInstance = ++untitledCount; - } - QString numString; - numString.setNum(mUntitledInstance);; - - return tr("Untitled") + numString; - } - else - { - QFileInfo fileInfo( mFileName ); - return fileInfo.baseName(); - } -} - - -/// -/// Get merge object -/// -merge::Merge* LabelModel::merge() const -{ - return mMerge; -} - - -/// -/// Set merge object -/// -void LabelModel::setMerge( merge::Merge* merge ) -{ - if ( merge != mMerge ) - { - delete mMerge; - mMerge = merge; - - connect( mMerge, SIGNAL(sourceChanged()), this, SLOT(onMergeSourceChanged()) ); - connect( mMerge, SIGNAL(selectionChanged()), this, SLOT(onMergeSelectionChanged()) ); - - setModified(); - - emit changed(); - emit mergeChanged(); - emit mergeSourceChanged(); - } -} - - -/// -/// Set modified status -/// -void LabelModel::setModified() -{ - mModified = true; - emit modifiedChanged(); -} - - -/// -/// Clear modified status -/// -void LabelModel::clearModified() -{ - mModified = false; - emit modifiedChanged(); -} - - -/// -/// Add object. -/// -void LabelModel::addObject( LabelModelObject* object ) -{ - object->setParent( this ); - mObjectList << object; - - connect( object, SIGNAL(changed()), this, SLOT(onObjectChanged()) ); - connect( object, SIGNAL(moved()), this, SLOT(onObjectMoved()) ); - - setModified(); - - emit changed(); -} - - -/// -/// Delete Object -/// -void LabelModel::deleteObject( LabelModelObject* object ) -{ - object->unselect(); - mObjectList.removeOne( object ); - - disconnect( object, 0, this, 0 ); - - setModified(); - - emit changed(); - - delete object; -} - - -/// -/// Object at x,y -/// -LabelModelObject* LabelModel::objectAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const -{ - /* Search object list in reverse order. I.e. from top to bottom. */ - QList::const_iterator it = mObjectList.end(); - while ( it != mObjectList.begin() ) - { - it--; - LabelModelObject* object = *it; - if ( object->isLocatedAt( scale, x, y ) ) - { - return object; - } } - return 0; -} - -/// -/// Handle at x,y -/// -Handle* LabelModel::handleAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const -{ - foreach( LabelModelObject* object, mObjectList ) - { - Handle* handle = object->handleAt( scale, x, y ); - if ( handle ) - { - return handle; - } - } - - return 0; -} - - -/// -/// Object Changed Slot -/// -void LabelModel::onObjectChanged() -{ - setModified(); - emit changed(); -} - - -/// -/// Object Moved Slot -/// -void LabelModel::onObjectMoved() -{ - setModified(); - emit changed(); -} - - -/// -/// Merge Source Changed Slot -/// -void LabelModel::onMergeSourceChanged() -{ - setModified(); - emit changed(); - emit mergeSourceChanged(); -} - - -/// -/// Merge Selection Changed Slot -/// -void LabelModel::onMergeSelectionChanged() -{ - emit changed(); - emit mergeSelectionChanged(); -} - - -/// -/// Select Object -/// -void LabelModel::selectObject( LabelModelObject* object ) -{ - object->select(); - - emit selectionChanged(); -} - - -/// -/// Unselect Object -/// -void LabelModel::unselectObject( LabelModelObject* object ) -{ - object->unselect(); - - emit selectionChanged(); -} - - -/// -/// Select All Objects -/// -void LabelModel::selectAll() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - object->select(); - } - - emit selectionChanged(); -} - - -/// -/// Unselect All Objects -/// -void LabelModel::unselectAll() -{ - foreach ( LabelModelObject* object, mObjectList ) + /// + /// Delete Object + /// + void LabelModel::deleteObject( LabelModelObject* object ) { object->unselect(); + mObjectList.removeOne( object ); + + disconnect( object, 0, this, 0 ); + + setModified(); + + emit changed(); + + delete object; } - emit selectionChanged(); -} - -/// -/// Select Region -/// -void LabelModel::selectRegion( const Region ®ion ) -{ - glabels::Distance rX1 = min( region.x1(), region.x2() ); - glabels::Distance rY1 = min( region.y1(), region.y2() ); - glabels::Distance rX2 = max( region.x1(), region.x2() ); - glabels::Distance rY2 = max( region.y1(), region.y2() ); - - foreach ( LabelModelObject* object, mObjectList ) + /// + /// Object at x,y + /// + LabelModelObject* LabelModel::objectAt( double scale, + const Distance& x, + const Distance& y ) const { - Region objectExtent = object->getExtent(); + /* Search object list in reverse order. I.e. from top to bottom. */ + QList::const_iterator it = mObjectList.end(); + while ( it != mObjectList.begin() ) + { + it--; + LabelModelObject* object = *it; + if ( object->isLocatedAt( scale, x, y ) ) + { + return object; + } + } - if ( (objectExtent.x1() >= rX1) && - (objectExtent.x2() <= rX2) && - (objectExtent.y1() >= rY1) && - (objectExtent.y2() <= rY2) ) + return 0; + } + + + /// + /// Handle at x,y + /// + Handle* LabelModel::handleAt( double scale, + const Distance& x, + const Distance& y ) const + { + foreach( LabelModelObject* object, mObjectList ) + { + Handle* handle = object->handleAt( scale, x, y ); + if ( handle ) + { + return handle; + } + } + + return 0; + } + + + /// + /// Object Changed Slot + /// + void LabelModel::onObjectChanged() + { + setModified(); + emit changed(); + } + + + /// + /// Object Moved Slot + /// + void LabelModel::onObjectMoved() + { + setModified(); + emit changed(); + } + + + /// + /// Merge Source Changed Slot + /// + void LabelModel::onMergeSourceChanged() + { + setModified(); + emit changed(); + emit mergeSourceChanged(); + } + + + /// + /// Merge Selection Changed Slot + /// + void LabelModel::onMergeSelectionChanged() + { + emit changed(); + emit mergeSelectionChanged(); + } + + + /// + /// Select Object + /// + void LabelModel::selectObject( LabelModelObject* object ) + { + object->select(); + + emit selectionChanged(); + } + + + /// + /// Unselect Object + /// + void LabelModel::unselectObject( LabelModelObject* object ) + { + object->unselect(); + + emit selectionChanged(); + } + + + /// + /// Select All Objects + /// + void LabelModel::selectAll() + { + foreach ( LabelModelObject* object, mObjectList ) { object->select(); } + + emit selectionChanged(); } - emit selectionChanged(); -} - -/// -/// Is Selection Empty? -/// -bool LabelModel::isSelectionEmpty() -{ - foreach ( LabelModelObject* object, mObjectList ) + /// + /// Unselect All Objects + /// + void LabelModel::unselectAll() { - if ( object->isSelected() ) + foreach ( LabelModelObject* object, mObjectList ) { - return false; + object->unselect(); } + + emit selectionChanged(); } - return true; -} - -/// -/// Is Selection Atomic? -/// -bool LabelModel::isSelectionAtomic() -{ - int nSelected = 0; - - foreach ( LabelModelObject* object, mObjectList ) + /// + /// Select Region + /// + void LabelModel::selectRegion( const Region ®ion ) { - if ( object->isSelected() ) + Distance rX1 = min( region.x1(), region.x2() ); + Distance rY1 = min( region.y1(), region.y2() ); + Distance rX2 = max( region.x1(), region.x2() ); + Distance rY2 = max( region.y1(), region.y2() ); + + foreach ( LabelModelObject* object, mObjectList ) { - nSelected++; - if ( nSelected > 1 ) + Region objectExtent = object->getExtent(); + + if ( (objectExtent.x1() >= rX1) && + (objectExtent.x2() <= rX2) && + (objectExtent.y1() >= rY1) && + (objectExtent.y2() <= rY2) ) + { + object->select(); + } + } + + emit selectionChanged(); + } + + + /// + /// Is Selection Empty? + /// + bool LabelModel::isSelectionEmpty() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) { return false; } } - } - return nSelected == 1; -} - - -/// -/// Get List of Selected Objects -/// -QList LabelModel::getSelection() -{ - QList selectedList; - - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - selectedList << object; - } - } - - return selectedList; -} - - -/// -/// Get First Object in Selection List -/// -LabelModelObject* LabelModel::getFirstSelectedObject() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - return object; - } - } -} - - -/// -/// Can Any Objects in Selection Accept Text Properties? -/// -bool LabelModel::canSelectionText() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() && object->canText() ) - { - return true; - } - } - - return false; -} - - -/// -/// Can Any Objects in Selection Accept Fill Property? -/// -bool LabelModel::canSelectionFill() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() && object->canFill() ) - { - return true; - } - } - - return false; -} - - -/// -/// Can Any Objects in Selection Accept Line Color Property? -/// -bool LabelModel::canSelectionLineColor() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() && object->canLineColor() ) - { - return true; - } - } - - return false; -} - - -/// -/// Can Any Objects in Selection Accept Line Width Property? -/// -bool LabelModel::canSelectionLineWidth() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() && object->canLineWidth() ) - { - return true; - } - } - - return false; -} - - -/// -/// Delete Selected Objects -/// -void LabelModel::deleteSelection() -{ - QList selectedList = getSelection(); - - foreach ( LabelModelObject* object, selectedList ) - { - deleteObject( object ); - } - - setModified(); - - emit changed(); - emit selectionChanged(); -} - - -/// -/// Raise Selected Objects To Top -/// -void LabelModel::raiseSelectionToTop() -{ - QList selectedList = getSelection(); - - foreach ( LabelModelObject* object, selectedList ) - { - mObjectList.removeOne( object ); - } - - /// Move to end of list, representing top most object. - foreach ( LabelModelObject* object, selectedList ) - { - mObjectList.push_back( object ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Lower Selected Objects To Bottom -/// -void LabelModel::lowerSelectionToBottom() -{ - QList selectedList = getSelection(); - - foreach ( LabelModelObject* object, selectedList ) - { - mObjectList.removeOne( object ); - } - - /// Move to front of list, representing bottom most object. - foreach ( LabelModelObject* object, selectedList ) - { - mObjectList.push_front( object ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Rotate Selected Objects -/// -void LabelModel::rotateSelection( double thetaDegs ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->rotate( thetaDegs ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Rotate Selected Objects Left 90 degrees -/// -void LabelModel::rotateSelectionLeft() -{ - rotateSelection( -90.0 ); -} - - -/// -/// Rotate Selected Objects Right 90 degrees -/// -void LabelModel::rotateSelectionRight() -{ - rotateSelection( 90.0 ); -} - - -/// -/// Flip Selected Objects Horizontally -/// -void LabelModel::flipSelectionHoriz() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->flipHoriz(); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Flip Selected Objects Vertically -/// -void LabelModel::flipSelectionVert() -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->flipVert(); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Left Edges -/// -void LabelModel::alignSelectionLeft() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find left-most edge. - glabels::Distance x1_min = 7200; /// Start with a very large value: 7200pts = 100in - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - if ( r.x1() < x1_min ) x1_min = r.x1(); - } - - /// Now adjust the object positions to line up the left edges at left-most edge. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dx = x1_min - r.x1(); - object->setPositionRelative( dx, 0 ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Right Edges -/// -void LabelModel::alignSelectionRight() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find right-most edge. - glabels::Distance x1_max = -7200; /// Start with a very large negative value: 7200pts = 100in - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - if ( r.x1() > x1_max ) x1_max = r.x1(); - } - - /// Now adjust the object positions to line up the right edges at right-most edge. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dx = x1_max - r.x1(); - object->setPositionRelative( dx, 0 ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Horizontal Centers -/// -void LabelModel::alignSelectionHCenter() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find average center of objects. - glabels::Distance xsum = 0; - int n = 0; - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - xsum += (r.x1() + r.x2()) / 2.0; - n++; - } - glabels::Distance xavg = xsum / n; - - /// Find object closest to average center of objects. - glabels::Distance xcenter = 7200; /// Start with very large value. - glabels::Distance dxmin = fabs( xavg - xcenter ); - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dx = fabs( xavg - (r.x1() + r.x2())/2.0 ); - if ( dx < dxmin ) - { - dxmin = dx; - xcenter = (r.x1() + r.x2()) / 2.0; - } - } - - /// Now adjust the object positions to line up with the center of this object. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dx = xcenter - (r.x1() + r.x2())/2.0; - object->setPositionRelative( dx, 0 ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Top Edges -/// -void LabelModel::alignSelectionTop() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find top-most edge. - glabels::Distance y1_min = 7200; /// Start with a very large value: 7200pts = 100in - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - if ( r.y1() < y1_min ) y1_min = r.y1(); - } - - /// Now adjust the object positions to line up the top edges at top-most edge. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dy = y1_min - r.y1(); - object->setPositionRelative( 0, dy ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Bottom Edges -/// -void LabelModel::alignSelectionBottom() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find bottom-most edge. - glabels::Distance y1_max = -7200; /// Start with a very large negative value: 7200pts = 100in - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - if ( r.y1() > y1_max ) y1_max = r.y1(); - } - - /// Now adjust the object positions to line up the bottom edges at bottom-most edge. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dy = y1_max - r.y1(); - object->setPositionRelative( 0, dy ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Their Vertical Centers Edges -/// -void LabelModel::alignSelectionVCenter() -{ - if ( isSelectionEmpty() || isSelectionAtomic() ) - { - return; - } - - QList selectedList = getSelection(); - - /// Find average center of objects. - glabels::Distance ysum = 0; - int n = 0; - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - ysum += (r.y1() + r.y2()) / 2.0; - n++; - } - glabels::Distance yavg = ysum / n; - - /// Find object closest to average center of objects. - glabels::Distance ycenter = 7200; /// Start with very large value. - glabels::Distance dymin = fabs( yavg - ycenter ); - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dy = fabs( yavg - (r.y1() + r.y2())/2.0 ); - if ( dy < dymin ) - { - dymin = dy; - ycenter = (r.y1() + r.y2()) / 2.0; - } - } - - /// Now adjust the object positions to line up with the center of this object. - foreach ( LabelModelObject* object, selectedList ) - { - Region r = object->getExtent(); - glabels::Distance dy = ycenter - (r.y1() + r.y2())/2.0; - object->setPositionRelative( 0, dy ); - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Center Of Label Horizontally -/// -void LabelModel::centerSelectionHoriz() -{ - glabels::Distance xLabelCenter = w() / 2.0; - - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - Region r = object->getExtent(); - glabels::Distance xObjectCenter = (r.x1() + r.x2()) / 2.0; - glabels::Distance dx = xLabelCenter - xObjectCenter; - object->setPositionRelative( dx, 0 ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Align Selected Objects To Center Of Label Vertically -/// -void LabelModel::centerSelectionVert() -{ - glabels::Distance yLabelCenter = h() / 2.0; - - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - Region r = object->getExtent(); - glabels::Distance yObjectCenter = (r.y1() + r.y2()) / 2.0; - glabels::Distance dy = yLabelCenter - yObjectCenter; - object->setPositionRelative( 0, dy ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Move Selected Objects By dx,dy -/// -void LabelModel::moveSelection( const glabels::Distance& dx, const glabels::Distance& dy ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setPositionRelative( dx, dy ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Font Family Of Selected Objects -/// -void LabelModel::setSelectionFontFamily( const QString &fontFamily ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setFontFamily( fontFamily ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Font Size Of Selected Objects -/// -void LabelModel::setSelectionFontSize( double fontSize ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setFontSize( fontSize ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Font Weight Of Selected Objects -/// -void LabelModel::setSelectionFontWeight( QFont::Weight fontWeight ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setFontWeight( fontWeight ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Font Italic Flag Of Selected Objects -/// -void LabelModel::setSelectionFontItalicFlag( bool fontItalicFlag ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setFontItalicFlag( fontItalicFlag ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Text Horizontal Alignment Of Selected Objects -/// -void LabelModel::setSelectionTextHAlign( Qt::Alignment textHAlign ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setTextHAlign( textHAlign ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Text Vertical Alignment Of Selected Objects -/// -void LabelModel::setSelectionTextVAlign( Qt::Alignment textVAlign ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setTextVAlign( textVAlign ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Text Line Spacing Of Selected Objects -/// -void LabelModel::setSelectionTextLineSpacing( double textLineSpacing ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setTextLineSpacing( textLineSpacing ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Text Color Node Of Selected Objects -/// -void LabelModel::setSelectionTextColorNode( ColorNode textColorNode ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setTextColorNode( textColorNode ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Line Width Of Selected Objects -/// -void LabelModel::setSelectionLineWidth( const glabels::Distance& lineWidth ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setLineWidth( lineWidth ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Line Color Node Of Selected Objects -/// -void LabelModel::setSelectionLineColorNode( ColorNode lineColorNode ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setLineColorNode( lineColorNode ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Set Fill Color Node Of Selected Objects -/// -void LabelModel::setSelectionFillColorNode( ColorNode fillColorNode ) -{ - foreach ( LabelModelObject* object, mObjectList ) - { - if ( object->isSelected() ) - { - object->setFillColorNode( fillColorNode ); - } - } - - setModified(); - - emit changed(); -} - - -/// -/// Copy selection to clipboard -/// -void LabelModel::copySelection() -{ - if ( !isSelectionEmpty() ) - { - QClipboard *clipboard = QApplication::clipboard(); - - QByteArray buffer; - XmlLabelCreator::serializeObjects( getSelection(), buffer ); - - QMimeData *mimeData = new QMimeData; - mimeData->setData( MIME_TYPE, buffer ); - - clipboard->setMimeData( mimeData ); - } -} - - -/// -/// Cut selection to clipboard -/// -void LabelModel::cutSelection() -{ - copySelection(); - deleteSelection(); -} - - -/// -/// Can we paste? -/// -bool LabelModel::canPaste() -{ - const QClipboard *clipboard = QApplication::clipboard(); - const QMimeData *mimeData = clipboard->mimeData(); - - if ( mimeData->hasFormat( MIME_TYPE ) ) - { return true; } - else if ( mimeData->hasImage() ) + + + /// + /// Is Selection Atomic? + /// + bool LabelModel::isSelectionAtomic() { - // TODO: return true - } - else if ( mimeData->hasText() ) - { - // TODO: return true - } - return false; -} + int nSelected = 0; - -/// -/// Paste from clipboard -/// -void LabelModel::paste() -{ - const QClipboard *clipboard = QApplication::clipboard(); - const QMimeData *mimeData = clipboard->mimeData(); - - if ( mimeData->hasFormat( MIME_TYPE ) ) - { - QByteArray buffer = mimeData->data( MIME_TYPE ); - QList objects = XmlLabelParser::deserializeObjects( buffer ); - - unselectAll(); - foreach ( LabelModelObject* object, objects ) + foreach ( LabelModelObject* object, mObjectList ) { - addObject( object ); - selectObject( object ); + if ( object->isSelected() ) + { + nSelected++; + if ( nSelected > 1 ) + { + return false; + } + } + } + + return nSelected == 1; + } + + + /// + /// Get List of Selected Objects + /// + QList LabelModel::getSelection() + { + QList selectedList; + + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + selectedList << object; + } + } + + return selectedList; + } + + + /// + /// Get First Object in Selection List + /// + LabelModelObject* LabelModel::getFirstSelectedObject() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + return object; + } } } - else if ( mimeData->hasImage() ) - { - // TODO: create an image object from image - } - else if ( mimeData->hasText() ) - { - // TODO: create a text object from text - } -} -/// -/// Draw label objects -/// -void LabelModel::draw( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - foreach ( LabelModelObject* object, mObjectList ) + /// + /// Can Any Objects in Selection Accept Text Properties? + /// + bool LabelModel::canSelectionText() { - object->draw( painter, inEditor, record ); + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() && object->canText() ) + { + return true; + } + } + + return false; } + + + /// + /// Can Any Objects in Selection Accept Fill Property? + /// + bool LabelModel::canSelectionFill() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() && object->canFill() ) + { + return true; + } + } + + return false; + } + + + /// + /// Can Any Objects in Selection Accept Line Color Property? + /// + bool LabelModel::canSelectionLineColor() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() && object->canLineColor() ) + { + return true; + } + } + + return false; + } + + + /// + /// Can Any Objects in Selection Accept Line Width Property? + /// + bool LabelModel::canSelectionLineWidth() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() && object->canLineWidth() ) + { + return true; + } + } + + return false; + } + + + /// + /// Delete Selected Objects + /// + void LabelModel::deleteSelection() + { + QList selectedList = getSelection(); + + foreach ( LabelModelObject* object, selectedList ) + { + deleteObject( object ); + } + + setModified(); + + emit changed(); + emit selectionChanged(); + } + + + /// + /// Raise Selected Objects To Top + /// + void LabelModel::raiseSelectionToTop() + { + QList selectedList = getSelection(); + + foreach ( LabelModelObject* object, selectedList ) + { + mObjectList.removeOne( object ); + } + + // Move to end of list, representing top most object. + foreach ( LabelModelObject* object, selectedList ) + { + mObjectList.push_back( object ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Lower Selected Objects To Bottom + /// + void LabelModel::lowerSelectionToBottom() + { + QList selectedList = getSelection(); + + foreach ( LabelModelObject* object, selectedList ) + { + mObjectList.removeOne( object ); + } + + // Move to front of list, representing bottom most object. + foreach ( LabelModelObject* object, selectedList ) + { + mObjectList.push_front( object ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Rotate Selected Objects + /// + void LabelModel::rotateSelection( double thetaDegs ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->rotate( thetaDegs ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Rotate Selected Objects Left 90 degrees + /// + void LabelModel::rotateSelectionLeft() + { + rotateSelection( -90.0 ); + } + + + /// + /// Rotate Selected Objects Right 90 degrees + /// + void LabelModel::rotateSelectionRight() + { + rotateSelection( 90.0 ); + } + + + /// + /// Flip Selected Objects Horizontally + /// + void LabelModel::flipSelectionHoriz() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->flipHoriz(); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Flip Selected Objects Vertically + /// + void LabelModel::flipSelectionVert() + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->flipVert(); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Left Edges + /// + void LabelModel::alignSelectionLeft() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find left-most edge. + Distance x1_min = 7200; // Start with a very large value: 7200pts = 100in + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + if ( r.x1() < x1_min ) x1_min = r.x1(); + } + + // Now adjust the object positions to line up the left edges at left-most edge. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dx = x1_min - r.x1(); + object->setPositionRelative( dx, 0 ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Right Edges + /// + void LabelModel::alignSelectionRight() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find right-most edge. + Distance x1_max = -7200; // Start with a very large negative value: 7200pts = 100in + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + if ( r.x1() > x1_max ) x1_max = r.x1(); + } + + // Now adjust the object positions to line up the right edges at right-most edge. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dx = x1_max - r.x1(); + object->setPositionRelative( dx, 0 ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Horizontal Centers + /// + void LabelModel::alignSelectionHCenter() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find average center of objects. + Distance xsum = 0; + int n = 0; + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + xsum += (r.x1() + r.x2()) / 2.0; + n++; + } + Distance xavg = xsum / n; + + // Find object closest to average center of objects. + Distance xcenter = 7200; // Start with very large value. + Distance dxmin = fabs( xavg - xcenter ); + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dx = fabs( xavg - (r.x1() + r.x2())/2.0 ); + if ( dx < dxmin ) + { + dxmin = dx; + xcenter = (r.x1() + r.x2()) / 2.0; + } + } + + // Now adjust the object positions to line up with the center of this object. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dx = xcenter - (r.x1() + r.x2())/2.0; + object->setPositionRelative( dx, 0 ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Top Edges + /// + void LabelModel::alignSelectionTop() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find top-most edge. + Distance y1_min = 7200; // Start with a very large value: 7200pts = 100in + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + if ( r.y1() < y1_min ) y1_min = r.y1(); + } + + // Now adjust the object positions to line up the top edges at top-most edge. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dy = y1_min - r.y1(); + object->setPositionRelative( 0, dy ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Bottom Edges + /// + void LabelModel::alignSelectionBottom() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find bottom-most edge. + Distance y1_max = -7200; // Start with a very large negative value: 7200pts = 100in + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + if ( r.y1() > y1_max ) y1_max = r.y1(); + } + + // Now adjust the object positions to line up the bottom edges at bottom-most edge. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dy = y1_max - r.y1(); + object->setPositionRelative( 0, dy ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Their Vertical Centers Edges + /// + void LabelModel::alignSelectionVCenter() + { + if ( isSelectionEmpty() || isSelectionAtomic() ) + { + return; + } + + QList selectedList = getSelection(); + + // Find average center of objects. + Distance ysum = 0; + int n = 0; + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + ysum += (r.y1() + r.y2()) / 2.0; + n++; + } + Distance yavg = ysum / n; + + // Find object closest to average center of objects. + Distance ycenter = 7200; // Start with very large value. + Distance dymin = fabs( yavg - ycenter ); + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dy = fabs( yavg - (r.y1() + r.y2())/2.0 ); + if ( dy < dymin ) + { + dymin = dy; + ycenter = (r.y1() + r.y2()) / 2.0; + } + } + + // Now adjust the object positions to line up with the center of this object. + foreach ( LabelModelObject* object, selectedList ) + { + Region r = object->getExtent(); + Distance dy = ycenter - (r.y1() + r.y2())/2.0; + object->setPositionRelative( 0, dy ); + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Center Of Label Horizontally + /// + void LabelModel::centerSelectionHoriz() + { + Distance xLabelCenter = w() / 2.0; + + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + Region r = object->getExtent(); + Distance xObjectCenter = (r.x1() + r.x2()) / 2.0; + Distance dx = xLabelCenter - xObjectCenter; + object->setPositionRelative( dx, 0 ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Align Selected Objects To Center Of Label Vertically + /// + void LabelModel::centerSelectionVert() + { + Distance yLabelCenter = h() / 2.0; + + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + Region r = object->getExtent(); + Distance yObjectCenter = (r.y1() + r.y2()) / 2.0; + Distance dy = yLabelCenter - yObjectCenter; + object->setPositionRelative( 0, dy ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Move Selected Objects By dx,dy + /// + void LabelModel::moveSelection( const Distance& dx, const Distance& dy ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setPositionRelative( dx, dy ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Font Family Of Selected Objects + /// + void LabelModel::setSelectionFontFamily( const QString &fontFamily ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setFontFamily( fontFamily ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Font Size Of Selected Objects + /// + void LabelModel::setSelectionFontSize( double fontSize ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setFontSize( fontSize ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Font Weight Of Selected Objects + /// + void LabelModel::setSelectionFontWeight( QFont::Weight fontWeight ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setFontWeight( fontWeight ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Font Italic Flag Of Selected Objects + /// + void LabelModel::setSelectionFontItalicFlag( bool fontItalicFlag ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setFontItalicFlag( fontItalicFlag ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Text Horizontal Alignment Of Selected Objects + /// + void LabelModel::setSelectionTextHAlign( Qt::Alignment textHAlign ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setTextHAlign( textHAlign ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Text Vertical Alignment Of Selected Objects + /// + void LabelModel::setSelectionTextVAlign( Qt::Alignment textVAlign ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setTextVAlign( textVAlign ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Text Line Spacing Of Selected Objects + /// + void LabelModel::setSelectionTextLineSpacing( double textLineSpacing ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setTextLineSpacing( textLineSpacing ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Text Color Node Of Selected Objects + /// + void LabelModel::setSelectionTextColorNode( ColorNode textColorNode ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setTextColorNode( textColorNode ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Line Width Of Selected Objects + /// + void LabelModel::setSelectionLineWidth( const Distance& lineWidth ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setLineWidth( lineWidth ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Line Color Node Of Selected Objects + /// + void LabelModel::setSelectionLineColorNode( ColorNode lineColorNode ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setLineColorNode( lineColorNode ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Set Fill Color Node Of Selected Objects + /// + void LabelModel::setSelectionFillColorNode( ColorNode fillColorNode ) + { + foreach ( LabelModelObject* object, mObjectList ) + { + if ( object->isSelected() ) + { + object->setFillColorNode( fillColorNode ); + } + } + + setModified(); + + emit changed(); + } + + + /// + /// Copy selection to clipboard + /// + void LabelModel::copySelection() + { + if ( !isSelectionEmpty() ) + { + QClipboard *clipboard = QApplication::clipboard(); + + QByteArray buffer; + XmlLabelCreator::serializeObjects( getSelection(), buffer ); + + QMimeData *mimeData = new QMimeData; + mimeData->setData( MIME_TYPE, buffer ); + + clipboard->setMimeData( mimeData ); + } + } + + + /// + /// Cut selection to clipboard + /// + void LabelModel::cutSelection() + { + copySelection(); + deleteSelection(); + } + + + /// + /// Can we paste? + /// + bool LabelModel::canPaste() + { + const QClipboard *clipboard = QApplication::clipboard(); + const QMimeData *mimeData = clipboard->mimeData(); + + if ( mimeData->hasFormat( MIME_TYPE ) ) + { + return true; + } + else if ( mimeData->hasImage() ) + { + // TODO: return true + } + else if ( mimeData->hasText() ) + { + // TODO: return true + } + return false; + } + + + /// + /// Paste from clipboard + /// + void LabelModel::paste() + { + const QClipboard *clipboard = QApplication::clipboard(); + const QMimeData *mimeData = clipboard->mimeData(); + + if ( mimeData->hasFormat( MIME_TYPE ) ) + { + QByteArray buffer = mimeData->data( MIME_TYPE ); + QList objects = XmlLabelParser::deserializeObjects( buffer ); + + unselectAll(); + foreach ( LabelModelObject* object, objects ) + { + addObject( object ); + selectObject( object ); + } + } + else if ( mimeData->hasImage() ) + { + // TODO: create an image object from image + } + else if ( mimeData->hasText() ) + { + // TODO: create a text object from text + } + } + + + /// + /// Draw label objects + /// + void LabelModel::draw( QPainter* painter, bool inEditor, merge::Record* record ) const + { + foreach ( LabelModelObject* object, mObjectList ) + { + object->draw( painter, inEditor, record ); + } + } + } diff --git a/glabels/LabelModel.h b/glabels/LabelModel.h index 7e00235..98aea41 100644 --- a/glabels/LabelModel.h +++ b/glabels/LabelModel.h @@ -32,205 +32,208 @@ #include "Merge/Merge.h" #include "Merge/Record.h" -// Forward References -class ColorNode; -class Handle; -class LabelModelObject; -class Region; - -////////////////////////////////////////////// -////////////////////////////////////////////// -// LabelModel -////////////////////////////////////////////// -////////////////////////////////////////////// -class LabelModel : public QObject +namespace glabels { - Q_OBJECT + + // Forward References + class ColorNode; + class Handle; + class LabelModelObject; + class Region; + + /// + /// LabelModel + /// + class LabelModel : public QObject + { + Q_OBJECT - ///////////////////////////////// - // Lifecycle - ///////////////////////////////// -public: - LabelModel(); - virtual ~LabelModel() {} + ///////////////////////////////// + // Lifecycle + ///////////////////////////////// + public: + LabelModel(); + virtual ~LabelModel() {} - ///////////////////////////////// - // Save/restore model state - ///////////////////////////////// - LabelModel* save() const; - void restore( const LabelModel *savedModel ); + ///////////////////////////////// + // Save/restore model state + ///////////////////////////////// + LabelModel* save() const; + void restore( const LabelModel *savedModel ); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void changed(); - void nameChanged(); - void sizeChanged(); - void selectionChanged(); - void modifiedChanged(); - void mergeChanged(); - void mergeSourceChanged(); - void mergeSelectionChanged(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void changed(); + void nameChanged(); + void sizeChanged(); + void selectionChanged(); + void modifiedChanged(); + void mergeChanged(); + void mergeSourceChanged(); + void mergeSelectionChanged(); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - bool isModified() const; - void setModified(); - void clearModified(); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + bool isModified() const; + void setModified(); + void clearModified(); - QString shortName(); - const QString& fileName() const; - void setFileName( const QString &fileName ); + QString shortName(); + const QString& fileName() const; + void setFileName( const QString &fileName ); - int compressionLevel() const; - void setCompressionLevel( int compressionLevel ); + int compressionLevel() const; + void setCompressionLevel( int compressionLevel ); - const glabels::Template* tmplate() const; - const glabels::Frame* frame() const; - void setTmplate( const glabels::Template* tmplate ); + const Template* tmplate() const; + const Frame* frame() const; + void setTmplate( const Template* tmplate ); - bool rotate() const; - void setRotate( bool rotate ); + bool rotate() const; + void setRotate( bool rotate ); - glabels::Distance w() const; - glabels::Distance h() const; + Distance w() const; + Distance h() const; - const QList& objectList() const; + const QList& objectList() const; - merge::Merge* merge() const; - void setMerge( merge::Merge* merge ); + merge::Merge* merge() const; + void setMerge( merge::Merge* merge ); - ///////////////////////////////// - // Manage objects - ///////////////////////////////// -public: - void addObject( LabelModelObject* object ); - void deleteObject( LabelModelObject* object ); + ///////////////////////////////// + // Manage objects + ///////////////////////////////// + public: + void addObject( LabelModelObject* object ); + void deleteObject( LabelModelObject* object ); - LabelModelObject* objectAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const; + LabelModelObject* objectAt( double scale, + const Distance& x, + const Distance& y ) const; - Handle* handleAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const; + Handle* handleAt( double scale, + const Distance& x, + const Distance& y ) const; - ///////////////////////////////// - // Manipulate selection - ///////////////////////////////// -public: - void selectObject( LabelModelObject* object ); - void unselectObject( LabelModelObject* object ); - void selectAll(); - void unselectAll(); - void selectRegion( const Region& region ); - bool isSelectionEmpty(); - bool isSelectionAtomic(); + ///////////////////////////////// + // Manipulate selection + ///////////////////////////////// + public: + void selectObject( LabelModelObject* object ); + void unselectObject( LabelModelObject* object ); + void selectAll(); + void unselectAll(); + void selectRegion( const Region& region ); + bool isSelectionEmpty(); + bool isSelectionAtomic(); - ///////////////////////////////// - // Get selected objects - ///////////////////////////////// -public: - QList getSelection(); - LabelModelObject* getFirstSelectedObject(); + ///////////////////////////////// + // Get selected objects + ///////////////////////////////// + public: + QList getSelection(); + LabelModelObject* getFirstSelectedObject(); - ///////////////////////////////// - // Query selection capabilities - ///////////////////////////////// -public: - bool canSelectionText(); - bool canSelectionFill(); - bool canSelectionLineColor(); - bool canSelectionLineWidth(); + ///////////////////////////////// + // Query selection capabilities + ///////////////////////////////// + public: + bool canSelectionText(); + bool canSelectionFill(); + bool canSelectionLineColor(); + bool canSelectionLineWidth(); - ///////////////////////////////// - // Operations on selections - ///////////////////////////////// -public: - void deleteSelection(); - void raiseSelectionToTop(); - void lowerSelectionToBottom(); - void rotateSelection( double thetaDegs ); - void rotateSelectionLeft(); - void rotateSelectionRight(); - void flipSelectionHoriz(); - void flipSelectionVert(); - void alignSelectionLeft(); - void alignSelectionRight(); - void alignSelectionHCenter(); - void alignSelectionTop(); - void alignSelectionBottom(); - void alignSelectionVCenter(); - void centerSelectionHoriz(); - void centerSelectionVert(); - void moveSelection( const glabels::Distance& dx, const glabels::Distance& dy ); - void setSelectionFontFamily( const QString& fontFamily ); - void setSelectionFontSize( double fontSize ); - void setSelectionFontWeight( QFont::Weight fontWeight ); - void setSelectionFontItalicFlag( bool fontItalicFlag ); - void setSelectionTextHAlign( Qt::Alignment textHAlign ); - void setSelectionTextVAlign( Qt::Alignment textVAlign ); - void setSelectionTextLineSpacing( double textLineSpacing ); - void setSelectionTextColorNode( ColorNode textColorNode ); - void setSelectionLineWidth( const glabels::Distance& lineWidth ); - void setSelectionLineColorNode( ColorNode lineColorNode ); - void setSelectionFillColorNode( ColorNode fillColorNode ); + ///////////////////////////////// + // Operations on selections + ///////////////////////////////// + public: + void deleteSelection(); + void raiseSelectionToTop(); + void lowerSelectionToBottom(); + void rotateSelection( double thetaDegs ); + void rotateSelectionLeft(); + void rotateSelectionRight(); + void flipSelectionHoriz(); + void flipSelectionVert(); + void alignSelectionLeft(); + void alignSelectionRight(); + void alignSelectionHCenter(); + void alignSelectionTop(); + void alignSelectionBottom(); + void alignSelectionVCenter(); + void centerSelectionHoriz(); + void centerSelectionVert(); + void moveSelection( const Distance& dx, const Distance& dy ); + void setSelectionFontFamily( const QString& fontFamily ); + void setSelectionFontSize( double fontSize ); + void setSelectionFontWeight( QFont::Weight fontWeight ); + void setSelectionFontItalicFlag( bool fontItalicFlag ); + void setSelectionTextHAlign( Qt::Alignment textHAlign ); + void setSelectionTextVAlign( Qt::Alignment textVAlign ); + void setSelectionTextLineSpacing( double textLineSpacing ); + void setSelectionTextColorNode( ColorNode textColorNode ); + void setSelectionLineWidth( const Distance& lineWidth ); + void setSelectionLineColorNode( ColorNode lineColorNode ); + void setSelectionFillColorNode( ColorNode fillColorNode ); - ///////////////////////////////// - // Clipboard operations - ///////////////////////////////// - void copySelection(); - void cutSelection(); - bool canPaste(); - void paste(); + ///////////////////////////////// + // Clipboard operations + ///////////////////////////////// + void copySelection(); + void cutSelection(); + bool canPaste(); + void paste(); - ///////////////////////////////// - // Drawing operations - ///////////////////////////////// -public: - void draw( QPainter* painter, bool inEditor = true, merge::Record* record = 0 ) const; + ///////////////////////////////// + // Drawing operations + ///////////////////////////////// + public: + void draw( QPainter* painter, bool inEditor = true, merge::Record* record = 0 ) const; - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onObjectChanged(); - void onObjectMoved(); - void onMergeSourceChanged(); - void onMergeSelectionChanged(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onObjectChanged(); + void onObjectMoved(); + void onMergeSourceChanged(); + void onMergeSelectionChanged(); - ///////////////////////////////// - // Private data - ///////////////////////////////// -private: - int mUntitledInstance; - bool mModified; - QString mFileName; - int mCompressionLevel; - const glabels::Template* mTmplate; - const glabels::Frame* mFrame; - bool mRotate; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + int mUntitledInstance; + bool mModified; + QString mFileName; + int mCompressionLevel; + const Template* mTmplate; + const Frame* mFrame; + bool mRotate; - QList mObjectList; + QList mObjectList; - merge::Merge* mMerge; -}; + merge::Merge* mMerge; + }; + +} #endif // LabelModel_h diff --git a/glabels/LabelModelBoxObject.cpp b/glabels/LabelModelBoxObject.cpp index cbc5889..af3b7bd 100644 --- a/glabels/LabelModelBoxObject.cpp +++ b/glabels/LabelModelBoxObject.cpp @@ -25,134 +25,146 @@ #include -namespace +namespace glabels { - const double slopPixels = 2; -} - -/// -/// Constructor -/// -LabelModelBoxObject::LabelModelBoxObject() -{ -} - - -/// -/// Copy constructor -/// -LabelModelBoxObject::LabelModelBoxObject( const LabelModelBoxObject* object ) : LabelModelShapeObject( object ) -{ -} - - -/// -/// Destructor -/// -LabelModelBoxObject::~LabelModelBoxObject() -{ -} - - -/// -/// Clone -/// -LabelModelBoxObject* LabelModelBoxObject::clone() const -{ - return new LabelModelBoxObject( this ); -} - - -/// -/// Draw shadow of object -/// -void LabelModelBoxObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - QColor fillColor = mFillColorNode.color( record ); - QColor shadowColor = mShadowColorNode.color( record ); - - shadowColor.setAlphaF( mShadowOpacity ); - - if ( fillColor.alpha() ) + // + // Private + // + namespace { - painter->setPen( Qt::NoPen ); - painter->setBrush( shadowColor ); + const double slopPixels = 2; + } - if ( lineColor.alpha() ) + + /// + /// Constructor + /// + LabelModelBoxObject::LabelModelBoxObject() + { + // empty + } + + + /// + /// Copy constructor + /// + LabelModelBoxObject::LabelModelBoxObject( const LabelModelBoxObject* object ) + : LabelModelShapeObject( object ) + { + // empty + } + + + /// + /// Destructor + /// + LabelModelBoxObject::~LabelModelBoxObject() + { + // empty + } + + + /// + /// Clone + /// + LabelModelBoxObject* LabelModelBoxObject::clone() const + { + return new LabelModelBoxObject( this ); + } + + + /// + /// Draw shadow of object + /// + void LabelModelBoxObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + QColor fillColor = mFillColorNode.color( record ); + QColor shadowColor = mShadowColorNode.color( record ); + + shadowColor.setAlphaF( mShadowOpacity ); + + if ( fillColor.alpha() ) { - /* Has FILL and OUTLINE: adjust size to account for line width. */ - painter->drawRect( QRectF( -mLineWidth.pt()/2, - -mLineWidth.pt()/2, - (mW + mLineWidth).pt(), - (mH + mLineWidth).pt() ) ); + painter->setPen( Qt::NoPen ); + painter->setBrush( shadowColor ); + + if ( lineColor.alpha() ) + { + /* Has FILL and OUTLINE: adjust size to account for line width. */ + painter->drawRect( QRectF( -mLineWidth.pt()/2, + -mLineWidth.pt()/2, + (mW + mLineWidth).pt(), + (mH + mLineWidth).pt() ) ); + } + else + { + /* Has FILL, but no OUTLINE. */ + painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } } else { - /* Has FILL, but no OUTLINE. */ - painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); - } - } - else - { - if ( lineColor.alpha() ) - { - /* Has only OUTLINE. */ - painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); - painter->setBrush( Qt::NoBrush ); + if ( lineColor.alpha() ) + { + /* Has only OUTLINE. */ + painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); + painter->setBrush( Qt::NoBrush ); - painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } } - } -} + } -/// -/// Draw object itself -/// -void LabelModelBoxObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - QColor fillColor = mFillColorNode.color( record ); + /// + /// Draw object itself + /// + void LabelModelBoxObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + QColor fillColor = mFillColorNode.color( record ); - painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); - painter->setBrush( fillColor ); + painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); + painter->setBrush( fillColor ); + + painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } + + + /// + /// Path to test for hover condition + /// + QPainterPath LabelModelBoxObject::hoverPath( double scale ) const + { + double s = 1 / scale; + + QPainterPath path; + + if ( mFillColorNode.color().alpha() && mLineColorNode.color().alpha() ) + { + path.addRect( -mLineWidth.pt()/2, -mLineWidth.pt()/2, (mW+mLineWidth).pt(), (mH+mLineWidth).pt() ); + } + else if ( mFillColorNode.color().alpha() && !(mLineColorNode.color().alpha()) ) + { + path.addRect( 0, 0, mW.pt(), mH.pt() ); + } + else if ( mLineColorNode.color().alpha() ) + { + path.addRect( (-mLineWidth.pt()/2) - s*slopPixels, + (-mLineWidth.pt()/2) - s*slopPixels, + (mW + mLineWidth).pt() + s*2*slopPixels, + (mH + mLineWidth).pt() + s*2*slopPixels ); + path.closeSubpath(); + path.addRect( mLineWidth.pt()/2 + s*slopPixels, + mLineWidth.pt()/2 + s*slopPixels, + (mW - mLineWidth).pt() - s*2*slopPixels, + (mH - mLineWidth).pt() - s*2*slopPixels ); + } + + return path; + } - painter->drawRect( QRectF( 0, 0, mW.pt(), mH.pt() ) ); -} - - -/// -/// Path to test for hover condition -/// -QPainterPath LabelModelBoxObject::hoverPath( double scale ) const -{ - double s = 1 / scale; - - QPainterPath path; - - if ( mFillColorNode.color().alpha() && mLineColorNode.color().alpha() ) - { - path.addRect( -mLineWidth.pt()/2, -mLineWidth.pt()/2, (mW+mLineWidth).pt(), (mH+mLineWidth).pt() ); - } - else if ( mFillColorNode.color().alpha() && !(mLineColorNode.color().alpha()) ) - { - path.addRect( 0, 0, mW.pt(), mH.pt() ); - } - else if ( mLineColorNode.color().alpha() ) - { - path.addRect( (-mLineWidth.pt()/2) - s*slopPixels, - (-mLineWidth.pt()/2) - s*slopPixels, - (mW + mLineWidth).pt() + s*2*slopPixels, - (mH + mLineWidth).pt() + s*2*slopPixels ); - path.closeSubpath(); - path.addRect( mLineWidth.pt()/2 + s*slopPixels, - mLineWidth.pt()/2 + s*slopPixels, - (mW - mLineWidth).pt() - s*2*slopPixels, - (mH - mLineWidth).pt() - s*2*slopPixels ); - } - - return path; } diff --git a/glabels/LabelModelBoxObject.h b/glabels/LabelModelBoxObject.h index 91f0b30..b6f86b3 100644 --- a/glabels/LabelModelBoxObject.h +++ b/glabels/LabelModelBoxObject.h @@ -25,37 +25,42 @@ #include "LabelModelShapeObject.h" -/// -/// Label Model Box Object -/// -class LabelModelBoxObject : public LabelModelShapeObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -public: - LabelModelBoxObject(); - LabelModelBoxObject( const LabelModelBoxObject* object ); - virtual ~LabelModelBoxObject(); + /// + /// Label Model Box Object + /// + class LabelModelBoxObject : public LabelModelShapeObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + public: + LabelModelBoxObject(); + LabelModelBoxObject( const LabelModelBoxObject* object ); + virtual ~LabelModelBoxObject(); - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelBoxObject* clone() const; + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelBoxObject* clone() const; - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual QPainterPath hoverPath( double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual QPainterPath hoverPath( double scale ) const; -}; + }; + +} #endif // LabelModelBoxObject_h diff --git a/glabels/LabelModelEllipseObject.cpp b/glabels/LabelModelEllipseObject.cpp index bbbceb1..d053685 100644 --- a/glabels/LabelModelEllipseObject.cpp +++ b/glabels/LabelModelEllipseObject.cpp @@ -25,134 +25,146 @@ #include -namespace +namespace glabels { - const double slopPixels = 2; -} - -/// -/// Constructor -/// -LabelModelEllipseObject::LabelModelEllipseObject() -{ -} - - -/// -/// Copy constructor -/// -LabelModelEllipseObject::LabelModelEllipseObject( const LabelModelEllipseObject* object ) : LabelModelShapeObject( object ) -{ -} - - -/// -/// Destructor -/// -LabelModelEllipseObject::~LabelModelEllipseObject() -{ -} - - -/// -/// Clone -/// -LabelModelEllipseObject* LabelModelEllipseObject::clone() const -{ - return new LabelModelEllipseObject( this ); -} - - -/// -/// Draw shadow of object -/// -void LabelModelEllipseObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - QColor fillColor = mFillColorNode.color( record ); - QColor shadowColor = mShadowColorNode.color( record ); - - shadowColor.setAlphaF( mShadowOpacity ); - - if ( fillColor.alpha() ) + // + // Private + // + namespace { - painter->setPen( Qt::NoPen ); - painter->setBrush( shadowColor ); + const double slopPixels = 2; + } - if ( lineColor.alpha() ) + + /// + /// Constructor + /// + LabelModelEllipseObject::LabelModelEllipseObject() + { + // empty + } + + + /// + /// Copy constructor + /// + LabelModelEllipseObject::LabelModelEllipseObject( const LabelModelEllipseObject* object ) + : LabelModelShapeObject( object ) + { + // empty + } + + + /// + /// Destructor + /// + LabelModelEllipseObject::~LabelModelEllipseObject() + { + // empty + } + + + /// + /// Clone + /// + LabelModelEllipseObject* LabelModelEllipseObject::clone() const + { + return new LabelModelEllipseObject( this ); + } + + + /// + /// Draw shadow of object + /// + void LabelModelEllipseObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + QColor fillColor = mFillColorNode.color( record ); + QColor shadowColor = mShadowColorNode.color( record ); + + shadowColor.setAlphaF( mShadowOpacity ); + + if ( fillColor.alpha() ) { - /* Has FILL and OUTLINE: adjust size to account for line width. */ - painter->drawEllipse( QRectF( -mLineWidth.pt()/2, - -mLineWidth.pt()/2, - (mW + mLineWidth).pt(), - (mH + mLineWidth).pt() ) ); + painter->setPen( Qt::NoPen ); + painter->setBrush( shadowColor ); + + if ( lineColor.alpha() ) + { + /* Has FILL and OUTLINE: adjust size to account for line width. */ + painter->drawEllipse( QRectF( -mLineWidth.pt()/2, + -mLineWidth.pt()/2, + (mW + mLineWidth).pt(), + (mH + mLineWidth).pt() ) ); + } + else + { + /* Has FILL, but no OUTLINE. */ + painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } } else { - /* Has FILL, but no OUTLINE. */ - painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); - } - } - else - { - if ( lineColor.alpha() ) - { - /* Has only OUTLINE. */ - painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); - painter->setBrush( Qt::NoBrush ); + if ( lineColor.alpha() ) + { + /* Has only OUTLINE. */ + painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); + painter->setBrush( Qt::NoBrush ); - painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } } - } -} + } -/// -/// Draw object itself -/// -void LabelModelEllipseObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - QColor fillColor = mFillColorNode.color( record ); + /// + /// Draw object itself + /// + void LabelModelEllipseObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + QColor fillColor = mFillColorNode.color( record ); - painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); - painter->setBrush( fillColor ); + painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); + painter->setBrush( fillColor ); + + painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); + } + + + /// + /// Path to test for hover condition + /// + QPainterPath LabelModelEllipseObject::hoverPath( double scale ) const + { + double s = 1 / scale; + + QPainterPath path; + + if ( mFillColorNode.color().alpha() && mLineColorNode.color().alpha() ) + { + path.addEllipse( -mLineWidth.pt()/2, -mLineWidth.pt()/2, (mW+mLineWidth).pt(), (mH+mLineWidth).pt() ); + } + else if ( mFillColorNode.color().alpha() && !(mLineColorNode.color().alpha()) ) + { + path.addEllipse( 0, 0, mW.pt(), mH.pt() ); + } + else if ( mLineColorNode.color().alpha() ) + { + path.addEllipse( (-mLineWidth.pt()/2) - s*slopPixels, + (-mLineWidth.pt()/2) - s*slopPixels, + (mW + mLineWidth).pt() + s*2*slopPixels, + (mH + mLineWidth).pt() + s*2*slopPixels ); + path.closeSubpath(); + path.addEllipse( mLineWidth.pt()/2 + s*slopPixels, + mLineWidth.pt()/2 + s*slopPixels, + (mW - mLineWidth).pt() - s*2*slopPixels, + (mH - mLineWidth).pt() - s*2*slopPixels ); + } + + return path; + } - painter->drawEllipse( QRectF( 0, 0, mW.pt(), mH.pt() ) ); -} - - -/// -/// Path to test for hover condition -/// -QPainterPath LabelModelEllipseObject::hoverPath( double scale ) const -{ - double s = 1 / scale; - - QPainterPath path; - - if ( mFillColorNode.color().alpha() && mLineColorNode.color().alpha() ) - { - path.addEllipse( -mLineWidth.pt()/2, -mLineWidth.pt()/2, (mW+mLineWidth).pt(), (mH+mLineWidth).pt() ); - } - else if ( mFillColorNode.color().alpha() && !(mLineColorNode.color().alpha()) ) - { - path.addEllipse( 0, 0, mW.pt(), mH.pt() ); - } - else if ( mLineColorNode.color().alpha() ) - { - path.addEllipse( (-mLineWidth.pt()/2) - s*slopPixels, - (-mLineWidth.pt()/2) - s*slopPixels, - (mW + mLineWidth).pt() + s*2*slopPixels, - (mH + mLineWidth).pt() + s*2*slopPixels ); - path.closeSubpath(); - path.addEllipse( mLineWidth.pt()/2 + s*slopPixels, - mLineWidth.pt()/2 + s*slopPixels, - (mW - mLineWidth).pt() - s*2*slopPixels, - (mH - mLineWidth).pt() - s*2*slopPixels ); - } - - return path; } diff --git a/glabels/LabelModelEllipseObject.h b/glabels/LabelModelEllipseObject.h index d321fe7..0a6c777 100644 --- a/glabels/LabelModelEllipseObject.h +++ b/glabels/LabelModelEllipseObject.h @@ -25,37 +25,42 @@ #include "LabelModelShapeObject.h" -/// -/// Label Model Ellipse Object -/// -class LabelModelEllipseObject : public LabelModelShapeObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -public: - LabelModelEllipseObject(); - LabelModelEllipseObject( const LabelModelEllipseObject* object ); - virtual ~LabelModelEllipseObject(); + /// + /// Label Model Ellipse Object + /// + class LabelModelEllipseObject : public LabelModelShapeObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + public: + LabelModelEllipseObject(); + LabelModelEllipseObject( const LabelModelEllipseObject* object ); + virtual ~LabelModelEllipseObject(); - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelEllipseObject* clone() const; + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelEllipseObject* clone() const; - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual QPainterPath hoverPath( double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual QPainterPath hoverPath( double scale ) const; -}; + }; + +} #endif // LabelModelEllipseObject_h diff --git a/glabels/LabelModelImageObject.cpp b/glabels/LabelModelImageObject.cpp index ce14c42..b3fbf4e 100644 --- a/glabels/LabelModelImageObject.cpp +++ b/glabels/LabelModelImageObject.cpp @@ -30,287 +30,287 @@ #include "Size.h" -namespace +namespace glabels { -} + + /// + /// Static data + /// + QImage* LabelModelImageObject::smDefaultImage = 0; -/// -/// Static data -/// -QImage* LabelModelImageObject::smDefaultImage = 0; - - -/// -/// Constructor -/// -LabelModelImageObject::LabelModelImageObject() : mImage(0), mSvg(0) -{ - mOutline = new Outline( this ); - - mHandles << new HandleNorthWest( this ); - mHandles << new HandleNorth( this ); - mHandles << new HandleNorthEast( this ); - mHandles << new HandleEast( this ); - mHandles << new HandleSouthEast( this ); - mHandles << new HandleSouth( this ); - mHandles << new HandleSouthWest( this ); - mHandles << new HandleWest( this ); - - if ( smDefaultImage == 0 ) + /// + /// Constructor + /// + LabelModelImageObject::LabelModelImageObject() : mImage(0), mSvg(0) { - smDefaultImage = new QImage( ":images/checkerboard.png" ); - } -} + mOutline = new Outline( this ); + mHandles << new HandleNorthWest( this ); + mHandles << new HandleNorth( this ); + mHandles << new HandleNorthEast( this ); + mHandles << new HandleEast( this ); + mHandles << new HandleSouthEast( this ); + mHandles << new HandleSouth( this ); + mHandles << new HandleSouthWest( this ); + mHandles << new HandleWest( this ); -/// -/// Copy constructor -/// -LabelModelImageObject::LabelModelImageObject( const LabelModelImageObject* object ) : LabelModelObject(object) -{ - mFilenameNode = object->mFilenameNode; -} - - -/// -/// Destructor -/// -LabelModelImageObject::~LabelModelImageObject() -{ - delete mOutline; - - foreach( Handle* handle, mHandles ) - { - delete handle; - } - mHandles.clear(); -} - - -/// -/// Clone -/// -LabelModelImageObject* LabelModelImageObject::clone() const -{ - return new LabelModelImageObject( this ); -} - - -/// -/// Image filenameNode Property Getter -/// -TextNode LabelModelImageObject::filenameNode( void ) const -{ - return mFilenameNode; -} - - -/// -/// Image filenameNode Property Setter -/// -void LabelModelImageObject::setFilenameNode( const TextNode& value ) -{ - if ( mFilenameNode != value ) - { - mFilenameNode = value; - loadImage(); - - emit changed(); - } -} - - -/// -/// Image originalSize Property Getter (assumes 72 DPI, i.e. 1pixel == 1pt) -/// -Size LabelModelImageObject::originalSize() const -{ - Size size( glabels::Distance::pt(72), glabels::Distance::pt(72) ); - - if ( mImage ) - { - QSize qsize = mImage->size(); - size.setW( glabels::Distance::pt( qsize.width() ) ); - size.setH( glabels::Distance::pt( qsize.height() ) ); - } - else if ( mSvg ) - { - QSize qsize = mSvg->defaultSize(); - size.setW( glabels::Distance::pt( qsize.width() ) ); - size.setH( glabels::Distance::pt( qsize.height() ) ); - } - - return size; -} - - -/// -/// Draw shadow of object -/// -void LabelModelImageObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QRectF destRect( 0, 0, mW.pt(), mH.pt() ); - - QColor shadowColor = mShadowColorNode.color( record ); - shadowColor.setAlphaF( mShadowOpacity ); - - if ( mImage && mImage->hasAlphaChannel() && (mImage->depth() == 32) ) - { - QImage* shadowImage = createShadowImage( shadowColor ); - painter->drawImage( destRect, *shadowImage ); - delete shadowImage; - } - else - { - if ( mImage || inEditor ) + if ( smDefaultImage == 0 ) { - painter->setBrush( shadowColor ); - painter->setPen( QPen( Qt::NoPen ) ); - - painter->drawRect( destRect ); + smDefaultImage = new QImage( ":images/checkerboard.png" ); } } -} - - -/// -/// Draw object itself -/// -void LabelModelImageObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QRectF destRect( 0, 0, mW.pt(), mH.pt() ); - - if ( inEditor && (mFilenameNode.isField() || (!mImage && !mSvg) ) ) - { - painter->save(); - painter->setRenderHint( QPainter::SmoothPixmapTransform, false ); - painter->drawImage( destRect, *smDefaultImage ); - painter->restore(); - } - else if ( mImage ) - { - painter->drawImage( destRect, *mImage ); - } - else if ( mSvg ) - { - mSvg->render( painter, destRect ); - } - else if ( mFilenameNode.isField() ) - { - // TODO - } -} -/// -/// Path to test for hover condition -/// -QPainterPath LabelModelImageObject::hoverPath( double scale ) const -{ - QPainterPath path; - path.addRect( 0, 0, mW.pt(), mH.pt() ); - - return path; -} - - -/// -/// Load image -/// -void LabelModelImageObject::loadImage() -{ - if ( mImage ) + /// + /// Copy constructor + /// + LabelModelImageObject::LabelModelImageObject( const LabelModelImageObject* object ) : LabelModelObject(object) { - delete mImage; - } - if ( mSvg ) - { - delete mSvg; + mFilenameNode = object->mFilenameNode; } - if ( mFilenameNode.isField() ) - { - mImage = 0; - mSvg = 0; - } - else - { - QString filename = mFilenameNode.data(); - QFileInfo fileInfo( filename ); - if ( fileInfo.isReadable() ) + /// + /// Destructor + /// + LabelModelImageObject::~LabelModelImageObject() + { + delete mOutline; + + foreach( Handle* handle, mHandles ) { - if ( (fileInfo.suffix() == "svg") || (fileInfo.suffix() == "SVG") ) + delete handle; + } + mHandles.clear(); + } + + + /// + /// Clone + /// + LabelModelImageObject* LabelModelImageObject::clone() const + { + return new LabelModelImageObject( this ); + } + + + /// + /// Image filenameNode Property Getter + /// + TextNode LabelModelImageObject::filenameNode( void ) const + { + return mFilenameNode; + } + + + /// + /// Image filenameNode Property Setter + /// + void LabelModelImageObject::setFilenameNode( const TextNode& value ) + { + if ( mFilenameNode != value ) + { + mFilenameNode = value; + loadImage(); + + emit changed(); + } + } + + + /// + /// Image originalSize Property Getter (assumes 72 DPI, i.e. 1pixel == 1pt) + /// + Size LabelModelImageObject::originalSize() const + { + Size size( Distance::pt(72), Distance::pt(72) ); + + if ( mImage ) + { + QSize qsize = mImage->size(); + size.setW( Distance::pt( qsize.width() ) ); + size.setH( Distance::pt( qsize.height() ) ); + } + else if ( mSvg ) + { + QSize qsize = mSvg->defaultSize(); + size.setW( Distance::pt( qsize.width() ) ); + size.setH( Distance::pt( qsize.height() ) ); + } + + return size; + } + + + /// + /// Draw shadow of object + /// + void LabelModelImageObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QRectF destRect( 0, 0, mW.pt(), mH.pt() ); + + QColor shadowColor = mShadowColorNode.color( record ); + shadowColor.setAlphaF( mShadowOpacity ); + + if ( mImage && mImage->hasAlphaChannel() && (mImage->depth() == 32) ) + { + QImage* shadowImage = createShadowImage( shadowColor ); + painter->drawImage( destRect, *shadowImage ); + delete shadowImage; + } + else + { + if ( mImage || inEditor ) { - mSvg = new QSvgRenderer( filename ); - if ( !mSvg->isValid() ) - { - mSvg = 0; - } - else - { - // Adjust size based on aspect ratio of SVG image - QRectF rect = mSvg->viewBoxF(); - double aspectRatio = rect.height() / rect.width(); - if ( mH > mW*aspectRatio ) - { - mH = mW*aspectRatio; - } - else - { - mW = mH/aspectRatio; - } - } + painter->setBrush( shadowColor ); + painter->setPen( QPen( Qt::NoPen ) ); + + painter->drawRect( destRect ); } - else + } + } + + + /// + /// Draw object itself + /// + void LabelModelImageObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QRectF destRect( 0, 0, mW.pt(), mH.pt() ); + + if ( inEditor && (mFilenameNode.isField() || (!mImage && !mSvg) ) ) + { + painter->save(); + painter->setRenderHint( QPainter::SmoothPixmapTransform, false ); + painter->drawImage( destRect, *smDefaultImage ); + painter->restore(); + } + else if ( mImage ) + { + painter->drawImage( destRect, *mImage ); + } + else if ( mSvg ) + { + mSvg->render( painter, destRect ); + } + else if ( mFilenameNode.isField() ) + { + // TODO + } + } + + + /// + /// Path to test for hover condition + /// + QPainterPath LabelModelImageObject::hoverPath( double scale ) const + { + QPainterPath path; + path.addRect( 0, 0, mW.pt(), mH.pt() ); + + return path; + } + + + /// + /// Load image + /// + void LabelModelImageObject::loadImage() + { + if ( mImage ) + { + delete mImage; + } + if ( mSvg ) + { + delete mSvg; + } + + if ( mFilenameNode.isField() ) + { + mImage = 0; + mSvg = 0; + } + else + { + QString filename = mFilenameNode.data(); + QFileInfo fileInfo( filename ); + + if ( fileInfo.isReadable() ) { - mImage = new QImage( filename ); - if ( mImage->isNull() ) + if ( (fileInfo.suffix() == "svg") || (fileInfo.suffix() == "SVG") ) { - mImage = 0; - } - else - { - // Adjust size based on aspect ratio of image - double imageW = mImage->width(); - double imageH = mImage->height(); - double aspectRatio = imageH / imageW; - if ( mH > mW*aspectRatio ) + mSvg = new QSvgRenderer( filename ); + if ( !mSvg->isValid() ) { - mH = mW*aspectRatio; + mSvg = 0; } else { - mW = mH/aspectRatio; + // Adjust size based on aspect ratio of SVG image + QRectF rect = mSvg->viewBoxF(); + double aspectRatio = rect.height() / rect.width(); + if ( mH > mW*aspectRatio ) + { + mH = mW*aspectRatio; + } + else + { + mW = mH/aspectRatio; + } + } + } + else + { + mImage = new QImage( filename ); + if ( mImage->isNull() ) + { + mImage = 0; + } + else + { + // Adjust size based on aspect ratio of image + double imageW = mImage->width(); + double imageH = mImage->height(); + double aspectRatio = imageH / imageW; + if ( mH > mW*aspectRatio ) + { + mH = mW*aspectRatio; + } + else + { + mW = mH/aspectRatio; + } } } } } } -} -/// -/// Create shadow image -/// -QImage* LabelModelImageObject::createShadowImage( const QColor& color ) const -{ - int r = color.red(); - int g = color.green(); - int b = color.blue(); - int a = color.alpha(); - - QImage* shadow = new QImage( *mImage ); - for ( int iy = 0; iy < shadow->height(); iy++ ) + /// + /// Create shadow image + /// + QImage* LabelModelImageObject::createShadowImage( const QColor& color ) const { - QRgb* scanLine = (QRgb*)shadow->scanLine( iy ); + int r = color.red(); + int g = color.green(); + int b = color.blue(); + int a = color.alpha(); - for ( int ix = 0; ix < shadow->width(); ix++ ) + QImage* shadow = new QImage( *mImage ); + for ( int iy = 0; iy < shadow->height(); iy++ ) { - scanLine[ix] = qRgba( r, g, b, (a*qAlpha(scanLine[ix]))/255 ); + QRgb* scanLine = (QRgb*)shadow->scanLine( iy ); + + for ( int ix = 0; ix < shadow->width(); ix++ ) + { + scanLine[ix] = qRgba( r, g, b, (a*qAlpha(scanLine[ix]))/255 ); + } } + + return shadow; } - return shadow; } diff --git a/glabels/LabelModelImageObject.h b/glabels/LabelModelImageObject.h index 38e1f9e..c8a9bc2 100644 --- a/glabels/LabelModelImageObject.h +++ b/glabels/LabelModelImageObject.h @@ -27,76 +27,81 @@ #include "LabelModelObject.h" -/// -/// Label Model Image Object -/// -class LabelModelImageObject : public LabelModelObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -public: - LabelModelImageObject(); - LabelModelImageObject( const LabelModelImageObject* object ); - virtual ~LabelModelImageObject(); + /// + /// Label Model Image Object + /// + class LabelModelImageObject : public LabelModelObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + public: + LabelModelImageObject(); + LabelModelImageObject( const LabelModelImageObject* object ); + virtual ~LabelModelImageObject(); - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelImageObject* clone() const; + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelImageObject* clone() const; - /////////////////////////////////////////////////////////////// - // Property Implementations - /////////////////////////////////////////////////////////////// -public: - // - // Image Property: filenameNode - // - virtual TextNode filenameNode( void ) const; - virtual void setFilenameNode( const TextNode& value ); + /////////////////////////////////////////////////////////////// + // Property Implementations + /////////////////////////////////////////////////////////////// + public: + // + // Image Property: filenameNode + // + virtual TextNode filenameNode( void ) const; + virtual void setFilenameNode( const TextNode& value ); - // - // Image Property: originalSize - // - virtual Size originalSize() const; + // + // Image Property: originalSize + // + virtual Size originalSize() const; - /////////////////////////////////////////////////////////////// - // Capability Implementations - /////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////// + // Capability Implementations + /////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual QPainterPath hoverPath( double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual QPainterPath hoverPath( double scale ) const; - /////////////////////////////////////////////////////////////// - // Private - /////////////////////////////////////////////////////////////// - void loadImage(); - QImage* createShadowImage( const QColor& color ) const; + /////////////////////////////////////////////////////////////// + // Private + /////////////////////////////////////////////////////////////// + void loadImage(); + QImage* createShadowImage( const QColor& color ) const; - /////////////////////////////////////////////////////////////// - // Private Members - /////////////////////////////////////////////////////////////// -protected: - TextNode mFilenameNode; - QImage* mImage; - QSvgRenderer* mSvg; + /////////////////////////////////////////////////////////////// + // Private Members + /////////////////////////////////////////////////////////////// + protected: + TextNode mFilenameNode; + QImage* mImage; + QSvgRenderer* mSvg; - static QImage* smDefaultImage; + static QImage* smDefaultImage; -}; + }; + +} #endif // LabelModelImageObject_h diff --git a/glabels/LabelModelLineObject.cpp b/glabels/LabelModelLineObject.cpp index 3bdec37..4a64f50 100644 --- a/glabels/LabelModelLineObject.cpp +++ b/glabels/LabelModelLineObject.cpp @@ -25,176 +25,185 @@ #include -namespace +namespace glabels { - const double slopPixels = 2; -} - -/// -/// Constructor -/// -LabelModelLineObject::LabelModelLineObject() -{ - mOutline = 0; - - mHandles << new HandleP1( this ); - mHandles << new HandleP2( this ); - - mLineWidth = 1.0; - mLineColorNode = ColorNode( QColor( 0, 0, 0 ) ); -} - - -/// -/// Copy constructor -/// -LabelModelLineObject::LabelModelLineObject( const LabelModelLineObject* object ) : LabelModelObject(object) -{ - mLineWidth = object->mLineWidth; - mLineColorNode = object->mLineColorNode; -} - - -/// -/// Destructor -/// -LabelModelLineObject::~LabelModelLineObject() -{ - foreach( Handle* handle, mHandles ) + // + // Private + // + namespace { - delete handle; + const double slopPixels = 2; } - mHandles.clear(); -} -/// -/// Clone -/// -LabelModelLineObject* LabelModelLineObject::clone() const -{ - return new LabelModelLineObject( this ); -} - - -/// -/// Line Width Property Getter -/// -glabels::Distance LabelModelLineObject::lineWidth( void ) const -{ - return mLineWidth; -} - - -/// -/// Line Width Property Setter -/// -void LabelModelLineObject::setLineWidth( const glabels::Distance& value ) -{ - if ( mLineWidth != value ) + /// + /// Constructor + /// + LabelModelLineObject::LabelModelLineObject() { - mLineWidth = value; - emit changed(); + mOutline = 0; + + mHandles << new HandleP1( this ); + mHandles << new HandleP2( this ); + + mLineWidth = 1.0; + mLineColorNode = ColorNode( QColor( 0, 0, 0 ) ); } -} -/// -/// Line Color Node Property Getter -/// -ColorNode LabelModelLineObject::lineColorNode( void ) const -{ - return mLineColorNode; -} - - -/// -/// Line Color Node Property Setter -/// -void LabelModelLineObject::setLineColorNode( const ColorNode& value ) -{ - if ( mLineColorNode != value ) + /// + /// Copy constructor + /// + LabelModelLineObject::LabelModelLineObject( const LabelModelLineObject* object ) + : LabelModelObject(object) { - mLineColorNode = value; - emit changed(); + mLineWidth = object->mLineWidth; + mLineColorNode = object->mLineColorNode; + } + + + /// + /// Destructor + /// + LabelModelLineObject::~LabelModelLineObject() + { + foreach( Handle* handle, mHandles ) + { + delete handle; + } + mHandles.clear(); + } + + + /// + /// Clone + /// + LabelModelLineObject* LabelModelLineObject::clone() const + { + return new LabelModelLineObject( this ); + } + + + /// + /// Line Width Property Getter + /// + Distance LabelModelLineObject::lineWidth( void ) const + { + return mLineWidth; + } + + + /// + /// Line Width Property Setter + /// + void LabelModelLineObject::setLineWidth( const Distance& value ) + { + if ( mLineWidth != value ) + { + mLineWidth = value; + emit changed(); + } + } + + + /// + /// Line Color Node Property Getter + /// + ColorNode LabelModelLineObject::lineColorNode( void ) const + { + return mLineColorNode; + } + + + /// + /// Line Color Node Property Setter + /// + void LabelModelLineObject::setLineColorNode( const ColorNode& value ) + { + if ( mLineColorNode != value ) + { + mLineColorNode = value; + emit changed(); + } } -} -/// -/// Can Line Color Capability Implementation -/// -bool LabelModelLineObject::canLineColor() -{ - return true; -} - - -/// -/// Can Line Width Capability Implementation -/// -bool LabelModelLineObject::canLineWidth() -{ - return true; -} - - -/// -/// Draw shadow of object -/// -void LabelModelLineObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - QColor shadowColor = mShadowColorNode.color( record ); - - shadowColor.setAlphaF( mShadowOpacity ); - - if ( lineColor.alpha() ) + /// + /// Can Line Color Capability Implementation + /// + bool LabelModelLineObject::canLineColor() { - painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); + return true; + } + + + /// + /// Can Line Width Capability Implementation + /// + bool LabelModelLineObject::canLineWidth() + { + return true; + } + + + /// + /// Draw shadow of object + /// + void LabelModelLineObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + QColor shadowColor = mShadowColorNode.color( record ); + + shadowColor.setAlphaF( mShadowOpacity ); + + if ( lineColor.alpha() ) + { + painter->setPen( QPen( shadowColor, mLineWidth.pt() ) ); + painter->drawLine( 0, 0, mW.pt(), mH.pt() ); + } + } + + + /// + /// Draw object itself + /// + void LabelModelLineObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const + { + QColor lineColor = mLineColorNode.color( record ); + + painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); painter->drawLine( 0, 0, mW.pt(), mH.pt() ); } -} - - -/// -/// Draw object itself -/// -void LabelModelLineObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor lineColor = mLineColorNode.color( record ); - - painter->setPen( QPen( lineColor, mLineWidth.pt() ) ); - painter->drawLine( 0, 0, mW.pt(), mH.pt() ); -} -/// -/// Path to test for hover condition -/// -QPainterPath LabelModelLineObject::hoverPath( double scale ) const -{ - QPainterPath path; - - if ( mLineColorNode.color().alpha() ) + /// + /// Path to test for hover condition + /// + QPainterPath LabelModelLineObject::hoverPath( double scale ) const { - // - // Build a thin rectangle representing line - // - double rPts = mLineWidth.pt()/2 + slopPixels / scale; + QPainterPath path; - double lengthPts = sqrt( mW.pt()*mW.pt() + mH.pt()*mH.pt() ); - double dx = mH.pt() / lengthPts; // horizontal pitch of perpendicular line - double dy = mW.pt() / lengthPts; // vertical pitch of perpendicular line + if ( mLineColorNode.color().alpha() ) + { + // + // Build a thin rectangle representing line + // + double rPts = mLineWidth.pt()/2 + slopPixels / scale; + + double lengthPts = sqrt( mW.pt()*mW.pt() + mH.pt()*mH.pt() ); + double dx = mH.pt() / lengthPts; // horizontal pitch of perpendicular line + double dy = mW.pt() / lengthPts; // vertical pitch of perpendicular line - path.moveTo( rPts*dx, - rPts*dy ); - path.lineTo( mW.pt() + rPts*dx, mH.pt() - rPts*dy ); - path.lineTo( mW.pt() - rPts*dx, mH.pt() + rPts*dy ); - path.lineTo( - rPts*dx, rPts*dy ); + path.moveTo( rPts*dx, - rPts*dy ); + path.lineTo( mW.pt() + rPts*dx, mH.pt() - rPts*dy ); + path.lineTo( mW.pt() - rPts*dx, mH.pt() + rPts*dy ); + path.lineTo( - rPts*dx, rPts*dy ); - path.closeSubpath(); + path.closeSubpath(); + } + + return path; } - return path; } diff --git a/glabels/LabelModelLineObject.h b/glabels/LabelModelLineObject.h index e43c485..4cc234e 100644 --- a/glabels/LabelModelLineObject.h +++ b/glabels/LabelModelLineObject.h @@ -25,71 +25,76 @@ #include "LabelModelObject.h" -/// -/// Label Model Line Object -/// -class LabelModelLineObject : public LabelModelObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -public: - LabelModelLineObject(); - LabelModelLineObject( const LabelModelLineObject* object ); - virtual ~LabelModelLineObject(); + /// + /// Label Model Line Object + /// + class LabelModelLineObject : public LabelModelObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + public: + LabelModelLineObject(); + LabelModelLineObject( const LabelModelLineObject* object ); + virtual ~LabelModelLineObject(); - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelLineObject* clone() const; + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelLineObject* clone() const; - /////////////////////////////////////////////////////////////// - // Property Implementations - /////////////////////////////////////////////////////////////// -public: - // - // Line Property: lineWidth - // - virtual glabels::Distance lineWidth( void ) const; - virtual void setLineWidth( const glabels::Distance& value ); + /////////////////////////////////////////////////////////////// + // Property Implementations + /////////////////////////////////////////////////////////////// + public: + // + // Line Property: lineWidth + // + virtual Distance lineWidth( void ) const; + virtual void setLineWidth( const Distance& value ); - // - // Line Property: lineColorNode - // - virtual ColorNode lineColorNode( void ) const; - virtual void setLineColorNode( const ColorNode& value ); + // + // Line Property: lineColorNode + // + virtual ColorNode lineColorNode( void ) const; + virtual void setLineColorNode( const ColorNode& value ); - /////////////////////////////////////////////////////////////// - // Capability Implementations - /////////////////////////////////////////////////////////////// -public: - virtual bool canLineColor(); - virtual bool canLineWidth(); + /////////////////////////////////////////////////////////////// + // Capability Implementations + /////////////////////////////////////////////////////////////// + public: + virtual bool canLineColor(); + virtual bool canLineWidth(); - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual QPainterPath hoverPath( double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual QPainterPath hoverPath( double scale ) const; - /////////////////////////////////////////////////////////////// - // Private Members - /////////////////////////////////////////////////////////////// -protected: - glabels::Distance mLineWidth; - ColorNode mLineColorNode; + /////////////////////////////////////////////////////////////// + // Private Members + /////////////////////////////////////////////////////////////// + protected: + Distance mLineWidth; + ColorNode mLineColorNode; -}; + }; + +} #endif // LabelModelLineObject_h diff --git a/glabels/LabelModelObject.cpp b/glabels/LabelModelObject.cpp index 43db1c2..33510a5 100644 --- a/glabels/LabelModelObject.cpp +++ b/glabels/LabelModelObject.cpp @@ -31,871 +31,841 @@ #include "TextNode.h" -/// -/// Next Object ID -/// -int LabelModelObject::msNextId = 0; - - -/// -/// Constructor -/// -LabelModelObject::LabelModelObject() : QObject(0) +namespace glabels { - mId = msNextId++; - mX0 = 0; - mY0 = 0; - mW = 0; - mH = 0; - mMatrix = QMatrix(); - - mShadowState = false; - mShadowX = 1.3; - mShadowY = 1.3; - mShadowColorNode = ColorNode( QColor( 0, 0, 0 ) ); - mShadowOpacity = 0.5; - - mSelectedFlag = false; - - mOutline = 0; -} + /// + /// Next Object ID + /// + int LabelModelObject::msNextId = 0; -/// -/// Copy constructor -/// -LabelModelObject::LabelModelObject( const LabelModelObject* object ) -{ - mId = msNextId++; - - mSelectedFlag = object->mSelectedFlag; - - mX0 = object->mX0; - mY0 = object->mY0; - mW = object->mW; - mH = object->mH; - - mShadowState = object->mShadowState; - mShadowX = object->mShadowX; - mShadowY = object->mShadowY; - mShadowOpacity = object->mShadowOpacity; - mShadowColorNode = object->mShadowColorNode; - - foreach ( Handle* handle, object->mHandles ) - { - mHandles.append( handle->clone( this ) ); - } - - if ( object->mOutline ) - { - mOutline = object->mOutline->clone( this ); - } - else + /// + /// Constructor + /// + LabelModelObject::LabelModelObject() : QObject(0) { + mId = msNextId++; + + mX0 = 0; + mY0 = 0; + mW = 0; + mH = 0; + mMatrix = QMatrix(); + + mShadowState = false; + mShadowX = 1.3; + mShadowY = 1.3; + mShadowColorNode = ColorNode( QColor( 0, 0, 0 ) ); + mShadowOpacity = 0.5; + + mSelectedFlag = false; + mOutline = 0; } - mMatrix = object->mMatrix; -} - -/// -/// Destructor -/// -LabelModelObject::~LabelModelObject() -{ -} - - -/// -/// ID Property Getter -/// -int LabelModelObject::id() const -{ - return mId; -} - - -/// -/// Selected Property Getter -/// -bool LabelModelObject::isSelected() const -{ - return mSelectedFlag; -} - - -/// -/// Selected Property Setter -/// -void LabelModelObject::select( bool value ) -{ - mSelectedFlag = value; -} - - -/// -/// Clear Selected Property Setter -/// -void LabelModelObject::unselect() -{ - mSelectedFlag = false; -} - - -/// -/// X0 Property Getter -/// -glabels::Distance LabelModelObject::x0() const -{ - return mX0; -} - - -/// -/// X0 Property Setter -/// -void LabelModelObject::setX0( const glabels::Distance& value ) -{ - if ( mX0 != value ) + /// + /// Copy constructor + /// + LabelModelObject::LabelModelObject( const LabelModelObject* object ) { - mX0 = value; - emit moved(); - } -} - - -/// -/// Y0 Property Getter -/// -glabels::Distance LabelModelObject::y0() const -{ - return mY0; -} - - -/// -/// Y0 Property Setter -/// -void LabelModelObject::setY0( const glabels::Distance& value ) -{ - if ( mY0 != value ) - { - mY0 = value; - emit moved(); - } -} - - -/// -/// W (Width) Property Getter -/// -glabels::Distance LabelModelObject::w() const -{ - return mW; -} - - -/// -/// W (Width) Property Setter -/// -void LabelModelObject::setW( const glabels::Distance& value ) -{ - if ( mW != value ) - { - mW = value; - sizeUpdated(); - emit changed(); - } -} - - -/// -/// H (Height) Property Getter -/// -glabels::Distance LabelModelObject::h() const -{ - return mH; -} - - -/// -/// H (Height) Property Setter -/// -void LabelModelObject::setH( const glabels::Distance& value ) -{ - if ( mH != value ) - { - mH = value; - sizeUpdated(); - emit changed(); - } -} - - -/// -/// Matrix Property Getter -/// -QMatrix LabelModelObject::matrix() const -{ - return mMatrix; -} - - -/// -/// Matrix Property Setter -/// -void LabelModelObject::setMatrix( const QMatrix& value ) -{ - if ( mMatrix != value ) - { - mMatrix = value; - emit changed(); - } -} - - -/// -/// Shadow State Property Getter -/// -bool LabelModelObject::shadow() const -{ - return mShadowState; -} - - -/// -/// Shadow State Property Setter -/// -void LabelModelObject::setShadow( bool value ) -{ - if ( mShadowState != value ) - { - mShadowState = value; - emit changed(); - } -} - - -/// -/// Shadow X Property Getter -/// -glabels::Distance LabelModelObject::shadowX() const -{ - return mShadowX; -} - - -/// -/// Shadow X Property Setter -/// -void LabelModelObject::setShadowX( const glabels::Distance& value ) -{ - if ( mShadowX != value ) - { - mShadowX = value; - emit changed(); - } -} - - -/// -/// Shadow Y Property Getter -/// -glabels::Distance LabelModelObject::shadowY() const -{ - return mShadowY; -} - - -/// -/// Shadow Y Property Setter -/// -void LabelModelObject::setShadowY( const glabels::Distance& value ) -{ - if ( mShadowY != value ) - { - mShadowY = value; - emit changed(); - } -} - - -/// -/// Shadow Opacity Property Getter -/// -double LabelModelObject::shadowOpacity() const -{ - return mShadowOpacity; -} - - -/// -/// Shadow Opacity Property Setter -/// -void LabelModelObject::setShadowOpacity( double value ) -{ - if ( mShadowOpacity != value ) - { - mShadowOpacity = value; - emit changed(); - } -} - - -/// -/// Shadow Color Node Property Getter -/// -ColorNode LabelModelObject::shadowColorNode() const -{ - return mShadowColorNode; -} - - -/// -/// Shadow Color Node Property Setter -/// -void LabelModelObject::setShadowColorNode( const ColorNode& value ) -{ - if ( mShadowColorNode != value ) - { - mShadowColorNode = value; - emit changed(); - } -} - - -/// -/// Virtual Text Property Default Getter -/// (Overridden by concrete class) -/// -QString LabelModelObject::text() const -{ - return ""; -} - - -/// -/// Virtual Text Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setText( const QString& value ) -{ -} - - -/// -/// Virtual Font Family Property Default Getter -/// (Overridden by concrete class) -/// -QString LabelModelObject::fontFamily() const -{ - return ""; -} - - -/// -/// Virtual Font Family Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFontFamily( const QString& value ) -{ -} - - -/// -/// Virtual Font Size Property Default Getter -/// (Overridden by concrete class) -/// -double LabelModelObject::fontSize() const -{ - return 0; -} - - -/// -/// Virtual Font Size Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFontSize( double value ) -{ -} - - -/// -/// Virtual Font Weight Property Default Getter -/// (Overridden by concrete class) -/// -QFont::Weight LabelModelObject::fontWeight() const -{ - return QFont::Normal; -} - - -/// -/// Virtual Font Weight Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFontWeight( QFont::Weight value ) -{ -} - - -/// -/// Virtual Font Italic Flag Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::fontItalicFlag() const -{ - return false; -} - - -/// -/// Virtual Font Italic Flag Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFontItalicFlag( bool value ) -{ -} - - -/// -/// Virtual Font Underline Flag Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::fontUnderlineFlag() const -{ - return false; -} - - -/// -/// Virtual Font Underline Flag Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFontUnderlineFlag( bool value ) -{ -} - - -/// -/// Virtual Text Color Node Property Default Getter -/// (Overridden by concrete class) -/// -ColorNode LabelModelObject::textColorNode() const -{ - return ColorNode( QColor::fromRgba(0x00000000) ); -} - - -/// -/// Virtual Text Color Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setTextColorNode( const ColorNode &value ) -{ -} - - -/// -/// Virtual Text Horizontal Alignment Property Default Getter -/// (Overridden by concrete class) -/// -Qt::Alignment LabelModelObject::textHAlign() const -{ - return Qt::AlignLeft; -} - - -/// -/// Virtual Text Horizontal Alignment Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setTextHAlign( Qt::Alignment value ) -{ -} - - -/// -/// Virtual Text Vertical Alignment Property Default Getter -/// (Overridden by concrete class) -/// -Qt::Alignment LabelModelObject::textVAlign() const -{ - return Qt::AlignTop; -} - - -/// -/// Virtual Text Vertical Alignment Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setTextVAlign( Qt::Alignment value ) -{ -} - - -/// -/// Virtual Text Line Spacing Property Default Getter -/// (Overridden by concrete class) -/// -double LabelModelObject::textLineSpacing() const -{ - return 0; -} - - -/// -/// Virtual Text Line Spacing Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setTextLineSpacing( double value ) -{ -} - - -/// -/// Virtual Filename Node Property Default Getter -/// (Overridden by concrete class) -/// -TextNode LabelModelObject::filenameNode() const -{ - return TextNode(); -} - - -/// -/// Virtual Filename Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFilenameNode( const TextNode& value ) -{ -} - - -/// -/// Virtual Original Size Property Default Getter -/// (Overridden by concrete class) -/// -Size LabelModelObject::originalSize() const -{ - return Size( glabels::Distance::pt(0), glabels::Distance::pt(0) ); -} - - -/// -/// Virtual Line Width Property Default Getter -/// (Overridden by concrete class) -/// -glabels::Distance LabelModelObject::lineWidth() const -{ - return 0; -} - - -/// -/// Virtual Line Width Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setLineWidth( const glabels::Distance& value ) -{ -} - - -/// -/// Virtual Line Color Node Property Default Getter -/// (Overridden by concrete class) -/// -ColorNode LabelModelObject::lineColorNode() const -{ - return ColorNode( QColor::fromRgba(0x00000000) ); -} - - -/// -/// Virtual Line Color Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setLineColorNode( const ColorNode &value ) -{ -} - - -/// -/// Virtual Fill Color Node Property Default Getter -/// (Overridden by concrete class) -/// -ColorNode LabelModelObject::fillColorNode() const -{ - return ColorNode( QColor::fromRgba(0x00000000) ); -} - - -/// -/// Virtual Fill Color Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setFillColorNode( const ColorNode &value ) -{ -} - - -/// -/// Virtual Barcode Data Node Property Default Getter -/// (Overridden by concrete class) -/// -TextNode LabelModelObject::bcDataNode() const -{ - return TextNode(); -} - - -/// -/// Virtual Barcode Data Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcDataNode( const TextNode &value ) -{ -} - - -/// -/// Virtual Barcode Text Flag Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::bcTextFlag() const -{ - return false; -} - - -/// -/// Virtual Barcode Text Flag Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcTextFlag( bool value ) -{ -} - - -/// -/// Virtual Barcode Checksum Flag Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::bcChecksumFlag() const -{ - return false; -} - - -/// -/// Virtual Barcode Checksum Flag Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcChecksumFlag( bool value ) -{ -} - - -/// -/// Virtual Barcode Color Node Property Default Getter -/// (Overridden by concrete class) -/// -ColorNode LabelModelObject::bcColorNode() const -{ - return ColorNode( QColor::fromRgba(0x00000000) ); -} - - -/// -/// Virtual Barcode Color Node Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcColorNode( const ColorNode &value ) -{ -} - - -/// -/// Virtual Barcode Style Property Default Getter -/// (Overridden by concrete class) -/// -BarcodeStyle LabelModelObject::bcStyle() const -{ - return BarcodeStyle(); -} - - -/// -/// Virtual Barcode Style Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcStyle( const BarcodeStyle &value ) -{ -} - - -/// -/// Virtual Barcode Format Digits Property Default Getter -/// (Overridden by concrete class) -/// -int LabelModelObject::bcFormatDigits() const -{ - return 0; -} - - -/// -/// Virtual Barcode Format Digits Property Default Setter -/// (Overridden by concrete class) -/// -void LabelModelObject::setBcFormatDigits( int value ) -{ -} - - -/// -/// Virtual Can Text Capability Read-Only Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::canText() const -{ - return false; -} - - -/// -/// Virtual Can Fill Capability Read-Only Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::canFill() const -{ - return false; -} - - -/// -/// Virtual Can Line Color Capability Read-Only Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::canLineColor() const -{ - return false; -} - - -/// -/// Virtual Can Line Width Capability Read-Only Property Default Getter -/// (Overridden by concrete class) -/// -bool LabelModelObject::canLineWidth() const -{ - return false; -} - - -/// -/// Set Absolute Position -/// -void LabelModelObject::setPosition( const glabels::Distance& x0, - const glabels::Distance& y0 ) -{ - if ( ( mX0 != x0 ) || ( mY0 != y0 ) ) - { - mX0 = x0; - mY0 = y0; - - emit moved(); - } -} - - -/// -/// Set Relative Position -/// -void LabelModelObject::setPositionRelative( const glabels::Distance& dx, - const glabels::Distance& dy ) -{ - if ( ( dx != 0 ) || ( dy != 0 ) ) - { - mX0 += dx; - mY0 += dy; - - emit moved(); - } -} - - -/// -/// Get Size -/// -Size LabelModelObject::size() const -{ - return Size( mW, mH ); -} - - -/// -/// Set Size -/// -void LabelModelObject::setSize( const glabels::Distance& w, - const glabels::Distance& h ) -{ - mW = w; - mH = h; - - sizeUpdated(); - emit changed(); -} - - -/// -/// Set Size -/// -void LabelModelObject::setSize( const Size& size ) -{ - mW = size.w(); - mH = size.h(); - - sizeUpdated(); - emit changed(); -} - - -/// -/// Set Size (But Maintain Current Aspect Ratio) -/// -void LabelModelObject::setSizeHonorAspect( const glabels::Distance& w, - const glabels::Distance& h ) -{ - double aspectRatio = mH / mW; - glabels::Distance wNew = w; - glabels::Distance hNew = h; - - if ( h > (w*aspectRatio) ) - { - hNew = w*aspectRatio; - } - else - { - wNew = h/aspectRatio; + mId = msNextId++; + + mSelectedFlag = object->mSelectedFlag; + + mX0 = object->mX0; + mY0 = object->mY0; + mW = object->mW; + mH = object->mH; + + mShadowState = object->mShadowState; + mShadowX = object->mShadowX; + mShadowY = object->mShadowY; + mShadowOpacity = object->mShadowOpacity; + mShadowColorNode = object->mShadowColorNode; + + foreach ( Handle* handle, object->mHandles ) + { + mHandles.append( handle->clone( this ) ); + } + + if ( object->mOutline ) + { + mOutline = object->mOutline->clone( this ); + } + else + { + mOutline = 0; + } + + mMatrix = object->mMatrix; } - setSize( wNew, hNew ); -} + + /// + /// Destructor + /// + LabelModelObject::~LabelModelObject() + { + // empty + } -/// -/// Set Width (But Maintain Current Aspect Ratio) -/// -void LabelModelObject::setWHonorAspect( const glabels::Distance& w ) -{ - double aspectRatio = mH / mW; - glabels::Distance h = w * aspectRatio; + /// + /// ID Property Getter + /// + int LabelModelObject::id() const + { + return mId; + } - if ( ( mW != w ) || ( mH != h ) ) + + /// + /// Selected Property Getter + /// + bool LabelModelObject::isSelected() const + { + return mSelectedFlag; + } + + + /// + /// Selected Property Setter + /// + void LabelModelObject::select( bool value ) + { + mSelectedFlag = value; + } + + + /// + /// Clear Selected Property Setter + /// + void LabelModelObject::unselect() + { + mSelectedFlag = false; + } + + + /// + /// X0 Property Getter + /// + Distance LabelModelObject::x0() const + { + return mX0; + } + + + /// + /// X0 Property Setter + /// + void LabelModelObject::setX0( const Distance& value ) + { + if ( mX0 != value ) + { + mX0 = value; + emit moved(); + } + } + + + /// + /// Y0 Property Getter + /// + Distance LabelModelObject::y0() const + { + return mY0; + } + + + /// + /// Y0 Property Setter + /// + void LabelModelObject::setY0( const Distance& value ) + { + if ( mY0 != value ) + { + mY0 = value; + emit moved(); + } + } + + + /// + /// W (Width) Property Getter + /// + Distance LabelModelObject::w() const + { + return mW; + } + + + /// + /// W (Width) Property Setter + /// + void LabelModelObject::setW( const Distance& value ) + { + if ( mW != value ) + { + mW = value; + sizeUpdated(); + emit changed(); + } + } + + + /// + /// H (Height) Property Getter + /// + Distance LabelModelObject::h() const + { + return mH; + } + + + /// + /// H (Height) Property Setter + /// + void LabelModelObject::setH( const Distance& value ) + { + if ( mH != value ) + { + mH = value; + sizeUpdated(); + emit changed(); + } + } + + + /// + /// Matrix Property Getter + /// + QMatrix LabelModelObject::matrix() const + { + return mMatrix; + } + + + /// + /// Matrix Property Setter + /// + void LabelModelObject::setMatrix( const QMatrix& value ) + { + if ( mMatrix != value ) + { + mMatrix = value; + emit changed(); + } + } + + + /// + /// Shadow State Property Getter + /// + bool LabelModelObject::shadow() const + { + return mShadowState; + } + + + /// + /// Shadow State Property Setter + /// + void LabelModelObject::setShadow( bool value ) + { + if ( mShadowState != value ) + { + mShadowState = value; + emit changed(); + } + } + + + /// + /// Shadow X Property Getter + /// + Distance LabelModelObject::shadowX() const + { + return mShadowX; + } + + + /// + /// Shadow X Property Setter + /// + void LabelModelObject::setShadowX( const Distance& value ) + { + if ( mShadowX != value ) + { + mShadowX = value; + emit changed(); + } + } + + + /// + /// Shadow Y Property Getter + /// + Distance LabelModelObject::shadowY() const + { + return mShadowY; + } + + + /// + /// Shadow Y Property Setter + /// + void LabelModelObject::setShadowY( const Distance& value ) + { + if ( mShadowY != value ) + { + mShadowY = value; + emit changed(); + } + } + + + /// + /// Shadow Opacity Property Getter + /// + double LabelModelObject::shadowOpacity() const + { + return mShadowOpacity; + } + + + /// + /// Shadow Opacity Property Setter + /// + void LabelModelObject::setShadowOpacity( double value ) + { + if ( mShadowOpacity != value ) + { + mShadowOpacity = value; + emit changed(); + } + } + + + /// + /// Shadow Color Node Property Getter + /// + ColorNode LabelModelObject::shadowColorNode() const + { + return mShadowColorNode; + } + + + /// + /// Shadow Color Node Property Setter + /// + void LabelModelObject::setShadowColorNode( const ColorNode& value ) + { + if ( mShadowColorNode != value ) + { + mShadowColorNode = value; + emit changed(); + } + } + + + /// + /// Virtual Text Property Default Getter + /// (Overridden by concrete class) + /// + QString LabelModelObject::text() const + { + return ""; + } + + + /// + /// Virtual Text Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setText( const QString& value ) + { + // empty + } + + + /// + /// Virtual Font Family Property Default Getter + /// (Overridden by concrete class) + /// + QString LabelModelObject::fontFamily() const + { + return ""; + } + + + /// + /// Virtual Font Family Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFontFamily( const QString& value ) + { + // empty + } + + + /// + /// Virtual Font Size Property Default Getter + /// (Overridden by concrete class) + /// + double LabelModelObject::fontSize() const + { + return 0; + } + + + /// + /// Virtual Font Size Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFontSize( double value ) + { + // empty + } + + + /// + /// Virtual Font Weight Property Default Getter + /// (Overridden by concrete class) + /// + QFont::Weight LabelModelObject::fontWeight() const + { + return QFont::Normal; + } + + + /// + /// Virtual Font Weight Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFontWeight( QFont::Weight value ) + { + // empty + } + + + /// + /// Virtual Font Italic Flag Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::fontItalicFlag() const + { + return false; + } + + + /// + /// Virtual Font Italic Flag Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFontItalicFlag( bool value ) + { + // empty + } + + + /// + /// Virtual Font Underline Flag Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::fontUnderlineFlag() const + { + return false; + } + + + /// + /// Virtual Font Underline Flag Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFontUnderlineFlag( bool value ) + { + // empty + } + + + /// + /// Virtual Text Color Node Property Default Getter + /// (Overridden by concrete class) + /// + ColorNode LabelModelObject::textColorNode() const + { + return ColorNode( QColor::fromRgba(0x00000000) ); + } + + + /// + /// Virtual Text Color Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setTextColorNode( const ColorNode &value ) + { + // empty + } + + + /// + /// Virtual Text Horizontal Alignment Property Default Getter + /// (Overridden by concrete class) + /// + Qt::Alignment LabelModelObject::textHAlign() const + { + return Qt::AlignLeft; + } + + + /// + /// Virtual Text Horizontal Alignment Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setTextHAlign( Qt::Alignment value ) + { + // empty + } + + + /// + /// Virtual Text Vertical Alignment Property Default Getter + /// (Overridden by concrete class) + /// + Qt::Alignment LabelModelObject::textVAlign() const + { + return Qt::AlignTop; + } + + + /// + /// Virtual Text Vertical Alignment Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setTextVAlign( Qt::Alignment value ) + { + // empty + } + + + /// + /// Virtual Text Line Spacing Property Default Getter + /// (Overridden by concrete class) + /// + double LabelModelObject::textLineSpacing() const + { + return 0; + } + + + /// + /// Virtual Text Line Spacing Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setTextLineSpacing( double value ) + { + // empty + } + + + /// + /// Virtual Filename Node Property Default Getter + /// (Overridden by concrete class) + /// + TextNode LabelModelObject::filenameNode() const + { + return TextNode(); + } + + + /// + /// Virtual Filename Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFilenameNode( const TextNode& value ) + { + // empty + } + + + /// + /// Virtual Original Size Property Default Getter + /// (Overridden by concrete class) + /// + Size LabelModelObject::originalSize() const + { + return Size( Distance::pt(0), Distance::pt(0) ); + } + + + /// + /// Virtual Line Width Property Default Getter + /// (Overridden by concrete class) + /// + Distance LabelModelObject::lineWidth() const + { + return 0; + } + + + /// + /// Virtual Line Width Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setLineWidth( const Distance& value ) + { + // empty + } + + + /// + /// Virtual Line Color Node Property Default Getter + /// (Overridden by concrete class) + /// + ColorNode LabelModelObject::lineColorNode() const + { + return ColorNode( QColor::fromRgba(0x00000000) ); + } + + + /// + /// Virtual Line Color Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setLineColorNode( const ColorNode &value ) + { + // empty + } + + + /// + /// Virtual Fill Color Node Property Default Getter + /// (Overridden by concrete class) + /// + ColorNode LabelModelObject::fillColorNode() const + { + return ColorNode( QColor::fromRgba(0x00000000) ); + } + + + /// + /// Virtual Fill Color Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setFillColorNode( const ColorNode &value ) + { + // empty + } + + + /// + /// Virtual Barcode Data Node Property Default Getter + /// (Overridden by concrete class) + /// + TextNode LabelModelObject::bcDataNode() const + { + return TextNode(); + } + + + /// + /// Virtual Barcode Data Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcDataNode( const TextNode &value ) + { + // empty + } + + + /// + /// Virtual Barcode Text Flag Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::bcTextFlag() const + { + return false; + } + + + /// + /// Virtual Barcode Text Flag Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcTextFlag( bool value ) + { + // empty + } + + + /// + /// Virtual Barcode Checksum Flag Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::bcChecksumFlag() const + { + return false; + } + + + /// + /// Virtual Barcode Checksum Flag Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcChecksumFlag( bool value ) + { + // empty + } + + + /// + /// Virtual Barcode Color Node Property Default Getter + /// (Overridden by concrete class) + /// + ColorNode LabelModelObject::bcColorNode() const + { + return ColorNode( QColor::fromRgba(0x00000000) ); + } + + + /// + /// Virtual Barcode Color Node Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcColorNode( const ColorNode &value ) + { + // empty + } + + + /// + /// Virtual Barcode Style Property Default Getter + /// (Overridden by concrete class) + /// + BarcodeStyle LabelModelObject::bcStyle() const + { + return BarcodeStyle(); + } + + + /// + /// Virtual Barcode Style Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcStyle( const BarcodeStyle &value ) + { + // empty + } + + + /// + /// Virtual Barcode Format Digits Property Default Getter + /// (Overridden by concrete class) + /// + int LabelModelObject::bcFormatDigits() const + { + return 0; + } + + + /// + /// Virtual Barcode Format Digits Property Default Setter + /// (Overridden by concrete class) + /// + void LabelModelObject::setBcFormatDigits( int value ) + { + // empty + } + + + /// + /// Virtual Can Text Capability Read-Only Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::canText() const + { + return false; + } + + + /// + /// Virtual Can Fill Capability Read-Only Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::canFill() const + { + return false; + } + + + /// + /// Virtual Can Line Color Capability Read-Only Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::canLineColor() const + { + return false; + } + + + /// + /// Virtual Can Line Width Capability Read-Only Property Default Getter + /// (Overridden by concrete class) + /// + bool LabelModelObject::canLineWidth() const + { + return false; + } + + + /// + /// Set Absolute Position + /// + void LabelModelObject::setPosition( const Distance& x0, + const Distance& y0 ) + { + if ( ( mX0 != x0 ) || ( mY0 != y0 ) ) + { + mX0 = x0; + mY0 = y0; + + emit moved(); + } + } + + + /// + /// Set Relative Position + /// + void LabelModelObject::setPositionRelative( const Distance& dx, + const Distance& dy ) + { + if ( ( dx != 0 ) || ( dy != 0 ) ) + { + mX0 += dx; + mY0 += dy; + + emit moved(); + } + } + + + /// + /// Get Size + /// + Size LabelModelObject::size() const + { + return Size( mW, mH ); + } + + + /// + /// Set Size + /// + void LabelModelObject::setSize( const Distance& w, + const Distance& h ) { mW = w; mH = h; @@ -903,205 +873,260 @@ void LabelModelObject::setWHonorAspect( const glabels::Distance& w ) sizeUpdated(); emit changed(); } -} -/// -/// Set Height (But Maintain Current Aspect Ratio) -/// -void LabelModelObject::setHHonorAspect( const glabels::Distance& h ) -{ - double aspectRatio = mH / mW; - glabels::Distance w = h / aspectRatio; - - if ( ( mW != w ) || ( mH != h ) ) + /// + /// Set Size + /// + void LabelModelObject::setSize( const Size& size ) { - mW = w; - mH = h; + mW = size.w(); + mH = size.h(); sizeUpdated(); emit changed(); } -} -/// -/// Get Extent of Bounding Box -/// -Region LabelModelObject::getExtent() -{ - using namespace glabels; + /// + /// Set Size (But Maintain Current Aspect Ratio) + /// + void LabelModelObject::setSizeHonorAspect( const Distance& w, + const Distance& h ) + { + double aspectRatio = mH / mW; + Distance wNew = w; + Distance hNew = h; + + if ( h > (w*aspectRatio) ) + { + hNew = w*aspectRatio; + } + else + { + wNew = h/aspectRatio; + } - QPointF a1( ( - lineWidth()/2).pt(), ( - lineWidth()/2).pt() ); - QPointF a2( (mW + lineWidth()/2).pt(), ( - lineWidth()/2).pt() ); - QPointF a3( (mW + lineWidth()/2).pt(), (mH + lineWidth()/2).pt() ); - QPointF a4( ( - lineWidth()/2).pt(), (mH + lineWidth()/2).pt() ); - - a1 = mMatrix.map( a1 ); - a2 = mMatrix.map( a2 ); - a3 = mMatrix.map( a3 ); - a4 = mMatrix.map( a4 ); - - Region region; - region.setX1( min( a1.x(), min( a2.x(), min( a3.x(), a4.x() ) ) ) + mX0 ); - region.setY1( min( a1.y(), min( a2.y(), min( a3.y(), a4.y() ) ) ) + mY0 ); - region.setX2( max( a1.x(), max( a2.x(), max( a3.x(), a4.x() ) ) ) + mX0 ); - region.setY2( max( a1.y(), max( a2.y(), max( a3.y(), a4.y() ) ) ) + mY0 ); - - return region; -} + setSize( wNew, hNew ); + } -/// -/// Rotate Object -/// -void LabelModelObject::rotate( double thetaDegs ) -{ - if ( thetaDegs != 0 ) + /// + /// Set Width (But Maintain Current Aspect Ratio) + /// + void LabelModelObject::setWHonorAspect( const Distance& w ) + { + double aspectRatio = mH / mW; + Distance h = w * aspectRatio; + + if ( ( mW != w ) || ( mH != h ) ) + { + mW = w; + mH = h; + + sizeUpdated(); + emit changed(); + } + } + + + /// + /// Set Height (But Maintain Current Aspect Ratio) + /// + void LabelModelObject::setHHonorAspect( const Distance& h ) + { + double aspectRatio = mH / mW; + Distance w = h / aspectRatio; + + if ( ( mW != w ) || ( mH != h ) ) + { + mW = w; + mH = h; + + sizeUpdated(); + emit changed(); + } + } + + + /// + /// Get Extent of Bounding Box + /// + Region LabelModelObject::getExtent() + { + QPointF a1( ( - lineWidth()/2).pt(), ( - lineWidth()/2).pt() ); + QPointF a2( (mW + lineWidth()/2).pt(), ( - lineWidth()/2).pt() ); + QPointF a3( (mW + lineWidth()/2).pt(), (mH + lineWidth()/2).pt() ); + QPointF a4( ( - lineWidth()/2).pt(), (mH + lineWidth()/2).pt() ); + + a1 = mMatrix.map( a1 ); + a2 = mMatrix.map( a2 ); + a3 = mMatrix.map( a3 ); + a4 = mMatrix.map( a4 ); + + Region region; + region.setX1( min( a1.x(), min( a2.x(), min( a3.x(), a4.x() ) ) ) + mX0 ); + region.setY1( min( a1.y(), min( a2.y(), min( a3.y(), a4.y() ) ) ) + mY0 ); + region.setX2( max( a1.x(), max( a2.x(), max( a3.x(), a4.x() ) ) ) + mX0 ); + region.setY2( max( a1.y(), max( a2.y(), max( a3.y(), a4.y() ) ) ) + mY0 ); + + return region; + } + + + /// + /// Rotate Object + /// + void LabelModelObject::rotate( double thetaDegs ) + { + if ( thetaDegs != 0 ) + { + QMatrix m; + m.rotate( thetaDegs ); + mMatrix *= m; + + emit changed(); + } + } + + + /// + /// Flip Object Horizontally + /// + void LabelModelObject::flipHoriz() { QMatrix m; - m.rotate( thetaDegs ); + m.scale( -1, 1 ); mMatrix *= m; emit changed(); } -} -/// -/// Flip Object Horizontally -/// -void LabelModelObject::flipHoriz() -{ - QMatrix m; - m.scale( -1, 1 ); - mMatrix *= m; - - emit changed(); -} - - -/// -/// Flip Object Vertically -/// -void LabelModelObject::flipVert() -{ - QMatrix m; - m.scale( 1, -1 ); - mMatrix *= m; - - emit changed(); -} - - -/// -/// Is this object located at x,y? -/// -bool LabelModelObject::isLocatedAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const -{ - QPointF p( x.pt(), y.pt() ); - - /* - * Change point to object relative coordinates - */ - p -= QPointF( mX0.pt(), mY0.pt() ); // Translate point to x0,y0 - p = mMatrix.inverted().map( p ); - - if ( hoverPath( scale ).contains( p ) ) + /// + /// Flip Object Vertically + /// + void LabelModelObject::flipVert() { - return true; + QMatrix m; + m.scale( 1, -1 ); + mMatrix *= m; + + emit changed(); } - else if ( isSelected() && mOutline ) + + + /// + /// Is this object located at x,y? + /// + bool LabelModelObject::isLocatedAt( double scale, + const Distance& x, + const Distance& y ) const { - if ( mOutline->hoverPath( scale ).contains( p ) ) + QPointF p( x.pt(), y.pt() ); + + /* + * Change point to object relative coordinates + */ + p -= QPointF( mX0.pt(), mY0.pt() ); // Translate point to x0,y0 + p = mMatrix.inverted().map( p ); + + if ( hoverPath( scale ).contains( p ) ) { return true; } - } - - return false; -} - - -/// -/// Is one of this object's handles locate at x,y? If so, return it. -/// -Handle* LabelModelObject::handleAt( double scale, - const glabels::Distance& x, - const glabels::Distance& y ) const -{ - if ( mSelectedFlag ) - { - QPointF p( x.pt(), y.pt() ); - p -= QPointF( mX0.pt(), mY0.pt() ); // Translate point to x0,y0 - - foreach ( Handle* handle, mHandles ) + else if ( isSelected() && mOutline ) { - QPainterPath handlePath = mMatrix.map( handle->path( scale ) ); - if ( handlePath.contains( p ) ) + if ( mOutline->hoverPath( scale ).contains( p ) ) { - return handle; + return true; } } + + return false; } - return 0; -} + + /// + /// Is one of this object's handles locate at x,y? If so, return it. + /// + Handle* LabelModelObject::handleAt( double scale, + const Distance& x, + const Distance& y ) const + { + if ( mSelectedFlag ) + { + QPointF p( x.pt(), y.pt() ); + p -= QPointF( mX0.pt(), mY0.pt() ); // Translate point to x0,y0 + + foreach ( Handle* handle, mHandles ) + { + QPainterPath handlePath = mMatrix.map( handle->path( scale ) ); + if ( handlePath.contains( p ) ) + { + return handle; + } + } + } + + return 0; + } -/// -/// Draw object + shadow -/// -void LabelModelObject::draw( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - painter->save(); - painter->translate( mX0.pt(), mY0.pt() ); - - if ( mShadowState ) + /// + /// Draw object + shadow + /// + void LabelModelObject::draw( QPainter* painter, bool inEditor, merge::Record* record ) const { painter->save(); - painter->translate( mShadowX.pt(), mShadowY.pt() ); + painter->translate( mX0.pt(), mY0.pt() ); + + if ( mShadowState ) + { + painter->save(); + painter->translate( mShadowX.pt(), mShadowY.pt() ); + painter->setMatrix( mMatrix, true ); + drawShadow( painter, inEditor, record ); + painter->restore(); + } + painter->setMatrix( mMatrix, true ); - drawShadow( painter, inEditor, record ); + drawObject( painter, inEditor, record ); + painter->restore(); } - painter->setMatrix( mMatrix, true ); - drawObject( painter, inEditor, record ); - painter->restore(); -} - - -/// -/// Draw selection highlights -/// -void LabelModelObject::drawSelectionHighlight( QPainter* painter, double scale ) const -{ - painter->save(); - - painter->translate( mX0.pt(), mY0.pt() ); - painter->setMatrix( mMatrix, true ); - - if ( mOutline ) + /// + /// Draw selection highlights + /// + void LabelModelObject::drawSelectionHighlight( QPainter* painter, double scale ) const { - mOutline->draw( painter ); - } + painter->save(); - foreach( Handle* handle, mHandles ) - { - handle->draw( painter, scale ); - } + painter->translate( mX0.pt(), mY0.pt() ); + painter->setMatrix( mMatrix, true ); + + if ( mOutline ) + { + mOutline->draw( painter ); + } + + foreach( Handle* handle, mHandles ) + { + handle->draw( painter, scale ); + } - painter->restore(); -} + painter->restore(); + } -/// -/// Default sizeUpdated implementation. -/// -void LabelModelObject::sizeUpdated() -{ + /// + /// Default sizeUpdated implementation. + /// + void LabelModelObject::sizeUpdated() + { + // empty + } + } diff --git a/glabels/LabelModelObject.h b/glabels/LabelModelObject.h index 2dcff3d..edcbd56 100644 --- a/glabels/LabelModelObject.h +++ b/glabels/LabelModelObject.h @@ -37,366 +37,371 @@ #include "Merge/Record.h" -// Forward References -class Region; -class Size; - - -/// -/// Label Model Object Base Class -/// -class LabelModelObject : public QObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -protected: - LabelModelObject(); - LabelModelObject( const LabelModelObject* object ); -public: - virtual ~LabelModelObject(); + // Forward References + class Region; + class Size; - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelObject* clone() const = 0; + /// + /// Label Model Object Base Class + /// + class LabelModelObject : public QObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + protected: + LabelModelObject(); + LabelModelObject( const LabelModelObject* object ); + public: + virtual ~LabelModelObject(); + + + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelObject* clone() const = 0; - /////////////////////////////////////////////////////////////// - // Signals - /////////////////////////////////////////////////////////////// -signals: - void moved(); - void changed(); + /////////////////////////////////////////////////////////////// + // Signals + /////////////////////////////////////////////////////////////// + signals: + void moved(); + void changed(); - /////////////////////////////////////////////////////////////// - // Common Properties - /////////////////////////////////////////////////////////////// -public: - // - // ID Property. - // - int id() const; + /////////////////////////////////////////////////////////////// + // Common Properties + /////////////////////////////////////////////////////////////// + public: + // + // ID Property. + // + int id() const; - // - // Selected Property. - // - bool isSelected() const; - void select( bool value = true ); - void unselect(); + // + // Selected Property. + // + bool isSelected() const; + void select( bool value = true ); + void unselect(); - // - // x0 Property ( x coordinate of origin ) - // - glabels::Distance x0() const; - void setX0( const glabels::Distance& value ); + // + // x0 Property ( x coordinate of origin ) + // + Distance x0() const; + void setX0( const Distance& value ); - // - // y0 Property ( y coordinate of origin ) - // - glabels::Distance y0() const; - void setY0( const glabels::Distance& value ); + // + // y0 Property ( y coordinate of origin ) + // + Distance y0() const; + void setY0( const Distance& value ); - // - // w Property ( width of bounding box ) - // - glabels::Distance w() const; - void setW( const glabels::Distance& value ); + // + // w Property ( width of bounding box ) + // + Distance w() const; + void setW( const Distance& value ); - // - // h Property ( height of bounding box ) - // - glabels::Distance h() const; - void setH( const glabels::Distance& value ); + // + // h Property ( height of bounding box ) + // + Distance h() const; + void setH( const Distance& value ); - // - // Transformation Matrix Property - // - QMatrix matrix() const; - void setMatrix( const QMatrix& value ); + // + // Transformation Matrix Property + // + QMatrix matrix() const; + void setMatrix( const QMatrix& value ); - // - // Shadow State Property - // - bool shadow() const; - void setShadow( bool value ); + // + // Shadow State Property + // + bool shadow() const; + void setShadow( bool value ); - // - // Shadow x Offset Property - // - glabels::Distance shadowX() const; - void setShadowX( const glabels::Distance& value ); + // + // Shadow x Offset Property + // + Distance shadowX() const; + void setShadowX( const Distance& value ); - // - // Shadow y Offset Property - // - glabels::Distance shadowY() const; - void setShadowY( const glabels::Distance& value ); + // + // Shadow y Offset Property + // + Distance shadowY() const; + void setShadowY( const Distance& value ); - // - // Shadow opacity Property - // - double shadowOpacity() const; - void setShadowOpacity( double value ); + // + // Shadow opacity Property + // + double shadowOpacity() const; + void setShadowOpacity( double value ); - // - // Shadow Color Property - // - ColorNode shadowColorNode() const; - void setShadowColorNode( const ColorNode& value ); + // + // Shadow Color Property + // + ColorNode shadowColorNode() const; + void setShadowColorNode( const ColorNode& value ); - /////////////////////////////////////////////////////////////// - // Text Properties Virtual Interface - /////////////////////////////////////////////////////////////// -public: - // - // Virtual Text Property: text - // - virtual QString text() const; - virtual void setText( const QString &value ); + /////////////////////////////////////////////////////////////// + // Text Properties Virtual Interface + /////////////////////////////////////////////////////////////// + public: + // + // Virtual Text Property: text + // + virtual QString text() const; + virtual void setText( const QString &value ); - // - // Virtual Text Property: fontFamily - // - virtual QString fontFamily() const; - virtual void setFontFamily( const QString &value ); + // + // Virtual Text Property: fontFamily + // + virtual QString fontFamily() const; + virtual void setFontFamily( const QString &value ); - // - // Virtual Text Property: fontSize - // - virtual double fontSize() const; - virtual void setFontSize( double value ); + // + // Virtual Text Property: fontSize + // + virtual double fontSize() const; + virtual void setFontSize( double value ); - // - // Virtual Text Property: fontWeight - // - virtual QFont::Weight fontWeight() const; - virtual void setFontWeight( QFont::Weight value ); + // + // Virtual Text Property: fontWeight + // + virtual QFont::Weight fontWeight() const; + virtual void setFontWeight( QFont::Weight value ); - // - // Virtual Text Property: fontItalicFlag - // - virtual bool fontItalicFlag() const; - virtual void setFontItalicFlag( bool value ); + // + // Virtual Text Property: fontItalicFlag + // + virtual bool fontItalicFlag() const; + virtual void setFontItalicFlag( bool value ); - // - // Virtual Text Property: fontUnderlineFlag - // - virtual bool fontUnderlineFlag() const; - virtual void setFontUnderlineFlag( bool value ); + // + // Virtual Text Property: fontUnderlineFlag + // + virtual bool fontUnderlineFlag() const; + virtual void setFontUnderlineFlag( bool value ); - // - // Virtual Text Property: textColorNode - // - virtual ColorNode textColorNode() const; - virtual void setTextColorNode( const ColorNode &value ); + // + // Virtual Text Property: textColorNode + // + virtual ColorNode textColorNode() const; + virtual void setTextColorNode( const ColorNode &value ); - // - // Virtual Text Property: textHAlign - // - virtual Qt::Alignment textHAlign() const; - virtual void setTextHAlign( Qt::Alignment value ); + // + // Virtual Text Property: textHAlign + // + virtual Qt::Alignment textHAlign() const; + virtual void setTextHAlign( Qt::Alignment value ); - // - // Virtual Text Property: textVAlign - // - virtual Qt::Alignment textVAlign() const; - virtual void setTextVAlign( Qt::Alignment value ); + // + // Virtual Text Property: textVAlign + // + virtual Qt::Alignment textVAlign() const; + virtual void setTextVAlign( Qt::Alignment value ); - // - // Virtual Text Property: textLineSpacing - // - virtual double textLineSpacing() const; - virtual void setTextLineSpacing( double value ); + // + // Virtual Text Property: textLineSpacing + // + virtual double textLineSpacing() const; + virtual void setTextLineSpacing( double value ); - /////////////////////////////////////////////////////////////// - // Image Properties Virtual Interface - /////////////////////////////////////////////////////////////// -public: - // - // Virtual Image Property: filenameNode - // - virtual TextNode filenameNode() const; - virtual void setFilenameNode( const TextNode &value ); + /////////////////////////////////////////////////////////////// + // Image Properties Virtual Interface + /////////////////////////////////////////////////////////////// + public: + // + // Virtual Image Property: filenameNode + // + virtual TextNode filenameNode() const; + virtual void setFilenameNode( const TextNode &value ); - // - // Virtual Image Property: originalSize (read-only) - // - virtual Size originalSize() const; + // + // Virtual Image Property: originalSize (read-only) + // + virtual Size originalSize() const; - /////////////////////////////////////////////////////////////// - // Shape Properties Virtual Interface - /////////////////////////////////////////////////////////////// -public: - // - // Virtual Shape Property: lineWidth - // - virtual glabels::Distance lineWidth() const; - virtual void setLineWidth( const glabels::Distance& value ); + /////////////////////////////////////////////////////////////// + // Shape Properties Virtual Interface + /////////////////////////////////////////////////////////////// + public: + // + // Virtual Shape Property: lineWidth + // + virtual Distance lineWidth() const; + virtual void setLineWidth( const Distance& value ); - // - // Virtual Shape Property: lineColorNode - // - virtual ColorNode lineColorNode() const; - virtual void setLineColorNode( const ColorNode &value ); + // + // Virtual Shape Property: lineColorNode + // + virtual ColorNode lineColorNode() const; + virtual void setLineColorNode( const ColorNode &value ); - // - // Virtual Shape Property: fillColorNode - // - virtual ColorNode fillColorNode() const; - virtual void setFillColorNode( const ColorNode &value ); + // + // Virtual Shape Property: fillColorNode + // + virtual ColorNode fillColorNode() const; + virtual void setFillColorNode( const ColorNode &value ); - /////////////////////////////////////////////////////////////// - // Barcode Properties Virtual Interface - /////////////////////////////////////////////////////////////// -public: - // - // Virtual Barcode Property: bcDataNode - // - virtual TextNode bcDataNode() const; - virtual void setBcDataNode( const TextNode &value ); + /////////////////////////////////////////////////////////////// + // Barcode Properties Virtual Interface + /////////////////////////////////////////////////////////////// + public: + // + // Virtual Barcode Property: bcDataNode + // + virtual TextNode bcDataNode() const; + virtual void setBcDataNode( const TextNode &value ); - // - // Virtual Barcode Property: bcTextFlag - // - virtual bool bcTextFlag() const; - virtual void setBcTextFlag( bool value ); + // + // Virtual Barcode Property: bcTextFlag + // + virtual bool bcTextFlag() const; + virtual void setBcTextFlag( bool value ); - // - // Virtual Barcode Property: bcChecksumFlag - // - virtual bool bcChecksumFlag() const; - virtual void setBcChecksumFlag( bool value ); + // + // Virtual Barcode Property: bcChecksumFlag + // + virtual bool bcChecksumFlag() const; + virtual void setBcChecksumFlag( bool value ); - // - // Virtual Barcode Property: bcColorNode - // - virtual ColorNode bcColorNode() const; - virtual void setBcColorNode( const ColorNode &value ); + // + // Virtual Barcode Property: bcColorNode + // + virtual ColorNode bcColorNode() const; + virtual void setBcColorNode( const ColorNode &value ); - // - // Virtual Barcode Property: bcStyle - // - virtual BarcodeStyle bcStyle() const; - virtual void setBcStyle( const BarcodeStyle &value ); + // + // Virtual Barcode Property: bcStyle + // + virtual BarcodeStyle bcStyle() const; + virtual void setBcStyle( const BarcodeStyle &value ); - // - // Virtual Barcode Property: bcFormatDigits - // - virtual int bcFormatDigits() const; - virtual void setBcFormatDigits( int value ); + // + // Virtual Barcode Property: bcFormatDigits + // + virtual int bcFormatDigits() const; + virtual void setBcFormatDigits( int value ); - /////////////////////////////////////////////////////////////// - // Capabilities (Overridden by concrete classes.) - /////////////////////////////////////////////////////////////// -public: - virtual bool canText() const; - virtual bool canFill() const; - virtual bool canLineColor() const; - virtual bool canLineWidth() const; + /////////////////////////////////////////////////////////////// + // Capabilities (Overridden by concrete classes.) + /////////////////////////////////////////////////////////////// + public: + virtual bool canText() const; + virtual bool canFill() const; + virtual bool canLineColor() const; + virtual bool canLineWidth() const; - /////////////////////////////////////////////////////////////// - // Position and Size methods - /////////////////////////////////////////////////////////////// -public: - void setPosition( const glabels::Distance& x0, const glabels::Distance& y0 ); - void setPositionRelative( const glabels::Distance& dx, const glabels::Distance& dy ); - Size size() const; - void setSize( const glabels::Distance& w, const glabels::Distance& h ); - void setSize( const Size& size ); - void setSizeHonorAspect( const glabels::Distance& w, const glabels::Distance& h ); - void setWHonorAspect( const glabels::Distance& w ); - void setHHonorAspect( const glabels::Distance& h ); - Region getExtent(); - void rotate( double thetaDegs ); - void flipHoriz(); - void flipVert(); - bool isLocatedAt( double scale, const glabels::Distance& x, const glabels::Distance& y ) const; - Handle* handleAt( double scale, const glabels::Distance& x, const glabels::Distance& y ) const; + /////////////////////////////////////////////////////////////// + // Position and Size methods + /////////////////////////////////////////////////////////////// + public: + void setPosition( const Distance& x0, const Distance& y0 ); + void setPositionRelative( const Distance& dx, const Distance& dy ); + Size size() const; + void setSize( const Distance& w, const Distance& h ); + void setSize( const Size& size ); + void setSizeHonorAspect( const Distance& w, const Distance& h ); + void setWHonorAspect( const Distance& w ); + void setHHonorAspect( const Distance& h ); + Region getExtent(); + void rotate( double thetaDegs ); + void flipHoriz(); + void flipVert(); + bool isLocatedAt( double scale, const Distance& x, const Distance& y ) const; + Handle* handleAt( double scale, const Distance& x, const Distance& y ) const; - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -public: - void draw( QPainter* painter, bool inEditor, merge::Record* record ) const; - void drawSelectionHighlight( QPainter* painter, double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + public: + void draw( QPainter* painter, bool inEditor, merge::Record* record ) const; + void drawSelectionHighlight( QPainter* painter, double scale ) const; -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const = 0; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const = 0; - virtual QPainterPath hoverPath( double scale ) const = 0; + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const = 0; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const = 0; + virtual QPainterPath hoverPath( double scale ) const = 0; - virtual void sizeUpdated(); + virtual void sizeUpdated(); - /////////////////////////////////////////////////////////////// - // Protected Members - /////////////////////////////////////////////////////////////// -protected: - bool mSelectedFlag; + /////////////////////////////////////////////////////////////// + // Protected Members + /////////////////////////////////////////////////////////////// + protected: + bool mSelectedFlag; - glabels::Distance mX0; - glabels::Distance mY0; - glabels::Distance mW; - glabels::Distance mH; + Distance mX0; + Distance mY0; + Distance mW; + Distance mH; - bool mShadowState; - glabels::Distance mShadowX; - glabels::Distance mShadowY; - double mShadowOpacity; - ColorNode mShadowColorNode; + bool mShadowState; + Distance mShadowX; + Distance mShadowY; + double mShadowOpacity; + ColorNode mShadowColorNode; - QList mHandles; - Outline* mOutline; + QList mHandles; + Outline* mOutline; - /////////////////////////////////////////////////////////////// - // Private Members - /////////////////////////////////////////////////////////////// -private: - static int msNextId; - int mId; + /////////////////////////////////////////////////////////////// + // Private Members + /////////////////////////////////////////////////////////////// + private: + static int msNextId; + int mId; - QMatrix mMatrix; + QMatrix mMatrix; -}; + }; + +} #endif // LabelModelObject_h diff --git a/glabels/LabelModelShapeObject.cpp b/glabels/LabelModelShapeObject.cpp index 62c0f8e..76eee63 100644 --- a/glabels/LabelModelShapeObject.cpp +++ b/glabels/LabelModelShapeObject.cpp @@ -25,142 +25,147 @@ #include -/// -/// Constructor -/// -LabelModelShapeObject::LabelModelShapeObject() +namespace glabels { - mOutline = new Outline( this ); - mHandles << new HandleNorthWest( this ); - mHandles << new HandleNorth( this ); - mHandles << new HandleNorthEast( this ); - mHandles << new HandleEast( this ); - mHandles << new HandleSouthEast( this ); - mHandles << new HandleSouth( this ); - mHandles << new HandleSouthWest( this ); - mHandles << new HandleWest( this ); - - mLineWidth = 1.0; - mLineColorNode = ColorNode( QColor( 0, 0, 0 ) ); - mFillColorNode = ColorNode( QColor( 0, 255, 0 ) ); -} - - -/// -/// Copy constructor -/// -LabelModelShapeObject::LabelModelShapeObject( const LabelModelShapeObject* object ) : LabelModelObject(object) -{ - mLineWidth = object->mLineWidth; - mLineColorNode = object->mLineColorNode; - mFillColorNode = object->mFillColorNode; -} - - -/// -/// Destructor -/// -LabelModelShapeObject::~LabelModelShapeObject() -{ - delete mOutline; - - foreach( Handle* handle, mHandles ) + /// + /// Constructor + /// + LabelModelShapeObject::LabelModelShapeObject() { - delete handle; + mOutline = new Outline( this ); + + mHandles << new HandleNorthWest( this ); + mHandles << new HandleNorth( this ); + mHandles << new HandleNorthEast( this ); + mHandles << new HandleEast( this ); + mHandles << new HandleSouthEast( this ); + mHandles << new HandleSouth( this ); + mHandles << new HandleSouthWest( this ); + mHandles << new HandleWest( this ); + + mLineWidth = 1.0; + mLineColorNode = ColorNode( QColor( 0, 0, 0 ) ); + mFillColorNode = ColorNode( QColor( 0, 255, 0 ) ); } - mHandles.clear(); -} -/// -/// Line Width Property Getter -/// -glabels::Distance LabelModelShapeObject::lineWidth( void ) const -{ - return mLineWidth; -} - - -/// -/// Line Width Property Setter -/// -void LabelModelShapeObject::setLineWidth( const glabels::Distance& value ) -{ - if ( mLineWidth != value ) + /// + /// Copy constructor + /// + LabelModelShapeObject::LabelModelShapeObject( const LabelModelShapeObject* object ) : LabelModelObject(object) { - mLineWidth = value; - emit changed(); + mLineWidth = object->mLineWidth; + mLineColorNode = object->mLineColorNode; + mFillColorNode = object->mFillColorNode; } -} -/// -/// Line Color Node Property Getter -/// -ColorNode LabelModelShapeObject::lineColorNode( void ) const -{ - return mLineColorNode; -} - - -/// -/// Line Color Node Property Setter -/// -void LabelModelShapeObject::setLineColorNode( const ColorNode& value ) -{ - if ( mLineColorNode != value ) + /// + /// Destructor + /// + LabelModelShapeObject::~LabelModelShapeObject() { - mLineColorNode = value; - emit changed(); + delete mOutline; + + foreach( Handle* handle, mHandles ) + { + delete handle; + } + mHandles.clear(); + } + + + /// + /// Line Width Property Getter + /// + Distance LabelModelShapeObject::lineWidth( void ) const + { + return mLineWidth; + } + + + /// + /// Line Width Property Setter + /// + void LabelModelShapeObject::setLineWidth( const Distance& value ) + { + if ( mLineWidth != value ) + { + mLineWidth = value; + emit changed(); + } + } + + + /// + /// Line Color Node Property Getter + /// + ColorNode LabelModelShapeObject::lineColorNode( void ) const + { + return mLineColorNode; + } + + + /// + /// Line Color Node Property Setter + /// + void LabelModelShapeObject::setLineColorNode( const ColorNode& value ) + { + if ( mLineColorNode != value ) + { + mLineColorNode = value; + emit changed(); + } } -} -/// -/// Fill Color Node Property Getter -/// -ColorNode LabelModelShapeObject::fillColorNode( void ) const -{ - return mFillColorNode; -} - - -/// -/// Fill Color Node Property Setter -/// -void LabelModelShapeObject::setFillColorNode( const ColorNode& value ) -{ - if ( mFillColorNode != value ) + /// + /// Fill Color Node Property Getter + /// + ColorNode LabelModelShapeObject::fillColorNode( void ) const { - mFillColorNode = value; - emit changed(); + return mFillColorNode; + } + + + /// + /// Fill Color Node Property Setter + /// + void LabelModelShapeObject::setFillColorNode( const ColorNode& value ) + { + if ( mFillColorNode != value ) + { + mFillColorNode = value; + emit changed(); + } } -} -/// -/// Can Fill Capability Implementation -/// -bool LabelModelShapeObject::canFill() -{ - return true; -} - - -/// -/// Can Line Color Capability Implementation -/// -bool LabelModelShapeObject::canLineColor() -{ - return true; -} - - -/// -/// Can Line Width Capability Implementation -/// -bool LabelModelShapeObject::canLineWidth() -{ - return true; + /// + /// Can Fill Capability Implementation + /// + bool LabelModelShapeObject::canFill() + { + return true; + } + + + /// + /// Can Line Color Capability Implementation + /// + bool LabelModelShapeObject::canLineColor() + { + return true; + } + + + /// + /// Can Line Width Capability Implementation + /// + bool LabelModelShapeObject::canLineWidth() + { + return true; + } + } diff --git a/glabels/LabelModelShapeObject.h b/glabels/LabelModelShapeObject.h index aba634d..e3b6d2a 100644 --- a/glabels/LabelModelShapeObject.h +++ b/glabels/LabelModelShapeObject.h @@ -25,66 +25,71 @@ #include "LabelModelObject.h" -/// -/// Label Model Shape Object (Box or Ellipse) -/// -class LabelModelShapeObject : public LabelModelObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -protected: - LabelModelShapeObject(); - LabelModelShapeObject( const LabelModelShapeObject* object ); -public: - virtual ~LabelModelShapeObject(); + /// + /// Label Model Shape Object (Box or Ellipse) + /// + class LabelModelShapeObject : public LabelModelObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + protected: + LabelModelShapeObject(); + LabelModelShapeObject( const LabelModelShapeObject* object ); + public: + virtual ~LabelModelShapeObject(); - /////////////////////////////////////////////////////////////// - // Property Implementations - /////////////////////////////////////////////////////////////// -public: - // - // Shape Property: lineWidth - // - virtual glabels::Distance lineWidth( void ) const; - virtual void setLineWidth( const glabels::Distance& value ); + /////////////////////////////////////////////////////////////// + // Property Implementations + /////////////////////////////////////////////////////////////// + public: + // + // Shape Property: lineWidth + // + virtual Distance lineWidth( void ) const; + virtual void setLineWidth( const Distance& value ); - // - // Shape Property: lineColorNode - // - virtual ColorNode lineColorNode( void ) const; - virtual void setLineColorNode( const ColorNode& value ); + // + // Shape Property: lineColorNode + // + virtual ColorNode lineColorNode( void ) const; + virtual void setLineColorNode( const ColorNode& value ); - // - // Shape Property: fillColorNode - // - virtual ColorNode fillColorNode( void ) const; - virtual void setFillColorNode( const ColorNode& value ); + // + // Shape Property: fillColorNode + // + virtual ColorNode fillColorNode( void ) const; + virtual void setFillColorNode( const ColorNode& value ); - /////////////////////////////////////////////////////////////// - // Capability Implementations - /////////////////////////////////////////////////////////////// -public: - virtual bool canFill(); - virtual bool canLineColor(); - virtual bool canLineWidth(); + /////////////////////////////////////////////////////////////// + // Capability Implementations + /////////////////////////////////////////////////////////////// + public: + virtual bool canFill(); + virtual bool canLineColor(); + virtual bool canLineWidth(); - /////////////////////////////////////////////////////////////// - // Private Members - /////////////////////////////////////////////////////////////// -protected: - glabels::Distance mLineWidth; - ColorNode mLineColorNode; - ColorNode mFillColorNode; + /////////////////////////////////////////////////////////////// + // Private Members + /////////////////////////////////////////////////////////////// + protected: + Distance mLineWidth; + ColorNode mLineColorNode; + ColorNode mFillColorNode; -}; + }; + +} #endif // LabelModelShapeObject_h diff --git a/glabels/LabelModelTextObject.cpp b/glabels/LabelModelTextObject.cpp index 8ef3a9d..335236c 100644 --- a/glabels/LabelModelTextObject.cpp +++ b/glabels/LabelModelTextObject.cpp @@ -29,600 +29,615 @@ #include -namespace +namespace glabels { - const double marginPts = 3; -} - -/// -/// Constructor -/// -LabelModelTextObject::LabelModelTextObject() -{ - mOutline = new Outline( this ); - - mHandles << new HandleNorthWest( this ); - mHandles << new HandleNorth( this ); - mHandles << new HandleNorthEast( this ); - mHandles << new HandleEast( this ); - mHandles << new HandleSouthEast( this ); - mHandles << new HandleSouth( this ); - mHandles << new HandleSouthWest( this ); - mHandles << new HandleWest( this ); - - mText = ""; - mFontFamily = "Sans"; - mFontSize = 10; - mFontWeight = QFont::Normal; - mFontItalicFlag = false; - mFontUnderlineFlag = false; - mTextColorNode = ColorNode( QColor( 0, 0, 0 ) ); - mTextHAlign = Qt::AlignLeft; - mTextVAlign = Qt::AlignTop; - mTextLineSpacing = 1; -} - - -/// -/// Copy constructor -/// -LabelModelTextObject::LabelModelTextObject( const LabelModelTextObject* object ) : LabelModelObject(object) -{ - mText = object->mText; - mFontFamily = object->mFontFamily; - mFontSize = object->mFontSize; - mFontWeight = object->mFontWeight; - mFontItalicFlag = object->mFontItalicFlag; - mFontUnderlineFlag = object->mFontUnderlineFlag; - mTextColorNode = object->mTextColorNode; - mTextHAlign = object->mTextHAlign; - mTextVAlign = object->mTextVAlign; - mTextLineSpacing = object->mTextLineSpacing; -} - - -/// -/// Destructor -/// -LabelModelTextObject::~LabelModelTextObject() -{ - delete mOutline; - - foreach( Handle* handle, mHandles ) + // + // Private + // + namespace { - delete handle; + const double marginPts = 3; } - mHandles.clear(); -} -/// -/// Clone -/// -LabelModelTextObject* LabelModelTextObject::clone() const -{ - return new LabelModelTextObject( this ); -} - - -/// -/// Text Property Getter -/// -QString LabelModelTextObject::text( void ) const -{ - return mText; -} - - -/// -/// Text Property Setter -/// -void LabelModelTextObject::setText( const QString& value ) -{ - if ( mText != value ) + /// + /// Constructor + /// + LabelModelTextObject::LabelModelTextObject() { - mText = value; - update(); - emit changed(); + mOutline = new Outline( this ); + + mHandles << new HandleNorthWest( this ); + mHandles << new HandleNorth( this ); + mHandles << new HandleNorthEast( this ); + mHandles << new HandleEast( this ); + mHandles << new HandleSouthEast( this ); + mHandles << new HandleSouth( this ); + mHandles << new HandleSouthWest( this ); + mHandles << new HandleWest( this ); + + mText = ""; + mFontFamily = "Sans"; + mFontSize = 10; + mFontWeight = QFont::Normal; + mFontItalicFlag = false; + mFontUnderlineFlag = false; + mTextColorNode = ColorNode( QColor( 0, 0, 0 ) ); + mTextHAlign = Qt::AlignLeft; + mTextVAlign = Qt::AlignTop; + mTextLineSpacing = 1; } -} -/// -/// FontFamily Property Getter -/// -QString LabelModelTextObject::fontFamily( void ) const -{ - return mFontFamily; -} - - -/// -/// FontFamily Property Setter -/// -void LabelModelTextObject::setFontFamily( const QString& value ) -{ - if ( mFontFamily != value ) + /// + /// Copy constructor + /// + LabelModelTextObject::LabelModelTextObject( const LabelModelTextObject* object ) + : LabelModelObject(object) { - mFontFamily = value; - update(); - emit changed(); + mText = object->mText; + mFontFamily = object->mFontFamily; + mFontSize = object->mFontSize; + mFontWeight = object->mFontWeight; + mFontItalicFlag = object->mFontItalicFlag; + mFontUnderlineFlag = object->mFontUnderlineFlag; + mTextColorNode = object->mTextColorNode; + mTextHAlign = object->mTextHAlign; + mTextVAlign = object->mTextVAlign; + mTextLineSpacing = object->mTextLineSpacing; } -} -/// -/// FontSize Property Getter -/// -double LabelModelTextObject::fontSize( void ) const -{ - return mFontSize; -} - - -/// -/// FontSize Property Setter -/// -void LabelModelTextObject::setFontSize( double value ) -{ - if ( mFontSize != value ) + /// + /// Destructor + /// + LabelModelTextObject::~LabelModelTextObject() { - mFontSize = value; - update(); - emit changed(); + delete mOutline; + + foreach( Handle* handle, mHandles ) + { + delete handle; + } + mHandles.clear(); } -} -/// -/// FontWeight Property Getter -/// -QFont::Weight LabelModelTextObject::fontWeight( void ) const -{ - return mFontWeight; -} - - -/// -/// FontWeight Property Setter -/// -void LabelModelTextObject::setFontWeight( QFont::Weight value ) -{ - if ( mFontWeight != value ) + /// + /// Clone + /// + LabelModelTextObject* LabelModelTextObject::clone() const { - mFontWeight = value; - update(); - emit changed(); + return new LabelModelTextObject( this ); } -} -/// -/// FontItalicFlag Property Getter -/// -bool LabelModelTextObject::fontItalicFlag( void ) const -{ - return mFontItalicFlag; -} - - -/// -/// FontItalicFlag Property Setter -/// -void LabelModelTextObject::setFontItalicFlag( bool value ) -{ - if ( mFontItalicFlag != value ) + /// + /// Text Property Getter + /// + QString LabelModelTextObject::text( void ) const { - mFontItalicFlag = value; - update(); - emit changed(); + return mText; } -} -/// -/// FontUnderlineFlag Property Getter -/// -bool LabelModelTextObject::fontUnderlineFlag( void ) const -{ - return mFontUnderlineFlag; -} - - -/// -/// FontUnderlineFlag Property Setter -/// -void LabelModelTextObject::setFontUnderlineFlag( bool value ) -{ - if ( mFontUnderlineFlag != value ) + /// + /// Text Property Setter + /// + void LabelModelTextObject::setText( const QString& value ) { - mFontUnderlineFlag = value; - update(); - emit changed(); + if ( mText != value ) + { + mText = value; + update(); + emit changed(); + } } -} -/// -/// Text Color Node Property Getter -/// -ColorNode LabelModelTextObject::textColorNode( void ) const -{ - return mTextColorNode; -} - - -/// -/// Text Color Node Property Setter -/// -void LabelModelTextObject::setTextColorNode( const ColorNode& value ) -{ - if ( mTextColorNode != value ) + /// + /// FontFamily Property Getter + /// + QString LabelModelTextObject::fontFamily( void ) const { - mTextColorNode = value; - update(); - emit changed(); + return mFontFamily; + } + + + /// + /// FontFamily Property Setter + /// + void LabelModelTextObject::setFontFamily( const QString& value ) + { + if ( mFontFamily != value ) + { + mFontFamily = value; + update(); + emit changed(); + } + } + + + /// + /// FontSize Property Getter + /// + double LabelModelTextObject::fontSize( void ) const + { + return mFontSize; + } + + + /// + /// FontSize Property Setter + /// + void LabelModelTextObject::setFontSize( double value ) + { + if ( mFontSize != value ) + { + mFontSize = value; + update(); + emit changed(); + } + } + + + /// + /// FontWeight Property Getter + /// + QFont::Weight LabelModelTextObject::fontWeight( void ) const + { + return mFontWeight; + } + + + /// + /// FontWeight Property Setter + /// + void LabelModelTextObject::setFontWeight( QFont::Weight value ) + { + if ( mFontWeight != value ) + { + mFontWeight = value; + update(); + emit changed(); + } + } + + + /// + /// FontItalicFlag Property Getter + /// + bool LabelModelTextObject::fontItalicFlag( void ) const + { + return mFontItalicFlag; + } + + + /// + /// FontItalicFlag Property Setter + /// + void LabelModelTextObject::setFontItalicFlag( bool value ) + { + if ( mFontItalicFlag != value ) + { + mFontItalicFlag = value; + update(); + emit changed(); + } + } + + + /// + /// FontUnderlineFlag Property Getter + /// + bool LabelModelTextObject::fontUnderlineFlag( void ) const + { + return mFontUnderlineFlag; + } + + + /// + /// FontUnderlineFlag Property Setter + /// + void LabelModelTextObject::setFontUnderlineFlag( bool value ) + { + if ( mFontUnderlineFlag != value ) + { + mFontUnderlineFlag = value; + update(); + emit changed(); + } + } + + + /// + /// Text Color Node Property Getter + /// + ColorNode LabelModelTextObject::textColorNode( void ) const + { + return mTextColorNode; + } + + + /// + /// Text Color Node Property Setter + /// + void LabelModelTextObject::setTextColorNode( const ColorNode& value ) + { + if ( mTextColorNode != value ) + { + mTextColorNode = value; + update(); + emit changed(); + } } -} -/// -/// TextHAlign Property Getter -/// -Qt::Alignment LabelModelTextObject::textHAlign( void ) const -{ - return mTextHAlign; -} - - -/// -/// TextHAlign Property Setter -/// -void LabelModelTextObject::setTextHAlign( Qt::Alignment value ) -{ - if ( mTextHAlign != value ) + /// + /// TextHAlign Property Getter + /// + Qt::Alignment LabelModelTextObject::textHAlign( void ) const { - mTextHAlign = value; - update(); - emit changed(); + return mTextHAlign; } -} -/// -/// TextVAlign Property Getter -/// -Qt::Alignment LabelModelTextObject::textVAlign( void ) const -{ - return mTextVAlign; -} - - -/// -/// TextVAlign Property Setter -/// -void LabelModelTextObject::setTextVAlign( Qt::Alignment value ) -{ - if ( mTextVAlign != value ) + /// + /// TextHAlign Property Setter + /// + void LabelModelTextObject::setTextHAlign( Qt::Alignment value ) { - mTextVAlign = value; - update(); - emit changed(); + if ( mTextHAlign != value ) + { + mTextHAlign = value; + update(); + emit changed(); + } } -} -/// -/// TextLineSpacing Property Getter -/// -double LabelModelTextObject::textLineSpacing( void ) const -{ - return mTextLineSpacing; -} - - -/// -/// TextLineSpacing Property Setter -/// -void LabelModelTextObject::setTextLineSpacing( double value ) -{ - if ( mTextLineSpacing != value ) + /// + /// TextVAlign Property Getter + /// + Qt::Alignment LabelModelTextObject::textVAlign( void ) const { - mTextLineSpacing = value; - update(); - emit changed(); + return mTextVAlign; } -} -/// -// Can Text Capability Implementation -/// -bool LabelModelTextObject::canText() -{ - return true; -} - - -/// -/// Draw shadow of object -/// -void LabelModelTextObject::drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor textColor = mTextColorNode.color( record ); - - if ( textColor.alpha() ) + /// + /// TextVAlign Property Setter + /// + void LabelModelTextObject::setTextVAlign( Qt::Alignment value ) { - QColor shadowColor = mShadowColorNode.color( record ); - shadowColor.setAlphaF( mShadowOpacity ); + if ( mTextVAlign != value ) + { + mTextVAlign = value; + update(); + emit changed(); + } + } + + + /// + /// TextLineSpacing Property Getter + /// + double LabelModelTextObject::textLineSpacing( void ) const + { + return mTextLineSpacing; + } + + + /// + /// TextLineSpacing Property Setter + /// + void LabelModelTextObject::setTextLineSpacing( double value ) + { + if ( mTextLineSpacing != value ) + { + mTextLineSpacing = value; + update(); + emit changed(); + } + } + + + /// + /// Can Text Capability Implementation + /// + bool LabelModelTextObject::canText() + { + return true; + } + + + /// + /// Draw shadow of object + /// + void LabelModelTextObject::drawShadow( QPainter* painter, + bool inEditor, + merge::Record* record ) const + { + QColor textColor = mTextColorNode.color( record ); + + if ( textColor.alpha() ) + { + QColor shadowColor = mShadowColorNode.color( record ); + shadowColor.setAlphaF( mShadowOpacity ); + + if ( inEditor ) + { + drawTextInEditor( painter, shadowColor ); + } + else + { + drawText( painter, shadowColor, record ); + } + } + } + + + /// + /// Draw object itself + /// + void LabelModelTextObject::drawObject( QPainter* painter, + bool inEditor, + merge::Record* record ) const + { + QColor textColor = mTextColorNode.color( record ); if ( inEditor ) { - drawTextInEditor( painter, shadowColor ); + drawTextInEditor( painter, textColor ); } else { - drawText( painter, shadowColor, record ); + drawText( painter, textColor, record ); } } -} - -/// -/// Draw object itself -/// -void LabelModelTextObject::drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const -{ - QColor textColor = mTextColorNode.color( record ); - if ( inEditor ) + /// + /// Path to test for hover condition + /// + QPainterPath LabelModelTextObject::hoverPath( double scale ) const { - drawTextInEditor( painter, textColor ); + return mHoverPath; } - else + + + /// + /// Size updated + /// + void LabelModelTextObject::sizeUpdated() { - drawText( painter, textColor, record ); + update(); } -} -/// -/// Path to test for hover condition -/// -QPainterPath LabelModelTextObject::hoverPath( double scale ) const -{ - return mHoverPath; -} - - -/// -/// Size updated -/// -void LabelModelTextObject::sizeUpdated() -{ - update(); -} - - -/// -/// Update cached information for editor view -/// -void LabelModelTextObject::update() -{ - QFont font; - font.setFamily( mFontFamily ); - font.setPointSizeF( mFontSize ); - font.setWeight( mFontWeight ); - font.setItalic( mFontItalicFlag ); - font.setUnderline( mFontUnderlineFlag ); - - QTextOption textOption; - textOption.setAlignment( mTextHAlign ); - textOption.setWrapMode( QTextOption::WordWrap ); - - QFontMetricsF fontMetrics( font ); - double dy = fontMetrics.lineSpacing() * mTextLineSpacing; - - QString displayText = mText.isEmpty() ? tr("Text") : mText; - QTextDocument document( displayText ); - - qDeleteAll( mEditorLayouts ); - mEditorLayouts.clear(); - - // Pass #1 -- do initial layouts - double x = 0; - double y = 0; - QRectF boundingRect; - for ( int i = 0; i < document.blockCount(); i++ ) + /// + /// Update cached information for editor view + /// + void LabelModelTextObject::update() { - QTextLayout* layout = new QTextLayout( document.findBlockByNumber(i).text() ); + QFont font; + font.setFamily( mFontFamily ); + font.setPointSizeF( mFontSize ); + font.setWeight( mFontWeight ); + font.setItalic( mFontItalicFlag ); + font.setUnderline( mFontUnderlineFlag ); + + QTextOption textOption; + textOption.setAlignment( mTextHAlign ); + textOption.setWrapMode( QTextOption::WordWrap ); + + QFontMetricsF fontMetrics( font ); + double dy = fontMetrics.lineSpacing() * mTextLineSpacing; + + QString displayText = mText.isEmpty() ? tr("Text") : mText; + QTextDocument document( displayText ); + + qDeleteAll( mEditorLayouts ); + mEditorLayouts.clear(); + + // Pass #1 -- do initial layouts + double x = 0; + double y = 0; + QRectF boundingRect; + for ( int i = 0; i < document.blockCount(); i++ ) + { + QTextLayout* layout = new QTextLayout( document.findBlockByNumber(i).text() ); - layout->setFont( font ); - layout->setTextOption( textOption ); - layout->setCacheEnabled(true); + layout->setFont( font ); + layout->setTextOption( textOption ); + layout->setCacheEnabled(true); - layout->beginLayout(); - for ( QTextLine l = layout->createLine(); l.isValid(); l = layout->createLine() ) - { - l.setLineWidth( mW.pt() - 2*marginPts ); - l.setPosition( QPointF( x, y ) ); - y += dy; - } - layout->endLayout(); - - mEditorLayouts.append( layout ); - - boundingRect = layout->boundingRect().united( boundingRect ); - } - double h = boundingRect.height(); - - - // Pass #2 -- adjust layout positions for vertical alignment and create hover path - x = marginPts; - switch ( mTextVAlign ) - { - case Qt::AlignVCenter: - y = mH.pt()/2 - h/2; - break; - case Qt::AlignBottom: - y = mH.pt() - h - marginPts; - break; - default: - y = marginPts; - break; - } - QPainterPath hoverPath; // new empty hover path - foreach ( QTextLayout* layout, mEditorLayouts ) - { - for ( int j = 0; j < layout->lineCount(); j++ ) - { - QTextLine l = layout->lineAt(j); - l.setPosition( QPointF( x, y ) ); - y += dy; - - hoverPath.addRect( l.naturalTextRect() ); // add to new hover path - } - } - - mHoverPath = hoverPath; // save new hover path -} - - -/// -/// Draw text in editor from cached information -/// -void LabelModelTextObject::drawTextInEditor( QPainter* painter, const QColor& color ) const -{ - if ( mText.isEmpty() ) - { - QColor mutedColor = color; - mutedColor.setAlphaF( 0.5 * color.alphaF() ); - painter->setPen( QPen( mutedColor ) ); - } - else - { - painter->setPen( QPen( color ) ); - } - - foreach ( QTextLayout* layout, mEditorLayouts ) - { - layout->draw( painter, QPointF( 0, 0 ) ); - } -} - - -/// -/// Draw text in final printout or preview -/// -void -LabelModelTextObject::drawText( QPainter* painter, const QColor&color, merge::Record* record ) const -{ - QFont font; - font.setFamily( mFontFamily ); - font.setPointSizeF( mFontSize ); - font.setWeight( mFontWeight ); - font.setItalic( mFontItalicFlag ); - font.setUnderline( mFontUnderlineFlag ); - - QTextOption textOption; - textOption.setAlignment( mTextHAlign ); - textOption.setWrapMode( QTextOption::WordWrap ); - - QFontMetricsF fontMetrics( font ); - double dy = fontMetrics.lineSpacing() * mTextLineSpacing; - - QTextDocument document( expandText( mText, record ) ); - - QList layouts; - - // Pass #1 -- do initial layouts - double x = 0; - double y = 0; - QRectF boundingRect; - for ( int i = 0; i < document.blockCount(); i++ ) - { - QTextLayout* layout = new QTextLayout( document.findBlockByNumber(i).text() ); - - layout->setFont( font ); - layout->setTextOption( textOption ); - layout->setCacheEnabled(true); - - layout->beginLayout(); - for ( QTextLine l = layout->createLine(); l.isValid(); l = layout->createLine() ) - { - l.setLineWidth( mW.pt() - 2*marginPts ); - l.setPosition( QPointF( x, y ) ); - y += dy; - } - layout->endLayout(); - - layouts.append( layout ); - - boundingRect = layout->boundingRect().united( boundingRect ); - } - double h = boundingRect.height(); - - - // Pass #2 -- adjust layout positions for vertical alignment and create hover path - x = marginPts; - switch ( mTextVAlign ) - { - case Qt::AlignVCenter: - y = mH.pt()/2 - h/2; - break; - case Qt::AlignBottom: - y = mH.pt() - h - marginPts; - break; - default: - y = marginPts; - break; - } - foreach ( QTextLayout* layout, layouts ) - { - for ( int j = 0; j < layout->lineCount(); j++ ) - { - QTextLine l = layout->lineAt(j); - l.setPosition( QPointF( x, y ) ); - y += dy; - } - } - - // Draw layouts - painter->setPen( QPen( color ) ); - foreach ( QTextLayout* layout, layouts ) - { - layout->draw( painter, QPointF( 0, 0 ) ); - } - - // Cleanup - qDeleteAll( layouts ); -} - - -/// -/// Expand text by replacing fields with their values from the given record -/// -QString LabelModelTextObject::expandText( QString text, merge::Record* record ) const -{ - if ( record ) - { - foreach ( QString key, record->keys() ) - { - // Special case: remove line when it contains only an empty field. - // e.g. an optional ${ADDR2} line. To bypass this case, include - // whitespace at end of line. - if ( record->value(key).isEmpty() ) + layout->beginLayout(); + for ( QTextLine l = layout->createLine(); l.isValid(); l = layout->createLine() ) { - QStringList v = text.split( '\n' ); - v.removeAll( "${"+key+"}" ); - text = v.join( '\n' ); + l.setLineWidth( mW.pt() - 2*marginPts ); + l.setPosition( QPointF( x, y ) ); + y += dy; } + layout->endLayout(); - // Nominal case: simple replacement - text.replace( "${"+key+"}", record->value(key) ); + mEditorLayouts.append( layout ); + + boundingRect = layout->boundingRect().united( boundingRect ); + } + double h = boundingRect.height(); + + + // Pass #2 -- adjust layout positions for vertical alignment and create hover path + x = marginPts; + switch ( mTextVAlign ) + { + case Qt::AlignVCenter: + y = mH.pt()/2 - h/2; + break; + case Qt::AlignBottom: + y = mH.pt() - h - marginPts; + break; + default: + y = marginPts; + break; + } + QPainterPath hoverPath; // new empty hover path + foreach ( QTextLayout* layout, mEditorLayouts ) + { + for ( int j = 0; j < layout->lineCount(); j++ ) + { + QTextLine l = layout->lineAt(j); + l.setPosition( QPointF( x, y ) ); + y += dy; + + hoverPath.addRect( l.naturalTextRect() ); // add to new hover path + } + } + + mHoverPath = hoverPath; // save new hover path + } + + + /// + /// Draw text in editor from cached information + /// + void LabelModelTextObject::drawTextInEditor( QPainter* painter, const QColor& color ) const + { + if ( mText.isEmpty() ) + { + QColor mutedColor = color; + mutedColor.setAlphaF( 0.5 * color.alphaF() ); + painter->setPen( QPen( mutedColor ) ); + } + else + { + painter->setPen( QPen( color ) ); + } + + foreach ( QTextLayout* layout, mEditorLayouts ) + { + layout->draw( painter, QPointF( 0, 0 ) ); } } - return text; + + /// + /// Draw text in final printout or preview + /// + void + LabelModelTextObject::drawText( QPainter* painter, + const QColor& color, + merge::Record* record ) const + { + QFont font; + font.setFamily( mFontFamily ); + font.setPointSizeF( mFontSize ); + font.setWeight( mFontWeight ); + font.setItalic( mFontItalicFlag ); + font.setUnderline( mFontUnderlineFlag ); + + QTextOption textOption; + textOption.setAlignment( mTextHAlign ); + textOption.setWrapMode( QTextOption::WordWrap ); + + QFontMetricsF fontMetrics( font ); + double dy = fontMetrics.lineSpacing() * mTextLineSpacing; + + QTextDocument document( expandText( mText, record ) ); + + QList layouts; + + // Pass #1 -- do initial layouts + double x = 0; + double y = 0; + QRectF boundingRect; + for ( int i = 0; i < document.blockCount(); i++ ) + { + QTextLayout* layout = new QTextLayout( document.findBlockByNumber(i).text() ); + + layout->setFont( font ); + layout->setTextOption( textOption ); + layout->setCacheEnabled(true); + + layout->beginLayout(); + for ( QTextLine l = layout->createLine(); l.isValid(); l = layout->createLine() ) + { + l.setLineWidth( mW.pt() - 2*marginPts ); + l.setPosition( QPointF( x, y ) ); + y += dy; + } + layout->endLayout(); + + layouts.append( layout ); + + boundingRect = layout->boundingRect().united( boundingRect ); + } + double h = boundingRect.height(); + + + // Pass #2 -- adjust layout positions for vertical alignment and create hover path + x = marginPts; + switch ( mTextVAlign ) + { + case Qt::AlignVCenter: + y = mH.pt()/2 - h/2; + break; + case Qt::AlignBottom: + y = mH.pt() - h - marginPts; + break; + default: + y = marginPts; + break; + } + foreach ( QTextLayout* layout, layouts ) + { + for ( int j = 0; j < layout->lineCount(); j++ ) + { + QTextLine l = layout->lineAt(j); + l.setPosition( QPointF( x, y ) ); + y += dy; + } + } + + // Draw layouts + painter->setPen( QPen( color ) ); + foreach ( QTextLayout* layout, layouts ) + { + layout->draw( painter, QPointF( 0, 0 ) ); + } + + // Cleanup + qDeleteAll( layouts ); + } + + + /// + /// Expand text by replacing fields with their values from the given record + /// + QString LabelModelTextObject::expandText( QString text, merge::Record* record ) const + { + if ( record ) + { + foreach ( QString key, record->keys() ) + { + // Special case: remove line when it contains only an empty field. + // e.g. an optional ${ADDR2} line. To bypass this case, include + // whitespace at end of line. + if ( record->value(key).isEmpty() ) + { + QStringList v = text.split( '\n' ); + v.removeAll( "${"+key+"}" ); + text = v.join( '\n' ); + } + + // Nominal case: simple replacement + text.replace( "${"+key+"}", record->value(key) ); + } + } + + return text; + } + } diff --git a/glabels/LabelModelTextObject.h b/glabels/LabelModelTextObject.h index e0f1b26..cb39974 100644 --- a/glabels/LabelModelTextObject.h +++ b/glabels/LabelModelTextObject.h @@ -27,148 +27,153 @@ #include "LabelModelObject.h" -/// -/// Label Model Line Object -/// -class LabelModelTextObject : public LabelModelObject +namespace glabels { - Q_OBJECT - /////////////////////////////////////////////////////////////// - // Lifecycle Methods - /////////////////////////////////////////////////////////////// -public: - LabelModelTextObject(); - LabelModelTextObject( const LabelModelTextObject* object ); - virtual ~LabelModelTextObject(); + /// + /// Label Model Line Object + /// + class LabelModelTextObject : public LabelModelObject + { + Q_OBJECT + + /////////////////////////////////////////////////////////////// + // Lifecycle Methods + /////////////////////////////////////////////////////////////// + public: + LabelModelTextObject(); + LabelModelTextObject( const LabelModelTextObject* object ); + virtual ~LabelModelTextObject(); - /////////////////////////////////////////////////////////////// - // Object duplication - /////////////////////////////////////////////////////////////// - virtual LabelModelTextObject* clone() const; + /////////////////////////////////////////////////////////////// + // Object duplication + /////////////////////////////////////////////////////////////// + virtual LabelModelTextObject* clone() const; - /////////////////////////////////////////////////////////////// - // Property Implementations - /////////////////////////////////////////////////////////////// -public: - // - // Text Property: text - // - virtual QString text() const; - virtual void setText( const QString &value ); + /////////////////////////////////////////////////////////////// + // Property Implementations + /////////////////////////////////////////////////////////////// + public: + // + // Text Property: text + // + virtual QString text() const; + virtual void setText( const QString &value ); - // - // Text Property: fontFamily - // - virtual QString fontFamily() const; - virtual void setFontFamily( const QString &value ); + // + // Text Property: fontFamily + // + virtual QString fontFamily() const; + virtual void setFontFamily( const QString &value ); - // - // Text Property: fontSize - // - virtual double fontSize() const; - virtual void setFontSize( double value ); + // + // Text Property: fontSize + // + virtual double fontSize() const; + virtual void setFontSize( double value ); - // - // Text Property: fontWeight - // - virtual QFont::Weight fontWeight() const; - virtual void setFontWeight( QFont::Weight value ); + // + // Text Property: fontWeight + // + virtual QFont::Weight fontWeight() const; + virtual void setFontWeight( QFont::Weight value ); - // - // Text Property: fontItalicFlag - // - virtual bool fontItalicFlag() const; - virtual void setFontItalicFlag( bool value ); + // + // Text Property: fontItalicFlag + // + virtual bool fontItalicFlag() const; + virtual void setFontItalicFlag( bool value ); - // - // Text Property: fontUnderlineFlag - // - virtual bool fontUnderlineFlag() const; - virtual void setFontUnderlineFlag( bool value ); + // + // Text Property: fontUnderlineFlag + // + virtual bool fontUnderlineFlag() const; + virtual void setFontUnderlineFlag( bool value ); - // - // Text Property: textColorNode - // - virtual ColorNode textColorNode() const; - virtual void setTextColorNode( const ColorNode &value ); + // + // Text Property: textColorNode + // + virtual ColorNode textColorNode() const; + virtual void setTextColorNode( const ColorNode &value ); - // - // Text Property: textHAlign - // - virtual Qt::Alignment textHAlign() const; - virtual void setTextHAlign( Qt::Alignment value ); + // + // Text Property: textHAlign + // + virtual Qt::Alignment textHAlign() const; + virtual void setTextHAlign( Qt::Alignment value ); - // - // Text Property: textVAlign - // - virtual Qt::Alignment textVAlign() const; - virtual void setTextVAlign( Qt::Alignment value ); + // + // Text Property: textVAlign + // + virtual Qt::Alignment textVAlign() const; + virtual void setTextVAlign( Qt::Alignment value ); - // - // Text Property: textLineSpacing - // - virtual double textLineSpacing() const; - virtual void setTextLineSpacing( double value ); + // + // Text Property: textLineSpacing + // + virtual double textLineSpacing() const; + virtual void setTextLineSpacing( double value ); - /////////////////////////////////////////////////////////////// - // Capability Implementations - /////////////////////////////////////////////////////////////// -public: - virtual bool canText(); + /////////////////////////////////////////////////////////////// + // Capability Implementations + /////////////////////////////////////////////////////////////// + public: + virtual bool canText(); - /////////////////////////////////////////////////////////////// - // Drawing operations - /////////////////////////////////////////////////////////////// -protected: - virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; - virtual QPainterPath hoverPath( double scale ) const; + /////////////////////////////////////////////////////////////// + // Drawing operations + /////////////////////////////////////////////////////////////// + protected: + virtual void drawShadow( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual void drawObject( QPainter* painter, bool inEditor, merge::Record* record ) const; + virtual QPainterPath hoverPath( double scale ) const; - /////////////////////////////////////////////////////////////// - // Private methods - /////////////////////////////////////////////////////////////// -private: - virtual void sizeUpdated(); - void update(); - void drawTextInEditor( QPainter* painter, const QColor& color ) const; - void drawText( QPainter* painter, const QColor&color, merge::Record* record ) const; - QString expandText( QString text, merge::Record* record ) const; + /////////////////////////////////////////////////////////////// + // Private methods + /////////////////////////////////////////////////////////////// + private: + virtual void sizeUpdated(); + void update(); + void drawTextInEditor( QPainter* painter, const QColor& color ) const; + void drawText( QPainter* painter, const QColor&color, merge::Record* record ) const; + QString expandText( QString text, merge::Record* record ) const; - /////////////////////////////////////////////////////////////// - // Private Members - /////////////////////////////////////////////////////////////// -private: - QString mText; - QString mFontFamily; - double mFontSize; - QFont::Weight mFontWeight; - bool mFontItalicFlag; - bool mFontUnderlineFlag; - ColorNode mTextColorNode; - Qt::Alignment mTextHAlign; - Qt::Alignment mTextVAlign; - double mTextLineSpacing; + /////////////////////////////////////////////////////////////// + // Private Members + /////////////////////////////////////////////////////////////// + private: + QString mText; + QString mFontFamily; + double mFontSize; + QFont::Weight mFontWeight; + bool mFontItalicFlag; + bool mFontUnderlineFlag; + ColorNode mTextColorNode; + Qt::Alignment mTextHAlign; + Qt::Alignment mTextVAlign; + double mTextLineSpacing; - QList mEditorLayouts; - QPainterPath mHoverPath; + QList mEditorLayouts; + QPainterPath mHoverPath; -}; + }; + +} #endif // LabelModelTextObject_h diff --git a/glabels/Layout.cpp b/glabels/Layout.cpp index dab24fe..3c6e5ee 100644 --- a/glabels/Layout.cpp +++ b/glabels/Layout.cpp @@ -23,7 +23,7 @@ #include -#include "privateConstants.h" +#include "Constants.h" namespace glabels @@ -37,6 +37,7 @@ namespace glabels const Distance& dy ) : mNx(nx), mNy(ny), mX0(x0), mY0(y0), mDx(dx), mDy(dy) { + // empty } @@ -44,6 +45,7 @@ namespace glabels : mNx(other.mNx), mNy(other.mNy), mX0(other.mX0), mY0(other.mY0), mDx(other.mDx), mDy(other.mDy) { + // empty } @@ -85,12 +87,12 @@ namespace glabels bool Layout::isSimilarTo( const Layout *other ) { - return ( (mNx == other->mNx) && - (mNy == other->mNy) && - (fabs(mX0 - other->mX0) < Constants::EPSILON) && - (fabs(mY0 - other->mY0) < Constants::EPSILON) && - (fabs(mDx - other->mDx) < Constants::EPSILON) && - (fabs(mDy - other->mDy) < Constants::EPSILON) ); + return ( (mNx == other->mNx) && + (mNy == other->mNy) && + (fabs(mX0 - other->mX0) < EPSILON) && + (fabs(mY0 - other->mY0) < EPSILON) && + (fabs(mDx - other->mDx) < EPSILON) && + (fabs(mDy - other->mDy) < EPSILON) ); } diff --git a/glabels/MainWindow.cpp b/glabels/MainWindow.cpp index 5e3b6c2..5845a92 100644 --- a/glabels/MainWindow.cpp +++ b/glabels/MainWindow.cpp @@ -52,1487 +52,1494 @@ #include "UndoRedoModel.h" -/// -/// Constructor -/// -MainWindow::MainWindow() - : mModel(0) +namespace glabels { - createActions(); - createMenus(); - createToolBars(); - createStatusBar(); - // Build pages - QWidget* welcomePage = createWelcomePage(); - QWidget* propertiesPage = createPropertiesPage(); - QWidget* editorPage = createEditorPage(); - QWidget* mergePage = createMergePage(); - QWidget* printPage = createPrintPage(); + /// + /// Constructor + /// + MainWindow::MainWindow() + : mModel(0) + { + createActions(); + createMenus(); + createToolBars(); + createStatusBar(); - // Table of contents widget - mContents = new QListWidget(); - mContents->setViewMode(QListView::ListMode); - mContents->setMovement(QListView::Static); - mContents->setMinimumWidth(96); - mContents->setMaximumWidth(96); - mContents->setSpacing(6); + // Build pages + QWidget* welcomePage = createWelcomePage(); + QWidget* propertiesPage = createPropertiesPage(); + QWidget* editorPage = createEditorPage(); + QWidget* mergePage = createMergePage(); + QWidget* printPage = createPrintPage(); + + // Table of contents widget + mContents = new QListWidget(); + mContents->setViewMode(QListView::ListMode); + mContents->setMovement(QListView::Static); + mContents->setMinimumWidth(96); + mContents->setMaximumWidth(96); + mContents->setSpacing(6); - // Pages widget - mPages = new QStackedWidget(); + // Pages widget + mPages = new QStackedWidget(); - // Add "Welcome" page - mPages->addWidget( welcomePage ); - mWelcomeButton = new QListWidgetItem(mContents); - mWelcomeButton->setText(tr("Welcome")); - mWelcomeButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + // Add "Welcome" page + mPages->addWidget( welcomePage ); + mWelcomeButton = new QListWidgetItem(mContents); + mWelcomeButton->setText(tr("Welcome")); + mWelcomeButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - // Add "Properties" page - mPages->addWidget( propertiesPage ); - mPropertiesButton = new QListWidgetItem(mContents); - mPropertiesButton->setText(tr("Properties")); - mPropertiesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + // Add "Properties" page + mPages->addWidget( propertiesPage ); + mPropertiesButton = new QListWidgetItem(mContents); + mPropertiesButton->setText(tr("Properties")); + mPropertiesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - // Add "Editor" page - mPages->addWidget( editorPage ); - mEditorButton = new QListWidgetItem(mContents); - mEditorButton->setText(tr("Editor")); - mEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + // Add "Editor" page + mPages->addWidget( editorPage ); + mEditorButton = new QListWidgetItem(mContents); + mEditorButton->setText(tr("Editor")); + mEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - // Add "Merge" page - mPages->addWidget( mergePage ); - mMergeButton = new QListWidgetItem(mContents); - mMergeButton->setText(tr("Merge")); - mMergeButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + // Add "Merge" page + mPages->addWidget( mergePage ); + mMergeButton = new QListWidgetItem(mContents); + mMergeButton->setText(tr("Merge")); + mMergeButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - // Add "Print" page - mPages->addWidget( printPage ); - mPrintButton = new QListWidgetItem(mContents); - mPrintButton->setText(tr("Print")); - mPrintButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + // Add "Print" page + mPages->addWidget( printPage ); + mPrintButton = new QListWidgetItem(mContents); + mPrintButton->setText(tr("Print")); + mPrintButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - // Set initial page selection - mWelcomeButton->setSelected( true ); - mPages->setCurrentIndex(mContents->row(mWelcomeButton)); + // Set initial page selection + mWelcomeButton->setSelected( true ); + mPages->setCurrentIndex(mContents->row(mWelcomeButton)); - // Create central widget - QWidget *centralWidget = new QWidget(); - QHBoxLayout *hLayout = new QHBoxLayout(); - hLayout->setContentsMargins( 0, 0, 0, 0 ); - hLayout->addWidget( mContents ); - hLayout->addWidget( mPages ); - centralWidget->setLayout( hLayout ); - setCentralWidget( centralWidget ); + // Create central widget + QWidget *centralWidget = new QWidget(); + QHBoxLayout *hLayout = new QHBoxLayout(); + hLayout->setContentsMargins( 0, 0, 0, 0 ); + hLayout->addWidget( mContents ); + hLayout->addWidget( mPages ); + centralWidget->setLayout( hLayout ); + setCentralWidget( centralWidget ); - setDocVerbsEnabled( false ); - setPasteVerbsEnabled( false ); - setWelcomeMode( true ); - setTitle(); + setDocVerbsEnabled( false ); + setPasteVerbsEnabled( false ); + setWelcomeMode( true ); + setTitle(); - // Connect - connect( mContents, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), - this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*))); - connect( mLabelEditor, SIGNAL(zoomChanged()), this, SLOT(onZoomChanged()) ); - connect( QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardChanged()) ); + // Connect + connect( mContents, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), + this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*))); + connect( mLabelEditor, SIGNAL(zoomChanged()), this, SLOT(onZoomChanged()) ); + connect( QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardChanged()) ); #if 0 - connect( mLabelEditor, SIGNAL(pointerMoved(double, double)), - this, SLOT(onPointerMoved(double, double)) ); - connect( mLabelEditor, SIGNAL(pointerExited()), this, SLOT(onPointerExit()) ); + connect( mLabelEditor, SIGNAL(pointerMoved(double, double)), + this, SLOT(onPointerMoved(double, double)) ); + connect( mLabelEditor, SIGNAL(pointerExited()), this, SLOT(onPointerExit()) ); #endif - readSettings(); -} + readSettings(); + } -/// -/// Destructor -/// -MainWindow::~MainWindow() -{ -} + /// + /// Destructor + /// + MainWindow::~MainWindow() + { + // empty + } -/// -/// Get model accessor -/// -LabelModel* MainWindow::model() const -{ - return mModel; -} + /// + /// Get model accessor + /// + LabelModel* MainWindow::model() const + { + return mModel; + } -/// -/// Set model accessor -/// -void MainWindow::setModel( LabelModel *label ) -{ - mModel = label; - mUndoRedoModel = new UndoRedoModel( mModel ); + /// + /// Set model accessor + /// + void MainWindow::setModel( LabelModel *label ) + { + mModel = label; + mUndoRedoModel = new UndoRedoModel( mModel ); - mPropertiesView->setModel( mModel, mUndoRedoModel ); - mLabelEditor->setModel( mModel, mUndoRedoModel ); - mObjectEditor->setModel( mModel, mUndoRedoModel ); - mMergeView->setModel( mModel , mUndoRedoModel ); - mPrintView->setModel( mModel ); + mPropertiesView->setModel( mModel, mUndoRedoModel ); + mLabelEditor->setModel( mModel, mUndoRedoModel ); + mObjectEditor->setModel( mModel, mUndoRedoModel ); + mMergeView->setModel( mModel , mUndoRedoModel ); + mPrintView->setModel( mModel ); - mContents->setCurrentItem( mEditorButton ); - mPages->setCurrentIndex(mContents->row(mEditorButton)); + mContents->setCurrentItem( mEditorButton ); + mPages->setCurrentIndex(mContents->row(mEditorButton)); - setDocVerbsEnabled( true ); - setSelectionVerbsEnabled( false ); - setMultiSelectionVerbsEnabled( false ); - setWelcomeMode( false ); - setTitle(); + setDocVerbsEnabled( true ); + setSelectionVerbsEnabled( false ); + setMultiSelectionVerbsEnabled( false ); + setWelcomeMode( false ); + setTitle(); - connect( mLabelEditor, SIGNAL(contextMenuActivate()), this, SLOT(onContextMenuActivate()) ); - connect( mModel, SIGNAL(nameChanged()), this, SLOT(onNameChanged()) ); - connect( mModel, SIGNAL(modifiedChanged()), this, SLOT(onModifiedChanged()) ); - connect( mModel, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()) ); - connect( mModel, SIGNAL(changed()), this, SLOT(onLabelChanged()) ); - connect( mUndoRedoModel, SIGNAL(changed()), this, SLOT(onUndoRedoChanged()) ); -} - - -/// -/// Is window empty? -/// -bool MainWindow::isEmpty() const -{ - return mModel == 0; -} - - -/// -/// Close Event Handler -/// -void MainWindow::closeEvent( QCloseEvent *event ) -{ - if ( isOkToClose() ) - { - writeSettings(); - event->accept(); + connect( mLabelEditor, SIGNAL(contextMenuActivate()), this, SLOT(onContextMenuActivate()) ); + connect( mModel, SIGNAL(nameChanged()), this, SLOT(onNameChanged()) ); + connect( mModel, SIGNAL(modifiedChanged()), this, SLOT(onModifiedChanged()) ); + connect( mModel, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()) ); + connect( mModel, SIGNAL(changed()), this, SLOT(onLabelChanged()) ); + connect( mUndoRedoModel, SIGNAL(changed()), this, SLOT(onUndoRedoChanged()) ); } - else + + + /// + /// Is window empty? + /// + bool MainWindow::isEmpty() const { - event->ignore(); + return mModel == 0; } -} -/// -/// Create Actions -/// -void MainWindow::createActions() -{ - /* File actions */ - fileNewAction = new QAction( tr("&New..."), this ); - fileNewAction->setIcon( QIcon::fromTheme( "document-new", Icons::Fallback::FileNew() ) ); - fileNewAction->setShortcut( QKeySequence::New ); - fileNewAction->setStatusTip( tr("Create a new gLabels project") ); - connect( fileNewAction, SIGNAL(triggered()), this, SLOT(fileNew()) ); - - fileOpenAction = new QAction( tr("&Open..."), this ); - fileOpenAction->setIcon( QIcon::fromTheme( "document-open", Icons::Fallback::FileOpen() ) ); - fileOpenAction->setShortcut( QKeySequence::Open ); - fileOpenAction->setStatusTip( tr("Open an existing gLabels project") ); - connect( fileOpenAction, SIGNAL(triggered()), this, SLOT(fileOpen()) ); - - fileSaveAction = new QAction( tr("&Save"), this ); - fileSaveAction->setIcon( QIcon::fromTheme( "document-save", Icons::Fallback::FileSave() ) ); - fileSaveAction->setShortcut( QKeySequence::Save ); - fileSaveAction->setStatusTip( tr("Save current gLabels project") ); - connect( fileSaveAction, SIGNAL(triggered()), this, SLOT(fileSave()) ); - - fileSaveAsAction = new QAction( tr("Save &As..."), this ); - fileSaveAsAction->setIcon( QIcon::fromTheme( "document-save-as", Icons::Fallback::FileSaveAs() ) ); - fileSaveAsAction->setShortcut( QKeySequence::SaveAs ); - fileSaveAsAction->setStatusTip( tr("Save current gLabels project to a different name") ); - connect( fileSaveAsAction, SIGNAL(triggered()), this, SLOT(fileSaveAs()) ); - - fileTemplateDesignerAction = new QAction( tr("Template &Designer..."), this ); - fileTemplateDesignerAction->setStatusTip( tr("Create custom templates") ); - connect( fileTemplateDesignerAction, SIGNAL(triggered()), this, SLOT(fileTemplateDesigner()) ); - - fileCloseAction = new QAction( tr("&Close"), this ); - fileCloseAction->setIcon( QIcon::fromTheme( "window-close" ) ); - fileCloseAction->setShortcut( QKeySequence::Close ); - fileCloseAction->setStatusTip( tr("Close the current window") ); - connect( fileCloseAction, SIGNAL(triggered()), this, SLOT(fileClose()) ); - - fileExitAction = new QAction( tr("E&xit"), this ); - fileExitAction->setIcon( QIcon::fromTheme( "application-exit" ) ); - fileExitAction->setShortcut( QKeySequence::Quit ); - fileExitAction->setStatusTip( tr("Exit glabels") ); - connect( fileExitAction, SIGNAL(triggered()), this, SLOT(fileExit()) ); - - - /* Edit actions */ - editUndoAction = new QAction( tr("Undo"), this ); - editUndoAction->setIcon( QIcon::fromTheme( "edit-undo" ) ); - editUndoAction->setShortcut( QKeySequence::Undo ); - editUndoAction->setStatusTip( tr("Undo") ); - connect( editUndoAction, SIGNAL(triggered()), this, SLOT(editUndo()) ); - - editRedoAction = new QAction( tr("Redo"), this ); - editRedoAction->setIcon( QIcon::fromTheme( "edit-redo" ) ); - editRedoAction->setShortcut( QKeySequence::Redo ); - editRedoAction->setStatusTip( tr("Redo") ); - connect( editRedoAction, SIGNAL(triggered()), this, SLOT(editRedo()) ); - - editCutAction = new QAction( tr("Cut"), this ); - editCutAction->setIcon( QIcon::fromTheme( "edit-cut", Icons::Fallback::EditCut() ) ); - editCutAction->setShortcut( QKeySequence::Cut ); - editCutAction->setStatusTip( tr("Cut the selection") ); - connect( editCutAction, SIGNAL(triggered()), this, SLOT(editCut()) ); - - editCopyAction = new QAction( tr("&Copy"), this ); - editCopyAction->setIcon( QIcon::fromTheme( "edit-copy", Icons::Fallback::EditCopy() ) ); - editCopyAction->setShortcut( QKeySequence::Copy ); - editCopyAction->setStatusTip( tr("Copy the selection") ); - connect( editCopyAction, SIGNAL(triggered()), this, SLOT(editCopy()) ); - - editPasteAction = new QAction( tr("&Paste"), this ); - editPasteAction->setIcon( QIcon::fromTheme( "edit-paste", Icons::Fallback::EditPaste() ) ); - editPasteAction->setShortcut( QKeySequence::Paste ); - editPasteAction->setStatusTip( tr("Paste the clipboard") ); - connect( editPasteAction, SIGNAL(triggered()), this, SLOT(editPaste()) ); - - editDeleteAction = new QAction( tr("&Delete"), this ); - editDeleteAction->setIcon( QIcon::fromTheme( "edit-delete" ) ); - editDeleteAction->setShortcut( QKeySequence::Delete ); - editDeleteAction->setStatusTip( tr("Delete the selected objects") ); - connect( editDeleteAction, SIGNAL(triggered()), this, SLOT(editDelete()) ); - - editSelectAllAction = new QAction( tr("Select &All"), this ); - editSelectAllAction->setIcon( QIcon::fromTheme( "edit-select-all" ) ); - editSelectAllAction->setShortcut( QKeySequence::SelectAll ); - editSelectAllAction->setStatusTip( tr("Select all objects") ); - connect( editSelectAllAction, SIGNAL(triggered()), this, SLOT(editSelectAll()) ); - - editUnSelectAllAction = new QAction( tr("Un-select All"), this ); - editUnSelectAllAction->setIcon( QIcon::fromTheme( "edit-unselect-all" ) ); - editUnSelectAllAction->setStatusTip( tr("Remove all selections") ); - connect( editUnSelectAllAction, SIGNAL(triggered()), this, SLOT(editUnSelectAll()) ); - - editPreferencesAction = new QAction( tr("Preferences"), this ); - editPreferencesAction->setIcon( QIcon::fromTheme( "edit-preferences" ) ); - editPreferencesAction->setShortcut( QKeySequence::Preferences ); - editPreferencesAction->setStatusTip( tr("Configure the application") ); - connect( editPreferencesAction, SIGNAL(triggered()), this, SLOT(editPreferences()) ); - - - /* View actions */ - viewFileToolBarAction = new QAction( tr("File"), this ); - viewFileToolBarAction->setCheckable( true ); - viewFileToolBarAction->setStatusTip( tr("Change visibility of file toolbar in current window") ); - connect( viewFileToolBarAction, SIGNAL(toggled(bool)), this, SLOT(viewFileToolBar(bool)) ); - - viewEditorToolBarAction = new QAction( tr("Editor"), this ); - viewEditorToolBarAction->setCheckable( true ); - viewEditorToolBarAction->setStatusTip( tr("Change visibility of editor toolbar in current window") ); - connect( viewEditorToolBarAction, SIGNAL(toggled(bool)), this, SLOT(viewEditorToolBar(bool)) ); - - - viewGridAction = new QAction( tr("Grid"), this ); - viewGridAction->setCheckable( true ); - viewGridAction->setStatusTip( tr("Change visibility of the grid in current window") ); - connect( viewGridAction, SIGNAL(toggled(bool)), this, SLOT(viewGrid(bool)) ); - - viewMarkupAction = new QAction( tr("Markup"), this ); - viewMarkupAction->setCheckable( true ); - viewMarkupAction->setStatusTip( tr("Change visibility of markup lines in current window") ); - connect( viewMarkupAction, SIGNAL(toggled(bool)), this, SLOT(viewMarkup(bool)) ); - - viewZoomInAction = new QAction( tr("Zoom &In"), this ); - viewZoomInAction->setIcon( QIcon::fromTheme( "zoom-in", Icons::Fallback::ZoomIn() ) ); - viewZoomInAction->setShortcut( QKeySequence::ZoomIn ); - viewZoomInAction->setStatusTip( tr("Increase magnification") ); - connect( viewZoomInAction, SIGNAL(triggered()), this, SLOT(viewZoomIn()) ); - - viewZoomOutAction = new QAction( tr("Zoom &Out"), this ); - viewZoomOutAction->setIcon( QIcon::fromTheme( "zoom-out", Icons::Fallback::ZoomOut() ) ); - viewZoomOutAction->setShortcut( QKeySequence::ZoomOut ); - viewZoomOutAction->setStatusTip( tr("Decrease magnification") ); - connect( viewZoomOutAction, SIGNAL(triggered()), this, SLOT(viewZoomOut()) ); - - viewZoom1To1Action = new QAction( tr("Zoom &1 to 1"), this ); - viewZoom1To1Action->setIcon( QIcon::fromTheme( "zoom-original", Icons::Fallback::ZoomOriginal() ) ); - viewZoom1To1Action->setStatusTip( tr("Restore scale to 100%") ); - connect( viewZoom1To1Action, SIGNAL(triggered()), this, SLOT(viewZoom1To1()) ); - - viewZoomToFitAction = new QAction( tr("Zoom to &Fit"), this ); - viewZoomToFitAction->setIcon( QIcon::fromTheme( "zoom-fit-best", Icons::Fallback::ZoomBestFit() ) ); - viewZoomToFitAction->setStatusTip( tr("Set scale to fit window") ); - connect( viewZoomToFitAction, SIGNAL(triggered()), this, SLOT(viewZoomToFit()) ); - - - /* Object actions */ - objectsArrowModeAction = new QAction( tr("Select Mode"), this ); - objectsArrowModeAction->setIcon( Icons::Arrow() ); - objectsArrowModeAction->setStatusTip( tr("Select, move and modify objects") ); - connect( objectsArrowModeAction, SIGNAL(triggered()), this, SLOT(objectsArrowMode()) ); - - objectsCreateTextAction = new QAction( tr("Text"), this ); - objectsCreateTextAction->setIcon( Icons::Text() ); - objectsCreateTextAction->setStatusTip( tr("Create text object") ); - connect( objectsCreateTextAction, SIGNAL(triggered()), this, SLOT(objectsCreateText()) ); - - objectsCreateBoxAction = new QAction( tr("Box"), this ); - objectsCreateBoxAction->setIcon( Icons::Box() ); - objectsCreateBoxAction->setStatusTip( tr("Create box object") ); - connect( objectsCreateBoxAction, SIGNAL(triggered()), this, SLOT(objectsCreateBox()) ); - - objectsCreateLineAction = new QAction( tr("Line"), this ); - objectsCreateLineAction->setIcon( Icons::Line() ); - objectsCreateLineAction->setStatusTip( tr("Create line object") ); - connect( objectsCreateLineAction, SIGNAL(triggered()), this, SLOT(objectsCreateLine()) ); - - objectsCreateEllipseAction = new QAction( tr("Ellipse"), this ); - objectsCreateEllipseAction->setIcon( Icons::Ellipse() ); - objectsCreateEllipseAction->setStatusTip( tr("Create ellipse/circle object") ); - connect( objectsCreateEllipseAction, SIGNAL(triggered()), this, SLOT(objectsCreateEllipse()) ); - - objectsCreateImageAction = new QAction( tr("Image"), this ); - objectsCreateImageAction->setIcon( Icons::Image() ); - objectsCreateImageAction->setStatusTip( tr("Create image object") ); - connect( objectsCreateImageAction, SIGNAL(triggered()), this, SLOT(objectsCreateImage()) ); - - objectsCreateBarcodeAction = new QAction( tr("Barcode"), this ); - objectsCreateBarcodeAction->setIcon( Icons::Barcode() ); - objectsCreateBarcodeAction->setStatusTip( tr("Create barcode object") ); - connect( objectsCreateBarcodeAction, SIGNAL(triggered()), this, SLOT(objectsCreateBarcode()) ); - - objectsOrderRaiseAction = new QAction( tr("Bring To Front"), this ); - objectsOrderRaiseAction->setIcon( Icons::OrderTop() ); - objectsOrderRaiseAction->setStatusTip( tr("Raise selection to top") ); - connect( objectsOrderRaiseAction, SIGNAL(triggered()), this, SLOT(objectsOrderRaise()) ); - - objectsOrderLowerAction = new QAction( tr("Send To Back"), this ); - objectsOrderLowerAction->setIcon( Icons::OrderBottom() ); - objectsOrderLowerAction->setStatusTip( tr("Lower selection to bottom") ); - connect( objectsOrderLowerAction, SIGNAL(triggered()), this, SLOT(objectsOrderLower()) ); - - objectsXformRotateLeftAction = new QAction( tr("Rotate Left"), this ); - objectsXformRotateLeftAction->setIcon( Icons::RotateLeft() ); - objectsXformRotateLeftAction->setStatusTip( tr("Rotate object(s) 90 degrees counter-clockwise") ); - connect( objectsXformRotateLeftAction, SIGNAL(triggered()), this, SLOT(objectsXformRotateLeft()) ); - - objectsXformRotateRightAction = new QAction( tr("Rotate Right"), this ); - objectsXformRotateRightAction->setIcon( Icons::RotateRight() ); - objectsXformRotateRightAction->setStatusTip( tr("Rotate object(s) 90 degrees clockwise") ); - connect( objectsXformRotateRightAction, SIGNAL(triggered()), this, SLOT(objectsXformRotateRight()) ); - - objectsXformFlipHorizAction = new QAction( tr("Flip Horizontally"), this ); - objectsXformFlipHorizAction->setIcon( Icons::FlipHoriz() ); - objectsXformFlipHorizAction->setStatusTip( tr("Flip object(s) horizontally") ); - connect( objectsXformFlipHorizAction, SIGNAL(triggered()), this, SLOT(objectsXformFlipHoriz()) ); - - objectsXformFlipVertAction = new QAction( tr("Flip Vertically"), this ); - objectsXformFlipVertAction->setIcon( Icons::FlipVert() ); - objectsXformFlipVertAction->setStatusTip( tr("Flip object(s) vertically") ); - connect( objectsXformFlipVertAction, SIGNAL(triggered()), this, SLOT(objectsXformFlipVert()) ); - - objectsAlignLeftAction = new QAction( tr("Align Left"), this ); - objectsAlignLeftAction->setIcon( Icons::AlignLeft() ); - objectsAlignLeftAction->setStatusTip( tr("Align objects to left edges") ); - connect( objectsAlignLeftAction, SIGNAL(triggered()), this, SLOT(objectsAlignLeft()) ); - - objectsAlignHCenterAction = new QAction( tr("Align Center"), this ); - objectsAlignHCenterAction->setIcon( Icons::AlignHCenter() ); - objectsAlignHCenterAction->setStatusTip( tr("Align objects to horizontal centers") ); - connect( objectsAlignHCenterAction, SIGNAL(triggered()), this, SLOT(objectsAlignHCenter()) ); - - objectsAlignRightAction = new QAction( tr("Align Right"), this ); - objectsAlignRightAction->setIcon( Icons::AlignRight() ); - objectsAlignRightAction->setStatusTip( tr("Align objects to right edges") ); - connect( objectsAlignRightAction, SIGNAL(triggered()), this, SLOT(objectsAlignRight()) ); - - objectsAlignTopAction = new QAction( tr("Align Top"), this ); - objectsAlignTopAction->setIcon( Icons::AlignTop() ); - objectsAlignTopAction->setStatusTip( tr("Align objects to top edges") ); - connect( objectsAlignTopAction, SIGNAL(triggered()), this, SLOT(objectsAlignTop()) ); - - objectsAlignVCenterAction = new QAction( tr("Align Middle"), this ); - objectsAlignVCenterAction->setIcon( Icons::AlignVCenter() ); - objectsAlignVCenterAction->setStatusTip( tr("Align objects to vertical centers") ); - connect( objectsAlignVCenterAction, SIGNAL(triggered()), this, SLOT(objectsAlignVCenter()) ); - - objectsAlignBottomAction = new QAction( tr("Align Bottom"), this ); - objectsAlignBottomAction->setIcon( Icons::AlignBottom() ); - objectsAlignBottomAction->setStatusTip( tr("Align objects to bottom edges") ); - connect( objectsAlignBottomAction, SIGNAL(triggered()), this, SLOT(objectsAlignBottom()) ); - - objectsCenterHorizAction = new QAction( tr("Center Horizontally"), this ); - objectsCenterHorizAction->setIcon( Icons::CenterHoriz() ); - objectsCenterHorizAction->setStatusTip( tr("Horizontally center objects in label") ); - connect( objectsCenterHorizAction, SIGNAL(triggered()), this, SLOT(objectsCenterHoriz()) ); - - objectsCenterVertAction = new QAction( tr("Center Vertically"), this ); - objectsCenterVertAction->setIcon( Icons::CenterVert() ); - objectsCenterVertAction->setStatusTip( tr("Vertically center objects in label") ); - connect( objectsCenterVertAction, SIGNAL(triggered()), this, SLOT(objectsCenterVert()) ); - - - /* Help actions */ - helpContentsAction = new QAction( tr("&Contents..."), this ); - helpContentsAction->setIcon( QIcon::fromTheme( "help-contents" ) ); - helpContentsAction->setShortcut( QKeySequence::HelpContents ); - helpContentsAction->setStatusTip( tr("Open gLabels manual") ); - connect( helpContentsAction, SIGNAL(triggered()), this, SLOT(helpContents()) ); - - helpAboutAction = new QAction( tr("&About..."), this ); - helpAboutAction->setIcon( QIcon::fromTheme( "help-about" ) ); - helpAboutAction->setStatusTip( tr("About gLabels") ); - connect( helpAboutAction, SIGNAL(triggered()), this, SLOT(helpAbout()) ); - - - /* Context menu version of edit actions */ - contextCutAction = new QAction( tr("Cut"), this ); - contextCutAction->setIcon( QIcon::fromTheme( "edit-cut", Icons::Fallback::EditCut() ) ); - contextCutAction->setStatusTip( tr("Cut the selection") ); - connect( contextCutAction, SIGNAL(triggered()), this, SLOT(editCut()) ); - - contextCopyAction = new QAction( tr("&Copy"), this ); - contextCopyAction->setIcon( QIcon::fromTheme( "edit-copy", Icons::Fallback::EditCopy() ) ); - contextCopyAction->setStatusTip( tr("Copy the selection") ); - connect( contextCopyAction, SIGNAL(triggered()), this, SLOT(editCopy()) ); - - contextPasteAction = new QAction( tr("&Paste"), this ); - contextPasteAction->setIcon( QIcon::fromTheme( "edit-paste", Icons::Fallback::EditPaste() ) ); - contextPasteAction->setStatusTip( tr("Paste the clipboard") ); - connect( contextPasteAction, SIGNAL(triggered()), this, SLOT(editPaste()) ); - - contextDeleteAction = new QAction( tr("&Delete"), this ); - contextDeleteAction->setIcon( QIcon::fromTheme( "edit-delete" ) ); - contextDeleteAction->setStatusTip( tr("Delete the selected objects") ); - connect( contextDeleteAction, SIGNAL(triggered()), this, SLOT(editDelete()) ); -} - - -/// -/// Create Menus -/// -void MainWindow::createMenus() -{ - fileMenu = menuBar()->addMenu( tr("&File") ); - fileMenu->addAction( fileNewAction ); - fileMenu->addAction( fileOpenAction ); - fileMenu->addAction( fileSaveAction ); - fileMenu->addAction( fileSaveAsAction ); - fileMenu->addSeparator(); - fileMenu->addAction( fileTemplateDesignerAction ); - fileMenu->addSeparator(); - fileMenu->addAction( fileCloseAction ); - fileMenu->addAction( fileExitAction ); - - editMenu = menuBar()->addMenu( tr("&Edit") ); - editMenu->addAction( editUndoAction ); - editMenu->addAction( editRedoAction ); - editMenu->addSeparator(); - editMenu->addAction( editCutAction ); - editMenu->addAction( editCopyAction ); - editMenu->addAction( editPasteAction ); - editMenu->addAction( editDeleteAction ); - editMenu->addSeparator(); - editMenu->addAction( editSelectAllAction ); - editMenu->addAction( editUnSelectAllAction ); - editMenu->addSeparator(); - editMenu->addAction( editPreferencesAction ); - - viewMenu = menuBar()->addMenu( tr("&View") ); - viewToolBarsMenu = viewMenu->addMenu( tr("Toolbars") ); - viewToolBarsMenu->addAction( viewFileToolBarAction ); - viewToolBarsMenu->addAction( viewEditorToolBarAction ); - viewMenu->addSeparator(); - viewMenu->addAction( viewGridAction ); - viewMenu->addAction( viewMarkupAction ); - viewMenu->addSeparator(); - viewMenu->addAction( viewZoomInAction ); - viewMenu->addAction( viewZoomOutAction ); - viewMenu->addAction( viewZoom1To1Action ); - viewMenu->addAction( viewZoomToFitAction ); - - objectsMenu = menuBar()->addMenu( tr("&Objects") ); - objectsMenu->addAction( objectsArrowModeAction ); - objectsCreateMenu = objectsMenu->addMenu( tr("&Create") ); - objectsCreateMenu->addAction( objectsCreateTextAction ); - objectsCreateMenu->addAction( objectsCreateBoxAction ); - objectsCreateMenu->addAction( objectsCreateLineAction ); - objectsCreateMenu->addAction( objectsCreateEllipseAction ); - objectsCreateMenu->addAction( objectsCreateImageAction ); - objectsCreateMenu->addAction( objectsCreateBarcodeAction ); - objectsMenu->addSeparator(); - objectsOrderMenu = objectsMenu->addMenu( tr("&Order") ); - objectsOrderMenu->addAction( objectsOrderRaiseAction ); - objectsOrderMenu->addAction( objectsOrderLowerAction ); - objectsXformMenu = objectsMenu->addMenu( tr("&Rotate/Flip") ); - objectsXformMenu->addAction( objectsXformRotateLeftAction ); - objectsXformMenu->addAction( objectsXformRotateRightAction ); - objectsXformMenu->addAction( objectsXformFlipHorizAction ); - objectsXformMenu->addAction( objectsXformFlipVertAction ); - objectsAlignMenu = objectsMenu->addMenu( tr("&Alignment") ); - objectsAlignMenu->addAction( objectsAlignLeftAction ); - objectsAlignMenu->addAction( objectsAlignHCenterAction ); - objectsAlignMenu->addAction( objectsAlignRightAction ); - objectsAlignMenu->addSeparator(); - objectsAlignMenu->addAction( objectsAlignTopAction ); - objectsAlignMenu->addAction( objectsAlignVCenterAction ); - objectsAlignMenu->addAction( objectsAlignBottomAction ); - objectsCenterMenu = objectsMenu->addMenu( tr("Center") ); - objectsCenterMenu->addAction( objectsCenterHorizAction ); - objectsCenterMenu->addAction( objectsCenterVertAction ); - - helpMenu = menuBar()->addMenu( tr("&Help") ); - helpMenu->addAction( helpContentsAction ); - helpMenu->addAction( helpAboutAction ); - - contextMenu = new QMenu(); - contextOrderMenu = contextMenu->addMenu( tr("&Order") ); - contextOrderMenu->addAction( objectsOrderRaiseAction ); - contextOrderMenu->addAction( objectsOrderLowerAction ); - contextXformMenu = contextMenu->addMenu( tr("&Rotate/Flip") ); - contextXformMenu->addAction( objectsXformRotateLeftAction ); - contextXformMenu->addAction( objectsXformRotateRightAction ); - contextXformMenu->addAction( objectsXformFlipHorizAction ); - contextXformMenu->addAction( objectsXformFlipVertAction ); - contextAlignMenu = contextMenu->addMenu( tr("&Alignment") ); - contextAlignMenu->addAction( objectsAlignLeftAction ); - contextAlignMenu->addAction( objectsAlignHCenterAction ); - contextAlignMenu->addAction( objectsAlignRightAction ); - contextAlignMenu->addSeparator(); - contextAlignMenu->addAction( objectsAlignTopAction ); - contextAlignMenu->addAction( objectsAlignVCenterAction ); - contextAlignMenu->addAction( objectsAlignBottomAction ); - contextCenterMenu = contextMenu->addMenu( tr("Center") ); - contextCenterMenu->addAction( objectsCenterHorizAction ); - contextCenterMenu->addAction( objectsCenterVertAction ); - contextMenu->addSeparator(); - contextMenu->addAction( contextCutAction ); - contextMenu->addAction( contextCopyAction ); - contextMenu->addAction( contextPasteAction ); - contextMenu->addAction( contextDeleteAction ); - - noSelectionContextMenu = new QMenu(); - noSelectionContextMenu->addAction( contextPasteAction ); -} - - -/// -/// Create Tool Bars -/// -void MainWindow::createToolBars() -{ - fileToolBar = addToolBar( tr("&File") ); - fileToolBar->addAction( fileNewAction ); - fileToolBar->addAction( fileOpenAction ); - fileToolBar->addAction( fileSaveAction ); - - zoomInfoLabel = new QLabel( " 999% " ); - zoomInfoLabel->setAlignment( Qt::AlignHCenter|Qt::AlignVCenter ); - zoomInfoLabel->setMinimumSize( zoomInfoLabel->sizeHint() ); - - editorToolBar = new QToolBar( tr("&Editor") ); - editorToolBar->addAction( objectsArrowModeAction ); - editorToolBar->addSeparator(); - editorToolBar->addAction( objectsCreateTextAction ); - editorToolBar->addAction( objectsCreateBoxAction ); - editorToolBar->addAction( objectsCreateLineAction ); - editorToolBar->addAction( objectsCreateEllipseAction ); - editorToolBar->addAction( objectsCreateImageAction ); - editorToolBar->addAction( objectsCreateBarcodeAction ); - editorToolBar->addSeparator(); - editorToolBar->addAction( editCutAction ); - editorToolBar->addAction( editCopyAction ); - editorToolBar->addAction( editPasteAction ); - editorToolBar->addSeparator(); - editorToolBar->addAction( viewZoomInAction ); - editorToolBar->addAction( viewZoomOutAction ); - editorToolBar->addAction( viewZoom1To1Action ); - editorToolBar->addAction( viewZoomToFitAction ); - editorToolBar->addWidget( zoomInfoLabel ); - editorToolBar->addSeparator(); -} - - -/// -/// Create Status Bar -/// -void MainWindow::createStatusBar() -{ - statusBar(); -} - - -/// -/// Create Welcome Page -/// -QWidget* MainWindow::createWelcomePage() -{ - mWelcomeView = new StartupView( this ); - - return mWelcomeView; -} - - -/// -/// Create Properties Page -/// -QWidget* MainWindow::createPropertiesPage() -{ - mPropertiesView = new PropertiesView(); - - return mPropertiesView; -} - - -/// -/// Create Editor Page -/// -QWidget* MainWindow::createEditorPage() -{ - QWidget* page = new QWidget; - - mLabelEditorScrollArea = new QScrollArea(); - mLabelEditorScrollArea->setMinimumSize( 640, 450 ); - mLabelEditorScrollArea->setWidgetResizable( true ); - - mLabelEditor = new LabelEditor( mLabelEditorScrollArea ); - mObjectEditor = new ObjectEditor(); - - mLabelEditorScrollArea->setWidget( mLabelEditor ); - - QVBoxLayout* editorVLayout = new QVBoxLayout; - editorVLayout->setContentsMargins( 0, 0, 0, 0 ); - editorVLayout->addWidget( editorToolBar ); - editorVLayout->addWidget( mLabelEditorScrollArea ); - - QHBoxLayout* editorHLayout = new QHBoxLayout; - editorHLayout->setContentsMargins( 0, 0, 0, 0 ); - editorHLayout->addLayout( editorVLayout ); - editorHLayout->addWidget( mObjectEditor ); - - page->setLayout( editorHLayout ); - - return page; -} - - -/// -/// Create Merge Page -/// -QWidget* MainWindow::createMergePage() -{ - mMergeView = new MergeView(); - - return mMergeView; -} - - -/// -/// Create Print Page -/// -QWidget* MainWindow::createPrintPage() -{ - mPrintView = new PrintView(); - - return mPrintView; -} - - -/// -/// Set enabled state of TOC buttons based on Welcome mode -/// -void MainWindow::setWelcomeMode( bool enabled ) -{ - mWelcomeButton->setHidden( !enabled ); - mPropertiesButton->setHidden( enabled ); - mEditorButton->setHidden( enabled ); - mMergeButton->setHidden( enabled ); - mPrintButton->setHidden( enabled ); -} - - -/// -/// Set enabled state of actions associated with a document. -/// -void MainWindow::setDocVerbsEnabled( bool enabled ) -{ - fileSaveAction->setEnabled( mModel && mModel->isModified() ); - fileSaveAsAction->setEnabled( mModel ); - editUndoAction->setEnabled( enabled && mUndoRedoModel->canUndo() ); - editRedoAction->setEnabled( enabled && mUndoRedoModel->canRedo() ); - editDeleteAction->setEnabled( enabled ); - editSelectAllAction->setEnabled( enabled ); - editUnSelectAllAction->setEnabled( enabled ); - viewZoomInAction->setEnabled( enabled ); - viewZoomOutAction->setEnabled( enabled ); - viewZoom1To1Action->setEnabled( enabled ); - viewZoomToFitAction->setEnabled( enabled ); - viewGridAction->setEnabled( enabled ); - viewMarkupAction->setEnabled( enabled ); - objectsArrowModeAction->setEnabled( enabled ); - objectsCreateMenu->setEnabled( enabled ); - objectsCreateTextAction->setEnabled( enabled ); - objectsCreateLineAction->setEnabled( enabled ); - objectsCreateBoxAction->setEnabled( enabled ); - objectsCreateEllipseAction->setEnabled( enabled ); - objectsCreateImageAction->setEnabled( enabled ); - objectsCreateBarcodeAction->setEnabled( enabled ); - objectsOrderMenu->setEnabled( enabled ); - objectsOrderRaiseAction->setEnabled( enabled ); - objectsOrderLowerAction->setEnabled( enabled ); - objectsXformMenu->setEnabled( enabled ); - objectsXformRotateLeftAction->setEnabled( enabled ); - objectsXformRotateRightAction->setEnabled( enabled ); - objectsXformFlipHorizAction->setEnabled( enabled ); - objectsXformFlipVertAction->setEnabled( enabled ); - objectsAlignMenu->setEnabled( enabled ); - objectsAlignLeftAction->setEnabled( enabled ); - objectsAlignRightAction->setEnabled( enabled ); - objectsAlignHCenterAction->setEnabled( enabled ); - objectsAlignTopAction->setEnabled( enabled ); - objectsAlignBottomAction->setEnabled( enabled ); - objectsAlignVCenterAction->setEnabled( enabled ); - objectsCenterMenu->setEnabled( enabled ); - objectsCenterHorizAction->setEnabled( enabled ); - objectsCenterVertAction->setEnabled( enabled ); -} - - -/// -/// Set enabled state of actions associated with a document being modified since last save. -/// -void MainWindow::setDocModifiedVerbsEnabled( bool enabled ) -{ - fileSaveAction->setEnabled( enabled ); -} - - -/// -/// Set enabled state of actions associated with data being available on clipboard. -/// -void MainWindow::setPasteVerbsEnabled( bool enabled ) -{ - editPasteAction->setEnabled( enabled ); - contextPasteAction->setEnabled( enabled ); -} - - -/// -/// Set enabled state of actions associated with a non-empty selection. -/// -void MainWindow::setSelectionVerbsEnabled( bool enabled ) -{ - editCutAction->setEnabled( enabled ); - editCopyAction->setEnabled( enabled ); - editDeleteAction->setEnabled( enabled ); - editUnSelectAllAction->setEnabled( enabled ); - objectsOrderMenu->setEnabled( enabled ); - objectsOrderRaiseAction->setEnabled( enabled ); - objectsOrderLowerAction->setEnabled( enabled ); - objectsXformMenu->setEnabled( enabled ); - objectsXformRotateLeftAction->setEnabled( enabled ); - objectsXformRotateRightAction->setEnabled( enabled ); - objectsXformFlipHorizAction->setEnabled( enabled ); - objectsXformFlipVertAction->setEnabled( enabled ); - objectsCenterMenu->setEnabled( enabled ); - objectsCenterHorizAction->setEnabled( enabled ); - objectsCenterVertAction->setEnabled( enabled ); -} - - -/// -/// Set enabled state of actions associated with a non-atomic selection. -/// -void MainWindow::setMultiSelectionVerbsEnabled( bool enabled ) -{ - objectsAlignMenu->setEnabled( enabled ); - objectsAlignLeftAction->setEnabled( enabled ); - objectsAlignRightAction->setEnabled( enabled ); - objectsAlignHCenterAction->setEnabled( enabled ); - objectsAlignTopAction->setEnabled( enabled ); - objectsAlignBottomAction->setEnabled( enabled ); - objectsAlignVCenterAction->setEnabled( enabled ); -} - - -/// -/// Set window title -/// -void MainWindow::setTitle() -{ - if ( mModel == 0 ) + /// + /// Close Event Handler + /// + void MainWindow::closeEvent( QCloseEvent *event ) { - setWindowTitle( "gLabels" ); - } - else - { - if ( mModel->isModified() ) + if ( isOkToClose() ) { - setWindowTitle( "gLabels - " + mModel->shortName() + " " + tr("(modified)") ); + writeSettings(); + event->accept(); } else { - setWindowTitle( "gLabels - " + mModel->shortName() ); + event->ignore(); } } -} -/// -/// Read MainWindow Settings -/// -void MainWindow::readSettings() -{ - QSettings settings; + /// + /// Create Actions + /// + void MainWindow::createActions() + { + /* File actions */ + fileNewAction = new QAction( tr("&New..."), this ); + fileNewAction->setIcon( QIcon::fromTheme( "document-new", Icons::FileNew() ) ); + fileNewAction->setShortcut( QKeySequence::New ); + fileNewAction->setStatusTip( tr("Create a new gLabels project") ); + connect( fileNewAction, SIGNAL(triggered()), this, SLOT(fileNew()) ); - settings.beginGroup( "MainWindow" ); - bool showFileToolBar = settings.value( "showFileToolBar", true ).toBool(); - bool showEditorToolBar = settings.value( "showEditToolBar", true ).toBool(); - bool showGrid = settings.value( "showGrid", true ).toBool(); - bool showMarkup = settings.value( "showMarkup", true ).toBool(); - settings.endGroup(); + fileOpenAction = new QAction( tr("&Open..."), this ); + fileOpenAction->setIcon( QIcon::fromTheme( "document-open", Icons::FileOpen() ) ); + fileOpenAction->setShortcut( QKeySequence::Open ); + fileOpenAction->setStatusTip( tr("Open an existing gLabels project") ); + connect( fileOpenAction, SIGNAL(triggered()), this, SLOT(fileOpen()) ); - viewFileToolBarAction ->setChecked( showFileToolBar ); - viewEditorToolBarAction ->setChecked( showEditorToolBar ); - viewGridAction ->setChecked( showGrid ); - viewMarkupAction ->setChecked( showMarkup ); + fileSaveAction = new QAction( tr("&Save"), this ); + fileSaveAction->setIcon( QIcon::fromTheme( "document-save", Icons::FileSave() ) ); + fileSaveAction->setShortcut( QKeySequence::Save ); + fileSaveAction->setStatusTip( tr("Save current gLabels project") ); + connect( fileSaveAction, SIGNAL(triggered()), this, SLOT(fileSave()) ); - fileToolBar ->setVisible( showFileToolBar ); - editorToolBar ->setVisible( showEditorToolBar ); - mLabelEditor ->setGridVisible( showGrid ); - mLabelEditor ->setMarkupVisible( showMarkup ); -} + fileSaveAsAction = new QAction( tr("Save &As..."), this ); + fileSaveAsAction->setIcon( QIcon::fromTheme( "document-save-as", Icons::FileSaveAs() ) ); + fileSaveAsAction->setShortcut( QKeySequence::SaveAs ); + fileSaveAsAction->setStatusTip( tr("Save current gLabels project to a different name") ); + connect( fileSaveAsAction, SIGNAL(triggered()), this, SLOT(fileSaveAs()) ); + + fileTemplateDesignerAction = new QAction( tr("Template &Designer..."), this ); + fileTemplateDesignerAction->setStatusTip( tr("Create custom templates") ); + connect( fileTemplateDesignerAction, SIGNAL(triggered()), this, SLOT(fileTemplateDesigner()) ); + + fileCloseAction = new QAction( tr("&Close"), this ); + fileCloseAction->setIcon( QIcon::fromTheme( "window-close" ) ); + fileCloseAction->setShortcut( QKeySequence::Close ); + fileCloseAction->setStatusTip( tr("Close the current window") ); + connect( fileCloseAction, SIGNAL(triggered()), this, SLOT(fileClose()) ); + + fileExitAction = new QAction( tr("E&xit"), this ); + fileExitAction->setIcon( QIcon::fromTheme( "application-exit" ) ); + fileExitAction->setShortcut( QKeySequence::Quit ); + fileExitAction->setStatusTip( tr("Exit glabels") ); + connect( fileExitAction, SIGNAL(triggered()), this, SLOT(fileExit()) ); -/// -/// Write MainWindow Settings -/// -void MainWindow::writeSettings() -{ - QSettings settings; + /* Edit actions */ + editUndoAction = new QAction( tr("Undo"), this ); + editUndoAction->setIcon( QIcon::fromTheme( "edit-undo" ) ); + editUndoAction->setShortcut( QKeySequence::Undo ); + editUndoAction->setStatusTip( tr("Undo") ); + connect( editUndoAction, SIGNAL(triggered()), this, SLOT(editUndo()) ); - settings.beginGroup( "MainWindow" ); - settings.setValue( "showFileToolBar", viewFileToolBarAction->isChecked() ); - settings.setValue( "showEditorToolBar", viewEditorToolBarAction->isChecked() ); - settings.setValue( "showGrid", viewGridAction->isChecked() ); - settings.setValue( "showMarkup", viewMarkupAction->isChecked() ); - settings.endGroup(); -} + editRedoAction = new QAction( tr("Redo"), this ); + editRedoAction->setIcon( QIcon::fromTheme( "edit-redo" ) ); + editRedoAction->setShortcut( QKeySequence::Redo ); + editRedoAction->setStatusTip( tr("Redo") ); + connect( editRedoAction, SIGNAL(triggered()), this, SLOT(editRedo()) ); + + editCutAction = new QAction( tr("Cut"), this ); + editCutAction->setIcon( QIcon::fromTheme( "edit-cut", Icons::EditCut() ) ); + editCutAction->setShortcut( QKeySequence::Cut ); + editCutAction->setStatusTip( tr("Cut the selection") ); + connect( editCutAction, SIGNAL(triggered()), this, SLOT(editCut()) ); + + editCopyAction = new QAction( tr("&Copy"), this ); + editCopyAction->setIcon( QIcon::fromTheme( "edit-copy", Icons::EditCopy() ) ); + editCopyAction->setShortcut( QKeySequence::Copy ); + editCopyAction->setStatusTip( tr("Copy the selection") ); + connect( editCopyAction, SIGNAL(triggered()), this, SLOT(editCopy()) ); + + editPasteAction = new QAction( tr("&Paste"), this ); + editPasteAction->setIcon( QIcon::fromTheme( "edit-paste", Icons::EditPaste() ) ); + editPasteAction->setShortcut( QKeySequence::Paste ); + editPasteAction->setStatusTip( tr("Paste the clipboard") ); + connect( editPasteAction, SIGNAL(triggered()), this, SLOT(editPaste()) ); + + editDeleteAction = new QAction( tr("&Delete"), this ); + editDeleteAction->setIcon( QIcon::fromTheme( "edit-delete" ) ); + editDeleteAction->setShortcut( QKeySequence::Delete ); + editDeleteAction->setStatusTip( tr("Delete the selected objects") ); + connect( editDeleteAction, SIGNAL(triggered()), this, SLOT(editDelete()) ); + + editSelectAllAction = new QAction( tr("Select &All"), this ); + editSelectAllAction->setIcon( QIcon::fromTheme( "edit-select-all" ) ); + editSelectAllAction->setShortcut( QKeySequence::SelectAll ); + editSelectAllAction->setStatusTip( tr("Select all objects") ); + connect( editSelectAllAction, SIGNAL(triggered()), this, SLOT(editSelectAll()) ); + + editUnSelectAllAction = new QAction( tr("Un-select All"), this ); + editUnSelectAllAction->setIcon( QIcon::fromTheme( "edit-unselect-all" ) ); + editUnSelectAllAction->setStatusTip( tr("Remove all selections") ); + connect( editUnSelectAllAction, SIGNAL(triggered()), this, SLOT(editUnSelectAll()) ); + + editPreferencesAction = new QAction( tr("Preferences"), this ); + editPreferencesAction->setIcon( QIcon::fromTheme( "edit-preferences" ) ); + editPreferencesAction->setShortcut( QKeySequence::Preferences ); + editPreferencesAction->setStatusTip( tr("Configure the application") ); + connect( editPreferencesAction, SIGNAL(triggered()), this, SLOT(editPreferences()) ); -/// -/// Is it ok to close window? -/// -bool MainWindow::isOkToClose() -{ - bool ok = true; + /* View actions */ + viewFileToolBarAction = new QAction( tr("File"), this ); + viewFileToolBarAction->setCheckable( true ); + viewFileToolBarAction->setStatusTip( tr("Change visibility of file toolbar in current window") ); + connect( viewFileToolBarAction, SIGNAL(toggled(bool)), this, SLOT(viewFileToolBar(bool)) ); - if ( !this->isEmpty() ) - { - if ( mModel->isModified() ) + viewEditorToolBarAction = new QAction( tr("Editor"), this ); + viewEditorToolBarAction->setCheckable( true ); + viewEditorToolBarAction->setStatusTip( tr("Change visibility of editor toolbar in current window") ); + connect( viewEditorToolBarAction, SIGNAL(toggled(bool)), this, SLOT(viewEditorToolBar(bool)) ); + + + viewGridAction = new QAction( tr("Grid"), this ); + viewGridAction->setCheckable( true ); + viewGridAction->setStatusTip( tr("Change visibility of the grid in current window") ); + connect( viewGridAction, SIGNAL(toggled(bool)), this, SLOT(viewGrid(bool)) ); + + viewMarkupAction = new QAction( tr("Markup"), this ); + viewMarkupAction->setCheckable( true ); + viewMarkupAction->setStatusTip( tr("Change visibility of markup lines in current window") ); + connect( viewMarkupAction, SIGNAL(toggled(bool)), this, SLOT(viewMarkup(bool)) ); + + viewZoomInAction = new QAction( tr("Zoom &In"), this ); + viewZoomInAction->setIcon( QIcon::fromTheme( "zoom-in", Icons::ZoomIn() ) ); + viewZoomInAction->setShortcut( QKeySequence::ZoomIn ); + viewZoomInAction->setStatusTip( tr("Increase magnification") ); + connect( viewZoomInAction, SIGNAL(triggered()), this, SLOT(viewZoomIn()) ); + + viewZoomOutAction = new QAction( tr("Zoom &Out"), this ); + viewZoomOutAction->setIcon( QIcon::fromTheme( "zoom-out", Icons::ZoomOut() ) ); + viewZoomOutAction->setShortcut( QKeySequence::ZoomOut ); + viewZoomOutAction->setStatusTip( tr("Decrease magnification") ); + connect( viewZoomOutAction, SIGNAL(triggered()), this, SLOT(viewZoomOut()) ); + + viewZoom1To1Action = new QAction( tr("Zoom &1 to 1"), this ); + viewZoom1To1Action->setIcon( QIcon::fromTheme( "zoom-original", Icons::ZoomOriginal() ) ); + viewZoom1To1Action->setStatusTip( tr("Restore scale to 100%") ); + connect( viewZoom1To1Action, SIGNAL(triggered()), this, SLOT(viewZoom1To1()) ); + + viewZoomToFitAction = new QAction( tr("Zoom to &Fit"), this ); + viewZoomToFitAction->setIcon( QIcon::fromTheme( "zoom-fit-best", Icons::ZoomBestFit() ) ); + viewZoomToFitAction->setStatusTip( tr("Set scale to fit window") ); + connect( viewZoomToFitAction, SIGNAL(triggered()), this, SLOT(viewZoomToFit()) ); + + + /* Object actions */ + objectsArrowModeAction = new QAction( tr("Select Mode"), this ); + objectsArrowModeAction->setIcon( Icons::Arrow() ); + objectsArrowModeAction->setStatusTip( tr("Select, move and modify objects") ); + connect( objectsArrowModeAction, SIGNAL(triggered()), this, SLOT(objectsArrowMode()) ); + + objectsCreateTextAction = new QAction( tr("Text"), this ); + objectsCreateTextAction->setIcon( Icons::Text() ); + objectsCreateTextAction->setStatusTip( tr("Create text object") ); + connect( objectsCreateTextAction, SIGNAL(triggered()), this, SLOT(objectsCreateText()) ); + + objectsCreateBoxAction = new QAction( tr("Box"), this ); + objectsCreateBoxAction->setIcon( Icons::Box() ); + objectsCreateBoxAction->setStatusTip( tr("Create box object") ); + connect( objectsCreateBoxAction, SIGNAL(triggered()), this, SLOT(objectsCreateBox()) ); + + objectsCreateLineAction = new QAction( tr("Line"), this ); + objectsCreateLineAction->setIcon( Icons::Line() ); + objectsCreateLineAction->setStatusTip( tr("Create line object") ); + connect( objectsCreateLineAction, SIGNAL(triggered()), this, SLOT(objectsCreateLine()) ); + + objectsCreateEllipseAction = new QAction( tr("Ellipse"), this ); + objectsCreateEllipseAction->setIcon( Icons::Ellipse() ); + objectsCreateEllipseAction->setStatusTip( tr("Create ellipse/circle object") ); + connect( objectsCreateEllipseAction, SIGNAL(triggered()), this, SLOT(objectsCreateEllipse()) ); + + objectsCreateImageAction = new QAction( tr("Image"), this ); + objectsCreateImageAction->setIcon( Icons::Image() ); + objectsCreateImageAction->setStatusTip( tr("Create image object") ); + connect( objectsCreateImageAction, SIGNAL(triggered()), this, SLOT(objectsCreateImage()) ); + + objectsCreateBarcodeAction = new QAction( tr("Barcode"), this ); + objectsCreateBarcodeAction->setIcon( Icons::Barcode() ); + objectsCreateBarcodeAction->setStatusTip( tr("Create barcode object") ); + connect( objectsCreateBarcodeAction, SIGNAL(triggered()), this, SLOT(objectsCreateBarcode()) ); + + objectsOrderRaiseAction = new QAction( tr("Bring To Front"), this ); + objectsOrderRaiseAction->setIcon( Icons::OrderTop() ); + objectsOrderRaiseAction->setStatusTip( tr("Raise selection to top") ); + connect( objectsOrderRaiseAction, SIGNAL(triggered()), this, SLOT(objectsOrderRaise()) ); + + objectsOrderLowerAction = new QAction( tr("Send To Back"), this ); + objectsOrderLowerAction->setIcon( Icons::OrderBottom() ); + objectsOrderLowerAction->setStatusTip( tr("Lower selection to bottom") ); + connect( objectsOrderLowerAction, SIGNAL(triggered()), this, SLOT(objectsOrderLower()) ); + + objectsXformRotateLeftAction = new QAction( tr("Rotate Left"), this ); + objectsXformRotateLeftAction->setIcon( Icons::RotateLeft() ); + objectsXformRotateLeftAction->setStatusTip( tr("Rotate object(s) 90 degrees counter-clockwise") ); + connect( objectsXformRotateLeftAction, SIGNAL(triggered()), this, SLOT(objectsXformRotateLeft()) ); + + objectsXformRotateRightAction = new QAction( tr("Rotate Right"), this ); + objectsXformRotateRightAction->setIcon( Icons::RotateRight() ); + objectsXformRotateRightAction->setStatusTip( tr("Rotate object(s) 90 degrees clockwise") ); + connect( objectsXformRotateRightAction, SIGNAL(triggered()), this, SLOT(objectsXformRotateRight()) ); + + objectsXformFlipHorizAction = new QAction( tr("Flip Horizontally"), this ); + objectsXformFlipHorizAction->setIcon( Icons::FlipHoriz() ); + objectsXformFlipHorizAction->setStatusTip( tr("Flip object(s) horizontally") ); + connect( objectsXformFlipHorizAction, SIGNAL(triggered()), this, SLOT(objectsXformFlipHoriz()) ); + + objectsXformFlipVertAction = new QAction( tr("Flip Vertically"), this ); + objectsXformFlipVertAction->setIcon( Icons::FlipVert() ); + objectsXformFlipVertAction->setStatusTip( tr("Flip object(s) vertically") ); + connect( objectsXformFlipVertAction, SIGNAL(triggered()), this, SLOT(objectsXformFlipVert()) ); + + objectsAlignLeftAction = new QAction( tr("Align Left"), this ); + objectsAlignLeftAction->setIcon( Icons::AlignLeft() ); + objectsAlignLeftAction->setStatusTip( tr("Align objects to left edges") ); + connect( objectsAlignLeftAction, SIGNAL(triggered()), this, SLOT(objectsAlignLeft()) ); + + objectsAlignHCenterAction = new QAction( tr("Align Center"), this ); + objectsAlignHCenterAction->setIcon( Icons::AlignHCenter() ); + objectsAlignHCenterAction->setStatusTip( tr("Align objects to horizontal centers") ); + connect( objectsAlignHCenterAction, SIGNAL(triggered()), this, SLOT(objectsAlignHCenter()) ); + + objectsAlignRightAction = new QAction( tr("Align Right"), this ); + objectsAlignRightAction->setIcon( Icons::AlignRight() ); + objectsAlignRightAction->setStatusTip( tr("Align objects to right edges") ); + connect( objectsAlignRightAction, SIGNAL(triggered()), this, SLOT(objectsAlignRight()) ); + + objectsAlignTopAction = new QAction( tr("Align Top"), this ); + objectsAlignTopAction->setIcon( Icons::AlignTop() ); + objectsAlignTopAction->setStatusTip( tr("Align objects to top edges") ); + connect( objectsAlignTopAction, SIGNAL(triggered()), this, SLOT(objectsAlignTop()) ); + + objectsAlignVCenterAction = new QAction( tr("Align Middle"), this ); + objectsAlignVCenterAction->setIcon( Icons::AlignVCenter() ); + objectsAlignVCenterAction->setStatusTip( tr("Align objects to vertical centers") ); + connect( objectsAlignVCenterAction, SIGNAL(triggered()), this, SLOT(objectsAlignVCenter()) ); + + objectsAlignBottomAction = new QAction( tr("Align Bottom"), this ); + objectsAlignBottomAction->setIcon( Icons::AlignBottom() ); + objectsAlignBottomAction->setStatusTip( tr("Align objects to bottom edges") ); + connect( objectsAlignBottomAction, SIGNAL(triggered()), this, SLOT(objectsAlignBottom()) ); + + objectsCenterHorizAction = new QAction( tr("Center Horizontally"), this ); + objectsCenterHorizAction->setIcon( Icons::CenterHoriz() ); + objectsCenterHorizAction->setStatusTip( tr("Horizontally center objects in label") ); + connect( objectsCenterHorizAction, SIGNAL(triggered()), this, SLOT(objectsCenterHoriz()) ); + + objectsCenterVertAction = new QAction( tr("Center Vertically"), this ); + objectsCenterVertAction->setIcon( Icons::CenterVert() ); + objectsCenterVertAction->setStatusTip( tr("Vertically center objects in label") ); + connect( objectsCenterVertAction, SIGNAL(triggered()), this, SLOT(objectsCenterVert()) ); + + + /* Help actions */ + helpContentsAction = new QAction( tr("&Contents..."), this ); + helpContentsAction->setIcon( QIcon::fromTheme( "help-contents" ) ); + helpContentsAction->setShortcut( QKeySequence::HelpContents ); + helpContentsAction->setStatusTip( tr("Open gLabels manual") ); + connect( helpContentsAction, SIGNAL(triggered()), this, SLOT(helpContents()) ); + + helpAboutAction = new QAction( tr("&About..."), this ); + helpAboutAction->setIcon( QIcon::fromTheme( "help-about" ) ); + helpAboutAction->setStatusTip( tr("About gLabels") ); + connect( helpAboutAction, SIGNAL(triggered()), this, SLOT(helpAbout()) ); + + + /* Context menu version of edit actions */ + contextCutAction = new QAction( tr("Cut"), this ); + contextCutAction->setIcon( QIcon::fromTheme( "edit-cut", Icons::EditCut() ) ); + contextCutAction->setStatusTip( tr("Cut the selection") ); + connect( contextCutAction, SIGNAL(triggered()), this, SLOT(editCut()) ); + + contextCopyAction = new QAction( tr("&Copy"), this ); + contextCopyAction->setIcon( QIcon::fromTheme( "edit-copy", Icons::EditCopy() ) ); + contextCopyAction->setStatusTip( tr("Copy the selection") ); + connect( contextCopyAction, SIGNAL(triggered()), this, SLOT(editCopy()) ); + + contextPasteAction = new QAction( tr("&Paste"), this ); + contextPasteAction->setIcon( QIcon::fromTheme( "edit-paste", Icons::EditPaste() ) ); + contextPasteAction->setStatusTip( tr("Paste the clipboard") ); + connect( contextPasteAction, SIGNAL(triggered()), this, SLOT(editPaste()) ); + + contextDeleteAction = new QAction( tr("&Delete"), this ); + contextDeleteAction->setIcon( QIcon::fromTheme( "edit-delete" ) ); + contextDeleteAction->setStatusTip( tr("Delete the selected objects") ); + connect( contextDeleteAction, SIGNAL(triggered()), this, SLOT(editDelete()) ); + } + + + /// + /// Create Menus + /// + void MainWindow::createMenus() + { + fileMenu = menuBar()->addMenu( tr("&File") ); + fileMenu->addAction( fileNewAction ); + fileMenu->addAction( fileOpenAction ); + fileMenu->addAction( fileSaveAction ); + fileMenu->addAction( fileSaveAsAction ); + fileMenu->addSeparator(); + fileMenu->addAction( fileTemplateDesignerAction ); + fileMenu->addSeparator(); + fileMenu->addAction( fileCloseAction ); + fileMenu->addAction( fileExitAction ); + + editMenu = menuBar()->addMenu( tr("&Edit") ); + editMenu->addAction( editUndoAction ); + editMenu->addAction( editRedoAction ); + editMenu->addSeparator(); + editMenu->addAction( editCutAction ); + editMenu->addAction( editCopyAction ); + editMenu->addAction( editPasteAction ); + editMenu->addAction( editDeleteAction ); + editMenu->addSeparator(); + editMenu->addAction( editSelectAllAction ); + editMenu->addAction( editUnSelectAllAction ); + editMenu->addSeparator(); + editMenu->addAction( editPreferencesAction ); + + viewMenu = menuBar()->addMenu( tr("&View") ); + viewToolBarsMenu = viewMenu->addMenu( tr("Toolbars") ); + viewToolBarsMenu->addAction( viewFileToolBarAction ); + viewToolBarsMenu->addAction( viewEditorToolBarAction ); + viewMenu->addSeparator(); + viewMenu->addAction( viewGridAction ); + viewMenu->addAction( viewMarkupAction ); + viewMenu->addSeparator(); + viewMenu->addAction( viewZoomInAction ); + viewMenu->addAction( viewZoomOutAction ); + viewMenu->addAction( viewZoom1To1Action ); + viewMenu->addAction( viewZoomToFitAction ); + + objectsMenu = menuBar()->addMenu( tr("&Objects") ); + objectsMenu->addAction( objectsArrowModeAction ); + objectsCreateMenu = objectsMenu->addMenu( tr("&Create") ); + objectsCreateMenu->addAction( objectsCreateTextAction ); + objectsCreateMenu->addAction( objectsCreateBoxAction ); + objectsCreateMenu->addAction( objectsCreateLineAction ); + objectsCreateMenu->addAction( objectsCreateEllipseAction ); + objectsCreateMenu->addAction( objectsCreateImageAction ); + objectsCreateMenu->addAction( objectsCreateBarcodeAction ); + objectsMenu->addSeparator(); + objectsOrderMenu = objectsMenu->addMenu( tr("&Order") ); + objectsOrderMenu->addAction( objectsOrderRaiseAction ); + objectsOrderMenu->addAction( objectsOrderLowerAction ); + objectsXformMenu = objectsMenu->addMenu( tr("&Rotate/Flip") ); + objectsXformMenu->addAction( objectsXformRotateLeftAction ); + objectsXformMenu->addAction( objectsXformRotateRightAction ); + objectsXformMenu->addAction( objectsXformFlipHorizAction ); + objectsXformMenu->addAction( objectsXformFlipVertAction ); + objectsAlignMenu = objectsMenu->addMenu( tr("&Alignment") ); + objectsAlignMenu->addAction( objectsAlignLeftAction ); + objectsAlignMenu->addAction( objectsAlignHCenterAction ); + objectsAlignMenu->addAction( objectsAlignRightAction ); + objectsAlignMenu->addSeparator(); + objectsAlignMenu->addAction( objectsAlignTopAction ); + objectsAlignMenu->addAction( objectsAlignVCenterAction ); + objectsAlignMenu->addAction( objectsAlignBottomAction ); + objectsCenterMenu = objectsMenu->addMenu( tr("Center") ); + objectsCenterMenu->addAction( objectsCenterHorizAction ); + objectsCenterMenu->addAction( objectsCenterVertAction ); + + helpMenu = menuBar()->addMenu( tr("&Help") ); + helpMenu->addAction( helpContentsAction ); + helpMenu->addAction( helpAboutAction ); + + contextMenu = new QMenu(); + contextOrderMenu = contextMenu->addMenu( tr("&Order") ); + contextOrderMenu->addAction( objectsOrderRaiseAction ); + contextOrderMenu->addAction( objectsOrderLowerAction ); + contextXformMenu = contextMenu->addMenu( tr("&Rotate/Flip") ); + contextXformMenu->addAction( objectsXformRotateLeftAction ); + contextXformMenu->addAction( objectsXformRotateRightAction ); + contextXformMenu->addAction( objectsXformFlipHorizAction ); + contextXformMenu->addAction( objectsXformFlipVertAction ); + contextAlignMenu = contextMenu->addMenu( tr("&Alignment") ); + contextAlignMenu->addAction( objectsAlignLeftAction ); + contextAlignMenu->addAction( objectsAlignHCenterAction ); + contextAlignMenu->addAction( objectsAlignRightAction ); + contextAlignMenu->addSeparator(); + contextAlignMenu->addAction( objectsAlignTopAction ); + contextAlignMenu->addAction( objectsAlignVCenterAction ); + contextAlignMenu->addAction( objectsAlignBottomAction ); + contextCenterMenu = contextMenu->addMenu( tr("Center") ); + contextCenterMenu->addAction( objectsCenterHorizAction ); + contextCenterMenu->addAction( objectsCenterVertAction ); + contextMenu->addSeparator(); + contextMenu->addAction( contextCutAction ); + contextMenu->addAction( contextCopyAction ); + contextMenu->addAction( contextPasteAction ); + contextMenu->addAction( contextDeleteAction ); + + noSelectionContextMenu = new QMenu(); + noSelectionContextMenu->addAction( contextPasteAction ); + } + + + /// + /// Create Tool Bars + /// + void MainWindow::createToolBars() + { + fileToolBar = addToolBar( tr("&File") ); + fileToolBar->addAction( fileNewAction ); + fileToolBar->addAction( fileOpenAction ); + fileToolBar->addAction( fileSaveAction ); + + zoomInfoLabel = new QLabel( " 999% " ); + zoomInfoLabel->setAlignment( Qt::AlignHCenter|Qt::AlignVCenter ); + zoomInfoLabel->setMinimumSize( zoomInfoLabel->sizeHint() ); + + editorToolBar = new QToolBar( tr("&Editor") ); + editorToolBar->addAction( objectsArrowModeAction ); + editorToolBar->addSeparator(); + editorToolBar->addAction( objectsCreateTextAction ); + editorToolBar->addAction( objectsCreateBoxAction ); + editorToolBar->addAction( objectsCreateLineAction ); + editorToolBar->addAction( objectsCreateEllipseAction ); + editorToolBar->addAction( objectsCreateImageAction ); + editorToolBar->addAction( objectsCreateBarcodeAction ); + editorToolBar->addSeparator(); + editorToolBar->addAction( editCutAction ); + editorToolBar->addAction( editCopyAction ); + editorToolBar->addAction( editPasteAction ); + editorToolBar->addSeparator(); + editorToolBar->addAction( viewZoomInAction ); + editorToolBar->addAction( viewZoomOutAction ); + editorToolBar->addAction( viewZoom1To1Action ); + editorToolBar->addAction( viewZoomToFitAction ); + editorToolBar->addWidget( zoomInfoLabel ); + editorToolBar->addSeparator(); + } + + + /// + /// Create Status Bar + /// + void MainWindow::createStatusBar() + { + statusBar(); + } + + + /// + /// Create Welcome Page + /// + QWidget* MainWindow::createWelcomePage() + { + mWelcomeView = new StartupView( this ); + + return mWelcomeView; + } + + + /// + /// Create Properties Page + /// + QWidget* MainWindow::createPropertiesPage() + { + mPropertiesView = new PropertiesView(); + + return mPropertiesView; + } + + + /// + /// Create Editor Page + /// + QWidget* MainWindow::createEditorPage() + { + QWidget* page = new QWidget; + + mLabelEditorScrollArea = new QScrollArea(); + mLabelEditorScrollArea->setMinimumSize( 640, 450 ); + mLabelEditorScrollArea->setWidgetResizable( true ); + + mLabelEditor = new LabelEditor( mLabelEditorScrollArea ); + mObjectEditor = new ObjectEditor(); + + mLabelEditorScrollArea->setWidget( mLabelEditor ); + + QVBoxLayout* editorVLayout = new QVBoxLayout; + editorVLayout->setContentsMargins( 0, 0, 0, 0 ); + editorVLayout->addWidget( editorToolBar ); + editorVLayout->addWidget( mLabelEditorScrollArea ); + + QHBoxLayout* editorHLayout = new QHBoxLayout; + editorHLayout->setContentsMargins( 0, 0, 0, 0 ); + editorHLayout->addLayout( editorVLayout ); + editorHLayout->addWidget( mObjectEditor ); + + page->setLayout( editorHLayout ); + + return page; + } + + + /// + /// Create Merge Page + /// + QWidget* MainWindow::createMergePage() + { + mMergeView = new MergeView(); + + return mMergeView; + } + + + /// + /// Create Print Page + /// + QWidget* MainWindow::createPrintPage() + { + mPrintView = new PrintView(); + + return mPrintView; + } + + + /// + /// Set enabled state of TOC buttons based on Welcome mode + /// + void MainWindow::setWelcomeMode( bool enabled ) + { + mWelcomeButton->setHidden( !enabled ); + mPropertiesButton->setHidden( enabled ); + mEditorButton->setHidden( enabled ); + mMergeButton->setHidden( enabled ); + mPrintButton->setHidden( enabled ); + } + + + /// + /// Set enabled state of actions associated with a document. + /// + void MainWindow::setDocVerbsEnabled( bool enabled ) + { + fileSaveAction->setEnabled( mModel && mModel->isModified() ); + fileSaveAsAction->setEnabled( mModel ); + editUndoAction->setEnabled( enabled && mUndoRedoModel->canUndo() ); + editRedoAction->setEnabled( enabled && mUndoRedoModel->canRedo() ); + editDeleteAction->setEnabled( enabled ); + editSelectAllAction->setEnabled( enabled ); + editUnSelectAllAction->setEnabled( enabled ); + viewZoomInAction->setEnabled( enabled ); + viewZoomOutAction->setEnabled( enabled ); + viewZoom1To1Action->setEnabled( enabled ); + viewZoomToFitAction->setEnabled( enabled ); + viewGridAction->setEnabled( enabled ); + viewMarkupAction->setEnabled( enabled ); + objectsArrowModeAction->setEnabled( enabled ); + objectsCreateMenu->setEnabled( enabled ); + objectsCreateTextAction->setEnabled( enabled ); + objectsCreateLineAction->setEnabled( enabled ); + objectsCreateBoxAction->setEnabled( enabled ); + objectsCreateEllipseAction->setEnabled( enabled ); + objectsCreateImageAction->setEnabled( enabled ); + objectsCreateBarcodeAction->setEnabled( enabled ); + objectsOrderMenu->setEnabled( enabled ); + objectsOrderRaiseAction->setEnabled( enabled ); + objectsOrderLowerAction->setEnabled( enabled ); + objectsXformMenu->setEnabled( enabled ); + objectsXformRotateLeftAction->setEnabled( enabled ); + objectsXformRotateRightAction->setEnabled( enabled ); + objectsXformFlipHorizAction->setEnabled( enabled ); + objectsXformFlipVertAction->setEnabled( enabled ); + objectsAlignMenu->setEnabled( enabled ); + objectsAlignLeftAction->setEnabled( enabled ); + objectsAlignRightAction->setEnabled( enabled ); + objectsAlignHCenterAction->setEnabled( enabled ); + objectsAlignTopAction->setEnabled( enabled ); + objectsAlignBottomAction->setEnabled( enabled ); + objectsAlignVCenterAction->setEnabled( enabled ); + objectsCenterMenu->setEnabled( enabled ); + objectsCenterHorizAction->setEnabled( enabled ); + objectsCenterVertAction->setEnabled( enabled ); + } + + + /// + /// Set enabled state of actions associated with a document being modified since last save. + /// + void MainWindow::setDocModifiedVerbsEnabled( bool enabled ) + { + fileSaveAction->setEnabled( enabled ); + } + + + /// + /// Set enabled state of actions associated with data being available on clipboard. + /// + void MainWindow::setPasteVerbsEnabled( bool enabled ) + { + editPasteAction->setEnabled( enabled ); + contextPasteAction->setEnabled( enabled ); + } + + + /// + /// Set enabled state of actions associated with a non-empty selection. + /// + void MainWindow::setSelectionVerbsEnabled( bool enabled ) + { + editCutAction->setEnabled( enabled ); + editCopyAction->setEnabled( enabled ); + editDeleteAction->setEnabled( enabled ); + editUnSelectAllAction->setEnabled( enabled ); + objectsOrderMenu->setEnabled( enabled ); + objectsOrderRaiseAction->setEnabled( enabled ); + objectsOrderLowerAction->setEnabled( enabled ); + objectsXformMenu->setEnabled( enabled ); + objectsXformRotateLeftAction->setEnabled( enabled ); + objectsXformRotateRightAction->setEnabled( enabled ); + objectsXformFlipHorizAction->setEnabled( enabled ); + objectsXformFlipVertAction->setEnabled( enabled ); + objectsCenterMenu->setEnabled( enabled ); + objectsCenterHorizAction->setEnabled( enabled ); + objectsCenterVertAction->setEnabled( enabled ); + } + + + /// + /// Set enabled state of actions associated with a non-atomic selection. + /// + void MainWindow::setMultiSelectionVerbsEnabled( bool enabled ) + { + objectsAlignMenu->setEnabled( enabled ); + objectsAlignLeftAction->setEnabled( enabled ); + objectsAlignRightAction->setEnabled( enabled ); + objectsAlignHCenterAction->setEnabled( enabled ); + objectsAlignTopAction->setEnabled( enabled ); + objectsAlignBottomAction->setEnabled( enabled ); + objectsAlignVCenterAction->setEnabled( enabled ); + } + + + /// + /// Set window title + /// + void MainWindow::setTitle() + { + if ( mModel == 0 ) { - QString msg = tr("Save changes to project \"%1\" before closing?").arg( mModel->shortName() ); - QString info = tr("Your changes will be lost if you don't save them."); - - int ret = QMessageBox::warning( this, - tr( "Save project?" ), - "" + msg + "

" + info + "

", - (QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel), - QMessageBox::Save ); - - switch (ret) { - case QMessageBox::Save: - // Save was clicked - ok = File::save( this ); - break; - case QMessageBox::Discard: - // Don't Save was clicked - ok = true; - break; - case QMessageBox::Cancel: - // Cancel was clicked - ok = false; - break; - default: - // should never be reached - ok = false; - break; + setWindowTitle( "gLabels" ); + } + else + { + if ( mModel->isModified() ) + { + setWindowTitle( "gLabels - " + mModel->shortName() + " " + tr("(modified)") ); + } + else + { + setWindowTitle( "gLabels - " + mModel->shortName() ); } } - } - - return ok; -} + } -/// -/// Change page -/// -void MainWindow::changePage(QListWidgetItem *current, QListWidgetItem *previous) -{ - if (!current) - { - current = previous; - } + /// + /// Read MainWindow Settings + /// + void MainWindow::readSettings() + { + QSettings settings; - int row = mContents->row(current); + settings.beginGroup( "MainWindow" ); + bool showFileToolBar = settings.value( "showFileToolBar", true ).toBool(); + bool showEditorToolBar = settings.value( "showEditToolBar", true ).toBool(); + bool showGrid = settings.value( "showGrid", true ).toBool(); + bool showMarkup = settings.value( "showMarkup", true ).toBool(); + settings.endGroup(); + + viewFileToolBarAction ->setChecked( showFileToolBar ); + viewEditorToolBarAction ->setChecked( showEditorToolBar ); + viewGridAction ->setChecked( showGrid ); + viewMarkupAction ->setChecked( showMarkup ); + + fileToolBar ->setVisible( showFileToolBar ); + editorToolBar ->setVisible( showEditorToolBar ); + mLabelEditor ->setGridVisible( showGrid ); + mLabelEditor ->setMarkupVisible( showMarkup ); + } + + + /// + /// Write MainWindow Settings + /// + void MainWindow::writeSettings() + { + QSettings settings; + + settings.beginGroup( "MainWindow" ); + settings.setValue( "showFileToolBar", viewFileToolBarAction->isChecked() ); + settings.setValue( "showEditorToolBar", viewEditorToolBarAction->isChecked() ); + settings.setValue( "showGrid", viewGridAction->isChecked() ); + settings.setValue( "showMarkup", viewMarkupAction->isChecked() ); + settings.endGroup(); + } + + + /// + /// Is it ok to close window? + /// + bool MainWindow::isOkToClose() + { + bool ok = true; + + if ( !this->isEmpty() ) + { + if ( mModel->isModified() ) + { + QString msg = tr("Save changes to project \"%1\" before closing?").arg( mModel->shortName() ); + QString info = tr("Your changes will be lost if you don't save them."); + + int ret = QMessageBox::warning( this, + tr( "Save project?" ), + "" + msg + "

" + info + "

", + (QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel), + QMessageBox::Save ); + + switch (ret) { + case QMessageBox::Save: + // Save was clicked + ok = File::save( this ); + break; + case QMessageBox::Discard: + // Don't Save was clicked + ok = true; + break; + case QMessageBox::Cancel: + // Cancel was clicked + ok = false; + break; + default: + // should never be reached + ok = false; + break; + } + } + } + + return ok; + } + + + /// + /// Change page + /// + void MainWindow::changePage(QListWidgetItem *current, QListWidgetItem *previous) + { + if (!current) + { + current = previous; + } + + int row = mContents->row(current); - mPages->setCurrentIndex(row); - bool isEditorPage = ( row == mContents->row(mEditorButton) ); + mPages->setCurrentIndex(row); + bool isEditorPage = ( row == mContents->row(mEditorButton) ); - setDocVerbsEnabled( isEditorPage ); - setSelectionVerbsEnabled( isEditorPage && !mModel->isSelectionEmpty() ); - setMultiSelectionVerbsEnabled( isEditorPage && !mModel->isSelectionAtomic() ); - setPasteVerbsEnabled( isEditorPage && mModel->canPaste() ); -} - - -/// -/// Clipboard contents changed -/// -void MainWindow::clipboardChanged() -{ - setPasteVerbsEnabled( mModel->canPaste() ); -} - - -/// -/// File->New Action -/// -void MainWindow::fileNew() -{ - File::newLabel( this ); -} - - -/// -/// File->Open Action -/// -void MainWindow::fileOpen() -{ - File::open( this ); -} - - -/// -/// File->Save Action -/// -void MainWindow::fileSave() -{ - File::save( this ); -} - - -/// -/// File->Save As Action -/// -void MainWindow::fileSaveAs() -{ - File::saveAs( this ); -} - - -/// -/// File->Template Designer Action -/// -void MainWindow::fileTemplateDesigner() -{ - qDebug() << "ACTION: file->Template Designer"; -} - - -/// -/// File->Close Action -/// -void MainWindow::fileClose() -{ - File::close( this ); -} - - -/// -/// File->Exit Action -/// -void MainWindow::fileExit() -{ - File::exit(); -} - - -/// -/// Edit->Undo Action -/// -void MainWindow::editUndo() -{ - mUndoRedoModel->undo(); -} - - -/// -/// Edit->Redo Action -/// -void MainWindow::editRedo() -{ - mUndoRedoModel->redo(); -} - - -/// -/// Edit->Cut Action -/// -void MainWindow::editCut() -{ - mUndoRedoModel->checkpoint( tr("Cut") ); - mModel->cutSelection(); -} - - -/// -/// Edit->Copy Action -/// -void MainWindow::editCopy() -{ - // Non-destructive -- do not checkpoint. - mModel->copySelection(); -} - - -/// -/// Edit->Paste Action -/// -void MainWindow::editPaste() -{ - mUndoRedoModel->checkpoint( tr("Paste") ); - mModel->paste(); -} - - -/// -/// Edit->Delete Action -/// -void MainWindow::editDelete() -{ - mUndoRedoModel->checkpoint( tr("Delete") ); - mModel->deleteSelection(); -} - - -/// -/// Edit->Select All Action -/// -void MainWindow::editSelectAll() -{ - mModel->selectAll(); -} - - -/// -/// Edit->Unselect All Action -/// -void MainWindow::editUnSelectAll() -{ - mModel->unselectAll(); -} - - -/// -/// Edit->Preferences Action -/// -void MainWindow::editPreferences() -{ - PreferencesDialog dialog( this ); - dialog.exec(); -} - - -/// -/// View->File Tool Bar Toggle Action -/// -void MainWindow::viewFileToolBar( bool state ) -{ - fileToolBar->setVisible( state ); -} - - -/// -/// View->Objects Tool Bar Toggle Action -/// -void MainWindow::viewEditorToolBar( bool state ) -{ - editorToolBar->setVisible( state ); -} - - -/// -/// View->Grid Toggle Action -/// -void MainWindow::viewGrid( bool state ) -{ - mLabelEditor->setGridVisible( state ); -} - - -/// -/// View->Markup Toggle Action -/// -void MainWindow::viewMarkup( bool state ) -{ - mLabelEditor->setMarkupVisible( state ); -} - - -/// -/// View->Zoom In Action -/// -void MainWindow::viewZoomIn() -{ - mLabelEditor->zoomIn(); -} - - -/// -/// View->Zoom Out Action -/// -void MainWindow::viewZoomOut() -{ - mLabelEditor->zoomOut(); -} - - -/// -/// View->Zoom 1:1 Action -/// -void MainWindow::viewZoom1To1() -{ - mLabelEditor->zoom1To1(); -} - - -/// -/// View->Zoom To Fit Action -/// -void MainWindow::viewZoomToFit() -{ - mLabelEditor->zoomToFit(); -} - - -/// -/// Objects->Arrow Mode Action -/// -void MainWindow::objectsArrowMode() -{ - mLabelEditor->arrowMode(); -} - - -/// -/// Objects->Create Text Mode Action -/// -void MainWindow::objectsCreateText() -{ - mUndoRedoModel->checkpoint( tr("Create Text") ); - mLabelEditor->createTextMode(); -} - - -/// -/// Objects->Create Box Mode Action -/// -void MainWindow::objectsCreateBox() -{ - mUndoRedoModel->checkpoint( tr("Create Box") ); - mLabelEditor->createBoxMode(); -} - - -/// -/// Objects->Create Line Mode Action -/// -void MainWindow::objectsCreateLine() -{ - mUndoRedoModel->checkpoint( tr("Create Line") ); - mLabelEditor->createLineMode(); -} - - -/// -/// Objects->Create Ellipse Mode Action -/// -void MainWindow::objectsCreateEllipse() -{ - mUndoRedoModel->checkpoint( tr("Create Ellipse") ); - mLabelEditor->createEllipseMode(); -} - - -/// -/// Objects->Create Image Mode Action -/// -void MainWindow::objectsCreateImage() -{ - mUndoRedoModel->checkpoint( tr("Create Image") ); - mLabelEditor->createImageMode(); -} - - -/// -/// Objects->Create Barcode Mode Action -/// -void MainWindow::objectsCreateBarcode() -{ - qDebug() << "ACTION: objects->Create->Barcode"; -} - - -/// -/// Objects->Order->Bring To Front Action -/// -void MainWindow::objectsOrderRaise() -{ - mUndoRedoModel->checkpoint( tr("Bring To Front") ); - mModel->raiseSelectionToTop(); -} - - -/// -/// Objects->Order->Send To Back Action -/// -void MainWindow::objectsOrderLower() -{ - mUndoRedoModel->checkpoint( tr("Send To Back") ); - mModel->lowerSelectionToBottom(); -} - - -/// -/// Objects->Rotate/Flip->Rotate Left Action -/// -void MainWindow::objectsXformRotateLeft() -{ - mUndoRedoModel->checkpoint( tr("Rotate Left") ); - mModel->rotateSelectionLeft(); -} - - -/// -/// Objects->Rotate/Flip->Rotate Right Action -/// -void MainWindow::objectsXformRotateRight() -{ - mUndoRedoModel->checkpoint( tr("Rotate Right") ); - mModel->rotateSelectionRight(); -} - - -/// -/// Objects->Rotate/Flip->Flip Horizontally Action -/// -void MainWindow::objectsXformFlipHoriz() -{ - mUndoRedoModel->checkpoint( tr("Flip Horizontally") ); - mModel->flipSelectionHoriz(); -} - - -/// -/// Objects->Rotate/Flip->Flip Vertically Action -/// -void MainWindow::objectsXformFlipVert() -{ - mUndoRedoModel->checkpoint( tr("Flip Vertically") ); - mModel->flipSelectionVert(); -} - - -/// -/// Objects->Align->Left Action -/// -void MainWindow::objectsAlignLeft() -{ - mUndoRedoModel->checkpoint( tr("Align Left") ); - mModel->alignSelectionLeft(); -} - - -/// -/// Objects->Align->Center Horizontally Action -/// -void MainWindow::objectsAlignHCenter() -{ - mUndoRedoModel->checkpoint( tr("Align Center") ); - mModel->alignSelectionHCenter(); -} - - -/// -/// Objects->Align->Right Action -/// -void MainWindow::objectsAlignRight() -{ - mUndoRedoModel->checkpoint( tr("Align Right") ); - mModel->alignSelectionRight(); -} - - -/// -/// Objects->Align->Top Action -/// -void MainWindow::objectsAlignTop() -{ - mUndoRedoModel->checkpoint( tr("Align Top") ); - mModel->alignSelectionTop(); -} - - -/// -/// Objects->Align->Center Vertically Action -/// -void MainWindow::objectsAlignVCenter() -{ - mUndoRedoModel->checkpoint( tr("Align Middle") ); - mModel->alignSelectionVCenter(); -} - - -/// -/// Objects->Align->Bottom Action -/// -void MainWindow::objectsAlignBottom() -{ - mUndoRedoModel->checkpoint( tr("Align Bottom") ); - mModel->alignSelectionBottom(); -} - - -/// -/// Objects->Center->Horizontally Action -/// -void MainWindow::objectsCenterHoriz() -{ - mUndoRedoModel->checkpoint( tr("Center Horizontally") ); - mModel->centerSelectionHoriz(); -} - - -/// -/// Objects->Center->Vertically Action -/// -void MainWindow::objectsCenterVert() -{ - mUndoRedoModel->checkpoint( tr("Center Vertically") ); - mModel->centerSelectionVert(); -} - - -/// -/// Help->Contents Action -/// -void MainWindow::helpContents() -{ - Help::displayContents( this ); -} - - -/// -/// Help->About Action -/// -void MainWindow::helpAbout() -{ - Help::displayAbout( this ); -} - - -/// -/// Context Menu Activation -/// -void MainWindow::onContextMenuActivate() -{ - if ( mModel->isSelectionEmpty() ) - { - noSelectionContextMenu->popup( QCursor::pos() ); + setDocVerbsEnabled( isEditorPage ); + setSelectionVerbsEnabled( isEditorPage && !mModel->isSelectionEmpty() ); + setMultiSelectionVerbsEnabled( isEditorPage && !mModel->isSelectionAtomic() ); + setPasteVerbsEnabled( isEditorPage && mModel->canPaste() ); } - else + + + /// + /// Clipboard contents changed + /// + void MainWindow::clipboardChanged() { - contextMenu->popup( QCursor::pos() ); + setPasteVerbsEnabled( mModel->canPaste() ); } -} - - -/// -/// Zoom changed: update Zoom Information in Status Bar -/// -void MainWindow::onZoomChanged() -{ - zoomInfoLabel->setText( QString( " %1% " ).arg(100*mLabelEditor->zoom(), 0, 'f', 0) ); - - viewZoomInAction->setEnabled( !mLabelEditor->isZoomMax() ); - viewZoomOutAction->setEnabled( !mLabelEditor->isZoomMin() ); -} - - -/// -/// Pointer moved: update Cursor Information in Status Bar -/// -void MainWindow::onPointerMoved( double x, double y ) -{ - /* TODO: convert x,y to locale units and set precision accordingly. */ - cursorInfoLabel->setText( QString( "%1, %2" ).arg(x).arg(y) ); -} - - -/// -/// Pointer exited view: update Zoom Information in Status Bar (Clears information) -/// -void MainWindow::onPointerExit() -{ - cursorInfoLabel->setText( "" ); -} - - -/// -/// Name changed handler -/// -void MainWindow::onNameChanged() -{ - setTitle(); -} - - -/// -/// Modified changed handler -/// -void MainWindow::onModifiedChanged() -{ - setTitle(); - setDocModifiedVerbsEnabled( mModel->isModified() ); -} - - -/// -/// Selection changed handler -/// -void MainWindow::onSelectionChanged() -{ - setSelectionVerbsEnabled( !mModel->isSelectionEmpty() ); - setMultiSelectionVerbsEnabled( !mModel->isSelectionAtomic() ); -} - - -/// -/// Label changed handler -/// -void MainWindow::onLabelChanged() -{ -} - - -/// -/// Undo/Redo changed handler -/// -void MainWindow::onUndoRedoChanged() -{ - editUndoAction->setEnabled( mUndoRedoModel->canUndo() ); - editRedoAction->setEnabled( mUndoRedoModel->canRedo() ); + + + /// + /// File->New Action + /// + void MainWindow::fileNew() + { + File::newLabel( this ); + } + + + /// + /// File->Open Action + /// + void MainWindow::fileOpen() + { + File::open( this ); + } + + + /// + /// File->Save Action + /// + void MainWindow::fileSave() + { + File::save( this ); + } + + + /// + /// File->Save As Action + /// + void MainWindow::fileSaveAs() + { + File::saveAs( this ); + } + + + /// + /// File->Template Designer Action + /// + void MainWindow::fileTemplateDesigner() + { + qDebug() << "ACTION: file->Template Designer"; + } + + + /// + /// File->Close Action + /// + void MainWindow::fileClose() + { + File::close( this ); + } + + + /// + /// File->Exit Action + /// + void MainWindow::fileExit() + { + File::exit(); + } + + + /// + /// Edit->Undo Action + /// + void MainWindow::editUndo() + { + mUndoRedoModel->undo(); + } + + + /// + /// Edit->Redo Action + /// + void MainWindow::editRedo() + { + mUndoRedoModel->redo(); + } + + + /// + /// Edit->Cut Action + /// + void MainWindow::editCut() + { + mUndoRedoModel->checkpoint( tr("Cut") ); + mModel->cutSelection(); + } + + + /// + /// Edit->Copy Action + /// + void MainWindow::editCopy() + { + // Non-destructive -- do not checkpoint. + mModel->copySelection(); + } + + + /// + /// Edit->Paste Action + /// + void MainWindow::editPaste() + { + mUndoRedoModel->checkpoint( tr("Paste") ); + mModel->paste(); + } + + + /// + /// Edit->Delete Action + /// + void MainWindow::editDelete() + { + mUndoRedoModel->checkpoint( tr("Delete") ); + mModel->deleteSelection(); + } + + + /// + /// Edit->Select All Action + /// + void MainWindow::editSelectAll() + { + mModel->selectAll(); + } + + + /// + /// Edit->Unselect All Action + /// + void MainWindow::editUnSelectAll() + { + mModel->unselectAll(); + } + + + /// + /// Edit->Preferences Action + /// + void MainWindow::editPreferences() + { + PreferencesDialog dialog( this ); + dialog.exec(); + } + + + /// + /// View->File Tool Bar Toggle Action + /// + void MainWindow::viewFileToolBar( bool state ) + { + fileToolBar->setVisible( state ); + } + + + /// + /// View->Objects Tool Bar Toggle Action + /// + void MainWindow::viewEditorToolBar( bool state ) + { + editorToolBar->setVisible( state ); + } + + + /// + /// View->Grid Toggle Action + /// + void MainWindow::viewGrid( bool state ) + { + mLabelEditor->setGridVisible( state ); + } + + + /// + /// View->Markup Toggle Action + /// + void MainWindow::viewMarkup( bool state ) + { + mLabelEditor->setMarkupVisible( state ); + } + + + /// + /// View->Zoom In Action + /// + void MainWindow::viewZoomIn() + { + mLabelEditor->zoomIn(); + } + + + /// + /// View->Zoom Out Action + /// + void MainWindow::viewZoomOut() + { + mLabelEditor->zoomOut(); + } + + + /// + /// View->Zoom 1:1 Action + /// + void MainWindow::viewZoom1To1() + { + mLabelEditor->zoom1To1(); + } + + + /// + /// View->Zoom To Fit Action + /// + void MainWindow::viewZoomToFit() + { + mLabelEditor->zoomToFit(); + } + + + /// + /// Objects->Arrow Mode Action + /// + void MainWindow::objectsArrowMode() + { + mLabelEditor->arrowMode(); + } + + + /// + /// Objects->Create Text Mode Action + /// + void MainWindow::objectsCreateText() + { + mUndoRedoModel->checkpoint( tr("Create Text") ); + mLabelEditor->createTextMode(); + } + + + /// + /// Objects->Create Box Mode Action + /// + void MainWindow::objectsCreateBox() + { + mUndoRedoModel->checkpoint( tr("Create Box") ); + mLabelEditor->createBoxMode(); + } + + + /// + /// Objects->Create Line Mode Action + /// + void MainWindow::objectsCreateLine() + { + mUndoRedoModel->checkpoint( tr("Create Line") ); + mLabelEditor->createLineMode(); + } + + + /// + /// Objects->Create Ellipse Mode Action + /// + void MainWindow::objectsCreateEllipse() + { + mUndoRedoModel->checkpoint( tr("Create Ellipse") ); + mLabelEditor->createEllipseMode(); + } + + + /// + /// Objects->Create Image Mode Action + /// + void MainWindow::objectsCreateImage() + { + mUndoRedoModel->checkpoint( tr("Create Image") ); + mLabelEditor->createImageMode(); + } + + + /// + /// Objects->Create Barcode Mode Action + /// + void MainWindow::objectsCreateBarcode() + { + qDebug() << "ACTION: objects->Create->Barcode"; + } + + + /// + /// Objects->Order->Bring To Front Action + /// + void MainWindow::objectsOrderRaise() + { + mUndoRedoModel->checkpoint( tr("Bring To Front") ); + mModel->raiseSelectionToTop(); + } + + + /// + /// Objects->Order->Send To Back Action + /// + void MainWindow::objectsOrderLower() + { + mUndoRedoModel->checkpoint( tr("Send To Back") ); + mModel->lowerSelectionToBottom(); + } + + + /// + /// Objects->Rotate/Flip->Rotate Left Action + /// + void MainWindow::objectsXformRotateLeft() + { + mUndoRedoModel->checkpoint( tr("Rotate Left") ); + mModel->rotateSelectionLeft(); + } + + + /// + /// Objects->Rotate/Flip->Rotate Right Action + /// + void MainWindow::objectsXformRotateRight() + { + mUndoRedoModel->checkpoint( tr("Rotate Right") ); + mModel->rotateSelectionRight(); + } + + + /// + /// Objects->Rotate/Flip->Flip Horizontally Action + /// + void MainWindow::objectsXformFlipHoriz() + { + mUndoRedoModel->checkpoint( tr("Flip Horizontally") ); + mModel->flipSelectionHoriz(); + } + + + /// + /// Objects->Rotate/Flip->Flip Vertically Action + /// + void MainWindow::objectsXformFlipVert() + { + mUndoRedoModel->checkpoint( tr("Flip Vertically") ); + mModel->flipSelectionVert(); + } + + + /// + /// Objects->Align->Left Action + /// + void MainWindow::objectsAlignLeft() + { + mUndoRedoModel->checkpoint( tr("Align Left") ); + mModel->alignSelectionLeft(); + } + + + /// + /// Objects->Align->Center Horizontally Action + /// + void MainWindow::objectsAlignHCenter() + { + mUndoRedoModel->checkpoint( tr("Align Center") ); + mModel->alignSelectionHCenter(); + } + + + /// + /// Objects->Align->Right Action + /// + void MainWindow::objectsAlignRight() + { + mUndoRedoModel->checkpoint( tr("Align Right") ); + mModel->alignSelectionRight(); + } + + + /// + /// Objects->Align->Top Action + /// + void MainWindow::objectsAlignTop() + { + mUndoRedoModel->checkpoint( tr("Align Top") ); + mModel->alignSelectionTop(); + } + + + /// + /// Objects->Align->Center Vertically Action + /// + void MainWindow::objectsAlignVCenter() + { + mUndoRedoModel->checkpoint( tr("Align Middle") ); + mModel->alignSelectionVCenter(); + } + + + /// + /// Objects->Align->Bottom Action + /// + void MainWindow::objectsAlignBottom() + { + mUndoRedoModel->checkpoint( tr("Align Bottom") ); + mModel->alignSelectionBottom(); + } + + + /// + /// Objects->Center->Horizontally Action + /// + void MainWindow::objectsCenterHoriz() + { + mUndoRedoModel->checkpoint( tr("Center Horizontally") ); + mModel->centerSelectionHoriz(); + } + + + /// + /// Objects->Center->Vertically Action + /// + void MainWindow::objectsCenterVert() + { + mUndoRedoModel->checkpoint( tr("Center Vertically") ); + mModel->centerSelectionVert(); + } + + + /// + /// Help->Contents Action + /// + void MainWindow::helpContents() + { + Help::displayContents( this ); + } + + + /// + /// Help->About Action + /// + void MainWindow::helpAbout() + { + Help::displayAbout( this ); + } + + + /// + /// Context Menu Activation + /// + void MainWindow::onContextMenuActivate() + { + if ( mModel->isSelectionEmpty() ) + { + noSelectionContextMenu->popup( QCursor::pos() ); + } + else + { + contextMenu->popup( QCursor::pos() ); + } + } + + + /// + /// Zoom changed: update Zoom Information in Status Bar + /// + void MainWindow::onZoomChanged() + { + zoomInfoLabel->setText( QString( " %1% " ).arg(100*mLabelEditor->zoom(), 0, 'f', 0) ); + + viewZoomInAction->setEnabled( !mLabelEditor->isZoomMax() ); + viewZoomOutAction->setEnabled( !mLabelEditor->isZoomMin() ); + } + + + /// + /// Pointer moved: update Cursor Information in Status Bar + /// + void MainWindow::onPointerMoved( double x, double y ) + { + /* TODO: convert x,y to locale units and set precision accordingly. */ + cursorInfoLabel->setText( QString( "%1, %2" ).arg(x).arg(y) ); + } + + + /// + /// Pointer exited view: update Zoom Information in Status Bar (Clears information) + /// + void MainWindow::onPointerExit() + { + cursorInfoLabel->setText( "" ); + } + + + /// + /// Name changed handler + /// + void MainWindow::onNameChanged() + { + setTitle(); + } + + + /// + /// Modified changed handler + /// + void MainWindow::onModifiedChanged() + { + setTitle(); + setDocModifiedVerbsEnabled( mModel->isModified() ); + } + + + /// + /// Selection changed handler + /// + void MainWindow::onSelectionChanged() + { + setSelectionVerbsEnabled( !mModel->isSelectionEmpty() ); + setMultiSelectionVerbsEnabled( !mModel->isSelectionAtomic() ); + } + + + /// + /// Label changed handler + /// + void MainWindow::onLabelChanged() + { + // TODO + } + + + /// + /// Undo/Redo changed handler + /// + void MainWindow::onUndoRedoChanged() + { + editUndoAction->setEnabled( mUndoRedoModel->canUndo() ); + editRedoAction->setEnabled( mUndoRedoModel->canRedo() ); + } + } diff --git a/glabels/MainWindow.h b/glabels/MainWindow.h index 1d11164..c2a9bc4 100644 --- a/glabels/MainWindow.h +++ b/glabels/MainWindow.h @@ -33,257 +33,264 @@ #include #include -// Forward References -class LabelEditor; -class LabelModel; -class MergeView; -class ObjectEditor; -class PrintView; -class PropertiesView; -class StartupView; -class UndoRedoModel; - -/// -/// MainWindow Widget -/// -class MainWindow : public QMainWindow +namespace glabels { - Q_OBJECT + + // Forward References + class LabelEditor; + class LabelModel; + class MergeView; + class ObjectEditor; + class PrintView; + class PropertiesView; + class StartupView; + class UndoRedoModel; - ///////////////////////////////////// - // Lifecycle - ///////////////////////////////////// -public: - MainWindow(); - virtual ~MainWindow(); + /// + /// MainWindow Widget + /// + class MainWindow : public QMainWindow + { + Q_OBJECT - ///////////////////////////////////// - // Public Methods - ///////////////////////////////////// -public: - LabelModel* model() const; - void setModel( LabelModel* label ); - bool isEmpty() const; + ///////////////////////////////////// + // Lifecycle + ///////////////////////////////////// + public: + MainWindow(); + virtual ~MainWindow(); - ///////////////////////////////////// - // Events - ///////////////////////////////////// -protected: - void closeEvent( QCloseEvent *event ); + ///////////////////////////////////// + // Public Methods + ///////////////////////////////////// + public: + LabelModel* model() const; + void setModel( LabelModel* label ); + bool isEmpty() const; - ///////////////////////////////////// - // Slots - ///////////////////////////////////// -private slots: - void changePage(QListWidgetItem *current, QListWidgetItem *previous); - - void clipboardChanged(); - - void fileNew(); - void fileOpen(); - void fileSave(); - void fileSaveAs(); - void fileTemplateDesigner(); - void fileClose(); - void fileExit(); - - void editUndo(); - void editRedo(); - void editCut(); - void editCopy(); - void editPaste(); - void editDelete(); - void editSelectAll(); - void editUnSelectAll(); - void editPreferences(); - - void viewFileToolBar( bool ); - void viewEditorToolBar( bool ); - void viewGrid( bool ); - void viewMarkup( bool ); - void viewZoomIn(); - void viewZoomOut(); - void viewZoom1To1(); - void viewZoomToFit(); - - void objectsArrowMode(); - void objectsCreateText(); - void objectsCreateBox(); - void objectsCreateLine(); - void objectsCreateEllipse(); - void objectsCreateImage(); - void objectsCreateBarcode(); - void objectsOrderRaise(); - void objectsOrderLower(); - void objectsXformRotateLeft(); - void objectsXformRotateRight(); - void objectsXformFlipHoriz(); - void objectsXformFlipVert(); - void objectsAlignLeft(); - void objectsAlignHCenter(); - void objectsAlignRight(); - void objectsAlignTop(); - void objectsAlignVCenter(); - void objectsAlignBottom(); - void objectsCenterHoriz(); - void objectsCenterVert(); - - void helpContents(); - void helpAbout(); - - void onContextMenuActivate(); - - void onZoomChanged(); - void onPointerMoved( double, double ); - void onPointerExit(); - - void onNameChanged(); - void onModifiedChanged(); - void onSelectionChanged(); - void onLabelChanged(); - void onUndoRedoChanged(); + ///////////////////////////////////// + // Events + ///////////////////////////////////// + protected: + void closeEvent( QCloseEvent *event ); - ///////////////////////////////////// - // Internal Private Methods - ///////////////////////////////////// -private: - void createActions(); - void createMenus(); - void createToolBars(); - void createStatusBar(); + ///////////////////////////////////// + // Slots + ///////////////////////////////////// + private slots: + void changePage(QListWidgetItem *current, QListWidgetItem *previous); - QWidget* createWelcomePage(); - QWidget* createPropertiesPage(); - QWidget* createEditorPage(); - QWidget* createMergePage(); - QWidget* createPrintPage(); + void clipboardChanged(); - void setWelcomeMode( bool ); - void setDocVerbsEnabled( bool ); - void setDocModifiedVerbsEnabled( bool ); - void setPasteVerbsEnabled( bool ); - void setSelectionVerbsEnabled( bool ); - void setMultiSelectionVerbsEnabled( bool ); + void fileNew(); + void fileOpen(); + void fileSave(); + void fileSaveAs(); + void fileTemplateDesigner(); + void fileClose(); + void fileExit(); - void setTitle(); + void editUndo(); + void editRedo(); + void editCut(); + void editCopy(); + void editPaste(); + void editDelete(); + void editSelectAll(); + void editUnSelectAll(); + void editPreferences(); - void readSettings(); - void writeSettings(); + void viewFileToolBar( bool ); + void viewEditorToolBar( bool ); + void viewGrid( bool ); + void viewMarkup( bool ); + void viewZoomIn(); + void viewZoomOut(); + void viewZoom1To1(); + void viewZoomToFit(); - bool isOkToClose(); + void objectsArrowMode(); + void objectsCreateText(); + void objectsCreateBox(); + void objectsCreateLine(); + void objectsCreateEllipse(); + void objectsCreateImage(); + void objectsCreateBarcode(); + void objectsOrderRaise(); + void objectsOrderLower(); + void objectsXformRotateLeft(); + void objectsXformRotateRight(); + void objectsXformFlipHoriz(); + void objectsXformFlipVert(); + void objectsAlignLeft(); + void objectsAlignHCenter(); + void objectsAlignRight(); + void objectsAlignTop(); + void objectsAlignVCenter(); + void objectsAlignBottom(); + void objectsCenterHoriz(); + void objectsCenterVert(); + + void helpContents(); + void helpAbout(); + + void onContextMenuActivate(); + + void onZoomChanged(); + void onPointerMoved( double, double ); + void onPointerExit(); + + void onNameChanged(); + void onModifiedChanged(); + void onSelectionChanged(); + void onLabelChanged(); + void onUndoRedoChanged(); + + + ///////////////////////////////////// + // Internal Private Methods + ///////////////////////////////////// + private: + void createActions(); + void createMenus(); + void createToolBars(); + void createStatusBar(); + + QWidget* createWelcomePage(); + QWidget* createPropertiesPage(); + QWidget* createEditorPage(); + QWidget* createMergePage(); + QWidget* createPrintPage(); + + void setWelcomeMode( bool ); + void setDocVerbsEnabled( bool ); + void setDocModifiedVerbsEnabled( bool ); + void setPasteVerbsEnabled( bool ); + void setSelectionVerbsEnabled( bool ); + void setMultiSelectionVerbsEnabled( bool ); + + void setTitle(); + + void readSettings(); + void writeSettings(); + + bool isOkToClose(); - ///////////////////////////////////// - // Private Data - ///////////////////////////////////// -private: - QMenu* fileMenu; - QMenu* editMenu; - QMenu* viewMenu; - QMenu* viewToolBarsMenu; - QMenu* objectsMenu; - QMenu* objectsCreateMenu; - QMenu* objectsOrderMenu; - QMenu* objectsXformMenu; - QMenu* objectsAlignMenu; - QMenu* objectsCenterMenu; - QMenu* helpMenu; + ///////////////////////////////////// + // Private Data + ///////////////////////////////////// + private: + QMenu* fileMenu; + QMenu* editMenu; + QMenu* viewMenu; + QMenu* viewToolBarsMenu; + QMenu* objectsMenu; + QMenu* objectsCreateMenu; + QMenu* objectsOrderMenu; + QMenu* objectsXformMenu; + QMenu* objectsAlignMenu; + QMenu* objectsCenterMenu; + QMenu* helpMenu; - QMenu* contextMenu; - QMenu* contextOrderMenu; - QMenu* contextXformMenu; - QMenu* contextAlignMenu; - QMenu* contextCenterMenu; - QMenu* noSelectionContextMenu; + QMenu* contextMenu; + QMenu* contextOrderMenu; + QMenu* contextXformMenu; + QMenu* contextAlignMenu; + QMenu* contextCenterMenu; + QMenu* noSelectionContextMenu; - QToolBar* fileToolBar; - QToolBar* editorToolBar; + QToolBar* fileToolBar; + QToolBar* editorToolBar; - LabelModel* mModel; - UndoRedoModel* mUndoRedoModel; + LabelModel* mModel; + UndoRedoModel* mUndoRedoModel; - QListWidget* mContents; - QListWidgetItem* mWelcomeButton; - QListWidgetItem* mPropertiesButton; - QListWidgetItem* mEditorButton; - QListWidgetItem* mMergeButton; - QListWidgetItem* mPrintButton; + QListWidget* mContents; + QListWidgetItem* mWelcomeButton; + QListWidgetItem* mPropertiesButton; + QListWidgetItem* mEditorButton; + QListWidgetItem* mMergeButton; + QListWidgetItem* mPrintButton; - QStackedWidget* mPages; - StartupView* mWelcomeView; - PropertiesView* mPropertiesView; - QScrollArea* mLabelEditorScrollArea; - LabelEditor* mLabelEditor; - ObjectEditor* mObjectEditor; - MergeView* mMergeView; - PrintView* mPrintView; + QStackedWidget* mPages; + StartupView* mWelcomeView; + PropertiesView* mPropertiesView; + QScrollArea* mLabelEditorScrollArea; + LabelEditor* mLabelEditor; + ObjectEditor* mObjectEditor; + MergeView* mMergeView; + PrintView* mPrintView; - QLabel* zoomInfoLabel; - QLabel* cursorInfoLabel; + QLabel* zoomInfoLabel; + QLabel* cursorInfoLabel; - QAction* fileNewAction; - QAction* fileOpenAction; - QAction* fileSaveAction; - QAction* fileSaveAsAction; - QAction* fileTemplateDesignerAction; - QAction* fileCloseAction; - QAction* fileExitAction; + QAction* fileNewAction; + QAction* fileOpenAction; + QAction* fileSaveAction; + QAction* fileSaveAsAction; + QAction* fileTemplateDesignerAction; + QAction* fileCloseAction; + QAction* fileExitAction; - QAction* editUndoAction; - QAction* editRedoAction; - QAction* editCutAction; - QAction* editCopyAction; - QAction* editPasteAction; - QAction* editDeleteAction; - QAction* editSelectAllAction; - QAction* editUnSelectAllAction; - QAction* editPreferencesAction; + QAction* editUndoAction; + QAction* editRedoAction; + QAction* editCutAction; + QAction* editCopyAction; + QAction* editPasteAction; + QAction* editDeleteAction; + QAction* editSelectAllAction; + QAction* editUnSelectAllAction; + QAction* editPreferencesAction; - QAction* viewFileToolBarAction; - QAction* viewEditorToolBarAction; - QAction* viewGridAction; - QAction* viewMarkupAction; - QAction* viewZoomInAction; - QAction* viewZoomOutAction; - QAction* viewZoom1To1Action; - QAction* viewZoomToFitAction; + QAction* viewFileToolBarAction; + QAction* viewEditorToolBarAction; + QAction* viewGridAction; + QAction* viewMarkupAction; + QAction* viewZoomInAction; + QAction* viewZoomOutAction; + QAction* viewZoom1To1Action; + QAction* viewZoomToFitAction; - QAction* objectsArrowModeAction; - QAction* objectsCreateTextAction; - QAction* objectsCreateBoxAction; - QAction* objectsCreateLineAction; - QAction* objectsCreateEllipseAction; - QAction* objectsCreateImageAction; - QAction* objectsCreateBarcodeAction; - QAction* objectsOrderRaiseAction; - QAction* objectsOrderLowerAction; - QAction* objectsXformRotateLeftAction; - QAction* objectsXformRotateRightAction; - QAction* objectsXformFlipHorizAction; - QAction* objectsXformFlipVertAction; - QAction* objectsAlignLeftAction; - QAction* objectsAlignHCenterAction; - QAction* objectsAlignRightAction; - QAction* objectsAlignTopAction; - QAction* objectsAlignVCenterAction; - QAction* objectsAlignBottomAction; - QAction* objectsCenterHorizAction; - QAction* objectsCenterVertAction; + QAction* objectsArrowModeAction; + QAction* objectsCreateTextAction; + QAction* objectsCreateBoxAction; + QAction* objectsCreateLineAction; + QAction* objectsCreateEllipseAction; + QAction* objectsCreateImageAction; + QAction* objectsCreateBarcodeAction; + QAction* objectsOrderRaiseAction; + QAction* objectsOrderLowerAction; + QAction* objectsXformRotateLeftAction; + QAction* objectsXformRotateRightAction; + QAction* objectsXformFlipHorizAction; + QAction* objectsXformFlipVertAction; + QAction* objectsAlignLeftAction; + QAction* objectsAlignHCenterAction; + QAction* objectsAlignRightAction; + QAction* objectsAlignTopAction; + QAction* objectsAlignVCenterAction; + QAction* objectsAlignBottomAction; + QAction* objectsCenterHorizAction; + QAction* objectsCenterVertAction; - QAction* helpContentsAction; - QAction* helpAboutAction; + QAction* helpContentsAction; + QAction* helpAboutAction; - QAction* contextCutAction; - QAction* contextCopyAction; - QAction* contextPasteAction; - QAction* contextDeleteAction; -}; + QAction* contextCutAction; + QAction* contextCopyAction; + QAction* contextPasteAction; + QAction* contextDeleteAction; + }; + + +} #endif // MainWindow_h diff --git a/glabels/Merge/Factory.cpp b/glabels/Merge/Factory.cpp index 1abd362..e74241e 100644 --- a/glabels/Merge/Factory.cpp +++ b/glabels/Merge/Factory.cpp @@ -31,191 +31,194 @@ #include "TextSemicolonKeys.h" -namespace merge +namespace glabels { - /// - /// Static data - /// - QMap Factory::mBackendIdMap; - QMap Factory::mBackendNameMap; - - QStringList Factory::mNameList; - - - /// - /// Constructor - /// - Factory::Factory() + namespace merge { - registerBackend( None::id(), - tr("None"), - NONE, - &None::create ); + + // + // Static data + // + QMap Factory::mBackendIdMap; + QMap Factory::mBackendNameMap; + QStringList Factory::mNameList; + + + /// + /// Constructor + /// + Factory::Factory() + { + registerBackend( None::id(), + tr("None"), + NONE, + &None::create ); - registerBackend( TextCsv::id(), - tr("Text: Comma Separated Values (CSV)"), - FILE, - &TextCsv::create ); + registerBackend( TextCsv::id(), + tr("Text: Comma Separated Values (CSV)"), + FILE, + &TextCsv::create ); - registerBackend( TextCsvKeys::id(), - tr("Text: Comma Separated Values (CSV), keys on line 1"), - FILE, - &TextCsvKeys::create ); + registerBackend( TextCsvKeys::id(), + tr("Text: Comma Separated Values (CSV), keys on line 1"), + FILE, + &TextCsvKeys::create ); - registerBackend( TextTsv::id(), - tr("Text: Tab Separated Values (TSV)"), - FILE, - &TextTsv::create ); + registerBackend( TextTsv::id(), + tr("Text: Tab Separated Values (TSV)"), + FILE, + &TextTsv::create ); - registerBackend( TextTsvKeys::id(), - tr("Text: Tab Separated Values (TSV), keys on line 1"), - FILE, - &TextTsvKeys::create ); + registerBackend( TextTsvKeys::id(), + tr("Text: Tab Separated Values (TSV), keys on line 1"), + FILE, + &TextTsvKeys::create ); - registerBackend( TextColon::id(), - tr("Text: Colon Separated Values"), - FILE, - &TextColon::create ); + registerBackend( TextColon::id(), + tr("Text: Colon Separated Values"), + FILE, + &TextColon::create ); - registerBackend( TextColonKeys::id(), - tr("Text: Colon Separated Values, keys on line 1"), - FILE, - &TextColonKeys::create ); + registerBackend( TextColonKeys::id(), + tr("Text: Colon Separated Values, keys on line 1"), + FILE, + &TextColonKeys::create ); - registerBackend( TextSemicolon::id(), - tr("Text: Semicolon Separated Values"), - FILE, - &TextSemicolon::create ); + registerBackend( TextSemicolon::id(), + tr("Text: Semicolon Separated Values"), + FILE, + &TextSemicolon::create ); - registerBackend( TextSemicolonKeys::id(), - tr("Text: Semicolon Separated Values, keys on line 1"), - FILE, - &TextSemicolonKeys::create ); - } - - - /// - /// Initialize - /// - void Factory::init() - { - static Factory* singletonInstance = 0; - if ( !singletonInstance ) - { - singletonInstance = new Factory(); + registerBackend( TextSemicolonKeys::id(), + tr("Text: Semicolon Separated Values, keys on line 1"), + FILE, + &TextSemicolonKeys::create ); } - } - /// - /// Create Merge object - /// - Merge* Factory::createMerge( const QString& id ) - { - QMap::iterator iBackend = mBackendIdMap.find( id ); - if ( iBackend != mBackendIdMap.end() ) + /// + /// Initialize + /// + void Factory::init() { - return iBackend->create(); + static Factory* singletonInstance = 0; + if ( !singletonInstance ) + { + singletonInstance = new Factory(); + } } + + + /// + /// Create Merge object + /// + Merge* Factory::createMerge( const QString& id ) + { + QMap::iterator iBackend = mBackendIdMap.find( id ); + if ( iBackend != mBackendIdMap.end() ) + { + return iBackend->create(); + } - return None::create(); - } - - - /// - /// Get name list - /// - QStringList Factory::nameList() - { - return mNameList; - } - - - /// - /// Convert ID to name - /// - QString Factory::idToName( const QString& id ) - { - if ( mBackendIdMap.contains( id ) ) - { - return mBackendIdMap[id].name; + return None::create(); } - else - { - return tr("None"); - } - } - /// - /// Convert name to ID - /// - QString Factory::nameToId( const QString& name ) - { - if ( mBackendNameMap.contains( name ) ) + /// + /// Get name list + /// + QStringList Factory::nameList() { - return mBackendNameMap[name].id; + return mNameList; } - else + + + /// + /// Convert ID to name + /// + QString Factory::idToName( const QString& id ) { + if ( mBackendIdMap.contains( id ) ) + { + return mBackendIdMap[id].name; + } + else + { + return tr("None"); + } + } + + + /// + /// Convert name to ID + /// + QString Factory::nameToId( const QString& name ) + { + if ( mBackendNameMap.contains( name ) ) + { + return mBackendNameMap[name].id; + } + else + { + return "None"; + } + } + + + /// + /// Convert ID to type + /// + Factory::SourceType Factory::idToType( const QString& id ) + { + if ( mBackendIdMap.contains( id ) ) + { + return mBackendIdMap[id].type; + } + else + { + return NONE; + } + } + + + /// + /// Lookup ID from index + /// + QString Factory::indexToId( int index ) + { + if ( (index > 0) && (index < mNameList.size()) ) + { + QString name = mNameList[index]; + + return mBackendNameMap[ name ].id; + } + return "None"; } - } - /// - /// Convert ID to type - /// - Factory::SourceType Factory::idToType( const QString& id ) - { - if ( mBackendIdMap.contains( id ) ) + /// + /// Register backend + /// + void Factory::registerBackend( const QString& id, + const QString& name, + SourceType type, + CreateFct create ) { - return mBackendIdMap[id].type; - } - else - { - return NONE; - } - } + BackendEntry backend; - - /// - /// Lookup ID from index - /// - QString Factory::indexToId( int index ) - { - if ( (index > 0) && (index < mNameList.size()) ) - { - QString name = mNameList[index]; - - return mBackendNameMap[ name ].id; - } - - return "None"; - } - - - /// - /// Register backend - /// - void Factory::registerBackend( const QString& id, - const QString& name, - SourceType type, - CreateFct create ) - { - BackendEntry backend; - - backend.id = id; - backend.name = name; - backend.type = type; - backend.create = create; + backend.id = id; + backend.name = name; + backend.type = type; + backend.create = create; - mBackendIdMap[ id ] = backend; - mBackendNameMap[ name ] = backend; + mBackendIdMap[ id ] = backend; + mBackendNameMap[ name ] = backend; + + mNameList << name; + } - mNameList << name; } } - diff --git a/glabels/Merge/Factory.h b/glabels/Merge/Factory.h index 91ee8c0..6d1b4a8 100644 --- a/glabels/Merge/Factory.h +++ b/glabels/Merge/Factory.h @@ -26,78 +26,86 @@ #include -namespace merge +namespace glabels { - class Merge; // Forward reference - - /// - /// Factory - /// - class Factory + namespace merge { - Q_DECLARE_TR_FUNCTIONS(Factory) + + // Forward references + class Merge; - ///////////////////////////////// - // Source Type - ///////////////////////////////// - public: - enum SourceType { NONE, FIXED, FILE }; - - - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - protected: - Factory(); - - - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static void init(); - - static Merge* createMerge( const QString& id ); - - static QStringList nameList(); - static QString idToName( const QString& id ); - static QString nameToId( const QString& name ); - static SourceType idToType( const QString& id ); - static QString indexToId( int index ); - - - ///////////////////////////////// - // private methods - ///////////////////////////////// - private: - typedef Merge* (*CreateFct)(); - - static void registerBackend( const QString& id, - const QString& name, - SourceType type, - CreateFct create ); - - - ///////////////////////////////// - // private data - ///////////////////////////////// - class BackendEntry + /// + /// Factory + /// + class Factory { - public: - QString id; - QString name; - SourceType type; - CreateFct create; - }; + Q_DECLARE_TR_FUNCTIONS(Factory) - static QMap mBackendIdMap; - static QMap mBackendNameMap; + + ///////////////////////////////// + // Source Type + ///////////////////////////////// + public: + enum SourceType { NONE, FIXED, FILE }; - static QStringList mNameList; - }; + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + protected: + Factory(); + + + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static void init(); + + static Merge* createMerge( const QString& id ); + + static QStringList nameList(); + static QString idToName( const QString& id ); + static QString nameToId( const QString& name ); + static SourceType idToType( const QString& id ); + static QString indexToId( int index ); + + + ///////////////////////////////// + // private methods + ///////////////////////////////// + private: + typedef Merge* (*CreateFct)(); + + static void registerBackend( const QString& id, + const QString& name, + SourceType type, + CreateFct create ); + + + ///////////////////////////////// + // private data + ///////////////////////////////// + class BackendEntry + { + public: + QString id; + QString name; + SourceType type; + CreateFct create; + }; + + static QMap mBackendIdMap; + static QMap mBackendNameMap; + + static QStringList mNameList; + }; + + } } + #endif // merge_Factory_h diff --git a/glabels/Merge/Merge.cpp b/glabels/Merge/Merge.cpp index 05366dd..8321c8d 100644 --- a/glabels/Merge/Merge.cpp +++ b/glabels/Merge/Merge.cpp @@ -23,188 +23,193 @@ #include "Record.h" -namespace merge +namespace glabels { - /// - /// Constructor - /// - Merge::Merge() + namespace merge { - } - - /// - /// Constructor - /// - Merge::Merge( const Merge* merge ) : mSource(merge->mSource) - { - foreach ( Record* record, merge->mRecordList ) + /// + /// Constructor + /// + Merge::Merge() { - mRecordList << record->clone(); } - } - /// - /// Destructor - /// - Merge::~Merge() - { - foreach ( Record* record, mRecordList ) + /// + /// Constructor + /// + Merge::Merge( const Merge* merge ) : mSource(merge->mSource) { - delete record; + foreach ( Record* record, merge->mRecordList ) + { + mRecordList << record->clone(); + } } - mRecordList.clear(); - } - /// - /// Get id - /// - QString Merge::id() const - { - return mId; - } - - - /// - /// Get source - /// - QString Merge::source() const - { - return mSource; - } - - - /// - /// Set source - /// - void Merge::setSource( const QString& source ) - { - mSource = source; - - // Clear out any old records - foreach ( Record* record, mRecordList ) + /// + /// Destructor + /// + Merge::~Merge() { - delete record; + foreach ( Record* record, mRecordList ) + { + delete record; + } + mRecordList.clear(); } - mRecordList.clear(); - open(); - for ( Record* record = readNextRecord(); record != 0; record = readNextRecord() ) + + /// + /// Get id + /// + QString Merge::id() const { - mRecordList.append( record ); + return mId; } - close(); + + + /// + /// Get source + /// + QString Merge::source() const + { + return mSource; + } + + + /// + /// Set source + /// + void Merge::setSource( const QString& source ) + { + mSource = source; + + // Clear out any old records + foreach ( Record* record, mRecordList ) + { + delete record; + } + mRecordList.clear(); + + open(); + for ( Record* record = readNextRecord(); record != 0; record = readNextRecord() ) + { + mRecordList.append( record ); + } + close(); - emit sourceChanged(); - } - - - /// - /// Get record list - /// - const QList& Merge::recordList( void ) const - { - return mRecordList; - } - - - /// - /// Select matching record - /// - void Merge::select( Record* record ) - { - record->setSelected( true ); - emit selectionChanged(); - } - - - /// - /// Unselect matching record - /// - void Merge::unselect( Record* record ) - { - record->setSelected( false ); - emit selectionChanged(); - } - - - /// - /// Select/unselect i'th record - /// - void Merge::setSelected( int i, bool state ) - { - if ( (i >= 0) && (i < mRecordList.size()) ) - { - mRecordList[i]->setSelected( state ); - emit selectionChanged(); + emit sourceChanged(); } - } - /// - /// Select all records - /// - void Merge::selectAll() - { - foreach ( Record* record, mRecordList ) + /// + /// Get record list + /// + const QList& Merge::recordList( void ) const + { + return mRecordList; + } + + + /// + /// Select matching record + /// + void Merge::select( Record* record ) { record->setSelected( true ); + emit selectionChanged(); } - emit selectionChanged(); - } - - /// - /// Unselect all records - /// - void Merge::unselectAll() - { - foreach ( Record* record, mRecordList ) + + /// + /// Unselect matching record + /// + void Merge::unselect( Record* record ) { record->setSelected( false ); + emit selectionChanged(); } - emit selectionChanged(); - } - /// - /// Return count of selected records - /// - int Merge::nSelectedRecords() const - { - int count = 0; - - foreach ( Record* record, mRecordList ) + /// + /// Select/unselect i'th record + /// + void Merge::setSelected( int i, bool state ) { - if ( record->isSelected() ) + if ( (i >= 0) && (i < mRecordList.size()) ) { - count++; + mRecordList[i]->setSelected( state ); + emit selectionChanged(); } } - return count; - } - - /// - /// Return list of selected records - /// - const QList Merge::selectedRecords() const - { - QList list; - - foreach ( Record* record, mRecordList ) + /// + /// Select all records + /// + void Merge::selectAll() { - if ( record->isSelected() ) + foreach ( Record* record, mRecordList ) { - list.append( record ); + record->setSelected( true ); } + emit selectionChanged(); + } + + + /// + /// Unselect all records + /// + void Merge::unselectAll() + { + foreach ( Record* record, mRecordList ) + { + record->setSelected( false ); + } + emit selectionChanged(); + } + + + /// + /// Return count of selected records + /// + int Merge::nSelectedRecords() const + { + int count = 0; + + foreach ( Record* record, mRecordList ) + { + if ( record->isSelected() ) + { + count++; + } + } + + return count; + } + + + /// + /// Return list of selected records + /// + const QList Merge::selectedRecords() const + { + QList list; + + foreach ( Record* record, mRecordList ) + { + if ( record->isSelected() ) + { + list.append( record ); + } + } + + return list; } - return list; } } diff --git a/glabels/Merge/Merge.h b/glabels/Merge/Merge.h index 345acff..ab5ff98 100644 --- a/glabels/Merge/Merge.h +++ b/glabels/Merge/Merge.h @@ -27,90 +27,98 @@ #include -namespace merge +namespace glabels { - class Record; // Forward reference - - /// - /// Merge Object - /// - struct Merge : QObject + namespace merge { - Q_OBJECT - - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - protected: - Merge(); - Merge( const Merge* merge ); - public: - virtual ~Merge(); - - - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - virtual Merge* clone() const = 0; - - - ///////////////////////////////// - // Properties - ///////////////////////////////// - public: - QString id() const; - QString source() const; - void setSource( const QString& source ); - - const QList& recordList( void ) const; - - - ///////////////////////////////// - // Selection methods - ///////////////////////////////// - public: - void select( Record* record ); - void unselect( Record* record ); - void setSelected( int i, bool state = true ); - void selectAll(); - void unselectAll(); + // Forward references + class Record; + - int nSelectedRecords() const; - const QList selectedRecords() const; + /// + /// Merge Object + /// + struct Merge : QObject + { + Q_OBJECT - ///////////////////////////////// - // Virtual methods - ///////////////////////////////// - public: - virtual QStringList keys() const = 0; - virtual QString primaryKey() const = 0; - protected: - virtual void open() = 0; - virtual void close() = 0; - virtual Record* readNextRecord() = 0; + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + protected: + Merge(); + Merge( const Merge* merge ); + public: + virtual ~Merge(); + + + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + virtual Merge* clone() const = 0; + + + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + QString id() const; + QString source() const; + void setSource( const QString& source ); + + const QList& recordList( void ) const; + + + ///////////////////////////////// + // Selection methods + ///////////////////////////////// + public: + void select( Record* record ); + void unselect( Record* record ); + void setSelected( int i, bool state = true ); + void selectAll(); + void unselectAll(); + + int nSelectedRecords() const; + const QList selectedRecords() const; + + + ///////////////////////////////// + // Virtual methods + ///////////////////////////////// + public: + virtual QStringList keys() const = 0; + virtual QString primaryKey() const = 0; + protected: + virtual void open() = 0; + virtual void close() = 0; + virtual Record* readNextRecord() = 0; - ///////////////////////////////// - // Signals - ///////////////////////////////// - signals: - void sourceChanged(); - void selectionChanged(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void sourceChanged(); + void selectionChanged(); - ///////////////////////////////// - // Private data - ///////////////////////////////// - protected: - QString mId; - private: - QString mSource; - QList mRecordList; - }; + ///////////////////////////////// + // Private data + ///////////////////////////////// + protected: + QString mId; + private: + QString mSource; + QList mRecordList; + }; + + } } + #endif // merge_Merge_h diff --git a/glabels/Merge/None.cpp b/glabels/Merge/None.cpp index c6cfc97..e041442 100644 --- a/glabels/Merge/None.cpp +++ b/glabels/Merge/None.cpp @@ -21,102 +21,107 @@ #include "None.h" -namespace merge +namespace glabels { - /// - /// Constructor - /// - None::None() : Merge() + namespace merge { - mId = "None"; - } + + /// + /// Constructor + /// + None::None() : Merge() + { + mId = "None"; + } - /// - /// Constructor - /// - None::None( const None* merge ) : Merge( merge ) - { - } + /// + /// Constructor + /// + None::None( const None* merge ) : Merge( merge ) + { + } - /// - /// Destructor - /// - None::~None() - { - } + /// + /// Destructor + /// + None::~None() + { + } - /// - /// Clone - /// - None* None::clone() const - { - return new None( this ); - } + /// + /// Clone + /// + None* None::clone() const + { + return new None( this ); + } - /// - /// Get ID - /// - QString None::id() - { - return "None"; - } + /// + /// Get ID + /// + QString None::id() + { + return "None"; + } - /// - /// Create - /// - Merge* None::create() - { - return new None(); - } + /// + /// Create + /// + Merge* None::create() + { + return new None(); + } - /// - /// Get key list - /// - QStringList None::keys() const - { - QStringList emptyList; - return emptyList; - } + /// + /// Get key list + /// + QStringList None::keys() const + { + QStringList emptyList; + return emptyList; + } - /// - /// Get primary key - /// - QString None::primaryKey() const - { - return ""; - } + /// + /// Get primary key + /// + QString None::primaryKey() const + { + return ""; + } - /// - /// Open source - /// - void None::open() - { - } + /// + /// Open source + /// + void None::open() + { + } - /// - /// Close source - /// - void None::close() - { - } + /// + /// Close source + /// + void None::close() + { + } - /// - /// Read next record - /// - Record* None::readNextRecord() - { - return 0; + /// + /// Read next record + /// + Record* None::readNextRecord() + { + return 0; + } + } } diff --git a/glabels/Merge/None.h b/glabels/Merge/None.h index 63c9fe4..1547002 100644 --- a/glabels/Merge/None.h +++ b/glabels/Merge/None.h @@ -24,51 +24,57 @@ #include "Merge.h" -namespace merge +namespace glabels { - - /// - /// None Merge Backend - /// - struct None : public Merge + + namespace merge { + + /// + /// None Merge Backend + /// + struct None : public Merge + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - public: - None(); - None( const None* merge ); - virtual ~None(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + None(); + None( const None* merge ); + virtual ~None(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - None* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + None* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - ///////////////////////////////// - // Implementation of virtual methods - ///////////////////////////////// - public: - QStringList keys() const; - QString primaryKey() const; - protected: - void open(); - void close(); - Record* readNextRecord(); + ///////////////////////////////// + // Implementation of virtual methods + ///////////////////////////////// + public: + QStringList keys() const; + QString primaryKey() const; + protected: + void open(); + void close(); + Record* readNextRecord(); - }; + }; + + } } + #endif // merge_None_h diff --git a/glabels/Merge/Record.cpp b/glabels/Merge/Record.cpp index 5286fa1..ec35a30 100644 --- a/glabels/Merge/Record.cpp +++ b/glabels/Merge/Record.cpp @@ -21,50 +21,55 @@ #include "Record.h" -namespace merge +namespace glabels { - /// - /// Constructor - /// - Record::Record() : mSelected( true ) + namespace merge { - } + + /// + /// Constructor + /// + Record::Record() : mSelected( true ) + { + } - /// - /// Constructor - /// - Record::Record( const Record* record ) - : QMap(*record), mSelected(record->mSelected) - { - } + /// + /// Constructor + /// + Record::Record( const Record* record ) + : QMap(*record), mSelected(record->mSelected) + { + } - /// - /// Clone - /// - Record* Record::clone() const - { - return new Record( this ); - } + /// + /// Clone + /// + Record* Record::clone() const + { + return new Record( this ); + } - /// - /// Is record selected? - /// - bool Record::isSelected() const - { - return mSelected; - } + /// + /// Is record selected? + /// + bool Record::isSelected() const + { + return mSelected; + } - /// - /// Set selected on not selected - /// - void Record::setSelected( bool value ) - { - mSelected = value; + /// + /// Set selected on not selected + /// + void Record::setSelected( bool value ) + { + mSelected = value; + } + } } diff --git a/glabels/Merge/Record.h b/glabels/Merge/Record.h index d672a59..58b0529 100644 --- a/glabels/Merge/Record.h +++ b/glabels/Merge/Record.h @@ -25,45 +25,51 @@ #include -namespace merge +namespace glabels { - - /// - /// Merge Record - /// - struct Record : public QMap + + namespace merge { + + /// + /// Merge Record + /// + struct Record : public QMap + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - public: - Record(); - Record( const Record* record ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + Record(); + Record( const Record* record ); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - Record* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + Record* clone() const; - ///////////////////////////////// - // Properties - ///////////////////////////////// - public: - bool isSelected() const; - void setSelected( bool value ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + bool isSelected() const; + void setSelected( bool value ); - ///////////////////////////////// - // Private data - ///////////////////////////////// - private: - bool mSelected; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + bool mSelected; - }; + }; + + } } + #endif // merge_Record_h diff --git a/glabels/Merge/Text.cpp b/glabels/Merge/Text.cpp index 67d87e1..c19ca06 100644 --- a/glabels/Merge/Text.cpp +++ b/glabels/Merge/Text.cpp @@ -24,392 +24,397 @@ #include -namespace merge +namespace glabels { - /// - /// Constructor - /// - Text::Text( QChar delimiter, bool line1HasKeys ) - : mNFieldsMax(0), mDelimeter(delimiter), mLine1HasKeys(line1HasKeys) + namespace merge { - } - - /// - /// Constructor - /// - Text::Text( const Text* merge ) - : Merge( merge ), - mNFieldsMax(merge->mNFieldsMax), - mDelimeter(merge->mDelimeter), mLine1HasKeys(merge->mLine1HasKeys) - { - } - - - /// - /// Destructor - /// - Text::~Text() - { - } - - - /// - /// Get key list - /// - QStringList Text::keys() const - { - QStringList keys; - for ( int iField = 0; iField < mNFieldsMax; iField++ ) + /// + /// Constructor + /// + Text::Text( QChar delimiter, bool line1HasKeys ) + : mNFieldsMax(0), mDelimeter(delimiter), mLine1HasKeys(line1HasKeys) { - keys << keyFromIndex(iField); } - return keys; - } - /// - /// Get primary key - /// - QString Text::primaryKey() const - { - return keyFromIndex(0); - } - - - /// - /// Open source - /// - void Text::open() - { - mFile.setFileName( source() ); - mFile.open( QIODevice::ReadOnly|QIODevice::Text ); - - mKeys.clear(); - mNFieldsMax = 0; - - if ( mLine1HasKeys && mFile.isOpen() ) + /// + /// Constructor + /// + Text::Text( const Text* merge ) + : Merge( merge ), + mNFieldsMax(merge->mNFieldsMax), + mDelimeter(merge->mDelimeter), mLine1HasKeys(merge->mLine1HasKeys) { - mKeys = parseLine(); - if ( (mKeys.size() == 1) && (mKeys[0] == "") ) + } + + + /// + /// Destructor + /// + Text::~Text() + { + } + + + /// + /// Get key list + /// + QStringList Text::keys() const + { + QStringList keys; + for ( int iField = 0; iField < mNFieldsMax; iField++ ) { - mKeys.clear(); + keys << keyFromIndex(iField); + } + return keys; + } + + + /// + /// Get primary key + /// + QString Text::primaryKey() const + { + return keyFromIndex(0); + } + + + /// + /// Open source + /// + void Text::open() + { + mFile.setFileName( source() ); + mFile.open( QIODevice::ReadOnly|QIODevice::Text ); + + mKeys.clear(); + mNFieldsMax = 0; + + if ( mLine1HasKeys && mFile.isOpen() ) + { + mKeys = parseLine(); + if ( (mKeys.size() == 1) && (mKeys[0] == "") ) + { + mKeys.clear(); + } + else + { + mNFieldsMax = mKeys.size(); + } + } + } + + + /// + /// Close source + /// + void Text::close() + { + if ( mFile.isOpen() ) + { + mFile.close(); + } + } + + + /// + /// Read next record + /// + Record* Text::readNextRecord() + { + QStringList values = parseLine(); + if ( !values.isEmpty() ) + { + Record* record = new Record(); + + int iField = 0; + foreach ( QString value, values ) + { + (*record)[ keyFromIndex(iField) ] = value; + iField++; + } + mNFieldsMax = std::max( mNFieldsMax, iField ); + + return record; + } + return 0; + } + + + /// + /// Key from field index + /// + QString Text::keyFromIndex( int iField ) const + { + if ( mLine1HasKeys && ( iField < mKeys.size() ) ) + { + return mKeys[iField]; } else { - mNFieldsMax = mKeys.size(); + return QString::number( iField+1 ); } } - } - /// - /// Close source - /// - void Text::close() - { - if ( mFile.isOpen() ) + /// + /// Parse line. + /// + /// Attempt to be a robust parser of various CSV (and similar) formats. + /// + /// Based on CSV format described in RFC 4180 section 2. + /// + /// Additions to RFC 4180 rules: + /// - delimeters and other special characters may be "escaped" by a leading + /// backslash (\) + /// - C escape sequences for newline (\n) and tab (\t) are also translated. + /// - if quoted text is not followed by a delimeter, any additional text is + /// concatenated with quoted portion. + /// + /// Returns a list of fields. A blank line is considered a line with one + /// empty field. Returns an empty list when done. + /// + QStringList Text::parseLine() { - mFile.close(); - } - } - - - /// - /// Read next record - /// - Record* Text::readNextRecord() - { - QStringList values = parseLine(); - if ( !values.isEmpty() ) - { - Record* record = new Record(); - - int iField = 0; - foreach ( QString value, values ) - { - (*record)[ keyFromIndex(iField) ] = value; - iField++; - } - mNFieldsMax = std::max( mNFieldsMax, iField ); - - return record; - } - return 0; - } - - - /// - /// Key from field index - /// - QString Text::keyFromIndex( int iField ) const - { - if ( mLine1HasKeys && ( iField < mKeys.size() ) ) - { - return mKeys[iField]; - } - else - { - return QString::number( iField+1 ); - } - } - - - /// - /// Parse line. - /// - /// Attempt to be a robust parser of various CSV (and similar) formats. - /// - /// Based on CSV format described in RFC 4180 section 2. - /// - /// Additions to RFC 4180 rules: - /// - delimeters and other special characters may be "escaped" by a leading - /// backslash (\) - /// - C escape sequences for newline (\n) and tab (\t) are also translated. - /// - if quoted text is not followed by a delimeter, any additional text is - /// concatenated with quoted portion. - /// - /// Returns a list of fields. A blank line is considered a line with one - /// empty field. Returns an empty list when done. - /// - QStringList Text::parseLine() - { - QStringList fields; + QStringList fields; - enum State - { - DELIM, QUOTED, QUOTED_QUOTE1, QUOTED_ESCAPED, SIMPLE, SIMPLE_ESCAPED, DONE - } state = DELIM; - - QByteArray field; - - while ( state != DONE ) - { - char c; - if ( mFile.getChar( &c ) ) + enum State { - switch (state) + DELIM, QUOTED, QUOTED_QUOTE1, QUOTED_ESCAPED, SIMPLE, SIMPLE_ESCAPED, DONE + } state = DELIM; + + QByteArray field; + + while ( state != DONE ) + { + char c; + if ( mFile.getChar( &c ) ) { - - case DELIM: - switch (c) + switch (state) { - case '\n': - /* last field is empty. */ - fields << ""; - state = DONE; - break; - case '\r': - /* ignore */ - state = DELIM; - break; - case '"': - /* start a quoted field. */ - state = QUOTED; - break; - case '\\': - /* simple field, but 1st character is an escape. */ - state = SIMPLE_ESCAPED; - break; - default: - if ( c == mDelimeter ) + + case DELIM: + switch (c) { - /* field is empty. */ + case '\n': + /* last field is empty. */ fields << ""; + state = DONE; + break; + case '\r': + /* ignore */ state = DELIM; - } - else - { - /* begining of a simple field. */ - field.append( c ); - state = SIMPLE; + break; + case '"': + /* start a quoted field. */ + state = QUOTED; + break; + case '\\': + /* simple field, but 1st character is an escape. */ + state = SIMPLE_ESCAPED; + break; + default: + if ( c == mDelimeter ) + { + /* field is empty. */ + fields << ""; + state = DELIM; + } + else + { + /* begining of a simple field. */ + field.append( c ); + state = SIMPLE; + } + break; } break; - } - break; - case QUOTED: - switch (c) - { - case '"': - /* Possible end of field, but could be 1st of a pair. */ - state = QUOTED_QUOTE1; - break; - case '\\': - /* Escape next character, or special escape, e.g. \n. */ - state = QUOTED_ESCAPED; - break; - default: - /* Use character literally. */ - field.append( c ); - break; - } - break; - - case QUOTED_QUOTE1: - switch (c) - { - case '\n': - /* line ended after quoted item */ - fields << QString( field ); - state = DONE; - break; - case '"': - /* second quote, insert and stay quoted. */ - field.append( c ); - state = QUOTED; - break; - case '\r': - /* ignore and go to fallback */ - state = SIMPLE; - break; - default: - if ( c == mDelimeter ) - { - /* end of field. */ - fields << QString( field ); - field.clear(); - state = DELIM; - } - else - { - /* fallback if not a delim or another quote. */ - field.append( c ); - state = SIMPLE; - } - break; - } - break; - - case QUOTED_ESCAPED: - switch (c) - { - case 'n': - /* Decode "\n" as newline. */ - field.append( '\n' ); - state = QUOTED; - break; - case 't': - /* Decode "\t" as tab. */ - field.append( '\t' ); - state = QUOTED; - break; - default: - /* Use character literally. */ - field.append( c ); - state = QUOTED; - break; - } - break; - - case SIMPLE: - switch (c) - { - case '\n': - /* line ended */ - fields << QString( field ); - state = DONE; - break; - case '\r': - /* ignore */ - state = SIMPLE; - break; - case '\\': - /* Escape next character, or special escape, e.g. \n. */ - state = SIMPLE_ESCAPED; - break; - default: - if ( c == mDelimeter ) - { - /* end of field. */ - fields << QString( field ); - field.clear(); - state = DELIM; - } - else + case QUOTED: + switch (c) { + case '"': + /* Possible end of field, but could be 1st of a pair. */ + state = QUOTED_QUOTE1; + break; + case '\\': + /* Escape next character, or special escape, e.g. \n. */ + state = QUOTED_ESCAPED; + break; + default: /* Use character literally. */ field.append( c ); - state = SIMPLE; + break; } break; - } - break; - case SIMPLE_ESCAPED: - switch (c) - { - case 'n': - /* Decode "\n" as newline. */ - field.append( '\n' ); - state = SIMPLE; + case QUOTED_QUOTE1: + switch (c) + { + case '\n': + /* line ended after quoted item */ + fields << QString( field ); + state = DONE; + break; + case '"': + /* second quote, insert and stay quoted. */ + field.append( c ); + state = QUOTED; + break; + case '\r': + /* ignore and go to fallback */ + state = SIMPLE; + break; + default: + if ( c == mDelimeter ) + { + /* end of field. */ + fields << QString( field ); + field.clear(); + state = DELIM; + } + else + { + /* fallback if not a delim or another quote. */ + field.append( c ); + state = SIMPLE; + } + break; + } break; - case 't': - /* Decode "\t" as tab. */ - field.append( '\t' ); - state = SIMPLE; + + case QUOTED_ESCAPED: + switch (c) + { + case 'n': + /* Decode "\n" as newline. */ + field.append( '\n' ); + state = QUOTED; + break; + case 't': + /* Decode "\t" as tab. */ + field.append( '\t' ); + state = QUOTED; + break; + default: + /* Use character literally. */ + field.append( c ); + state = QUOTED; + break; + } break; + + case SIMPLE: + switch (c) + { + case '\n': + /* line ended */ + fields << QString( field ); + state = DONE; + break; + case '\r': + /* ignore */ + state = SIMPLE; + break; + case '\\': + /* Escape next character, or special escape, e.g. \n. */ + state = SIMPLE_ESCAPED; + break; + default: + if ( c == mDelimeter ) + { + /* end of field. */ + fields << QString( field ); + field.clear(); + state = DELIM; + } + else + { + /* Use character literally. */ + field.append( c ); + state = SIMPLE; + } + break; + } + break; + + case SIMPLE_ESCAPED: + switch (c) + { + case 'n': + /* Decode "\n" as newline. */ + field.append( '\n' ); + state = SIMPLE; + break; + case 't': + /* Decode "\t" as tab. */ + field.append( '\t' ); + state = SIMPLE; + break; + default: + /* Use character literally. */ + field.append( (char)c ); + state = SIMPLE; + break; + } + break; + default: - /* Use character literally. */ - field.append( (char)c ); - state = SIMPLE; + qWarning( "merge::Text::parseLine()::Should not be reached! #1" ); break; } - break; - default: - qWarning( "merge::Text::parseLine()::Should not be reached! #1" ); - break; } - - } - else - { - /* Handle EOF (could also be an error while reading). */ - switch (state) + else { + /* Handle EOF (could also be an error while reading). */ + switch (state) + { - case DELIM: - /* EOF, no more lines. */ - break; + case DELIM: + /* EOF, no more lines. */ + break; - case QUOTED: - /* File ended midway through quoted item. Truncate field. */ - fields << QString( field ); - break; + case QUOTED: + /* File ended midway through quoted item. Truncate field. */ + fields << QString( field ); + break; - case QUOTED_QUOTE1: - /* File ended after quoted item. */ - fields << QString( field ); - break; + case QUOTED_QUOTE1: + /* File ended after quoted item. */ + fields << QString( field ); + break; - case QUOTED_ESCAPED: - /* File ended midway through quoted item. Truncate field. */ - fields << QString( field ); - break; + case QUOTED_ESCAPED: + /* File ended midway through quoted item. Truncate field. */ + fields << QString( field ); + break; - case SIMPLE: - /* File ended after simple item. */ - fields << QString( field ); - break; + case SIMPLE: + /* File ended after simple item. */ + fields << QString( field ); + break; - case SIMPLE_ESCAPED: - /* File ended midway through escaped item. */ - fields << QString( field ); - break; + case SIMPLE_ESCAPED: + /* File ended midway through escaped item. */ + fields << QString( field ); + break; - default: - qWarning( "merge::Text::parseLine()::Should not be reached! #2" ); - break; - } + default: + qWarning( "merge::Text::parseLine()::Should not be reached! #2" ); + break; + } - state = DONE; + state = DONE; + } } - } - return fields; + return fields; + } + } } diff --git a/glabels/Merge/Text.h b/glabels/Merge/Text.h index ae9c872..3ce9c3c 100644 --- a/glabels/Merge/Text.h +++ b/glabels/Merge/Text.h @@ -26,55 +26,61 @@ #include -namespace merge +namespace glabels { - - /// - /// Text Merge Backend - /// - struct Text : public Merge + + namespace merge { + + /// + /// Text Merge Backend + /// + struct Text : public Merge + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - protected: - Text( QChar delimiter, bool line1HasKeys ); - Text( const Text* merge ); - virtual ~Text(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + protected: + Text( QChar delimiter, bool line1HasKeys ); + Text( const Text* merge ); + virtual ~Text(); - ///////////////////////////////// - // Implementation of virtual methods - ///////////////////////////////// - public: - QStringList keys() const; - QString primaryKey() const; - protected: - void open(); - void close(); - Record* readNextRecord(); + ///////////////////////////////// + // Implementation of virtual methods + ///////////////////////////////// + public: + QStringList keys() const; + QString primaryKey() const; + protected: + void open(); + void close(); + Record* readNextRecord(); - ///////////////////////////////// - // Private methods - ///////////////////////////////// - QString keyFromIndex( int iField ) const; - QStringList parseLine(); + ///////////////////////////////// + // Private methods + ///////////////////////////////// + QString keyFromIndex( int iField ) const; + QStringList parseLine(); - ///////////////////////////////// - // Private data - ///////////////////////////////// - private: - QChar mDelimeter; - bool mLine1HasKeys; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + QChar mDelimeter; + bool mLine1HasKeys; - QFile mFile; - QStringList mKeys; - int mNFieldsMax; - }; + QFile mFile; + QStringList mKeys; + int mNFieldsMax; + }; + + } } + #endif // merge_Text_h diff --git a/glabels/Merge/TextColon.cpp b/glabels/Merge/TextColon.cpp index 55deba1..0d6da02 100644 --- a/glabels/Merge/TextColon.cpp +++ b/glabels/Merge/TextColon.cpp @@ -21,60 +21,65 @@ #include "TextColon.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Colon"; - - /// - /// Constructor - /// - TextColon::TextColon() : Text(':',false) + namespace merge { - mId = ID; - } + static const QString ID = "Text/Colon"; - /// - /// Constructor - /// - TextColon::TextColon( const TextColon* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextColon::TextColon() : Text(':',false) + { + mId = ID; + } - /// - /// Destructor - /// - TextColon::~TextColon() - { - } + /// + /// Constructor + /// + TextColon::TextColon( const TextColon* merge ) : Text( merge ) + { + } - /// - /// Clone - /// - TextColon* TextColon::clone() const - { - return new TextColon( this ); - } + /// + /// Destructor + /// + TextColon::~TextColon() + { + } - /// - /// Get ID - /// - QString TextColon::id() - { - return ID; - } + /// + /// Clone + /// + TextColon* TextColon::clone() const + { + return new TextColon( this ); + } - /// - /// Create - /// - Merge* TextColon::create() - { - return new TextColon(); + /// + /// Get ID + /// + QString TextColon::id() + { + return ID; + } + + + /// + /// Create + /// + Merge* TextColon::create() + { + return new TextColon(); + } + } } diff --git a/glabels/Merge/TextColon.h b/glabels/Merge/TextColon.h index 9f9005e..be07c4d 100644 --- a/glabels/Merge/TextColon.h +++ b/glabels/Merge/TextColon.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextColon Merge Backend - /// - struct TextColon : public Text + + namespace merge { + + /// + /// TextColon Merge Backend + /// + struct TextColon : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextColon(); - TextColon( const TextColon* merge ); - virtual ~TextColon(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextColon(); + TextColon( const TextColon* merge ); + virtual ~TextColon(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextColon* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextColon* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextColon_h diff --git a/glabels/Merge/TextColonKeys.cpp b/glabels/Merge/TextColonKeys.cpp index 8414e68..8f0be5d 100644 --- a/glabels/Merge/TextColonKeys.cpp +++ b/glabels/Merge/TextColonKeys.cpp @@ -21,60 +21,65 @@ #include "TextColonKeys.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Colon/Line1Keys"; + + namespace merge + { + static const QString ID = "Text/Colon/Line1Keys"; - /// - /// Constructor - /// - TextColonKeys::TextColonKeys() : Text(':',true) - { - mId = ID; - } + /// + /// Constructor + /// + TextColonKeys::TextColonKeys() : Text(':',true) + { + mId = ID; + } - /// - /// Constructor - /// - TextColonKeys::TextColonKeys( const TextColonKeys* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextColonKeys::TextColonKeys( const TextColonKeys* merge ) : Text( merge ) + { + } - /// - /// Destructor - /// - TextColonKeys::~TextColonKeys() - { - } + /// + /// Destructor + /// + TextColonKeys::~TextColonKeys() + { + } - /// - /// Clone - /// - TextColonKeys* TextColonKeys::clone() const - { - return new TextColonKeys( this ); - } + /// + /// Clone + /// + TextColonKeys* TextColonKeys::clone() const + { + return new TextColonKeys( this ); + } - /// - /// Get ID - /// - QString TextColonKeys::id() - { - return ID; - } + /// + /// Get ID + /// + QString TextColonKeys::id() + { + return ID; + } - /// - /// Create - /// - Merge* TextColonKeys::create() - { - return new TextColonKeys(); + /// + /// Create + /// + Merge* TextColonKeys::create() + { + return new TextColonKeys(); + } + } } diff --git a/glabels/Merge/TextColonKeys.h b/glabels/Merge/TextColonKeys.h index ce83e16..4eeaf61 100644 --- a/glabels/Merge/TextColonKeys.h +++ b/glabels/Merge/TextColonKeys.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextColonKeys Merge Backend - /// - struct TextColonKeys : public Text + + namespace merge { + + /// + /// TextColonKeys Merge Backend + /// + struct TextColonKeys : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextColonKeys(); - TextColonKeys( const TextColonKeys* merge ); - virtual ~TextColonKeys(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextColonKeys(); + TextColonKeys( const TextColonKeys* merge ); + virtual ~TextColonKeys(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextColonKeys* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextColonKeys* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextColonKeys_h diff --git a/glabels/Merge/TextCsv.cpp b/glabels/Merge/TextCsv.cpp index bfb7aaa..0a5aa37 100644 --- a/glabels/Merge/TextCsv.cpp +++ b/glabels/Merge/TextCsv.cpp @@ -21,60 +21,65 @@ #include "TextCsv.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Comma"; + + namespace merge + { + static const QString ID = "Text/Comma"; - /// - /// Constructor - /// - TextCsv::TextCsv() : Text(',',false) - { - mId = ID; - } + /// + /// Constructor + /// + TextCsv::TextCsv() : Text(',',false) + { + mId = ID; + } - /// - /// Constructor - /// - TextCsv::TextCsv( const TextCsv* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextCsv::TextCsv( const TextCsv* merge ) : Text( merge ) + { + } - /// - /// Destructor - /// - TextCsv::~TextCsv() - { - } + /// + /// Destructor + /// + TextCsv::~TextCsv() + { + } - /// - /// Clone - /// - TextCsv* TextCsv::clone() const - { - return new TextCsv( this ); - } + /// + /// Clone + /// + TextCsv* TextCsv::clone() const + { + return new TextCsv( this ); + } - /// - /// Get ID - /// - QString TextCsv::id() - { - return ID; - } + /// + /// Get ID + /// + QString TextCsv::id() + { + return ID; + } - /// - /// Create - /// - Merge* TextCsv::create() - { - return new TextCsv(); + /// + /// Create + /// + Merge* TextCsv::create() + { + return new TextCsv(); + } + } } diff --git a/glabels/Merge/TextCsv.h b/glabels/Merge/TextCsv.h index 2bb52d2..e1f3cd3 100644 --- a/glabels/Merge/TextCsv.h +++ b/glabels/Merge/TextCsv.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextCsv Merge Backend - /// - struct TextCsv : public Text + + namespace merge { + + /// + /// TextCsv Merge Backend + /// + struct TextCsv : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextCsv(); - TextCsv( const TextCsv* merge ); - virtual ~TextCsv(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextCsv(); + TextCsv( const TextCsv* merge ); + virtual ~TextCsv(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextCsv* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextCsv* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextCsv_h diff --git a/glabels/Merge/TextCsvKeys.cpp b/glabels/Merge/TextCsvKeys.cpp index 791f0b2..5499042 100644 --- a/glabels/Merge/TextCsvKeys.cpp +++ b/glabels/Merge/TextCsvKeys.cpp @@ -21,60 +21,65 @@ #include "TextCsvKeys.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Comma/Line1Keys"; + + namespace merge + { + static const QString ID = "Text/Comma/Line1Keys"; - /// - /// Constructor - /// - TextCsvKeys::TextCsvKeys() : Text(',',true) - { - mId = ID; - } + /// + /// Constructor + /// + TextCsvKeys::TextCsvKeys() : Text(',',true) + { + mId = ID; + } - /// - /// Constructor - /// - TextCsvKeys::TextCsvKeys( const TextCsvKeys* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextCsvKeys::TextCsvKeys( const TextCsvKeys* merge ) : Text( merge ) + { + } - /// - /// Destructor - /// - TextCsvKeys::~TextCsvKeys() - { - } + /// + /// Destructor + /// + TextCsvKeys::~TextCsvKeys() + { + } - /// - /// Clone - /// - TextCsvKeys* TextCsvKeys::clone() const - { - return new TextCsvKeys( this ); - } + /// + /// Clone + /// + TextCsvKeys* TextCsvKeys::clone() const + { + return new TextCsvKeys( this ); + } - /// - /// Get ID - /// - QString TextCsvKeys::id() - { - return ID; - } + /// + /// Get ID + /// + QString TextCsvKeys::id() + { + return ID; + } - /// - /// Create - /// - Merge* TextCsvKeys::create() - { - return new TextCsvKeys(); + /// + /// Create + /// + Merge* TextCsvKeys::create() + { + return new TextCsvKeys(); + } + } } diff --git a/glabels/Merge/TextCsvKeys.h b/glabels/Merge/TextCsvKeys.h index 515c6d2..de1a5e3 100644 --- a/glabels/Merge/TextCsvKeys.h +++ b/glabels/Merge/TextCsvKeys.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextCsvKeys Merge Backend - /// - struct TextCsvKeys : public Text + + namespace merge { + + /// + /// TextCsvKeys Merge Backend + /// + struct TextCsvKeys : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextCsvKeys(); - TextCsvKeys( const TextCsvKeys* merge ); - virtual ~TextCsvKeys(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextCsvKeys(); + TextCsvKeys( const TextCsvKeys* merge ); + virtual ~TextCsvKeys(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextCsvKeys* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextCsvKeys* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextCsvKeys_h diff --git a/glabels/Merge/TextSemicolon.cpp b/glabels/Merge/TextSemicolon.cpp index b9931c6..ddcf3be 100644 --- a/glabels/Merge/TextSemicolon.cpp +++ b/glabels/Merge/TextSemicolon.cpp @@ -21,60 +21,65 @@ #include "TextSemicolon.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Semicolon"; - - /// - /// Constructor - /// - TextSemicolon::TextSemicolon() : Text(';',false) + namespace merge { - mId = ID; - } + static const QString ID = "Text/Semicolon"; - /// - /// Constructor - /// - TextSemicolon::TextSemicolon( const TextSemicolon* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextSemicolon::TextSemicolon() : Text(';',false) + { + mId = ID; + } - /// - /// Destructor - /// - TextSemicolon::~TextSemicolon() - { - } + /// + /// Constructor + /// + TextSemicolon::TextSemicolon( const TextSemicolon* merge ) : Text( merge ) + { + } - /// - /// Clone - /// - TextSemicolon* TextSemicolon::clone() const - { - return new TextSemicolon( this ); - } + /// + /// Destructor + /// + TextSemicolon::~TextSemicolon() + { + } - /// - /// Get ID - /// - QString TextSemicolon::id() - { - return ID; - } + /// + /// Clone + /// + TextSemicolon* TextSemicolon::clone() const + { + return new TextSemicolon( this ); + } - /// - /// Create - /// - Merge* TextSemicolon::create() - { - return new TextSemicolon(); + /// + /// Get ID + /// + QString TextSemicolon::id() + { + return ID; + } + + + /// + /// Create + /// + Merge* TextSemicolon::create() + { + return new TextSemicolon(); + } + } } diff --git a/glabels/Merge/TextSemicolon.h b/glabels/Merge/TextSemicolon.h index fa73481..ae12f46 100644 --- a/glabels/Merge/TextSemicolon.h +++ b/glabels/Merge/TextSemicolon.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextSemicolon Merge Backend - /// - struct TextSemicolon : public Text + + namespace merge { + + /// + /// TextSemicolon Merge Backend + /// + struct TextSemicolon : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextSemicolon(); - TextSemicolon( const TextSemicolon* merge ); - virtual ~TextSemicolon(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextSemicolon(); + TextSemicolon( const TextSemicolon* merge ); + virtual ~TextSemicolon(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextSemicolon* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextSemicolon* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextSemicolon_h diff --git a/glabels/Merge/TextSemicolonKeys.cpp b/glabels/Merge/TextSemicolonKeys.cpp index 270b9ea..b457559 100644 --- a/glabels/Merge/TextSemicolonKeys.cpp +++ b/glabels/Merge/TextSemicolonKeys.cpp @@ -21,60 +21,65 @@ #include "TextSemicolonKeys.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Semicolon/Keys"; - - /// - /// Constructor - /// - TextSemicolonKeys::TextSemicolonKeys() : Text(';',true) + namespace merge { - mId = ID; - } + static const QString ID = "Text/Semicolon/Keys"; - /// - /// Constructor - /// - TextSemicolonKeys::TextSemicolonKeys( const TextSemicolonKeys* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextSemicolonKeys::TextSemicolonKeys() : Text(';',true) + { + mId = ID; + } - /// - /// Destructor - /// - TextSemicolonKeys::~TextSemicolonKeys() - { - } + /// + /// Constructor + /// + TextSemicolonKeys::TextSemicolonKeys( const TextSemicolonKeys* merge ) : Text( merge ) + { + } - /// - /// Clone - /// - TextSemicolonKeys* TextSemicolonKeys::clone() const - { - return new TextSemicolonKeys( this ); - } + /// + /// Destructor + /// + TextSemicolonKeys::~TextSemicolonKeys() + { + } - /// - /// Get ID - /// - QString TextSemicolonKeys::id() - { - return ID; - } + /// + /// Clone + /// + TextSemicolonKeys* TextSemicolonKeys::clone() const + { + return new TextSemicolonKeys( this ); + } - /// - /// Create - /// - Merge* TextSemicolonKeys::create() - { - return new TextSemicolonKeys(); + /// + /// Get ID + /// + QString TextSemicolonKeys::id() + { + return ID; + } + + + /// + /// Create + /// + Merge* TextSemicolonKeys::create() + { + return new TextSemicolonKeys(); + } + } } diff --git a/glabels/Merge/TextSemicolonKeys.h b/glabels/Merge/TextSemicolonKeys.h index 43d28dd..e7ed43c 100644 --- a/glabels/Merge/TextSemicolonKeys.h +++ b/glabels/Merge/TextSemicolonKeys.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextSemicolonKeys Merge Backend - /// - struct TextSemicolonKeys : public Text + + namespace merge { + + /// + /// TextSemicolonKeys Merge Backend + /// + struct TextSemicolonKeys : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextSemicolonKeys(); - TextSemicolonKeys( const TextSemicolonKeys* merge ); - virtual ~TextSemicolonKeys(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextSemicolonKeys(); + TextSemicolonKeys( const TextSemicolonKeys* merge ); + virtual ~TextSemicolonKeys(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextSemicolonKeys* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextSemicolonKeys* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextSemicolonKeys_h diff --git a/glabels/Merge/TextTsv.cpp b/glabels/Merge/TextTsv.cpp index ea47701..52ace5a 100644 --- a/glabels/Merge/TextTsv.cpp +++ b/glabels/Merge/TextTsv.cpp @@ -21,60 +21,65 @@ #include "TextTsv.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Tab"; + + namespace merge + { + static const QString ID = "Text/Tab"; - /// - /// Constructor - /// - TextTsv::TextTsv() : Text('\t',false) - { - mId = ID; - } + /// + /// Constructor + /// + TextTsv::TextTsv() : Text('\t',false) + { + mId = ID; + } - /// - /// Constructor - /// - TextTsv::TextTsv( const TextTsv* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextTsv::TextTsv( const TextTsv* merge ) : Text( merge ) + { + } - /// - /// Destructor - /// - TextTsv::~TextTsv() - { - } + /// + /// Destructor + /// + TextTsv::~TextTsv() + { + } - /// - /// Clone - /// - TextTsv* TextTsv::clone() const - { - return new TextTsv( this ); - } + /// + /// Clone + /// + TextTsv* TextTsv::clone() const + { + return new TextTsv( this ); + } - /// - /// Get ID - /// - QString TextTsv::id() - { - return ID; - } + /// + /// Get ID + /// + QString TextTsv::id() + { + return ID; + } - /// - /// Create - /// - Merge* TextTsv::create() - { - return new TextTsv(); + /// + /// Create + /// + Merge* TextTsv::create() + { + return new TextTsv(); + } + } } diff --git a/glabels/Merge/TextTsv.h b/glabels/Merge/TextTsv.h index 0404467..9e3bbf4 100644 --- a/glabels/Merge/TextTsv.h +++ b/glabels/Merge/TextTsv.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextTsv Merge Backend - /// - struct TextTsv : public Text + + namespace merge { + + /// + /// TextTsv Merge Backend + /// + struct TextTsv : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextTsv(); - TextTsv( const TextTsv* merge ); - virtual ~TextTsv(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextTsv(); + TextTsv( const TextTsv* merge ); + virtual ~TextTsv(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextTsv* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextTsv* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextTsv_h diff --git a/glabels/Merge/TextTsvKeys.cpp b/glabels/Merge/TextTsvKeys.cpp index 7dd2b8d..41a1320 100644 --- a/glabels/Merge/TextTsvKeys.cpp +++ b/glabels/Merge/TextTsvKeys.cpp @@ -21,60 +21,65 @@ #include "TextTsvKeys.h" -namespace merge +namespace glabels { - static const QString ID = "Text/Tab/Line1Keys"; - - /// - /// Constructor - /// - TextTsvKeys::TextTsvKeys() : Text('\t',true) + namespace merge { - mId = ID; - } + static const QString ID = "Text/Tab/Line1Keys"; - /// - /// Constructor - /// - TextTsvKeys::TextTsvKeys( const TextTsvKeys* merge ) : Text( merge ) - { - } + /// + /// Constructor + /// + TextTsvKeys::TextTsvKeys() : Text('\t',true) + { + mId = ID; + } - /// - /// Destructor - /// - TextTsvKeys::~TextTsvKeys() - { - } + /// + /// Constructor + /// + TextTsvKeys::TextTsvKeys( const TextTsvKeys* merge ) : Text( merge ) + { + } - /// - /// Clone - /// - TextTsvKeys* TextTsvKeys::clone() const - { - return new TextTsvKeys( this ); - } + /// + /// Destructor + /// + TextTsvKeys::~TextTsvKeys() + { + } - /// - /// Get ID - /// - QString TextTsvKeys::id() - { - return ID; - } + /// + /// Clone + /// + TextTsvKeys* TextTsvKeys::clone() const + { + return new TextTsvKeys( this ); + } - /// - /// Create - /// - Merge* TextTsvKeys::create() - { - return new TextTsvKeys(); + /// + /// Get ID + /// + QString TextTsvKeys::id() + { + return ID; + } + + + /// + /// Create + /// + Merge* TextTsvKeys::create() + { + return new TextTsvKeys(); + } + } } diff --git a/glabels/Merge/TextTsvKeys.h b/glabels/Merge/TextTsvKeys.h index fd94809..1c3caec 100644 --- a/glabels/Merge/TextTsvKeys.h +++ b/glabels/Merge/TextTsvKeys.h @@ -24,40 +24,46 @@ #include "Text.h" -namespace merge +namespace glabels { - - /// - /// TextTsvKeys Merge Backend - /// - struct TextTsvKeys : public Text + + namespace merge { + + /// + /// TextTsvKeys Merge Backend + /// + struct TextTsvKeys : public Text + { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// - private: - TextTsvKeys(); - TextTsvKeys( const TextTsvKeys* merge ); - virtual ~TextTsvKeys(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + TextTsvKeys(); + TextTsvKeys( const TextTsvKeys* merge ); + virtual ~TextTsvKeys(); - ///////////////////////////////// - // Object duplication - ///////////////////////////////// - public: - TextTsvKeys* clone() const; + ///////////////////////////////// + // Object duplication + ///////////////////////////////// + public: + TextTsvKeys* clone() const; - ///////////////////////////////// - // Static methods - ///////////////////////////////// - public: - static QString id(); - static Merge* create(); + ///////////////////////////////// + // Static methods + ///////////////////////////////// + public: + static QString id(); + static Merge* create(); - }; + }; + + } } + #endif // merge_TextTsvKeys_h diff --git a/glabels/MergeView.cpp b/glabels/MergeView.cpp index f06c491..087d184 100644 --- a/glabels/MergeView.cpp +++ b/glabels/MergeView.cpp @@ -30,289 +30,302 @@ #include "Merge/Factory.h" -/// -/// Constructor -/// -MergeView::MergeView( QWidget *parent ) - : QWidget(parent), mModel(0), mBlock(false) +namespace glabels { - setupUi( this ); - mMergeFormatNames = merge::Factory::nameList(); - formatCombo->addItems( mMergeFormatNames ); -} - - -/// -/// Destructor -/// -MergeView::~MergeView() -{ -} - - -/// -/// Set Model -/// -void MergeView::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) -{ - mModel = model; - mUndoRedoModel = undoRedoModel; - - // Initialize CWD - if ( model->fileName().isEmpty() ) + /// + /// Constructor + /// + MergeView::MergeView( QWidget *parent ) + : QWidget(parent), mModel(0), mBlock(false) { - mCwd = "."; - } - else - { - mCwd = QFileInfo( model->fileName() ).absolutePath(); + setupUi( this ); + + mMergeFormatNames = merge::Factory::nameList(); + formatCombo->addItems( mMergeFormatNames ); } - onMergeChanged(); - connect( mModel, SIGNAL(mergeChanged()), this, SLOT(onMergeChanged()) ); -} - -/// -/// Merge changed handler -/// -void MergeView::onMergeChanged() -{ - int index = mMergeFormatNames.indexOf( merge::Factory::idToName( mModel->merge()->id() ) ); - mOldFormatComboIndex = index; - formatCombo->setCurrentIndex( index ); - - switch ( merge::Factory::idToType( mModel->merge()->id() ) ) + /// + /// Destructor + /// + MergeView::~MergeView() { - case merge::Factory::NONE: - case merge::Factory::FIXED: - locationLabel->setEnabled( false ); - locationButton->setEnabled( false ); - locationButton->setText( "" ); - break; + // empty + } - case merge::Factory::FILE: - locationLabel->setEnabled( true ); - locationButton->setEnabled( true ); - if ( mModel->merge()->source().isEmpty() ) + + /// + /// Set Model + /// + void MergeView::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) + { + mModel = model; + mUndoRedoModel = undoRedoModel; + + // Initialize CWD + if ( model->fileName().isEmpty() ) { - locationButton->setText( "Select file..." ); + mCwd = "."; } else { - locationButton->setText( mModel->merge()->source() ); + mCwd = QFileInfo( model->fileName() ).absolutePath(); } - break; - default: - qWarning( "MergeView::onMergeChanged()::Should not be reached!" ); - break; + onMergeChanged(); + connect( mModel, SIGNAL(mergeChanged()), this, SLOT(onMergeChanged()) ); } - recordsTable->clear(); - recordsTable->setColumnCount( 0 ); - loadHeaders( mModel->merge() ); - loadTable( mModel->merge() ); - connect( mModel->merge(), SIGNAL(sourceChanged()), this, SLOT(onMergeSourceChanged()) ); - connect( mModel->merge(), SIGNAL(selectionChanged()), this, SLOT(onMergeSelectionChanged()) ); - - connect( recordsTable, SIGNAL(cellChanged(int,int)), this, SLOT(onCellChanged(int,int)) ); -} - - -/// -/// Merge source changed handler -/// -void MergeView::onMergeSourceChanged() -{ - locationButton->setText( mModel->merge()->source() ); - - recordsTable->clear(); - recordsTable->setColumnCount( 0 ); - loadHeaders( mModel->merge() ); - loadTable( mModel->merge() ); -} - - -/// -/// Merge selection changed handler -/// -void MergeView::onMergeSelectionChanged() -{ - mBlock = true; // Don't recurse - - const QList& records = mModel->merge()->recordList(); - - int iRow = 0; - foreach ( merge::Record* record, records ) - { - QTableWidgetItem* item = recordsTable->item( iRow, 0 ); - item->setCheckState( record->isSelected() ? Qt::Checked : Qt::Unchecked ); - - iRow++; - } - - mBlock = false; -} - - -/// -/// Format combo changed handler -void MergeView::onFormatComboActivated() -{ - int index = formatCombo->currentIndex(); - if ( index != mOldFormatComboIndex ) + /// + /// Merge changed handler + /// + void MergeView::onMergeChanged() { + QString name = merge::Factory::idToName( mModel->merge()->id() ); + int index = mMergeFormatNames.indexOf( name ); mOldFormatComboIndex = index; + formatCombo->setCurrentIndex( index ); - mModel->setMerge( merge::Factory::createMerge( merge::Factory::indexToId(index) ) ); - } -} - - -/// -/// Location button clicked handler -/// -void MergeView::onLocationButtonClicked() -{ - QString fileName = - QFileDialog::getOpenFileName( this, - tr("Select merge file"), - mCwd, - tr("All files (*)") ); - if ( !fileName.isEmpty() ) - { - mModel->merge()->setSource( fileName ); - mCwd = QFileInfo( fileName ).absolutePath(); // Update CWD - } -} - - -/// -/// Select all button clicked handler -/// -void MergeView::onSelectAllButtonClicked() -{ - mModel->merge()->selectAll(); -} - - -/// -/// Unselect all button clicked handler -/// -void MergeView::onUnselectAllButtonClicked() -{ - mModel->merge()->unselectAll(); -} - - -/// -/// Cell changed handler -/// -void MergeView::onCellChanged( int iRow, int iCol ) -{ - if ( !mBlock ) - { - QTableWidgetItem* item = recordsTable->item( iRow, 0 ); - bool state = (item->checkState() == Qt::Unchecked) ? false : true; - - mModel->merge()->setSelected( iRow, state ); - } -} - - -/// -/// Load headers -/// -void MergeView::loadHeaders( merge::Merge* merge ) -{ - mPrimaryKey = merge->primaryKey(); - mKeys = merge->keys(); - - if ( mKeys.size() > 0 ) - { - recordsTable->setColumnCount( mKeys.size() + 1 ); // Include extra column - - // First column = primay Key - QTableWidgetItem* item = new QTableWidgetItem( mPrimaryKey ); - item->setFlags( Qt::ItemIsEnabled ); - recordsTable->setHorizontalHeaderItem( 0, item ); - - // Starting on second column, one column per key, skip primary Key - int iCol = 1; - foreach ( QString key, mKeys ) + switch ( merge::Factory::idToType( mModel->merge()->id() ) ) { - if ( key != mPrimaryKey ) - { - QTableWidgetItem* item = new QTableWidgetItem( key ); - item->setFlags( Qt::ItemIsEnabled ); - recordsTable->setHorizontalHeaderItem( iCol, item ); + case merge::Factory::NONE: + case merge::Factory::FIXED: + locationLabel->setEnabled( false ); + locationButton->setEnabled( false ); + locationButton->setText( "" ); + break; - iCol++; + case merge::Factory::FILE: + locationLabel->setEnabled( true ); + locationButton->setEnabled( true ); + if ( mModel->merge()->source().isEmpty() ) + { + locationButton->setText( "Select file..." ); } - - } - - // Extra dummy column to fill any extra horizontal space - QTableWidgetItem* fillItem = new QTableWidgetItem(); - fillItem->setFlags( Qt::NoItemFlags ); - recordsTable->setHorizontalHeaderItem( iCol, fillItem ); - recordsTable->horizontalHeader()->setStretchLastSection( true ); - } -} - - -/// -/// Load table -/// -void MergeView::loadTable( merge::Merge* merge ) -{ - mBlock = true; - - const QList& records = merge->recordList(); - recordsTable->setRowCount( records.size() ); - - int iRow = 0; - foreach ( merge::Record* record, records ) - { - // First column for primay field - QTableWidgetItem* item = new QTableWidgetItem(); - if ( record->contains( mPrimaryKey ) ) - { - item->setText( (*record)[mPrimaryKey] ); - } - item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); - item->setCheckState( record->isSelected() ? Qt::Checked : Qt::Unchecked ); - recordsTable->setItem( iRow, 0, item ); - recordsTable->resizeColumnToContents( 0 ); - - // Starting on second column, one column per field (even if empty), skip primary field - int iCol = 1; - foreach ( QString key, mKeys ) - { - if ( key != mPrimaryKey ) + else { - if ( record->contains( key ) ) + locationButton->setText( mModel->merge()->source() ); + } + break; + + default: + qWarning( "MergeView::onMergeChanged()::Should not be reached!" ); + break; + } + + recordsTable->clear(); + recordsTable->setColumnCount( 0 ); + loadHeaders( mModel->merge() ); + loadTable( mModel->merge() ); + + connect( mModel->merge(), SIGNAL(sourceChanged()), + this, SLOT(onMergeSourceChanged()) ); + + connect( mModel->merge(), SIGNAL(selectionChanged()), + this, SLOT(onMergeSelectionChanged()) ); + + connect( recordsTable, SIGNAL(cellChanged(int,int)), + this, SLOT(onCellChanged(int,int)) ); + } + + + /// + /// Merge source changed handler + /// + void MergeView::onMergeSourceChanged() + { + locationButton->setText( mModel->merge()->source() ); + + recordsTable->clear(); + recordsTable->setColumnCount( 0 ); + loadHeaders( mModel->merge() ); + loadTable( mModel->merge() ); + } + + + /// + /// Merge selection changed handler + /// + void MergeView::onMergeSelectionChanged() + { + mBlock = true; // Don't recurse + + const QList& records = mModel->merge()->recordList(); + + int iRow = 0; + foreach ( merge::Record* record, records ) + { + QTableWidgetItem* item = recordsTable->item( iRow, 0 ); + item->setCheckState( record->isSelected() ? Qt::Checked : Qt::Unchecked ); + + iRow++; + } + + mBlock = false; + } + + + /// + /// Format combo changed handler + /// + void MergeView::onFormatComboActivated() + { + int index = formatCombo->currentIndex(); + if ( index != mOldFormatComboIndex ) + { + mOldFormatComboIndex = index; + + QString id = merge::Factory::indexToId(index); + mModel->setMerge( merge::Factory::createMerge( id ) ); + } + } + + + /// + /// Location button clicked handler + /// + void MergeView::onLocationButtonClicked() + { + QString fileName = + QFileDialog::getOpenFileName( this, + tr("Select merge file"), + mCwd, + tr("All files (*)") ); + if ( !fileName.isEmpty() ) + { + mModel->merge()->setSource( fileName ); + mCwd = QFileInfo( fileName ).absolutePath(); // Update CWD + } + } + + + /// + /// Select all button clicked handler + /// + void MergeView::onSelectAllButtonClicked() + { + mModel->merge()->selectAll(); + } + + + /// + /// Unselect all button clicked handler + /// + void MergeView::onUnselectAllButtonClicked() + { + mModel->merge()->unselectAll(); + } + + + /// + /// Cell changed handler + /// + void MergeView::onCellChanged( int iRow, int iCol ) + { + if ( !mBlock ) + { + QTableWidgetItem* item = recordsTable->item( iRow, 0 ); + bool state = (item->checkState() == Qt::Unchecked) ? false : true; + + mModel->merge()->setSelected( iRow, state ); + } + } + + + /// + /// Load headers + /// + void MergeView::loadHeaders( merge::Merge* merge ) + { + mPrimaryKey = merge->primaryKey(); + mKeys = merge->keys(); + + if ( mKeys.size() > 0 ) + { + recordsTable->setColumnCount( mKeys.size() + 1 ); // Include extra column + + // First column = primay Key + QTableWidgetItem* item = new QTableWidgetItem( mPrimaryKey ); + item->setFlags( Qt::ItemIsEnabled ); + recordsTable->setHorizontalHeaderItem( 0, item ); + + // Starting on second column, one column per key, skip primary Key + int iCol = 1; + foreach ( QString key, mKeys ) + { + if ( key != mPrimaryKey ) { - QTableWidgetItem* item = new QTableWidgetItem( (*record)[key] ); + QTableWidgetItem* item = new QTableWidgetItem( key ); item->setFlags( Qt::ItemIsEnabled ); - recordsTable->setItem( iRow, iCol, item ); - recordsTable->resizeColumnToContents( iCol ); + recordsTable->setHorizontalHeaderItem( iCol, item ); + + iCol++; } - iCol++; } + + // Extra dummy column to fill any extra horizontal space + QTableWidgetItem* fillItem = new QTableWidgetItem(); + fillItem->setFlags( Qt::NoItemFlags ); + recordsTable->setHorizontalHeaderItem( iCol, fillItem ); + recordsTable->horizontalHeader()->setStretchLastSection( true ); } - - // Extra dummy column to fill any extra horizontal space - QTableWidgetItem* fillItem = new QTableWidgetItem(); - fillItem->setFlags( Qt::NoItemFlags ); - recordsTable->setItem( iRow, iCol, fillItem ); - - iRow++; } - mBlock = false; + + /// + /// Load table + /// + void MergeView::loadTable( merge::Merge* merge ) + { + mBlock = true; + + const QList& records = merge->recordList(); + recordsTable->setRowCount( records.size() ); + + int iRow = 0; + foreach ( merge::Record* record, records ) + { + // First column for primay field + QTableWidgetItem* item = new QTableWidgetItem(); + if ( record->contains( mPrimaryKey ) ) + { + item->setText( (*record)[mPrimaryKey] ); + } + item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); + item->setCheckState( record->isSelected() ? Qt::Checked : Qt::Unchecked ); + recordsTable->setItem( iRow, 0, item ); + recordsTable->resizeColumnToContents( 0 ); + + // Starting on 2nd column, 1 column per field, skip primary field + int iCol = 1; + foreach ( QString key, mKeys ) + { + if ( key != mPrimaryKey ) + { + if ( record->contains( key ) ) + { + QTableWidgetItem* item = new QTableWidgetItem( (*record)[key] ); + item->setFlags( Qt::ItemIsEnabled ); + recordsTable->setItem( iRow, iCol, item ); + recordsTable->resizeColumnToContents( iCol ); + } + + iCol++; + } + } + + // Extra dummy column to fill any extra horizontal space + QTableWidgetItem* fillItem = new QTableWidgetItem(); + fillItem->setFlags( Qt::NoItemFlags ); + recordsTable->setItem( iRow, iCol, fillItem ); + + iRow++; + } + + mBlock = false; + } + } diff --git a/glabels/MergeView.h b/glabels/MergeView.h index e67cd26..1a0e849 100644 --- a/glabels/MergeView.h +++ b/glabels/MergeView.h @@ -26,74 +26,80 @@ #include "Merge/Merge.h" -// Forward references -class LabelModel; -class UndoRedoModel; - -/// -/// merge::Merge Property Editor Widget -/// -class MergeView : public QWidget, public Ui_MergeView +namespace glabels { - Q_OBJECT - - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - MergeView( QWidget *parent = 0 ); - ~MergeView(); - - - ///////////////////////////////// - // Public methods - ///////////////////////////////// - void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); - - - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onMergeChanged(); - void onMergeSourceChanged(); - void onMergeSelectionChanged(); - - void onFormatComboActivated(); - void onLocationButtonClicked(); - void onSelectAllButtonClicked(); - void onUnselectAllButtonClicked(); - void onCellChanged( int iRow, int iCol ); - - - ///////////////////////////////// - // Private methods - ///////////////////////////////// -private: - void loadHeaders( merge::Merge* merge ); - void loadTable( merge::Merge* merge ); - - - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - QStringList mMergeFormatNames; + // Forward references + class LabelModel; + class UndoRedoModel; - LabelModel* mModel; - UndoRedoModel* mUndoRedoModel; - QStringList mKeys; - QString mPrimaryKey; + /// + /// merge::Merge Property Editor Widget + /// + class MergeView : public QWidget, public Ui_MergeView + { + Q_OBJECT - QString mCwd; - bool mBlock; - int mOldFormatComboIndex; + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + MergeView( QWidget *parent = 0 ); + ~MergeView(); -}; + + ///////////////////////////////// + // Public methods + ///////////////////////////////// + void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); + + + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onMergeChanged(); + void onMergeSourceChanged(); + void onMergeSelectionChanged(); + + void onFormatComboActivated(); + void onLocationButtonClicked(); + void onSelectAllButtonClicked(); + void onUnselectAllButtonClicked(); + void onCellChanged( int iRow, int iCol ); + + + ///////////////////////////////// + // Private methods + ///////////////////////////////// + private: + void loadHeaders( merge::Merge* merge ); + void loadTable( merge::Merge* merge ); + + + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + QStringList mMergeFormatNames; + + LabelModel* mModel; + UndoRedoModel* mUndoRedoModel; + + QStringList mKeys; + QString mPrimaryKey; + + QString mCwd; + + bool mBlock; + int mOldFormatComboIndex; + + }; + +} #endif // MergeView_h diff --git a/glabels/MiniPreviewPixmap.cpp b/glabels/MiniPreviewPixmap.cpp index ce63f52..11c12d1 100644 --- a/glabels/MiniPreviewPixmap.cpp +++ b/glabels/MiniPreviewPixmap.cpp @@ -24,23 +24,27 @@ #include "Template.h" -namespace -{ - const QColor paperColor( 217, 217, 217 ); - const QColor paperOutlineColor( 0, 0, 0 ); - const double paperOutlineWidthPixels = 1.0; - - const QColor labelColor( 242, 242, 242 ); - const QColor labelOutlineColor( 64, 64, 64 ); - const double labelOutlineWidthPixels = 1.0; -} - - namespace glabels { + // + // Private + // + namespace + { + const QColor paperColor( 217, 217, 217 ); + const QColor paperOutlineColor( 0, 0, 0 ); + const double paperOutlineWidthPixels = 1.0; + + const QColor labelColor( 242, 242, 242 ); + const QColor labelOutlineColor( 64, 64, 64 ); + const double labelOutlineWidthPixels = 1.0; + } + + MiniPreviewPixmap::MiniPreviewPixmap() { + // empty } diff --git a/glabels/ObjectEditor.cpp b/glabels/ObjectEditor.cpp index 074c7af..dbc569f 100644 --- a/glabels/ObjectEditor.cpp +++ b/glabels/ObjectEditor.cpp @@ -39,648 +39,662 @@ #include "Merge/Merge.h" -/// -/// Constructor -/// -ObjectEditor::ObjectEditor( QWidget *parent ) - : mModel(0), mObject(0), mImageCwd("."), mBlocked(false) +namespace glabels { - setupUi( this ); - textHAlignGroup = new QButtonGroup( this ); - textHAlignGroup->addButton( textHAlignLeftToggle, Qt::AlignLeft ); - textHAlignGroup->addButton( textHAlignCenterToggle, Qt::AlignHCenter ); - textHAlignGroup->addButton( textHAlignRightToggle, Qt::AlignRight ); + /// + /// Constructor + /// + ObjectEditor::ObjectEditor( QWidget *parent ) + : mModel(0), mObject(0), mImageCwd("."), mBlocked(false) + { + setupUi( this ); - textVAlignGroup = new QButtonGroup( this ); - textVAlignGroup->addButton( textVAlignTopToggle, Qt::AlignTop ); - textVAlignGroup->addButton( textVAlignMiddleToggle, Qt::AlignVCenter ); - textVAlignGroup->addButton( textVAlignBottomToggle, Qt::AlignBottom ); + textHAlignGroup = new QButtonGroup( this ); + textHAlignGroup->addButton( textHAlignLeftToggle, Qt::AlignLeft ); + textHAlignGroup->addButton( textHAlignCenterToggle, Qt::AlignHCenter ); + textHAlignGroup->addButton( textHAlignRightToggle, Qt::AlignRight ); - lineColorButton->init( "No line", QColor(0,0,0,0), QColor(0,0,0,255) ); - fillColorButton->init( "No fill", QColor(0,0,0,0), QColor(0,0,0,255) ); - textColorButton->init( "Default", QColor(0,0,0,255), QColor(0,0,0,255) ); - shadowColorButton->init( "Default", QColor(0,0,0,255), QColor(0,0,0,255) ); + textVAlignGroup = new QButtonGroup( this ); + textVAlignGroup->addButton( textVAlignTopToggle, Qt::AlignTop ); + textVAlignGroup->addButton( textVAlignMiddleToggle, Qt::AlignVCenter ); + textVAlignGroup->addButton( textVAlignBottomToggle, Qt::AlignBottom ); - textInsertFieldCombo->setName( "Insert Field" ); - imageFieldCombo->setName( "Key" ); + lineColorButton->init( "No line", QColor(0,0,0,0), QColor(0,0,0,255) ); + fillColorButton->init( "No fill", QColor(0,0,0,0), QColor(0,0,0,255) ); + textColorButton->init( "Default", QColor(0,0,0,255), QColor(0,0,0,255) ); + shadowColorButton->init( "Default", QColor(0,0,0,255), QColor(0,0,0,255) ); - setEnabled( false ); - hidePages(); + textInsertFieldCombo->setName( "Insert Field" ); + imageFieldCombo->setName( "Key" ); - connect( Settings::instance(), SIGNAL(changed()), this, SLOT(onSettingsChanged()) ); - onSettingsChanged(); -} + setEnabled( false ); + hidePages(); + + connect( Settings::instance(), SIGNAL(changed()), + this, SLOT(onSettingsChanged()) ); + + onSettingsChanged(); + } -void ObjectEditor::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) -{ - mModel = model; - mUndoRedoModel = undoRedoModel; + void ObjectEditor::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) + { + mModel = model; + mUndoRedoModel = undoRedoModel; - connect( mModel, SIGNAL(sizeChanged()), this, SLOT(onLabelSizeChanged()) ); - connect( mModel, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()) ); - connect( mModel, SIGNAL(mergeSourceChanged()), this, SLOT(onMergeSourceChanged()) ); + connect( mModel, SIGNAL(sizeChanged()), + this, SLOT(onLabelSizeChanged()) ); + + connect( mModel, SIGNAL(selectionChanged()), + this, SLOT(onSelectionChanged()) ); + + connect( mModel, SIGNAL(mergeSourceChanged()), + this, SLOT(onMergeSourceChanged()) ); - onLabelSizeChanged(); - onSelectionChanged(); - onMergeSourceChanged(); -} + onLabelSizeChanged(); + onSelectionChanged(); + onMergeSourceChanged(); + } -void ObjectEditor::hidePages() -{ - notebook->removeTab( notebook->indexOf(textPage) ); - notebook->removeTab( notebook->indexOf(barcodePage) ); - notebook->removeTab( notebook->indexOf(imagePage) ); - notebook->removeTab( notebook->indexOf(lineFillPage) ); - notebook->removeTab( notebook->indexOf(posSizePage) ); - notebook->removeTab( notebook->indexOf(shadowPage) ); -} - - -void ObjectEditor::loadImagePage() -{ - if ( mObject ) + void ObjectEditor::hidePages() { - mBlocked = true; - - TextNode filenameNode = mObject->filenameNode(); - - if ( filenameNode.isField() ) - { - imageFilenameLineEdit->setText( QString("${%1}").arg( filenameNode.data() ) ); - } - else - { - imageFilenameLineEdit->setText( filenameNode.data() ); - } - - mBlocked = false; + notebook->removeTab( notebook->indexOf(textPage) ); + notebook->removeTab( notebook->indexOf(barcodePage) ); + notebook->removeTab( notebook->indexOf(imagePage) ); + notebook->removeTab( notebook->indexOf(lineFillPage) ); + notebook->removeTab( notebook->indexOf(posSizePage) ); + notebook->removeTab( notebook->indexOf(shadowPage) ); } -} -void ObjectEditor::loadLineFillPage() -{ - if ( mObject ) - { - mBlocked = true; - - lineWidthSpin->setValue( mObject->lineWidth().pt() ); - lineColorButton->setColorNode( mObject->lineColorNode() ); - fillColorButton->setColorNode( mObject->fillColorNode() ); - - mBlocked = false; - } -} - - -void ObjectEditor::loadPositionPage() -{ - if ( mObject ) - { - mBlocked = true; - - posXSpin->setDecimals( mSpinDigits ); - posXSpin->setSingleStep( mSpinStep ); - posXSpin->setSuffix( " " + mUnits.toIdString() ); - - posYSpin->setDecimals( mSpinDigits ); - posYSpin->setSingleStep( mSpinStep ); - posYSpin->setSuffix( " " + mUnits.toIdString() ); - - posXSpin->setValue( mObject->x0().inUnits(mUnits) ); - posYSpin->setValue( mObject->y0().inUnits(mUnits) ); - - mBlocked = false; - } -} - - -void ObjectEditor::loadRectSizePage() -{ - if ( mObject ) - { - mBlocked = true; - - sizeWSpin->setDecimals( mSpinDigits ); - sizeWSpin->setSingleStep( mSpinStep ); - sizeWSpin->setSuffix( " " + mUnits.toIdString() ); - - sizeHSpin->setDecimals( mSpinDigits ); - sizeHSpin->setSingleStep( mSpinStep ); - sizeHSpin->setSuffix( " " + mUnits.toIdString() ); - - sizeWSpin->setValue( mObject->w().inUnits(mUnits) ); - sizeHSpin->setValue( mObject->h().inUnits(mUnits) ); - - Size originalSize = mObject->originalSize(); - QString originalSizeString = QString( "%1: %2 x %3 %4" ) - .arg( tr("Original size") ) - .arg( originalSize.w().inUnits(mUnits), 0, 'f', mSpinDigits ) - .arg( originalSize.h().inUnits(mUnits), 0, 'f', mSpinDigits ) - .arg( mUnits.toIdString() ); - sizeOriginalSizeLabel->setText( originalSizeString ); - - mBlocked = false; - } -} - - -void ObjectEditor::loadLineSizePage() -{ - if ( mObject ) - { - mBlocked = true; - - sizeLineLengthSpin->setDecimals( mSpinDigits ); - sizeLineLengthSpin->setSingleStep( mSpinStep ); - sizeLineLengthSpin->setSuffix( " " + mUnits.toIdString() ); - - double w = mObject->w().inUnits(mUnits); - double h = mObject->h().inUnits(mUnits); - sizeLineLengthSpin->setValue( sqrt( w*w + h*h ) ); - sizeLineAngleSpin->setValue( qRadiansToDegrees( qAtan2( h, w ) ) ); - - mBlocked = false; - } -} - - -void ObjectEditor::loadTextPage() -{ - if ( mObject ) - { - mBlocked = true; - - textFontFamilyCombo->setCurrentText( mObject->fontFamily() ); - textFontSizeSpin->setValue( mObject->fontSize() ); - textFontBoldToggle->setChecked( mObject->fontWeight() == QFont::Bold ); - textFontItalicToggle->setChecked( mObject->fontItalicFlag() ); - textFontUnderlineToggle->setChecked( mObject->fontUnderlineFlag() ); - textColorButton->setColorNode( mObject->textColorNode() ); - textHAlignGroup->button( mObject->textHAlign() )->setChecked( true ); - textVAlignGroup->button( mObject->textVAlign() )->setChecked( true ); - textLineSpacingSpin->setValue( mObject->textLineSpacing() ); - textEdit->setText( mObject->text() ); - - mBlocked = false; - } -} - - -void ObjectEditor::loadShadowPage() -{ - if ( mObject ) - { - mBlocked = true; - - shadowXSpin->setDecimals( mSpinDigits ); - shadowXSpin->setSingleStep( mSpinStep ); - shadowXSpin->setSuffix( " " + mUnits.toIdString() ); - - shadowYSpin->setDecimals( mSpinDigits ); - shadowYSpin->setSingleStep( mSpinStep ); - shadowYSpin->setSuffix( " " + mUnits.toIdString() ); - - shadowEnableCheck->setChecked( mObject->shadow() ); - shadowXSpin->setValue( mObject->shadowX().inUnits(mUnits) ); - shadowYSpin->setValue( mObject->shadowY().inUnits(mUnits) ); - shadowColorButton->setColorNode( mObject->shadowColorNode() ); - shadowOpacitySpin->setValue( 100*mObject->shadowOpacity() ); - - mBlocked = false; - } -} - - -void ObjectEditor::onSettingsChanged() -{ - mUnits = Settings::units(); - mSpinDigits = mUnits.resolutionDigits(); - mSpinStep = mUnits.resolution(); - - /* Must now update limits and reload any active pages with appropriate units . */ - onLabelSizeChanged(); - onSelectionChanged(); -} - - -void ObjectEditor::onLabelSizeChanged() -{ - if ( mModel ) - { - mBlocked = true; - - glabels::Distance whMax = std::max( mModel->w(), mModel->h() ); - - posXSpin->setRange( -whMax.inUnits(mUnits), 2*whMax.inUnits(mUnits) ); - posYSpin->setRange( -whMax.inUnits(mUnits), 2*whMax.inUnits(mUnits) ); - sizeWSpin->setRange( 0, 2*whMax.inUnits(mUnits) ); - sizeHSpin->setRange( 0, 2*whMax.inUnits(mUnits) ); - - mBlocked = false; - } -} - - -void ObjectEditor::onSelectionChanged() -{ - if ( mModel ) + void ObjectEditor::loadImagePage() { if ( mObject ) { - disconnect( mObject, 0, this, 0 ); - } + mBlocked = true; - hidePages(); + TextNode filenameNode = mObject->filenameNode(); - if ( mModel->isSelectionAtomic() ) - { - mObject = mModel->getFirstSelectedObject(); - - if ( dynamic_cast(mObject) ) + if ( filenameNode.isField() ) { - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-box.png") ); - titleLabel->setText( tr("Box object properties") ); - - notebook->addTab( lineFillPage, "line/fill" ); - notebook->addTab( posSizePage, "position/size" ); - notebook->addTab( shadowPage, "shadow" ); - - fillFrame->setVisible( true ); - sizeRectFrame->setVisible( true ); - sizeOriginalSizeGroup->setVisible( false ); - sizeLineFrame->setVisible( false ); - - loadLineFillPage(); - loadPositionPage(); - loadRectSizePage(); - loadShadowPage(); - - setEnabled( true ); - } - else if ( dynamic_cast(mObject) ) - { - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-ellipse.png") ); - titleLabel->setText( tr("Ellipse object properties") ); - - notebook->addTab( lineFillPage, "line/fill" ); - notebook->addTab( posSizePage, "position/size" ); - notebook->addTab( shadowPage, "shadow" ); - - fillFrame->setVisible( true ); - sizeRectFrame->setVisible( true ); - sizeOriginalSizeGroup->setVisible( false ); - sizeLineFrame->setVisible( false ); - - loadLineFillPage(); - loadPositionPage(); - loadRectSizePage(); - loadShadowPage(); - - setEnabled( true ); - } - else if ( dynamic_cast(mObject) ) - { - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-image.png") ); - titleLabel->setText( tr("Image object properties") ); - - notebook->addTab( imagePage, "image" ); - notebook->addTab( posSizePage, "position/size" ); - notebook->addTab( shadowPage, "shadow" ); - - sizeRectFrame->setVisible( true ); - sizeOriginalSizeGroup->setVisible( true ); - sizeLineFrame->setVisible( false ); - - loadImagePage(); - loadPositionPage(); - loadRectSizePage(); - loadShadowPage(); - - setEnabled( true ); - } - else if ( dynamic_cast(mObject) ) - { - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-line.png") ); - titleLabel->setText( tr("Line object properties") ); - - notebook->addTab( lineFillPage, "line/fill" ); - notebook->addTab( posSizePage, "position/size" ); - notebook->addTab( shadowPage, "shadow" ); - - fillFrame->setVisible( false ); - sizeRectFrame->setVisible( false ); - sizeOriginalSizeGroup->setVisible( false ); - sizeLineFrame->setVisible( true ); - - loadLineFillPage(); - loadPositionPage(); - loadLineSizePage(); - loadShadowPage(); - - setEnabled( true ); - } - else if ( dynamic_cast(mObject) ) - { - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-text.png") ); - titleLabel->setText( tr("Text object properties") ); - - notebook->addTab( textPage, "text" ); - notebook->addTab( posSizePage, "position/size" ); - notebook->addTab( shadowPage, "shadow" ); - - sizeRectFrame->setVisible( true ); - sizeOriginalSizeGroup->setVisible( false ); - sizeLineFrame->setVisible( false ); - - loadTextPage(); - loadPositionPage(); - loadShadowPage(); - - setEnabled( true ); + QString field = QString("${%1}").arg( filenameNode.data() ); + imageFilenameLineEdit->setText( field ); } else { - Q_ASSERT_X( false, "ObjectEditor::onSelectionChanged", "Invalid object" ); + imageFilenameLineEdit->setText( filenameNode.data() ); } - connect( mObject, SIGNAL(changed()), this, SLOT(onObjectChanged()) ); - connect( mObject, SIGNAL(moved()), this, SLOT(onObjectMoved()) ); - connect( mObject, SIGNAL(destroyed(QObject*)), this, SLOT(onObjectDestroyed()) ); + mBlocked = false; } - else + } + + + void ObjectEditor::loadLineFillPage() + { + if ( mObject ) { - mObject = 0; + mBlocked = true; + + lineWidthSpin->setValue( mObject->lineWidth().pt() ); + lineColorButton->setColorNode( mObject->lineColorNode() ); + fillColorButton->setColorNode( mObject->fillColorNode() ); - titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-object-properties.png") ); - titleLabel->setText( "Object properties" ); - setEnabled( false ); + mBlocked = false; } } -} - -void ObjectEditor::onMergeSourceChanged() -{ - if ( !mBlocked ) + + void ObjectEditor::loadPositionPage() { - QStringList keys = mModel->merge()->keys(); - lineColorButton->setKeys( keys ); - fillColorButton->setKeys( keys ); - textInsertFieldCombo->setKeys( keys ); - imageFieldCombo->setKeys( keys ); - shadowColorButton->setKeys( keys ); - } -} - - -void ObjectEditor::onObjectChanged() -{ - if ( !mBlocked ) - { - loadLineFillPage(); - loadRectSizePage(); - loadLineSizePage(); - loadImagePage(); - loadShadowPage(); - } -} - - -void ObjectEditor::onObjectMoved() -{ - if ( !mBlocked ) - { - loadPositionPage(); - } -} - - -void ObjectEditor::onObjectDestroyed() -{ - disconnect( mObject, 0, this, 0 ); - mObject = 0; -} - - -void ObjectEditor::onLineControlsChanged() -{ - if ( !mBlocked ) - { - mBlocked = true; - - mUndoRedoModel->checkpoint( tr("Line") ); - - mObject->setLineWidth( glabels::Distance::pt(lineWidthSpin->value()) ); - mObject->setLineColorNode( lineColorButton->colorNode() ); - - mBlocked = false; - } -} - - -void ObjectEditor::onFillControlsChanged() -{ - if ( !mBlocked ) - { - mBlocked = true; - - mUndoRedoModel->checkpoint( tr("Fill") ); - - mObject->setFillColorNode( fillColorButton->colorNode() ); - - mBlocked = false; - } -} - - -void ObjectEditor::onImageFileButtonClicked() -{ - // Either use saved CWD from a previous open or the current file, if it exists - QString cwd = mImageCwd; - if ( !mObject->filenameNode().isField() ) - { - QFileInfo fileInfo( mObject->filenameNode().data() ); - if ( fileInfo.isFile() ) + if ( mObject ) { - cwd = fileInfo.filePath(); + mBlocked = true; + + posXSpin->setDecimals( mSpinDigits ); + posXSpin->setSingleStep( mSpinStep ); + posXSpin->setSuffix( " " + mUnits.toIdString() ); + + posYSpin->setDecimals( mSpinDigits ); + posYSpin->setSingleStep( mSpinStep ); + posYSpin->setSuffix( " " + mUnits.toIdString() ); + + posXSpin->setValue( mObject->x0().inUnits(mUnits) ); + posYSpin->setValue( mObject->y0().inUnits(mUnits) ); + + mBlocked = false; } } - QString filters = - tr("Image files (*.png *.jpg *.jpeg *.gif *.bmp *.pbm *.pgm *.ppm *.xbm *.xpm *.svg)") + ";;" + - tr("All files (*)") + ";;" + - tr("PNG - Portable Network Graphics (*.png)") + ";;" + - tr("BMP - Windows Bitmap (*.bmp)") + ";;" + - tr("GIF - Graphics Interchange Format (*.gif)") + ";;" + - tr("JPEG - Joint Photographic Experts Group (*.jpg *.jpeg)") + ";;" + - tr("PBM - Portable Bitmap (*.pbm)") + ";;" + - tr("PGM - Portable Graymap (*.pgm)") + ";;" + - tr("PPM - Portable Pixmap (*.ppm)") + ";;" + - tr("SVG - Scalable Vector Graphics (*.svg)") + ";;" + - tr("XBM - X11 Bitmap (*.xbm)") + ";;" + - tr("XPM - X11 Pixmap (*.xpm)"); - - QString filename = - QFileDialog::getOpenFileName( this->window(), - tr("gLabels - Select image file"), - cwd, filters ); - if ( !filename.isEmpty() ) + void ObjectEditor::loadRectSizePage() + { + if ( mObject ) + { + mBlocked = true; + + sizeWSpin->setDecimals( mSpinDigits ); + sizeWSpin->setSingleStep( mSpinStep ); + sizeWSpin->setSuffix( " " + mUnits.toIdString() ); + + sizeHSpin->setDecimals( mSpinDigits ); + sizeHSpin->setSingleStep( mSpinStep ); + sizeHSpin->setSuffix( " " + mUnits.toIdString() ); + + sizeWSpin->setValue( mObject->w().inUnits(mUnits) ); + sizeHSpin->setValue( mObject->h().inUnits(mUnits) ); + + Size originalSize = mObject->originalSize(); + QString originalSizeString = QString( "%1: %2 x %3 %4" ) + .arg( tr("Original size") ) + .arg( originalSize.w().inUnits(mUnits), 0, 'f', mSpinDigits ) + .arg( originalSize.h().inUnits(mUnits), 0, 'f', mSpinDigits ) + .arg( mUnits.toIdString() ); + sizeOriginalSizeLabel->setText( originalSizeString ); + + mBlocked = false; + } + } + + + void ObjectEditor::loadLineSizePage() + { + if ( mObject ) + { + mBlocked = true; + + sizeLineLengthSpin->setDecimals( mSpinDigits ); + sizeLineLengthSpin->setSingleStep( mSpinStep ); + sizeLineLengthSpin->setSuffix( " " + mUnits.toIdString() ); + + double w = mObject->w().inUnits(mUnits); + double h = mObject->h().inUnits(mUnits); + sizeLineLengthSpin->setValue( sqrt( w*w + h*h ) ); + sizeLineAngleSpin->setValue( qRadiansToDegrees( qAtan2( h, w ) ) ); + + mBlocked = false; + } + } + + + void ObjectEditor::loadTextPage() + { + if ( mObject ) + { + mBlocked = true; + + textFontFamilyCombo->setCurrentText( mObject->fontFamily() ); + textFontSizeSpin->setValue( mObject->fontSize() ); + textFontBoldToggle->setChecked( mObject->fontWeight() == QFont::Bold ); + textFontItalicToggle->setChecked( mObject->fontItalicFlag() ); + textFontUnderlineToggle->setChecked( mObject->fontUnderlineFlag() ); + textColorButton->setColorNode( mObject->textColorNode() ); + textHAlignGroup->button( mObject->textHAlign() )->setChecked( true ); + textVAlignGroup->button( mObject->textVAlign() )->setChecked( true ); + textLineSpacingSpin->setValue( mObject->textLineSpacing() ); + textEdit->setText( mObject->text() ); + + mBlocked = false; + } + } + + + void ObjectEditor::loadShadowPage() + { + if ( mObject ) + { + mBlocked = true; + + shadowXSpin->setDecimals( mSpinDigits ); + shadowXSpin->setSingleStep( mSpinStep ); + shadowXSpin->setSuffix( " " + mUnits.toIdString() ); + + shadowYSpin->setDecimals( mSpinDigits ); + shadowYSpin->setSingleStep( mSpinStep ); + shadowYSpin->setSuffix( " " + mUnits.toIdString() ); + + shadowEnableCheck->setChecked( mObject->shadow() ); + shadowXSpin->setValue( mObject->shadowX().inUnits(mUnits) ); + shadowYSpin->setValue( mObject->shadowY().inUnits(mUnits) ); + shadowColorButton->setColorNode( mObject->shadowColorNode() ); + shadowOpacitySpin->setValue( 100*mObject->shadowOpacity() ); + + mBlocked = false; + } + } + + + void ObjectEditor::onSettingsChanged() + { + mUnits = Settings::units(); + mSpinDigits = mUnits.resolutionDigits(); + mSpinStep = mUnits.resolution(); + + /* Must now update limits and reload any active pages with appropriate units. */ + onLabelSizeChanged(); + onSelectionChanged(); + } + + + void ObjectEditor::onLabelSizeChanged() + { + if ( mModel ) + { + mBlocked = true; + + Distance whMax = std::max( mModel->w(), mModel->h() ); + + posXSpin->setRange( -whMax.inUnits(mUnits), 2*whMax.inUnits(mUnits) ); + posYSpin->setRange( -whMax.inUnits(mUnits), 2*whMax.inUnits(mUnits) ); + sizeWSpin->setRange( 0, 2*whMax.inUnits(mUnits) ); + sizeHSpin->setRange( 0, 2*whMax.inUnits(mUnits) ); + + mBlocked = false; + } + } + + + void ObjectEditor::onSelectionChanged() + { + if ( mModel ) + { + if ( mObject ) + { + disconnect( mObject, 0, this, 0 ); + } + + hidePages(); + + if ( mModel->isSelectionAtomic() ) + { + mObject = mModel->getFirstSelectedObject(); + + if ( dynamic_cast(mObject) ) + { + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-box.png") ); + titleLabel->setText( tr("Box object properties") ); + + notebook->addTab( lineFillPage, "line/fill" ); + notebook->addTab( posSizePage, "position/size" ); + notebook->addTab( shadowPage, "shadow" ); + + fillFrame->setVisible( true ); + sizeRectFrame->setVisible( true ); + sizeOriginalSizeGroup->setVisible( false ); + sizeLineFrame->setVisible( false ); + + loadLineFillPage(); + loadPositionPage(); + loadRectSizePage(); + loadShadowPage(); + + setEnabled( true ); + } + else if ( dynamic_cast(mObject) ) + { + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-ellipse.png") ); + titleLabel->setText( tr("Ellipse object properties") ); + + notebook->addTab( lineFillPage, "line/fill" ); + notebook->addTab( posSizePage, "position/size" ); + notebook->addTab( shadowPage, "shadow" ); + + fillFrame->setVisible( true ); + sizeRectFrame->setVisible( true ); + sizeOriginalSizeGroup->setVisible( false ); + sizeLineFrame->setVisible( false ); + + loadLineFillPage(); + loadPositionPage(); + loadRectSizePage(); + loadShadowPage(); + + setEnabled( true ); + } + else if ( dynamic_cast(mObject) ) + { + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-image.png") ); + titleLabel->setText( tr("Image object properties") ); + + notebook->addTab( imagePage, "image" ); + notebook->addTab( posSizePage, "position/size" ); + notebook->addTab( shadowPage, "shadow" ); + + sizeRectFrame->setVisible( true ); + sizeOriginalSizeGroup->setVisible( true ); + sizeLineFrame->setVisible( false ); + + loadImagePage(); + loadPositionPage(); + loadRectSizePage(); + loadShadowPage(); + + setEnabled( true ); + } + else if ( dynamic_cast(mObject) ) + { + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-line.png") ); + titleLabel->setText( tr("Line object properties") ); + + notebook->addTab( lineFillPage, "line/fill" ); + notebook->addTab( posSizePage, "position/size" ); + notebook->addTab( shadowPage, "shadow" ); + + fillFrame->setVisible( false ); + sizeRectFrame->setVisible( false ); + sizeOriginalSizeGroup->setVisible( false ); + sizeLineFrame->setVisible( true ); + + loadLineFillPage(); + loadPositionPage(); + loadLineSizePage(); + loadShadowPage(); + + setEnabled( true ); + } + else if ( dynamic_cast(mObject) ) + { + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-text.png") ); + titleLabel->setText( tr("Text object properties") ); + + notebook->addTab( textPage, "text" ); + notebook->addTab( posSizePage, "position/size" ); + notebook->addTab( shadowPage, "shadow" ); + + sizeRectFrame->setVisible( true ); + sizeOriginalSizeGroup->setVisible( false ); + sizeLineFrame->setVisible( false ); + + loadTextPage(); + loadPositionPage(); + loadShadowPage(); + + setEnabled( true ); + } + else + { + Q_ASSERT_X( false, "ObjectEditor::onSelectionChanged", "Invalid object" ); + } + + connect( mObject, SIGNAL(changed()), this, SLOT(onObjectChanged()) ); + connect( mObject, SIGNAL(moved()), this, SLOT(onObjectMoved()) ); + connect( mObject, SIGNAL(destroyed(QObject*)), this, SLOT(onObjectDestroyed()) ); + } + else + { + mObject = 0; + + titleImageLabel->setPixmap( QPixmap(":icons/24x24/actions/glabels-object-properties.png") ); + titleLabel->setText( "Object properties" ); + setEnabled( false ); + } + } + } + + + void ObjectEditor::onMergeSourceChanged() + { + if ( !mBlocked ) + { + QStringList keys = mModel->merge()->keys(); + lineColorButton->setKeys( keys ); + fillColorButton->setKeys( keys ); + textInsertFieldCombo->setKeys( keys ); + imageFieldCombo->setKeys( keys ); + shadowColorButton->setKeys( keys ); + } + } + + + void ObjectEditor::onObjectChanged() + { + if ( !mBlocked ) + { + loadLineFillPage(); + loadRectSizePage(); + loadLineSizePage(); + loadImagePage(); + loadShadowPage(); + } + } + + + void ObjectEditor::onObjectMoved() + { + if ( !mBlocked ) + { + loadPositionPage(); + } + } + + + void ObjectEditor::onObjectDestroyed() + { + disconnect( mObject, 0, this, 0 ); + mObject = 0; + } + + + void ObjectEditor::onLineControlsChanged() + { + if ( !mBlocked ) + { + mBlocked = true; + + mUndoRedoModel->checkpoint( tr("Line") ); + + mObject->setLineWidth( Distance::pt(lineWidthSpin->value()) ); + mObject->setLineColorNode( lineColorButton->colorNode() ); + + mBlocked = false; + } + } + + + void ObjectEditor::onFillControlsChanged() + { + if ( !mBlocked ) + { + mBlocked = true; + + mUndoRedoModel->checkpoint( tr("Fill") ); + + mObject->setFillColorNode( fillColorButton->colorNode() ); + + mBlocked = false; + } + } + + + void ObjectEditor::onImageFileButtonClicked() + { + // Either use saved CWD from a previous open or the current file, if it exists + QString cwd = mImageCwd; + if ( !mObject->filenameNode().isField() ) + { + QFileInfo fileInfo( mObject->filenameNode().data() ); + if ( fileInfo.isFile() ) + { + cwd = fileInfo.filePath(); + } + } + + QString filters = + tr("Image files (*.png *.jpg *.jpeg *.gif *.bmp *.pbm *.pgm *.ppm *.xbm *.xpm *.svg)") + ";;" + + tr("All files (*)") + ";;" + + tr("PNG - Portable Network Graphics (*.png)") + ";;" + + tr("BMP - Windows Bitmap (*.bmp)") + ";;" + + tr("GIF - Graphics Interchange Format (*.gif)") + ";;" + + tr("JPEG - Joint Photographic Experts Group (*.jpg *.jpeg)") + ";;" + + tr("PBM - Portable Bitmap (*.pbm)") + ";;" + + tr("PGM - Portable Graymap (*.pgm)") + ";;" + + tr("PPM - Portable Pixmap (*.ppm)") + ";;" + + tr("SVG - Scalable Vector Graphics (*.svg)") + ";;" + + tr("XBM - X11 Bitmap (*.xbm)") + ";;" + + tr("XPM - X11 Pixmap (*.xpm)"); + + QString filename = + QFileDialog::getOpenFileName( this->window(), + tr("gLabels - Select image file"), + cwd, filters ); + + if ( !filename.isEmpty() ) + { + mUndoRedoModel->checkpoint( tr("Set image") ); + mObject->setFilenameNode( TextNode( false, filename ) ); + + // Save CWD for next open + QFileInfo fileInfo( filename ); + mImageCwd = fileInfo.absolutePath(); + } + } + + + void ObjectEditor::onImageKeySelected( QString key ) { mUndoRedoModel->checkpoint( tr("Set image") ); - mObject->setFilenameNode( TextNode( false, filename ) ); - - // Save CWD for next open - QFileInfo fileInfo( filename ); - mImageCwd = fileInfo.absolutePath(); + mObject->setFilenameNode( TextNode( true, key ) ); } -} -void ObjectEditor::onImageKeySelected( QString key ) -{ - mUndoRedoModel->checkpoint( tr("Set image") ); - mObject->setFilenameNode( TextNode( true, key ) ); -} - - -void ObjectEditor::onPositionControlsChanged() -{ - if ( !mBlocked ) + void ObjectEditor::onPositionControlsChanged() { - mBlocked = true; - - mUndoRedoModel->checkpoint( tr("Move") ); - - glabels::Distance x = glabels::Distance(posXSpin->value(), mUnits); - glabels::Distance y = glabels::Distance(posYSpin->value(), mUnits); - - mObject->setPosition( x, y ); - - mBlocked = false; - } -} - - -void ObjectEditor::onRectSizeControlsChanged() -{ - if ( !mBlocked ) - { - mBlocked = true; - - mUndoRedoModel->checkpoint( tr("Size") ); - - glabels::Distance spinW = glabels::Distance(sizeWSpin->value(), mUnits); - glabels::Distance spinH = glabels::Distance(sizeHSpin->value(), mUnits); - - if ( sizeAspectCheck->isChecked() ) + if ( !mBlocked ) { - if ( fabs(spinW - mObject->w()) > fabs(spinH - mObject->h()) ) + mBlocked = true; + + mUndoRedoModel->checkpoint( tr("Move") ); + + Distance x = Distance(posXSpin->value(), mUnits); + Distance y = Distance(posYSpin->value(), mUnits); + + mObject->setPosition( x, y ); + + mBlocked = false; + } + } + + + void ObjectEditor::onRectSizeControlsChanged() + { + if ( !mBlocked ) + { + mBlocked = true; + + mUndoRedoModel->checkpoint( tr("Size") ); + + Distance spinW = Distance(sizeWSpin->value(), mUnits); + Distance spinH = Distance(sizeHSpin->value(), mUnits); + + if ( sizeAspectCheck->isChecked() ) { - mObject->setWHonorAspect( spinW ); - sizeHSpin->setValue( mObject->h().inUnits(mUnits) ); + if ( fabs(spinW - mObject->w()) > fabs(spinH - mObject->h()) ) + { + mObject->setWHonorAspect( spinW ); + sizeHSpin->setValue( mObject->h().inUnits(mUnits) ); + } + else + { + mObject->setHHonorAspect( spinH ); + sizeWSpin->setValue( mObject->w().inUnits(mUnits) ); + } } else { - mObject->setHHonorAspect( spinH ); - sizeWSpin->setValue( mObject->w().inUnits(mUnits) ); + mObject->setSize( spinW, spinH ); } + + mBlocked = false; } - else + } + + + void ObjectEditor::onLineSizeControlsChanged() + { + if ( !mBlocked ) { - mObject->setSize( spinW, spinH ); - } + mBlocked = true; - mBlocked = false; - } -} - - -void ObjectEditor::onLineSizeControlsChanged() -{ - if ( !mBlocked ) - { - mBlocked = true; - - mUndoRedoModel->checkpoint( tr("Size") ); + mUndoRedoModel->checkpoint( tr("Size") ); - glabels::Distance spinLength = glabels::Distance(sizeLineLengthSpin->value(), mUnits); - double spinAngleRads = qDegreesToRadians( sizeLineAngleSpin->value() ); + Distance spinLength = Distance(sizeLineLengthSpin->value(), mUnits); + double spinAngleRads = qDegreesToRadians( sizeLineAngleSpin->value() ); - mObject->setSize( spinLength*qCos(spinAngleRads), spinLength*qSin(spinAngleRads) ); + mObject->setSize( spinLength*qCos(spinAngleRads), + spinLength*qSin(spinAngleRads) ); - mBlocked = false; + mBlocked = false; + } } -} -void ObjectEditor::onTextControlsChanged() -{ - if ( !mBlocked ) + void ObjectEditor::onTextControlsChanged() { - mBlocked = true; + if ( !mBlocked ) + { + mBlocked = true; - mUndoRedoModel->checkpoint( tr("Text") ); + mUndoRedoModel->checkpoint( tr("Text") ); - mObject->setFontFamily( textFontFamilyCombo->currentText() ); - mObject->setFontSize( textFontSizeSpin->value() ); - mObject->setFontWeight( textFontBoldToggle->isChecked() ? QFont::Bold : QFont::Normal ); - mObject->setFontItalicFlag( textFontItalicToggle->isChecked() ); - mObject->setFontUnderlineFlag( textFontUnderlineToggle->isChecked() ); - mObject->setTextColorNode( textColorButton->colorNode() ); - mObject->setTextHAlign( Qt::AlignmentFlag( textHAlignGroup->checkedId() ) ); - mObject->setTextVAlign( Qt::AlignmentFlag( textVAlignGroup->checkedId() ) ); - mObject->setTextLineSpacing( textLineSpacingSpin->value() ); - mObject->setText( textEdit->toPlainText() ); + mObject->setFontFamily( textFontFamilyCombo->currentText() ); + mObject->setFontSize( textFontSizeSpin->value() ); + mObject->setFontWeight( textFontBoldToggle->isChecked() ? QFont::Bold : QFont::Normal ); + mObject->setFontItalicFlag( textFontItalicToggle->isChecked() ); + mObject->setFontUnderlineFlag( textFontUnderlineToggle->isChecked() ); + mObject->setTextColorNode( textColorButton->colorNode() ); + mObject->setTextHAlign( Qt::AlignmentFlag( textHAlignGroup->checkedId() ) ); + mObject->setTextVAlign( Qt::AlignmentFlag( textVAlignGroup->checkedId() ) ); + mObject->setTextLineSpacing( textLineSpacingSpin->value() ); + mObject->setText( textEdit->toPlainText() ); - mBlocked = false; + mBlocked = false; + } } -} -void ObjectEditor::onTextInsertFieldKeySelected( QString key ) -{ - textEdit->insertPlainText( "${" + key + "}" ); -} - - -void ObjectEditor::onResetImageSize() -{ - mObject->setSize( mObject->originalSize() ); -} - - -void ObjectEditor::onShadowControlsChanged() -{ - if ( !mBlocked ) + void ObjectEditor::onTextInsertFieldKeySelected( QString key ) { - mBlocked = true; + textEdit->insertPlainText( "${" + key + "}" ); + } - mUndoRedoModel->checkpoint( tr("Shadow") ); + + void ObjectEditor::onResetImageSize() + { + mObject->setSize( mObject->originalSize() ); + } + + + void ObjectEditor::onShadowControlsChanged() + { + if ( !mBlocked ) + { + mBlocked = true; + + mUndoRedoModel->checkpoint( tr("Shadow") ); - mObject->setShadow( shadowEnableCheck->isChecked() ); - mObject->setShadowX( glabels::Distance(shadowXSpin->value(), mUnits) ); - mObject->setShadowY( glabels::Distance(shadowYSpin->value(), mUnits) ); - mObject->setShadowColorNode( shadowColorButton->colorNode() ); - mObject->setShadowOpacity( shadowOpacitySpin->value()/100.0 ); + mObject->setShadow( shadowEnableCheck->isChecked() ); + mObject->setShadowX( Distance(shadowXSpin->value(), mUnits) ); + mObject->setShadowY( Distance(shadowYSpin->value(), mUnits) ); + mObject->setShadowColorNode( shadowColorButton->colorNode() ); + mObject->setShadowOpacity( shadowOpacitySpin->value()/100.0 ); - mBlocked = false; + mBlocked = false; + } } -} -void ObjectEditor::onChanged() -{ - if ( !mBlocked ) + void ObjectEditor::onChanged() { - mBlocked = true; + if ( !mBlocked ) + { + mBlocked = true; - qDebug() << "Form changed."; + qDebug() << "Form changed."; - mBlocked = false; + mBlocked = false; + } } + } diff --git a/glabels/ObjectEditor.h b/glabels/ObjectEditor.h index d6cb2b8..393d7b3 100644 --- a/glabels/ObjectEditor.h +++ b/glabels/ObjectEditor.h @@ -28,92 +28,98 @@ #include "Distance.h" -// Forward references -class LabelModel; -class LabelModelObject; -class UndoRedoModel; - -/// -/// Object Editor Widget -/// -class ObjectEditor : public QWidget, public Ui_ObjectEditor +namespace glabels { - Q_OBJECT + + // Forward references + class LabelModel; + class LabelModelObject; + class UndoRedoModel; + + + /// + /// Object Editor Widget + /// + class ObjectEditor : public QWidget, public Ui_ObjectEditor + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - ObjectEditor( QWidget *parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + ObjectEditor( QWidget *parent = 0 ); - ///////////////////////////////// - // Public methods - ///////////////////////////////// - void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); + ///////////////////////////////// + // Public methods + ///////////////////////////////// + void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); - ///////////////////////////////// - // Private methods - ///////////////////////////////// -private: - void hidePages(); - void loadImagePage(); - void loadLineFillPage(); - void loadPositionPage(); - void loadRectSizePage(); - void loadLineSizePage(); - void loadTextPage(); - void loadShadowPage(); + ///////////////////////////////// + // Private methods + ///////////////////////////////// + private: + void hidePages(); + void loadImagePage(); + void loadLineFillPage(); + void loadPositionPage(); + void loadRectSizePage(); + void loadLineSizePage(); + void loadTextPage(); + void loadShadowPage(); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onSettingsChanged(); - void onLabelSizeChanged(); - void onSelectionChanged(); - void onMergeSourceChanged(); - void onObjectChanged(); - void onObjectMoved(); - void onObjectDestroyed(); - void onLineControlsChanged(); - void onFillControlsChanged(); - void onImageFileButtonClicked(); - void onImageKeySelected( QString key ); - void onPositionControlsChanged(); - void onRectSizeControlsChanged(); - void onLineSizeControlsChanged(); - void onTextControlsChanged(); - void onTextInsertFieldKeySelected( QString key ); - void onResetImageSize(); - void onShadowControlsChanged(); - void onChanged(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onSettingsChanged(); + void onLabelSizeChanged(); + void onSelectionChanged(); + void onMergeSourceChanged(); + void onObjectChanged(); + void onObjectMoved(); + void onObjectDestroyed(); + void onLineControlsChanged(); + void onFillControlsChanged(); + void onImageFileButtonClicked(); + void onImageKeySelected( QString key ); + void onPositionControlsChanged(); + void onRectSizeControlsChanged(); + void onLineSizeControlsChanged(); + void onTextControlsChanged(); + void onTextInsertFieldKeySelected( QString key ); + void onResetImageSize(); + void onShadowControlsChanged(); + void onChanged(); - ///////////////////////////////// - // Private data - ///////////////////////////////// -private: - LabelModel* mModel; - LabelModelObject* mObject; - UndoRedoModel* mUndoRedoModel; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + LabelModel* mModel; + LabelModelObject* mObject; + UndoRedoModel* mUndoRedoModel; - glabels::Units mUnits; - int mSpinDigits; - double mSpinStep; + Units mUnits; + int mSpinDigits; + double mSpinStep; - QButtonGroup* textHAlignGroup; - QButtonGroup* textVAlignGroup; + QButtonGroup* textHAlignGroup; + QButtonGroup* textVAlignGroup; - QString mImageCwd; + QString mImageCwd; - bool mBlocked; + bool mBlocked; -}; + }; + +} #endif // ObjectEditor_h diff --git a/glabels/Outline.cpp b/glabels/Outline.cpp index cc58a34..29b01be 100644 --- a/glabels/Outline.cpp +++ b/glabels/Outline.cpp @@ -26,104 +26,111 @@ #include "LabelModelObject.h" -namespace +namespace glabels { - const qreal dashSize = 2; - const double slopPixels = 2; - const double outlineWidthPixels = 1; - const QColor outlineColor1( 0, 0, 0 ); - const QColor outlineColor2( 255, 255, 255 ); -} + // + // Private + // + namespace + { + const qreal dashSize = 2; + + const double slopPixels = 2; + const double outlineWidthPixels = 1; + const QColor outlineColor1( 0, 0, 0 ); + const QColor outlineColor2( 255, 255, 255 ); + } -/// -/// Outline Constructor -/// -Outline::Outline( LabelModelObject* owner ) - : mOwner(owner) -{ - mDashes << dashSize << dashSize; + /// + /// Outline Constructor + /// + Outline::Outline( LabelModelObject* owner ) + : mOwner(owner) + { + mDashes << dashSize << dashSize; - mPen1.setColor( outlineColor1 ); - mPen1.setWidth( outlineWidthPixels ); - mPen1.setCosmetic( true ); - mPen1.setCapStyle( Qt::FlatCap ); - mPen1.setDashPattern( mDashes ); + mPen1.setColor( outlineColor1 ); + mPen1.setWidth( outlineWidthPixels ); + mPen1.setCosmetic( true ); + mPen1.setCapStyle( Qt::FlatCap ); + mPen1.setDashPattern( mDashes ); - mPen2.setColor( outlineColor2 ); - mPen2.setWidth( outlineWidthPixels ); - mPen2.setCosmetic( true ); - mPen2.setCapStyle( Qt::FlatCap ); - mPen2.setDashPattern( mDashes ); - mPen2.setDashOffset( dashSize ); -} + mPen2.setColor( outlineColor2 ); + mPen2.setWidth( outlineWidthPixels ); + mPen2.setCosmetic( true ); + mPen2.setCapStyle( Qt::FlatCap ); + mPen2.setDashPattern( mDashes ); + mPen2.setDashOffset( dashSize ); + } -/// -/// Outline Copy constructor -/// -Outline::Outline( const Outline* outline, LabelModelObject* newOwner ) - : mOwner(newOwner) -{ - mDashes = outline->mDashes; - mPen1 = outline->mPen1; - mPen2 = outline->mPen2; -} + /// + /// Outline Copy constructor + /// + Outline::Outline( const Outline* outline, LabelModelObject* newOwner ) + : mOwner(newOwner) + { + mDashes = outline->mDashes; + mPen1 = outline->mPen1; + mPen2 = outline->mPen2; + } -/// -/// Outline Destructor -/// -Outline::~Outline() -{ -} + /// + /// Outline Destructor + /// + Outline::~Outline() + { + // empty + } -/// -/// Clone Outline -/// -Outline* Outline::clone( LabelModelObject* newOwner ) const -{ - return new Outline( this, newOwner ); -} + /// + /// Clone Outline + /// + Outline* Outline::clone( LabelModelObject* newOwner ) const + { + return new Outline( this, newOwner ); + } -/// -/// Draw Outline -/// -void Outline::draw( QPainter* painter ) const -{ - painter->save(); + /// + /// Draw Outline + /// + void Outline::draw( QPainter* painter ) const + { + painter->save(); - painter->setBrush( Qt::NoBrush ); + painter->setBrush( Qt::NoBrush ); - painter->setPen( mPen1 ); - painter->drawRect( QRectF( 0, 0, mOwner->w().pt(), mOwner->h().pt() ) ); + painter->setPen( mPen1 ); + painter->drawRect( QRectF( 0, 0, mOwner->w().pt(), mOwner->h().pt() ) ); - painter->setPen( mPen2 ); - painter->drawRect( QRectF( 0, 0, mOwner->w().pt(), mOwner->h().pt() ) ); + painter->setPen( mPen2 ); + painter->drawRect( QRectF( 0, 0, mOwner->w().pt(), mOwner->h().pt() ) ); - painter->restore(); -} + painter->restore(); + } -/// -/// Create path for testing for hover condition -/// -QPainterPath Outline::hoverPath( double scale ) const -{ - double s = 1 / scale; + /// + /// Create path for testing for hover condition + /// + QPainterPath Outline::hoverPath( double scale ) const + { + double s = 1 / scale; - QPainterPath path; + QPainterPath path; - path.addRect( -s*slopPixels, -s*slopPixels, - mOwner->w().pt()+s*2*slopPixels, mOwner->h().pt()+s*2*slopPixels ); - path.closeSubpath(); - path.addRect( s*slopPixels, s*slopPixels, - mOwner->w().pt()-s*2*slopPixels, mOwner->h().pt()-s*2*slopPixels ); + path.addRect( -s*slopPixels, -s*slopPixels, + mOwner->w().pt()+s*2*slopPixels, mOwner->h().pt()+s*2*slopPixels ); + path.closeSubpath(); + path.addRect( s*slopPixels, s*slopPixels, + mOwner->w().pt()-s*2*slopPixels, mOwner->h().pt()-s*2*slopPixels ); - return path; + return path; + } + } - - diff --git a/glabels/Outline.h b/glabels/Outline.h index 260c14d..6fa2258 100644 --- a/glabels/Outline.h +++ b/glabels/Outline.h @@ -25,49 +25,55 @@ #include #include -// Forward references -class LabelModelObject; - -/// -/// Outline Base Class -/// -class Outline +namespace glabels { - //////////////////////////// - // Lifecycle Methods - //////////////////////////// -public: - Outline( LabelModelObject* owner ); - Outline( const Outline* outline, LabelModelObject* newOwner ); - virtual ~Outline(); + + // Forward references + class LabelModelObject; + + + /// + /// Outline Base Class + /// + class Outline + { + //////////////////////////// + // Lifecycle Methods + //////////////////////////// + public: + Outline( LabelModelObject* owner ); + Outline( const Outline* outline, LabelModelObject* newOwner ); + virtual ~Outline(); - //////////////////////////// - // Duplication - //////////////////////////// - Outline* clone( LabelModelObject* newOwner ) const; + //////////////////////////// + // Duplication + //////////////////////////// + Outline* clone( LabelModelObject* newOwner ) const; - //////////////////////////// - // Drawing Methods - //////////////////////////// -public: - void draw( QPainter* painter ) const; - QPainterPath hoverPath( double scale ) const; + //////////////////////////// + // Drawing Methods + //////////////////////////// + public: + void draw( QPainter* painter ) const; + QPainterPath hoverPath( double scale ) const; - //////////////////////////// - // Private Data - //////////////////////////// -private: - LabelModelObject* mOwner; + //////////////////////////// + // Private Data + //////////////////////////// + private: + LabelModelObject* mOwner; - QVector mDashes; - QPen mPen1; - QPen mPen2; + QVector mDashes; + QPen mPen1; + QPen mPen2; -}; + }; + +} #endif // Outline_h diff --git a/glabels/PageRenderer.cpp b/glabels/PageRenderer.cpp index 5367dbc..3b99ba2 100644 --- a/glabels/PageRenderer.cpp +++ b/glabels/PageRenderer.cpp @@ -30,363 +30,370 @@ #include "Merge/Record.h" -namespace +namespace glabels { - const QColor labelOutlineColor( 0, 0, 0 ); - const double labelOutlineWidth = 0.25; - const double tickOffset = 2.25; - const double tickLength = 18; -} - - -PageRenderer::PageRenderer() - : mModel(0), mNCopies(0), mStartLabel(0), - mPrintOutlines(false), mPrintCropMarks(false), mPrintReverse(false), - mIsMerge(false), mIPage(0), mNPages(0) -{ -} - - -void PageRenderer::setModel( const LabelModel* model ) -{ - mModel = model; - - connect( mModel, SIGNAL(changed()), this, SLOT(onModelChanged()) ); - onModelChanged(); -} - - -const LabelModel* PageRenderer::model() const -{ - return mModel; -} - - -void PageRenderer::onModelChanged() -{ - mMerge = mModel->merge(); - mOrigins = mModel->frame()->getOrigins(); - mNLabelsPerPage = mModel->frame()->nLabels(); - mIsMerge = ( dynamic_cast(mMerge) == 0 ); - updateNPages(); - - emit changed(); -} - - -void PageRenderer::setNCopies( int nCopies ) -{ - mNCopies = nCopies; - updateNPages(); - - emit changed(); -} - - -void PageRenderer::setStartLabel( int startLabel ) -{ - mStartLabel = startLabel; - updateNPages(); - - emit changed(); -} - - -void PageRenderer::setPrintOutlines( bool printOutlinesFlag ) -{ - mPrintOutlines = printOutlinesFlag; - - emit changed(); -} - - -void PageRenderer::setPrintCropMarks( bool printCropMarksFlag ) -{ - mPrintCropMarks = printCropMarksFlag; - - emit changed(); -} - - -void PageRenderer::setPrintReverse( bool printReverseFlag ) -{ - mPrintReverse = printReverseFlag; - - emit changed(); -} - - -void PageRenderer::setIPage( int iPage ) -{ - mIPage = iPage; - - emit changed(); -} - - -int PageRenderer::nItems() const -{ - return mLastLabel - mStartLabel; -} - - -int PageRenderer::nPages() const -{ - return mNPages; -} - - -QRectF PageRenderer::pageRect() const -{ - if ( mModel ) + // + // Private + // + namespace { - return QRectF( 0, 0, mModel->tmplate()->pageWidth().pt(), mModel->tmplate()->pageHeight().pt() ); + const QColor labelOutlineColor( 0, 0, 0 ); + const double labelOutlineWidth = 0.25; + const double tickOffset = 2.25; + const double tickLength = 18; } - else + + + PageRenderer::PageRenderer() + : mModel(0), mNCopies(0), mStartLabel(0), + mPrintOutlines(false), mPrintCropMarks(false), mPrintReverse(false), + mIsMerge(false), mIPage(0), mNPages(0) { - return QRectF( 0, 0, 0, 0 ); + // empty + } + + + void PageRenderer::setModel( const LabelModel* model ) + { + mModel = model; + + connect( mModel, SIGNAL(changed()), this, SLOT(onModelChanged()) ); + + onModelChanged(); + } + + + const LabelModel* PageRenderer::model() const + { + return mModel; + } + + + void PageRenderer::onModelChanged() + { + mMerge = mModel->merge(); + mOrigins = mModel->frame()->getOrigins(); + mNLabelsPerPage = mModel->frame()->nLabels(); + mIsMerge = ( dynamic_cast(mMerge) == 0 ); + updateNPages(); + + emit changed(); + } + + + void PageRenderer::setNCopies( int nCopies ) + { + mNCopies = nCopies; + updateNPages(); + + emit changed(); + } + + + void PageRenderer::setStartLabel( int startLabel ) + { + mStartLabel = startLabel; + updateNPages(); + + emit changed(); + } + + + void PageRenderer::setPrintOutlines( bool printOutlinesFlag ) + { + mPrintOutlines = printOutlinesFlag; + + emit changed(); + } + + + void PageRenderer::setPrintCropMarks( bool printCropMarksFlag ) + { + mPrintCropMarks = printCropMarksFlag; + + emit changed(); + } + + + void PageRenderer::setPrintReverse( bool printReverseFlag ) + { + mPrintReverse = printReverseFlag; + + emit changed(); + } + + + void PageRenderer::setIPage( int iPage ) + { + mIPage = iPage; + + emit changed(); + } + + + int PageRenderer::nItems() const + { + return mLastLabel - mStartLabel; } -} -void PageRenderer::updateNPages() -{ - if ( mModel ) + int PageRenderer::nPages() const { - if ( mIsMerge ) + return mNPages; + } + + + QRectF PageRenderer::pageRect() const + { + if ( mModel ) { - mLastLabel = mStartLabel + mNCopies*mMerge->nSelectedRecords(); + return QRectF( 0, 0, mModel->tmplate()->pageWidth().pt(), mModel->tmplate()->pageHeight().pt() ); } else { - mLastLabel = mStartLabel + mNCopies; + return QRectF( 0, 0, 0, 0 ); } + } + + + void PageRenderer::updateNPages() + { + if ( mModel ) + { + if ( mIsMerge ) + { + mLastLabel = mStartLabel + mNCopies*mMerge->nSelectedRecords(); + } + else + { + mLastLabel = mStartLabel + mNCopies; + } - mNPages = mLastLabel / mNLabelsPerPage; - if ( mLastLabel % mNLabelsPerPage ) - { - mNPages++; - } - } - else - { - mNPages = 0; - } -} - - -/// -/// Print page using persistent page number -/// -void PageRenderer::printPage( QPainter* painter ) const -{ - printPage( painter, mIPage ); -} - - -/// -/// Print page -/// -void PageRenderer::printPage( QPainter* painter, int iPage ) const -{ - if ( mModel ) - { - if ( mIsMerge ) - { - printMergePage( painter, iPage ); + mNPages = mLastLabel / mNLabelsPerPage; + if ( mLastLabel % mNLabelsPerPage ) + { + mNPages++; + } } else { - printSimplePage( painter, iPage ); + mNPages = 0; } } -} - - -void PageRenderer::printSimplePage( QPainter* painter, int iPage ) const -{ - int iStart = 0; - int iEnd = mNLabelsPerPage; - - if ( iPage == 0 ) - { - iStart = mStartLabel; - } - - if ( (mLastLabel / mNLabelsPerPage) == iPage ) - { - iEnd = mLastLabel % mNLabelsPerPage; - } - - printCropMarks( painter ); - - for ( int i = iStart; i < iEnd; i++ ) - { - painter->save(); - - painter->translate( mOrigins[i].x().pt(), mOrigins[i].y().pt() ); - - painter->save(); - - clipLabel( painter ); - printLabel( painter, 0 ); - - painter->restore(); // From before clip - - printOutline( painter ); - - painter->restore(); // From before translation - } -} -void PageRenderer::printMergePage( QPainter* painter, int iPage ) const -{ - int iRecord = 0; - int iStart = 0; - int iEnd = mNLabelsPerPage; - - if ( iPage == 0 ) + /// + /// Print page using persistent page number + /// + void PageRenderer::printPage( QPainter* painter ) const { - iStart = mStartLabel; + printPage( painter, mIPage ); } - if ( (mLastLabel / mNLabelsPerPage) == iPage ) + + /// + /// Print page + /// + void PageRenderer::printPage( QPainter* painter, int iPage ) const { - iEnd = mLastLabel % mNLabelsPerPage; - } - - const QList records = mMerge->selectedRecords(); - if ( records.size() ) - { - iRecord = (iPage*mNLabelsPerPage + iStart - mStartLabel) % records.size(); - } - - printCropMarks( painter ); - - for ( int i = iStart; i < iEnd; i++ ) - { - painter->save(); - - painter->translate( mOrigins[i].x().pt(), mOrigins[i].y().pt() ); - - painter->save(); - - clipLabel( painter ); - printLabel( painter, records[iRecord] ); - - painter->restore(); // From before clip - - printOutline( painter ); - - painter->restore(); // From before translation - - iRecord = (iRecord + 1) % records.size(); - } -} - - -void PageRenderer::printCropMarks( QPainter* painter ) const -{ - using namespace glabels; - - if ( mPrintCropMarks ) - { - painter->save(); - - painter->setBrush( QBrush( Qt::NoBrush ) ); - painter->setPen( QPen( labelOutlineColor, labelOutlineWidth ) ); - - Distance w = mModel->frame()->w(); - Distance h = mModel->frame()->h(); - - foreach ( Layout* layout, mModel->frame()->layouts() ) + if ( mModel ) { - Distance xMin = layout->x0(); - Distance yMin = layout->y0(); - Distance xMax = layout->x0() + layout->dx()*(layout->nx()-1) + w; - Distance yMax = layout->y0() + layout->dy()*(layout->ny()-1) + h; - - for ( int ix = 0; ix < layout->nx(); ix++ ) + if ( mIsMerge ) { - Distance x1 = xMin + ix*layout->dx(); - Distance x2 = x1 + w; - - Distance y1 = max( yMin-tickOffset, Distance::pt(0) ); - Distance y2 = max( y1-tickLength, Distance::pt(0) ); - - Distance y3 = min( yMax+tickOffset, mModel->tmplate()->pageHeight() ); - Distance y4 = min( y3+tickLength, mModel->tmplate()->pageHeight() ); - - painter->drawLine( x1.pt(), y1.pt(), x1.pt(), y2.pt() ); - painter->drawLine( x2.pt(), y1.pt(), x2.pt(), y2.pt() ); - painter->drawLine( x1.pt(), y3.pt(), x1.pt(), y4.pt() ); - painter->drawLine( x2.pt(), y3.pt(), x2.pt(), y4.pt() ); + printMergePage( painter, iPage ); } - - for ( int iy = 0; iy < layout->ny(); iy++ ) + else { - Distance y1 = yMin + iy*layout->dy(); - Distance y2 = y1 + h; - - Distance x1 = max( xMin-tickOffset, Distance::pt(0) ); - Distance x2 = max( x1-tickLength, Distance::pt(0) ); - - Distance x3 = min( xMax+tickOffset, mModel->tmplate()->pageWidth() ); - Distance x4 = min( x3+tickLength, mModel->tmplate()->pageWidth() ); - - painter->drawLine( x1.pt(), y1.pt(), x2.pt(), y1.pt() ); - painter->drawLine( x1.pt(), y2.pt(), x2.pt(), y2.pt() ); - painter->drawLine( x3.pt(), y1.pt(), x4.pt(), y1.pt() ); - painter->drawLine( x3.pt(), y2.pt(), x4.pt(), y2.pt() ); + printSimplePage( painter, iPage ); } } - - painter->restore(); } -} + + + void PageRenderer::printSimplePage( QPainter* painter, int iPage ) const + { + int iStart = 0; + int iEnd = mNLabelsPerPage; + + if ( iPage == 0 ) + { + iStart = mStartLabel; + } + + if ( (mLastLabel / mNLabelsPerPage) == iPage ) + { + iEnd = mLastLabel % mNLabelsPerPage; + } + + printCropMarks( painter ); + + for ( int i = iStart; i < iEnd; i++ ) + { + painter->save(); + + painter->translate( mOrigins[i].x().pt(), mOrigins[i].y().pt() ); + + painter->save(); + + clipLabel( painter ); + printLabel( painter, 0 ); + + painter->restore(); // From before clip + + printOutline( painter ); + + painter->restore(); // From before translation + } + } -void PageRenderer::printOutline( QPainter* painter ) const -{ - if ( mPrintOutlines ) + void PageRenderer::printMergePage( QPainter* painter, int iPage ) const + { + int iRecord = 0; + int iStart = 0; + int iEnd = mNLabelsPerPage; + + if ( iPage == 0 ) + { + iStart = mStartLabel; + } + + if ( (mLastLabel / mNLabelsPerPage) == iPage ) + { + iEnd = mLastLabel % mNLabelsPerPage; + } + + const QList records = mMerge->selectedRecords(); + if ( records.size() ) + { + iRecord = (iPage*mNLabelsPerPage + iStart - mStartLabel) % records.size(); + } + + printCropMarks( painter ); + + for ( int i = iStart; i < iEnd; i++ ) + { + painter->save(); + + painter->translate( mOrigins[i].x().pt(), mOrigins[i].y().pt() ); + + painter->save(); + + clipLabel( painter ); + printLabel( painter, records[iRecord] ); + + painter->restore(); // From before clip + + printOutline( painter ); + + painter->restore(); // From before translation + + iRecord = (iRecord + 1) % records.size(); + } + } + + + void PageRenderer::printCropMarks( QPainter* painter ) const + { + if ( mPrintCropMarks ) + { + painter->save(); + + painter->setBrush( QBrush( Qt::NoBrush ) ); + painter->setPen( QPen( labelOutlineColor, labelOutlineWidth ) ); + + Distance w = mModel->frame()->w(); + Distance h = mModel->frame()->h(); + + foreach ( Layout* layout, mModel->frame()->layouts() ) + { + Distance xMin = layout->x0(); + Distance yMin = layout->y0(); + Distance xMax = layout->x0() + layout->dx()*(layout->nx()-1) + w; + Distance yMax = layout->y0() + layout->dy()*(layout->ny()-1) + h; + + for ( int ix = 0; ix < layout->nx(); ix++ ) + { + Distance x1 = xMin + ix*layout->dx(); + Distance x2 = x1 + w; + + Distance y1 = max( yMin-tickOffset, Distance::pt(0) ); + Distance y2 = max( y1-tickLength, Distance::pt(0) ); + + Distance y3 = min( yMax+tickOffset, mModel->tmplate()->pageHeight() ); + Distance y4 = min( y3+tickLength, mModel->tmplate()->pageHeight() ); + + painter->drawLine( x1.pt(), y1.pt(), x1.pt(), y2.pt() ); + painter->drawLine( x2.pt(), y1.pt(), x2.pt(), y2.pt() ); + painter->drawLine( x1.pt(), y3.pt(), x1.pt(), y4.pt() ); + painter->drawLine( x2.pt(), y3.pt(), x2.pt(), y4.pt() ); + } + + for ( int iy = 0; iy < layout->ny(); iy++ ) + { + Distance y1 = yMin + iy*layout->dy(); + Distance y2 = y1 + h; + + Distance x1 = max( xMin-tickOffset, Distance::pt(0) ); + Distance x2 = max( x1-tickLength, Distance::pt(0) ); + + Distance x3 = min( xMax+tickOffset, mModel->tmplate()->pageWidth() ); + Distance x4 = min( x3+tickLength, mModel->tmplate()->pageWidth() ); + + painter->drawLine( x1.pt(), y1.pt(), x2.pt(), y1.pt() ); + painter->drawLine( x1.pt(), y2.pt(), x2.pt(), y2.pt() ); + painter->drawLine( x3.pt(), y1.pt(), x4.pt(), y1.pt() ); + painter->drawLine( x3.pt(), y2.pt(), x4.pt(), y2.pt() ); + } + } + + painter->restore(); + } + } + + + void PageRenderer::printOutline( QPainter* painter ) const + { + if ( mPrintOutlines ) + { + painter->save(); + + painter->setBrush( QBrush( Qt::NoBrush ) ); + painter->setPen( QPen( labelOutlineColor, labelOutlineWidth ) ); + + painter->drawPath( mModel->frame()->path() ); + + painter->restore(); + } + } + + + void PageRenderer::clipLabel( QPainter* painter ) const + { + painter->setClipPath( mModel->frame()->clipPath() ); + } + + + void PageRenderer::printLabel( QPainter* painter, merge::Record* record ) const { painter->save(); - painter->setBrush( QBrush( Qt::NoBrush ) ); - painter->setPen( QPen( labelOutlineColor, labelOutlineWidth ) ); + if ( mModel->rotate() ) + { + painter->rotate( -90.0 ); + painter->translate( -mModel->w().pt(), 0 ); + } + + if ( mPrintReverse ) + { + painter->translate( mModel->w().pt(), 0 ); + painter->scale( -1, 1 ); + } + + mModel->draw( painter, false, record ); - painter->drawPath( mModel->frame()->path() ); - painter->restore(); } -} - - -void PageRenderer::clipLabel( QPainter* painter ) const -{ - painter->setClipPath( mModel->frame()->clipPath() ); -} - - -void PageRenderer::printLabel( QPainter* painter, merge::Record* record ) const -{ - painter->save(); - - if ( mModel->rotate() ) - { - painter->rotate( -90.0 ); - painter->translate( -mModel->w().pt(), 0 ); - } - - if ( mPrintReverse ) - { - painter->translate( mModel->w().pt(), 0 ); - painter->scale( -1, 1 ); - } - - mModel->draw( painter, false, record ); - - painter->restore(); + } diff --git a/glabels/PageRenderer.h b/glabels/PageRenderer.h index 74a2088..90bb90d 100644 --- a/glabels/PageRenderer.h +++ b/glabels/PageRenderer.h @@ -31,91 +31,97 @@ #include "Merge/Merge.h" #include "Merge/Record.h" -// Forward references -class LabelModel; - -/// -/// PageRenderer Widget -/// -class PageRenderer : public QObject +namespace glabels { - Q_OBJECT + + // Forward references + class LabelModel; + + + /// + /// PageRenderer Widget + /// + class PageRenderer : public QObject + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - PageRenderer(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + PageRenderer(); - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void setModel( const LabelModel* model ); - const LabelModel* model() const; - void setNCopies( int nCopies ); - void setStartLabel( int startLabel ); - void setPrintOutlines( bool printOutlinesFlag ); - void setPrintCropMarks( bool printCropMarksFlag ); - void setPrintReverse( bool printReverseFlag ); - void setIPage( int iPage ); - int nItems() const; - int nPages() const; - QRectF pageRect() const; - void printPage( QPainter* painter ) const; - void printPage( QPainter* painter, int iPage ) const; + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void setModel( const LabelModel* model ); + const LabelModel* model() const; + void setNCopies( int nCopies ); + void setStartLabel( int startLabel ); + void setPrintOutlines( bool printOutlinesFlag ); + void setPrintCropMarks( bool printCropMarksFlag ); + void setPrintReverse( bool printReverseFlag ); + void setIPage( int iPage ); + int nItems() const; + int nPages() const; + QRectF pageRect() const; + void printPage( QPainter* painter ) const; + void printPage( QPainter* painter, int iPage ) const; - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void changed(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void changed(); - ///////////////////////////////// - // Private slots - ///////////////////////////////// -private slots: - void onModelChanged(); + ///////////////////////////////// + // Private slots + ///////////////////////////////// + private slots: + void onModelChanged(); - ///////////////////////////////// - // Internal Methods - ///////////////////////////////// -private: - void updateNPages(); - void printSimplePage( QPainter* painter, int iPage ) const; - void printMergePage( QPainter* painter, int iPage ) const; - void printCropMarks( QPainter* painter ) const; - void printOutline( QPainter* painter ) const; - void clipLabel( QPainter* painter ) const; - void printLabel( QPainter* painter, merge::Record* record ) const; + ///////////////////////////////// + // Internal Methods + ///////////////////////////////// + private: + void updateNPages(); + void printSimplePage( QPainter* painter, int iPage ) const; + void printMergePage( QPainter* painter, int iPage ) const; + void printCropMarks( QPainter* painter ) const; + void printOutline( QPainter* painter ) const; + void clipLabel( QPainter* painter ) const; + void printLabel( QPainter* painter, merge::Record* record ) const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - const LabelModel* mModel; - const merge::Merge* mMerge; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + const LabelModel* mModel; + const merge::Merge* mMerge; - int mNCopies; - int mStartLabel; - int mLastLabel; - bool mPrintOutlines; - bool mPrintCropMarks; - bool mPrintReverse; - int mIPage; + int mNCopies; + int mStartLabel; + int mLastLabel; + bool mPrintOutlines; + bool mPrintCropMarks; + bool mPrintReverse; + int mIPage; - bool mIsMerge; - int mNPages; - int mNLabelsPerPage; + bool mIsMerge; + int mNPages; + int mNLabelsPerPage; - QVector mOrigins; -}; + QVector mOrigins; + }; + +} #endif // PageRenderer_h diff --git a/glabels/Paper.cpp b/glabels/Paper.cpp index e6f3fbe..001fee6 100644 --- a/glabels/Paper.cpp +++ b/glabels/Paper.cpp @@ -31,6 +31,7 @@ namespace glabels const QString& pwgSize ) : mId(id), mName(name), mWidth(width), mHeight(height), mPwgSize(pwgSize) { + // empty } diff --git a/glabels/Point.cpp b/glabels/Point.cpp index 5ae0be2..36ceaeb 100644 --- a/glabels/Point.cpp +++ b/glabels/Point.cpp @@ -26,11 +26,13 @@ namespace glabels Point::Point() : mX(Distance(0)), mY(Distance(0)) { + // empty } Point::Point( Distance x, Distance y ) : mX(x), mY(y) { + // empty } diff --git a/glabels/PreferencesDialog.cpp b/glabels/PreferencesDialog.cpp index d6ab99d..bb31ea6 100644 --- a/glabels/PreferencesDialog.cpp +++ b/glabels/PreferencesDialog.cpp @@ -24,58 +24,63 @@ #include "Settings.h" -/// -/// Constructor -/// -PreferencesDialog::PreferencesDialog( QWidget *parent ) - : QDialog(parent) +namespace glabels { - setupUi( this ); - switch ( Settings::units().toEnum() ) + /// + /// Constructor + /// + PreferencesDialog::PreferencesDialog( QWidget *parent ) + : QDialog(parent) { - case glabels::Units::IN: - unitsInchesRadio->setChecked( true ); - break; - case glabels::Units::MM: - unitsMillimetersRadio->setChecked( true ); - break; - case glabels::Units::CM: - unitsCentimetersRadio->setChecked( true ); - break; - case glabels::Units::PC: - unitsPicasRadio->setChecked( true ); - break; - default: - unitsPointsRadio->setChecked( true ); - break; - } -} - - -/// -/// Units Radios Changed -/// -void PreferencesDialog::onUnitsRadiosChanged() -{ - if ( unitsInchesRadio->isChecked() ) - { - Settings::setUnits( glabels::Units::in() ); - } - else if ( unitsMillimetersRadio->isChecked() ) - { - Settings::setUnits( glabels::Units::mm() ); - } - else if ( unitsCentimetersRadio->isChecked() ) - { - Settings::setUnits( glabels::Units::cm() ); - } - else if ( unitsPicasRadio->isChecked() ) - { - Settings::setUnits( glabels::Units::pc() ); - } - else - { - Settings::setUnits( glabels::Units::pt() ); + setupUi( this ); + + switch ( Settings::units().toEnum() ) + { + case Units::IN: + unitsInchesRadio->setChecked( true ); + break; + case Units::MM: + unitsMillimetersRadio->setChecked( true ); + break; + case Units::CM: + unitsCentimetersRadio->setChecked( true ); + break; + case Units::PC: + unitsPicasRadio->setChecked( true ); + break; + default: + unitsPointsRadio->setChecked( true ); + break; + } } + + + /// + /// Units Radios Changed + /// + void PreferencesDialog::onUnitsRadiosChanged() + { + if ( unitsInchesRadio->isChecked() ) + { + Settings::setUnits( Units::in() ); + } + else if ( unitsMillimetersRadio->isChecked() ) + { + Settings::setUnits( Units::mm() ); + } + else if ( unitsCentimetersRadio->isChecked() ) + { + Settings::setUnits( Units::cm() ); + } + else if ( unitsPicasRadio->isChecked() ) + { + Settings::setUnits( Units::pc() ); + } + else + { + Settings::setUnits( Units::pt() ); + } + } + } diff --git a/glabels/PreferencesDialog.h b/glabels/PreferencesDialog.h index 694c7dc..d0515d8 100644 --- a/glabels/PreferencesDialog.h +++ b/glabels/PreferencesDialog.h @@ -25,27 +25,32 @@ #include "ui_PreferencesDialog.h" -/// -/// New Label Dialog Widget -/// -class PreferencesDialog : public QDialog, public Ui_PreferencesDialog +namespace glabels { - Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - PreferencesDialog( QWidget *parent = 0 ); + /// + /// New Label Dialog Widget + /// + class PreferencesDialog : public QDialog, public Ui_PreferencesDialog + { + Q_OBJECT + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + PreferencesDialog( QWidget *parent = 0 ); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onUnitsRadiosChanged(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onUnitsRadiosChanged(); -}; + }; + +} #endif // PreferencesDialog_h diff --git a/glabels/Preview.cpp b/glabels/Preview.cpp index f78b10a..a5d6d6e 100644 --- a/glabels/Preview.cpp +++ b/glabels/Preview.cpp @@ -29,171 +29,174 @@ #include "PreviewOverlayItem.h" -// -// Private Configuration Data -// -namespace +namespace glabels { - const QColor paperColor( 255, 255, 255 ); - const QColor paperOutlineColor( 0, 0, 0 ); - const double paperOutlineWidthPixels = 1; - const QColor shadowColor( 64, 64, 64 ); - const double shadowOffsetPixels = 3; - const double shadowRadiusPixels = 12; - - const QColor labelColor( 255, 255, 255 ); - const QColor labelOutlineColor( 215, 215, 215 ); - const double labelOutlineWidthPixels = 1; -} - - -/// -/// Constructor -/// -Preview::Preview( QWidget *parent ) - : mModel(0), mRenderer(0), QGraphicsView(parent) -{ - mScene = new QGraphicsScene(); - setScene( mScene ); - - setAttribute(Qt::WA_TranslucentBackground); - viewport()->setAutoFillBackground(false); - - setFrameStyle( QFrame::NoFrame ); - setRenderHints( QPainter::Antialiasing ); -} - - -/// -/// Set renderer -/// -void Preview::setRenderer( const PageRenderer* renderer ) -{ - mRenderer = renderer; - - connect( mRenderer, SIGNAL(changed()), this, SLOT(onRendererChanged()) ); - onRendererChanged(); -} - - -/// -/// Renderer changed handler -/// -void Preview::onRendererChanged() -{ - mModel = mRenderer->model(); - - clearScene(); - - if ( mModel != NULL ) + // + // Private + // + namespace { - // Set scene up with a 5% margin around paper - glabels::Distance x = -0.05 * mModel->tmplate()->pageWidth(); - glabels::Distance y = -0.05 * mModel->tmplate()->pageHeight(); - glabels::Distance w = 1.10 * mModel->tmplate()->pageWidth(); - glabels::Distance h = 1.10 * mModel->tmplate()->pageHeight(); + const QColor paperColor( 255, 255, 255 ); + const QColor paperOutlineColor( 0, 0, 0 ); + const double paperOutlineWidthPixels = 1; - mScene->setSceneRect( x.pt(), y.pt(), w.pt(), h.pt() ); + const QColor shadowColor( 64, 64, 64 ); + const double shadowOffsetPixels = 3; + const double shadowRadiusPixels = 12; + + const QColor labelColor( 255, 255, 255 ); + const QColor labelOutlineColor( 215, 215, 215 ); + const double labelOutlineWidthPixels = 1; + } + + + /// + /// Constructor + /// + Preview::Preview( QWidget *parent ) + : mModel(0), mRenderer(0), QGraphicsView(parent) + { + mScene = new QGraphicsScene(); + setScene( mScene ); + + setAttribute(Qt::WA_TranslucentBackground); + viewport()->setAutoFillBackground(false); + + setFrameStyle( QFrame::NoFrame ); + setRenderHints( QPainter::Antialiasing ); + } + + + /// + /// Set renderer + /// + void Preview::setRenderer( const PageRenderer* renderer ) + { + mRenderer = renderer; + + connect( mRenderer, SIGNAL(changed()), this, SLOT(onRendererChanged()) ); + onRendererChanged(); + } + + + /// + /// Renderer changed handler + /// + void Preview::onRendererChanged() + { + mModel = mRenderer->model(); + + clearScene(); + + if ( mModel != NULL ) + { + // Set scene up with a 5% margin around paper + Distance x = -0.05 * mModel->tmplate()->pageWidth(); + Distance y = -0.05 * mModel->tmplate()->pageHeight(); + Distance w = 1.10 * mModel->tmplate()->pageWidth(); + Distance h = 1.10 * mModel->tmplate()->pageHeight(); + + mScene->setSceneRect( x.pt(), y.pt(), w.pt(), h.pt() ); + fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); + + drawPaper( mModel->tmplate()->pageWidth(), mModel->tmplate()->pageHeight() ); + drawLabels(); + drawPreviewOverlay(); + } + } + + + /// + /// Resize Event Handler + /// + void Preview::resizeEvent( QResizeEvent* event ) + { fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); - - drawPaper( mModel->tmplate()->pageWidth(), mModel->tmplate()->pageHeight() ); - drawLabels(); - drawPreviewOverlay(); } -} -/// -/// Resize Event Handler -/// -void Preview::resizeEvent( QResizeEvent* event ) -{ - fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); -} - - -/// -/// Clear View -/// -void Preview::clearScene() -{ - foreach ( QGraphicsItem *item, mScene->items() ) + /// + /// Clear View + /// + void Preview::clearScene() { - mScene->removeItem( item ); - delete item; + foreach ( QGraphicsItem *item, mScene->items() ) + { + mScene->removeItem( item ); + delete item; + } } -} -/// -/// Draw Paper -/// -void Preview::drawPaper( const glabels::Distance& pw, const glabels::Distance& ph ) -{ - QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(); - shadowEffect->setColor( shadowColor ); - shadowEffect->setOffset( shadowOffsetPixels ); - shadowEffect->setBlurRadius( shadowRadiusPixels ); + /// + /// Draw Paper + /// + void Preview::drawPaper( const Distance& pw, const Distance& ph ) + { + QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(); + shadowEffect->setColor( shadowColor ); + shadowEffect->setOffset( shadowOffsetPixels ); + shadowEffect->setBlurRadius( shadowRadiusPixels ); - QBrush brush( paperColor ); - QPen pen( paperOutlineColor ); - pen.setCosmetic( true ); - pen.setWidthF( paperOutlineWidthPixels ); + QBrush brush( paperColor ); + QPen pen( paperOutlineColor ); + pen.setCosmetic( true ); + pen.setWidthF( paperOutlineWidthPixels ); - QGraphicsRectItem *pageItem = new QGraphicsRectItem( 0, 0, pw.pt(), ph.pt() ); - pageItem->setBrush( brush ); - pageItem->setPen( pen ); - pageItem->setGraphicsEffect( shadowEffect ); + QGraphicsRectItem *pageItem = new QGraphicsRectItem( 0, 0, pw.pt(), ph.pt() ); + pageItem->setBrush( brush ); + pageItem->setPen( pen ); + pageItem->setGraphicsEffect( shadowEffect ); - mScene->addItem( pageItem ); -} - - -/// -/// Draw Labels on Paper -/// -void Preview::drawLabels() -{ - glabels::Frame *frame = mModel->tmplate()->frames().first(); - - foreach (glabels::Point origin, frame->getOrigins() ) - { - drawLabel( origin.x(), origin.y(), frame->path() ); + mScene->addItem( pageItem ); } -} -/// -/// Draw a Single Label at x,y -/// -void Preview::drawLabel( const glabels::Distance& x, - const glabels::Distance& y, - const QPainterPath& path ) -{ - QBrush brush( Qt::NoBrush ); - QPen pen( labelOutlineColor ); - pen.setStyle( Qt::DotLine ); - pen.setCosmetic( true ); - pen.setWidthF( labelOutlineWidthPixels ); - - QGraphicsPathItem *labelOutlineItem = new QGraphicsPathItem( path ); - labelOutlineItem->setBrush( brush ); - labelOutlineItem->setPen( pen ); - labelOutlineItem->setPos( x.pt(), y.pt() ); - - mScene->addItem( labelOutlineItem ); -} - - -/// -/// Draw Preview Overlay -/// -void Preview::drawPreviewOverlay() -{ - if ( mRenderer ) + /// + /// Draw Labels on Paper + /// + void Preview::drawLabels() { - PreviewOverlayItem* overlayItem = new PreviewOverlayItem( mRenderer ); - mScene->addItem( overlayItem ); + Frame *frame = mModel->tmplate()->frames().first(); + + foreach (Point origin, frame->getOrigins() ) + { + drawLabel( origin.x(), origin.y(), frame->path() ); + } } + + + /// + /// Draw a Single Label at x,y + /// + void Preview::drawLabel( const Distance& x, const Distance& y, const QPainterPath& path ) + { + QBrush brush( Qt::NoBrush ); + QPen pen( labelOutlineColor ); + pen.setStyle( Qt::DotLine ); + pen.setCosmetic( true ); + pen.setWidthF( labelOutlineWidthPixels ); + + QGraphicsPathItem *labelOutlineItem = new QGraphicsPathItem( path ); + labelOutlineItem->setBrush( brush ); + labelOutlineItem->setPen( pen ); + labelOutlineItem->setPos( x.pt(), y.pt() ); + + mScene->addItem( labelOutlineItem ); + } + + + /// + /// Draw Preview Overlay + /// + void Preview::drawPreviewOverlay() + { + if ( mRenderer ) + { + PreviewOverlayItem* overlayItem = new PreviewOverlayItem( mRenderer ); + mScene->addItem( overlayItem ); + } + } + } diff --git a/glabels/Preview.h b/glabels/Preview.h index 0afaf40..145dd4d 100644 --- a/glabels/Preview.h +++ b/glabels/Preview.h @@ -27,64 +27,68 @@ #include "PageRenderer.h" -// Forward references -class LabelModel; - -/// -/// Preview Widget -/// -class Preview : public QGraphicsView +namespace glabels { - Q_OBJECT + + // Forward references + class LabelModel; - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - Preview( QWidget *parent = 0 ); + /// + /// Preview Widget + /// + class Preview : public QGraphicsView + { + Q_OBJECT - ///////////////////////////////// - // Renderer - ///////////////////////////////// -public: - void setRenderer( const PageRenderer* renderer ); -private slots: - void onRendererChanged(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + Preview( QWidget *parent = 0 ); - ///////////////////////////////////// - // Event handlers - ///////////////////////////////////// -protected: - void resizeEvent( QResizeEvent* event ); + ///////////////////////////////// + // Renderer + ///////////////////////////////// + public: + void setRenderer( const PageRenderer* renderer ); + private slots: + void onRendererChanged(); + + + ///////////////////////////////////// + // Event handlers + ///////////////////////////////////// + protected: + void resizeEvent( QResizeEvent* event ); - ///////////////////////////////// - // Internal Methods - ///////////////////////////////// -private: - void clearScene(); - void drawPaper( const glabels::Distance& pw, const glabels::Distance& ph ); - void drawLabels(); - void drawLabel( const glabels::Distance& x, - const glabels::Distance& y, - const QPainterPath& path ); + ///////////////////////////////// + // Internal Methods + ///////////////////////////////// + private: + void clearScene(); + void drawPaper( const Distance& pw, const Distance& ph ); + void drawLabels(); + void drawLabel( const Distance& x, const Distance& y, const QPainterPath& path ); - void drawPreviewOverlay(); + void drawPreviewOverlay(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - const LabelModel* mModel; - const PageRenderer* mRenderer; - QGraphicsScene* mScene; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + const LabelModel* mModel; + const PageRenderer* mRenderer; + QGraphicsScene* mScene; -}; + }; + +} #endif // Preview_h diff --git a/glabels/PreviewOverlayItem.cpp b/glabels/PreviewOverlayItem.cpp index f522efa..0525afb 100644 --- a/glabels/PreviewOverlayItem.cpp +++ b/glabels/PreviewOverlayItem.cpp @@ -26,19 +26,25 @@ #include "PageRenderer.h" -PreviewOverlayItem::PreviewOverlayItem( const PageRenderer* renderer, QGraphicsItem* parent ) - : QGraphicsItem(parent), mRenderer(renderer) +namespace glabels { -} - - -QRectF PreviewOverlayItem::boundingRect() const -{ - return mRenderer->pageRect(); -} - - -void PreviewOverlayItem::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget ) -{ - mRenderer->printPage( painter ); + + PreviewOverlayItem::PreviewOverlayItem( const PageRenderer* renderer, QGraphicsItem* parent ) + : QGraphicsItem(parent), mRenderer(renderer) + { + // empty + } + + + QRectF PreviewOverlayItem::boundingRect() const + { + return mRenderer->pageRect(); + } + + + void PreviewOverlayItem::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget ) + { + mRenderer->printPage( painter ); + } + } diff --git a/glabels/PreviewOverlayItem.h b/glabels/PreviewOverlayItem.h index 32a0cb9..5b462c6 100644 --- a/glabels/PreviewOverlayItem.h +++ b/glabels/PreviewOverlayItem.h @@ -24,38 +24,44 @@ #include -// Forward references -class PageRenderer; - -/// -/// PreviewOverlayItem Widget -/// -class PreviewOverlayItem : public QGraphicsItem +namespace glabels { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - PreviewOverlayItem( const PageRenderer* renderer, QGraphicsItem* parent = 0 ); + // Forward references + class PageRenderer; - ///////////////////////////////////// - // Virtual method implementations - ///////////////////////////////////// -public: - QRectF boundingRect() const; - void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget ); + /// + /// PreviewOverlayItem Widget + /// + class PreviewOverlayItem : public QGraphicsItem + { + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + PreviewOverlayItem( const PageRenderer* renderer, QGraphicsItem* parent = 0 ); + + + ///////////////////////////////////// + // Virtual method implementations + ///////////////////////////////////// + public: + QRectF boundingRect() const; + void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget ); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - const PageRenderer* mRenderer; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + const PageRenderer* mRenderer; -}; + }; + +} #endif // PreviewOverlayItem_h diff --git a/glabels/PrintView.cpp b/glabels/PrintView.cpp index b71b2e6..55dd454 100644 --- a/glabels/PrintView.cpp +++ b/glabels/PrintView.cpp @@ -27,126 +27,131 @@ #include "LabelModel.h" -/// -/// Constructor -/// -PrintView::PrintView( QWidget *parent ) - : QWidget(parent), mModel(0), mBlocked(false) +namespace glabels { - setupUi( this ); - preview->setRenderer( &mRenderer ); - mPrinter = new QPrinter( QPrinter::HighResolution ); -} - - -/// -/// Destructor -/// -PrintView::~PrintView() -{ - delete mPrinter; -} - - -/// -/// Set Model -/// -void PrintView::setModel( LabelModel* model ) -{ - mModel = model; - mRenderer.setModel( mModel ); - - connect( mModel, SIGNAL(changed()), this, SLOT(onModelChanged()) ); - - onFormChanged(); -} - - -/// -/// Model changed handler -/// -void PrintView::onModelChanged() -{ - updateView(); -} - - -/// -/// Update view -/// -void PrintView::updateView() -{ - copiesStartSpin->setRange( 1, mModel->frame()->nLabels() ); - - copiesDescriptionLabel->setText( tr("(Will print a total of %1 items on %2 pages.)") - .arg(mRenderer.nItems()).arg(mRenderer.nPages()) ); - - pageSpin->setRange( 1, mRenderer.nPages() ); - nPagesLabel->setText( QString::number( mRenderer.nPages() ) ); -} - - -/// -/// Form changed handler -/// -void PrintView::onFormChanged() -{ - if ( !mBlocked ) + /// + /// Constructor + /// + PrintView::PrintView( QWidget *parent ) + : QWidget(parent), mModel(0), mBlocked(false) { - mBlocked = true; - - mRenderer.setNCopies( copiesSpin->value() ); - mRenderer.setStartLabel( copiesStartSpin->value() - 1 ); + setupUi( this ); + preview->setRenderer( &mRenderer ); - mRenderer.setPrintOutlines( printOutlinesCheck->isChecked() ); - mRenderer.setPrintCropMarks( printCropMarksCheck->isChecked() ); - mRenderer.setPrintReverse( printReverseCheck->isChecked() ); - - mRenderer.setIPage( pageSpin->value() - 1 ); - - updateView(); - - mBlocked = false; + mPrinter = new QPrinter( QPrinter::HighResolution ); } -} -/// -/// Print Button Clicked handler -/// -void PrintView::onPrintButtonClicked() -{ - QSizeF pageSize( mModel->tmplate()->pageWidth().pt(), mModel->tmplate()->pageHeight().pt() ); - mPrinter->setPaperSize( pageSize, QPrinter::Point ); - mPrinter->setFullPage( true ); - mPrinter->setPageMargins( 0, 0, 0, 0, QPrinter::Point ); - - QPrintDialog printDialog( mPrinter, this ); - - printDialog.setOption( QAbstractPrintDialog::PrintToFile, true ); - printDialog.setOption( QAbstractPrintDialog::PrintSelection, false ); - printDialog.setOption( QAbstractPrintDialog::PrintPageRange, false ); - printDialog.setOption( QAbstractPrintDialog::PrintShowPageSize, true ); - printDialog.setOption( QAbstractPrintDialog::PrintCollateCopies, false ); - printDialog.setOption( QAbstractPrintDialog::PrintCurrentPage, false ); - - if ( printDialog.exec() == QDialog::Accepted ) + /// + /// Destructor + /// + PrintView::~PrintView() { - QPainter painter( mPrinter ); - - QSizeF sizePx = mPrinter->paperSize( QPrinter::DevicePixel ); - QSizeF sizePts = mPrinter->paperSize( QPrinter::Point ); - painter.scale( sizePx.width()/sizePts.width(), sizePx.height()/sizePts.height() ); + delete mPrinter; + } - for ( int iPage = 0; iPage < mRenderer.nPages(); iPage++ ) + + /// + /// Set Model + /// + void PrintView::setModel( LabelModel* model ) + { + mModel = model; + mRenderer.setModel( mModel ); + + connect( mModel, SIGNAL(changed()), this, SLOT(onModelChanged()) ); + + onFormChanged(); + } + + + /// + /// Model changed handler + /// + void PrintView::onModelChanged() + { + updateView(); + } + + + /// + /// Update view + /// + void PrintView::updateView() + { + copiesStartSpin->setRange( 1, mModel->frame()->nLabels() ); + + copiesDescriptionLabel->setText( tr("(Will print a total of %1 items on %2 pages.)") + .arg(mRenderer.nItems()).arg(mRenderer.nPages()) ); + + pageSpin->setRange( 1, mRenderer.nPages() ); + nPagesLabel->setText( QString::number( mRenderer.nPages() ) ); + } + + + /// + /// Form changed handler + /// + void PrintView::onFormChanged() + { + if ( !mBlocked ) { - if ( iPage ) - { - mPrinter->newPage(); - } + mBlocked = true; + + mRenderer.setNCopies( copiesSpin->value() ); + mRenderer.setStartLabel( copiesStartSpin->value() - 1 ); - mRenderer.printPage( &painter, iPage ); + mRenderer.setPrintOutlines( printOutlinesCheck->isChecked() ); + mRenderer.setPrintCropMarks( printCropMarksCheck->isChecked() ); + mRenderer.setPrintReverse( printReverseCheck->isChecked() ); + + mRenderer.setIPage( pageSpin->value() - 1 ); + + updateView(); + + mBlocked = false; } } + + + /// + /// Print Button Clicked handler + /// + void PrintView::onPrintButtonClicked() + { + QSizeF pageSize( mModel->tmplate()->pageWidth().pt(), mModel->tmplate()->pageHeight().pt() ); + mPrinter->setPaperSize( pageSize, QPrinter::Point ); + mPrinter->setFullPage( true ); + mPrinter->setPageMargins( 0, 0, 0, 0, QPrinter::Point ); + + QPrintDialog printDialog( mPrinter, this ); + + printDialog.setOption( QAbstractPrintDialog::PrintToFile, true ); + printDialog.setOption( QAbstractPrintDialog::PrintSelection, false ); + printDialog.setOption( QAbstractPrintDialog::PrintPageRange, false ); + printDialog.setOption( QAbstractPrintDialog::PrintShowPageSize, true ); + printDialog.setOption( QAbstractPrintDialog::PrintCollateCopies, false ); + printDialog.setOption( QAbstractPrintDialog::PrintCurrentPage, false ); + + if ( printDialog.exec() == QDialog::Accepted ) + { + QPainter painter( mPrinter ); + + QSizeF sizePx = mPrinter->paperSize( QPrinter::DevicePixel ); + QSizeF sizePts = mPrinter->paperSize( QPrinter::Point ); + painter.scale( sizePx.width()/sizePts.width(), sizePx.height()/sizePts.height() ); + + for ( int iPage = 0; iPage < mRenderer.nPages(); iPage++ ) + { + if ( iPage ) + { + mPrinter->newPage(); + } + + mRenderer.printPage( &painter, iPage ); + } + } + } + } diff --git a/glabels/PrintView.h b/glabels/PrintView.h index 22986dd..dea4c83 100644 --- a/glabels/PrintView.h +++ b/glabels/PrintView.h @@ -27,53 +27,59 @@ #include "ui_PrintView.h" #include "PageRenderer.h" -// Forward references -class LabelModel; + +namespace glabels +{ + + // Forward references + class LabelModel; -/// -/// Print View Widget -/// -class PrintView : public QWidget, public Ui_PrintView -{ - Q_OBJECT + /// + /// Print View Widget + /// + class PrintView : public QWidget, public Ui_PrintView + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - PrintView( QWidget *parent = 0 ); - ~PrintView(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + PrintView( QWidget *parent = 0 ); + ~PrintView(); - ///////////////////////////////// - // Public methods - ///////////////////////////////// - void setModel( LabelModel* model ); + ///////////////////////////////// + // Public methods + ///////////////////////////////// + void setModel( LabelModel* model ); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onModelChanged(); - void updateView(); - void onFormChanged(); - void onPrintButtonClicked(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onModelChanged(); + void updateView(); + void onFormChanged(); + void onPrintButtonClicked(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - LabelModel* mModel; - QPrinter* mPrinter; - PageRenderer mRenderer; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + LabelModel* mModel; + QPrinter* mPrinter; + PageRenderer mRenderer; - bool mBlocked; + bool mBlocked; -}; + }; + +} #endif // PrintView_h diff --git a/glabels/PropertiesView.cpp b/glabels/PropertiesView.cpp index eab1304..085695e 100644 --- a/glabels/PropertiesView.cpp +++ b/glabels/PropertiesView.cpp @@ -31,194 +31,204 @@ #include "UndoRedoModel.h" -/// -/// Constructor -/// -PropertiesView::PropertiesView( QWidget *parent ) - : QWidget(parent), mModel(0) +namespace glabels { - setupUi( this ); - // Hack to get orientationCombo item height to follow icon size plus some additional padding - QStyledItemDelegate* itemDelegate = new QStyledItemDelegate(); - orientationCombo->setItemDelegate( itemDelegate ); - orientationCombo->setStyleSheet( "* QAbstractItemView::item { padding: 8px; }" ); - - similarBrowser->setAttribute(Qt::WA_TranslucentBackground); - similarBrowser->viewport()->setAutoFillBackground(false); - - connect( Settings::instance(), SIGNAL(changed()), this, SLOT(onSettingsChanged()) ); - onSettingsChanged(); -} - - -/// -/// Destructor -/// -PropertiesView::~PropertiesView() -{ -} - - -/// -/// Set Model -/// -void PropertiesView::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) -{ - mModel = model; - mUndoRedoModel = undoRedoModel; - - connect( mModel, SIGNAL(sizeChanged()), this, SLOT(onLabelSizeChanged()) ); - - onLabelSizeChanged(); -} - - -/// -/// Settings changed handler -/// -void PropertiesView::onSettingsChanged() -{ - mUnits = Settings::units(); - if (mModel) + /// + /// Constructor + /// + PropertiesView::PropertiesView( QWidget *parent ) + : QWidget(parent), mModel(0) { + setupUi( this ); + + // Hack to get orientationCombo item height to follow icon size plus padding + QStyledItemDelegate* itemDelegate = new QStyledItemDelegate(); + orientationCombo->setItemDelegate( itemDelegate ); + orientationCombo->setStyleSheet( "* QAbstractItemView::item { padding: 8px; }" ); + + similarBrowser->setAttribute(Qt::WA_TranslucentBackground); + similarBrowser->viewport()->setAutoFillBackground(false); + + connect( Settings::instance(), SIGNAL(changed()), + this, SLOT(onSettingsChanged()) ); + + onSettingsChanged(); + } + + + /// + /// Destructor + /// + PropertiesView::~PropertiesView() + { + // empty + } + + + /// + /// Set Model + /// + void PropertiesView::setModel( LabelModel* model, UndoRedoModel* undoRedoModel ) + { + mModel = model; + mUndoRedoModel = undoRedoModel; + + connect( mModel, SIGNAL(sizeChanged()), this, SLOT(onLabelSizeChanged()) ); + onLabelSizeChanged(); } -} -/// -/// Label size changed handler -/// -void PropertiesView::onLabelSizeChanged() -{ - const glabels::Template *tmplate = mModel->tmplate(); - const glabels::Frame *frame = tmplate->frames().first(); - bool isRotated = mModel->rotate(); - - preview->setTemplate( tmplate ); - preview->setRotate( isRotated ); - - const glabels::Vendor *vendor = glabels::Db::lookupVendorFromName( tmplate->brand() ); - if ( (vendor != NULL) && (vendor->url() != NULL) ) + /// + /// Settings changed handler + /// + void PropertiesView::onSettingsChanged() { - QString markup = "" + vendor->name() + ""; - vendorLabel->setText( markup ); - } - else - { - vendorLabel->setText( tmplate->brand() ); - } - - if ( tmplate->productUrl() != NULL ) - { - QString markup = "" + tmplate->part() + ""; - partLabel->setText( markup ); - } - else - { - partLabel->setText( tmplate->part() ); - } - - descriptionLabel->setText( tmplate->description() ); - - QString pgSizeString = glabels::Db::lookupPaperNameFromId( tmplate->paperId() ); - pageSizeLabel->setText( pgSizeString ); - - QString labelSizeString = frame->sizeDescription( mUnits ); - labelSizeLabel->setText( labelSizeString ); - - QString layoutString = frame->layoutDescription(); - layoutLabel->setText( layoutString ); - - QStringList list = glabels::Db::getNameListOfSimilarTemplates( tmplate->name() ); - if ( list.isEmpty() ) - { - similarProductsGroupBox->hide(); - similarProductsNullBox->show(); - } - else - { - similarProductsGroupBox->show(); - similarProductsNullBox->hide(); - - QString similarListString; - foreach ( QString name, list ) + mUnits = Settings::units(); + if (mModel) { - similarListString += name + "\n"; + onLabelSizeChanged(); } - similarBrowser->setText( similarListString ); } - orientationCombo->setEnabled( frame->w() != frame->h() ); - if ( frame->w() == frame->h() ) + + /// + /// Label size changed handler + /// + void PropertiesView::onLabelSizeChanged() { - orientationCombo->setCurrentIndex(0); - } - else if ( frame->w() > frame->h() ) - { - orientationCombo->setCurrentIndex( isRotated ? 1 : 0 ); - } - else - { - orientationCombo->setCurrentIndex( isRotated ? 0 : 1 ); - } - mOldOrientationIndex = orientationCombo->currentIndex(); -} + const Template *tmplate = mModel->tmplate(); + const Frame *frame = tmplate->frames().first(); + bool isRotated = mModel->rotate(); + preview->setTemplate( tmplate ); + preview->setRotate( isRotated ); -/// -/// Orientation combo box changed handler -/// -void PropertiesView::onOrientationActivated() -{ - const glabels::Template *tmplate = mModel->tmplate(); - const glabels::Frame *frame = tmplate->frames().first(); - - // Make sure index actually changed. - int index = orientationCombo->currentIndex(); - if ( index != mOldOrientationIndex ) - { - mOldOrientationIndex = index; - - mUndoRedoModel->checkpoint( tr("Product Rotate") ); - - if ( frame->w() == frame->h() ) + const Vendor *vendor = Db::lookupVendorFromName( tmplate->brand() ); + if ( (vendor != NULL) && (vendor->url() != NULL) ) { - mModel->setRotate( false ); - } - else if ( frame->w() > frame->h() ) - { - mModel->setRotate( index == 1 ); + QString markup = QString( "%2" ) + .arg( vendor->url() ).arg( vendor->name() ); + vendorLabel->setText( markup ); } else { - mModel->setRotate( index == 0 ); + vendorLabel->setText( tmplate->brand() ); } - } -} + if ( tmplate->productUrl() != NULL ) + { + QString markup = QString( "%2" ) + .arg( tmplate->productUrl() ).arg( tmplate->part() ); + partLabel->setText( markup ); + } + else + { + partLabel->setText( tmplate->part() ); + } -/// -/// Change Product Button Clicked handler -/// -void PropertiesView::onChangeProductButtonClicked() -{ - SelectProductDialog selectProductDialog( this ); - selectProductDialog.exec(); + descriptionLabel->setText( tmplate->description() ); - const glabels::Template* tmplate = selectProductDialog.tmplate(); - if ( tmplate ) - { - mUndoRedoModel->checkpoint( tr("Change Product") ); + QString pgSizeString = Db::lookupPaperNameFromId( tmplate->paperId() ); + pageSizeLabel->setText( pgSizeString ); - mModel->setTmplate( tmplate ); + QString labelSizeString = frame->sizeDescription( mUnits ); + labelSizeLabel->setText( labelSizeString ); - // Don't rotate circular or round labels - const glabels::Frame *frame = tmplate->frames().first(); + QString layoutString = frame->layoutDescription(); + layoutLabel->setText( layoutString ); + + QStringList list = Db::getNameListOfSimilarTemplates( tmplate->name() ); + if ( list.isEmpty() ) + { + similarProductsGroupBox->hide(); + similarProductsNullBox->show(); + } + else + { + similarProductsGroupBox->show(); + similarProductsNullBox->hide(); + + QString similarListString; + foreach ( QString name, list ) + { + similarListString += name + "\n"; + } + similarBrowser->setText( similarListString ); + } + + orientationCombo->setEnabled( frame->w() != frame->h() ); if ( frame->w() == frame->h() ) { - mModel->setRotate( false ); + orientationCombo->setCurrentIndex(0); + } + else if ( frame->w() > frame->h() ) + { + orientationCombo->setCurrentIndex( isRotated ? 1 : 0 ); + } + else + { + orientationCombo->setCurrentIndex( isRotated ? 0 : 1 ); + } + mOldOrientationIndex = orientationCombo->currentIndex(); + } + + + /// + /// Orientation combo box changed handler + /// + void PropertiesView::onOrientationActivated() + { + const Template *tmplate = mModel->tmplate(); + const Frame *frame = tmplate->frames().first(); + + // Make sure index actually changed. + int index = orientationCombo->currentIndex(); + if ( index != mOldOrientationIndex ) + { + mOldOrientationIndex = index; + + mUndoRedoModel->checkpoint( tr("Product Rotate") ); + + if ( frame->w() == frame->h() ) + { + mModel->setRotate( false ); + } + else if ( frame->w() > frame->h() ) + { + mModel->setRotate( index == 1 ); + } + else + { + mModel->setRotate( index == 0 ); + } } } + + + /// + /// Change Product Button Clicked handler + /// + void PropertiesView::onChangeProductButtonClicked() + { + SelectProductDialog selectProductDialog( this ); + selectProductDialog.exec(); + + const Template* tmplate = selectProductDialog.tmplate(); + if ( tmplate ) + { + mUndoRedoModel->checkpoint( tr("Change Product") ); + + mModel->setTmplate( tmplate ); + + // Don't rotate circular or round labels + const Frame *frame = tmplate->frames().first(); + if ( frame->w() == frame->h() ) + { + mModel->setRotate( false ); + } + } + } + } diff --git a/glabels/PropertiesView.h b/glabels/PropertiesView.h index a2b8b89..f1ee215 100644 --- a/glabels/PropertiesView.h +++ b/glabels/PropertiesView.h @@ -26,52 +26,58 @@ #include "Units.h" -// Forward references -class LabelModel; -class UndoRedoModel; + +namespace glabels +{ + + // Forward references + class LabelModel; + class UndoRedoModel; -/// -/// Properties View Widget -/// -class PropertiesView : public QWidget, public Ui_PropertiesView -{ - Q_OBJECT + /// + /// Properties View Widget + /// + class PropertiesView : public QWidget, public Ui_PropertiesView + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - PropertiesView( QWidget *parent = 0 ); - ~PropertiesView(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + PropertiesView( QWidget *parent = 0 ); + ~PropertiesView(); - ///////////////////////////////// - // Public methods - ///////////////////////////////// - void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); + ///////////////////////////////// + // Public methods + ///////////////////////////////// + void setModel( LabelModel* model, UndoRedoModel* undoRedoModel ); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onSettingsChanged(); - void onLabelSizeChanged(); - void onOrientationActivated(); - void onChangeProductButtonClicked(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onSettingsChanged(); + void onLabelSizeChanged(); + void onOrientationActivated(); + void onChangeProductButtonClicked(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - LabelModel* mModel; - UndoRedoModel* mUndoRedoModel; - glabels::Units mUnits; - int mOldOrientationIndex; -}; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + LabelModel* mModel; + UndoRedoModel* mUndoRedoModel; + Units mUnits; + int mOldOrientationIndex; + }; + +} #endif // PropertiesView_h diff --git a/glabels/Region.cpp b/glabels/Region.cpp index 854c107..a5509ff 100644 --- a/glabels/Region.cpp +++ b/glabels/Region.cpp @@ -21,107 +21,114 @@ #include "Region.h" -/// -/// Constructor -/// -Region::Region() : mX1(0), mY1(0), mX2(0), mY2(0) +namespace glabels { -} - - -/// -/// Constructor -/// -Region::Region( const glabels::Distance& x1, const glabels::Distance& y1, - const glabels::Distance& x2, const glabels::Distance& y2 ) - : mX1(x1), mY1(y1), mX2(x2), mY2(y2) -{ -} - - -/// -/// Get x1 -/// -glabels::Distance Region::x1( void ) const -{ - return mX1; -} - - -/// -/// Set x1 -/// -void Region::setX1( const glabels::Distance& value ) -{ - mX1 = value; -} - - -/// -/// Get y1 -/// -glabels::Distance Region::y1( void ) const -{ - return mY1; -} - - -/// -/// Set y1 -/// -void Region::setY1( const glabels::Distance& value ) -{ - mY1 = value; -} - - -/// -/// Get x2 -/// -glabels::Distance Region::x2( void ) const -{ - return mX2; -} - - -/// -/// Set x2 -/// -void Region::setX2( const glabels::Distance& value ) -{ - mX2 = value; -} - - -/// -/// Get y2 -/// -glabels::Distance Region::y2( void ) const -{ - return mY2; -} - - -/// -/// Set y2 -/// -void Region::setY2( const glabels::Distance& value ) -{ - mY2 = value; -} - - -/// -/// Convert to a QRectF -/// -QRectF Region::rect() const -{ - QRectF r; - - r.setX( min( mX1, mX2 ).pt() ); - r.setY( min( mY1, mY2 ).pt() ); - r.setWidth( fabs( mX2 - mX1 ).pt() ); - r.setHeight( fabs( mY2 - mY1 ).pt() ); - - return r; + + /// + /// Constructor + /// + Region::Region() : mX1(0), mY1(0), mX2(0), mY2(0) + { + // empty + } + + + /// + /// Constructor + /// + Region::Region( const Distance& x1, const Distance& y1, + const Distance& x2, const Distance& y2 ) + : mX1(x1), mY1(y1), mX2(x2), mY2(y2) + { + // empty + } + + + /// + /// Get x1 + /// + Distance Region::x1( void ) const + { + return mX1; + } + + + /// + /// Set x1 + /// + void Region::setX1( const Distance& value ) + { + mX1 = value; + } + + + /// + /// Get y1 + /// + Distance Region::y1( void ) const + { + return mY1; + } + + + /// + /// Set y1 + /// + void Region::setY1( const Distance& value ) + { + mY1 = value; + } + + + /// + /// Get x2 + /// + Distance Region::x2( void ) const + { + return mX2; + } + + + /// + /// Set x2 + /// + void Region::setX2( const Distance& value ) + { + mX2 = value; + } + + + /// + /// Get y2 + /// + Distance Region::y2( void ) const + { + return mY2; + } + + + /// + /// Set y2 + /// + void Region::setY2( const Distance& value ) + { + mY2 = value; + } + + + /// + /// Convert to a QRectF + /// + QRectF Region::rect() const + { + QRectF r; + + r.setX( min( mX1, mX2 ).pt() ); + r.setY( min( mY1, mY2 ).pt() ); + r.setWidth( fabs( mX2 - mX1 ).pt() ); + r.setHeight( fabs( mY2 - mY1 ).pt() ); + + return r; + } + } diff --git a/glabels/Region.h b/glabels/Region.h index 1fc8e2f..3d27a4a 100644 --- a/glabels/Region.h +++ b/glabels/Region.h @@ -27,70 +27,75 @@ #include "Distance.h" -/// -/// Label Region Type -/// -struct Region +namespace glabels { - ///////////////////////////////// - // Constructors - ///////////////////////////////// -public: - Region(); - Region( const glabels::Distance& x1, const glabels::Distance& y1, - const glabels::Distance& x2, const glabels::Distance& y2 ); + /// + /// Label Region Type + /// + struct Region + { + + ///////////////////////////////// + // Constructors + ///////////////////////////////// + public: + Region(); + Region( const Distance& x1, const Distance& y1, + const Distance& x2, const Distance& y2 ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - // - // X1 Property - // - glabels::Distance x1( void ) const; - void setX1( const glabels::Distance& value ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + // + // X1 Property + // + Distance x1( void ) const; + void setX1( const Distance& value ); - // - // Y1 Property - // - glabels::Distance y1( void ) const; - void setY1( const glabels::Distance& value ); + // + // Y1 Property + // + Distance y1( void ) const; + void setY1( const Distance& value ); - // - // X2 Property - // - glabels::Distance x2( void ) const; - void setX2( const glabels::Distance& value ); + // + // X2 Property + // + Distance x2( void ) const; + void setX2( const Distance& value ); - // - // Y2 Property - // - glabels::Distance y2( void ) const; - void setY2( const glabels::Distance& value ); + // + // Y2 Property + // + Distance y2( void ) const; + void setY2( const Distance& value ); - ///////////////////////////////// - // Methods - ///////////////////////////////// -public: - QRectF rect() const; + ///////////////////////////////// + // Methods + ///////////////////////////////// + public: + QRectF rect() const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - glabels::Distance mX1; - glabels::Distance mY1; - glabels::Distance mX2; - glabels::Distance mY2; -}; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + Distance mX1; + Distance mY1; + Distance mX2; + Distance mY2; + }; + +} #endif // Region_h diff --git a/glabels/SelectProductDialog.cpp b/glabels/SelectProductDialog.cpp index bbfefe5..987d04a 100644 --- a/glabels/SelectProductDialog.cpp +++ b/glabels/SelectProductDialog.cpp @@ -28,210 +28,216 @@ #include "TemplatePickerItem.h" -/// -/// Constructor -/// -SelectProductDialog::SelectProductDialog( QWidget *parent ) - : QDialog(parent), mCanceled(false) +namespace glabels { - setupUi( this ); - - pageSizeIsoCheck->setChecked( Settings::searchIsoPaperSizes() ); - pageSizeUsCheck->setChecked( Settings::searchUsPaperSizes() ); - pageSizeOtherCheck->setChecked( Settings::searchOtherPaperSizes() ); - - allCategoriesRadio->setChecked( Settings::searchAllCategories() ); - selectedCategoriesRadio->setChecked( !Settings::searchAllCategories() ); - - categoriesCheckContainer->setEnabled( !Settings::searchAllCategories() ); - mCategoryIdList = Settings::searchCategoryList(); - QList categories = glabels::Db::categories(); - foreach ( glabels::Category *category, categories ) + /// + /// Constructor + /// + SelectProductDialog::SelectProductDialog( QWidget *parent ) + : QDialog(parent), mCanceled(false) { - QCheckBox* check = new QCheckBox( category->name() ); - check->setChecked( mCategoryIdList.contains( category->id() ) ); - categoriesLayout->addWidget( check ); + setupUi( this ); - mCheckToCategoryMap[check] = category->id(); + pageSizeIsoCheck->setChecked( Settings::searchIsoPaperSizes() ); + pageSizeUsCheck->setChecked( Settings::searchUsPaperSizes() ); + pageSizeOtherCheck->setChecked( Settings::searchOtherPaperSizes() ); - connect( check, SIGNAL(clicked()), this, SLOT(onCategoryCheckClicked()) ); - } + allCategoriesRadio->setChecked( Settings::searchAllCategories() ); + selectedCategoriesRadio->setChecked( !Settings::searchAllCategories() ); - QList tmplates = glabels::Db::templates(); - templatePicker->setTemplates( tmplates ); - - if ( Settings::recentTemplateList().count() > 0 ) - { - modeNotebook->setCurrentIndex(1); - } - - onModeTabChanged(); -} - -/// -/// Get selected template -/// -const glabels::Template* SelectProductDialog::tmplate() const -{ - if ( !mCanceled ) - { - return templatePicker->selectedTemplate(); - } - else - { - return 0; - } -} - - -/// -/// Mode Notebook Tab Changed Slot -/// -void SelectProductDialog::onModeTabChanged() -{ - switch (modeNotebook->currentIndex()) - { - case 0: - // Search Tab - templatePicker->applyFilter( searchEntry->text(), - pageSizeIsoCheck->isChecked(), - pageSizeUsCheck->isChecked(), - pageSizeOtherCheck->isChecked(), - allCategoriesRadio->isChecked(), - mCategoryIdList ); - break; - case 1: - // Recent Tab - templatePicker->applyFilter( Settings::recentTemplateList() ); - break; - default: - qDebug() << "onModeTabChanged(): unknown tab!"; - } -} - - -/// -/// Search Entry Text Changed Slot -/// -void SelectProductDialog::onSearchEntryTextChanged() -{ - templatePicker->applyFilter( searchEntry->text(), - pageSizeIsoCheck->isChecked(), - pageSizeUsCheck->isChecked(), - pageSizeOtherCheck->isChecked(), - allCategoriesRadio->isChecked(), - mCategoryIdList ); -} - - -/// -/// Search Entry Text Changed Slot -/// -void SelectProductDialog::onSearchClearButtonClicked() -{ - searchEntry->setText( "" ); -} - - -/// -/// Page Size Check Clicked Slot -/// -void SelectProductDialog::onPageSizeCheckClicked() -{ - Settings::setSearchIsoPaperSizes( pageSizeIsoCheck->isChecked() ); - Settings::setSearchUsPaperSizes( pageSizeUsCheck->isChecked() ); - Settings::setSearchOtherPaperSizes( pageSizeOtherCheck->isChecked() ); - - templatePicker->applyFilter( searchEntry->text(), - pageSizeIsoCheck->isChecked(), - pageSizeUsCheck->isChecked(), - pageSizeOtherCheck->isChecked(), - allCategoriesRadio->isChecked(), - mCategoryIdList ); -} - - -/// -/// Category Radio Clicked Slot -/// -void SelectProductDialog::onCategoryRadioClicked() -{ - categoriesCheckContainer->setEnabled( selectedCategoriesRadio->isChecked() ); - loadCategoryList(); - - templatePicker->applyFilter( searchEntry->text(), - pageSizeIsoCheck->isChecked(), - pageSizeUsCheck->isChecked(), - pageSizeOtherCheck->isChecked(), - allCategoriesRadio->isChecked(), - mCategoryIdList ); - - Settings::setSearchAllCategories( allCategoriesRadio->isChecked() ); -} - - -/// -/// Category Check Clicked Slot -/// -void SelectProductDialog::onCategoryCheckClicked() -{ - loadCategoryList(); - - templatePicker->applyFilter( searchEntry->text(), - pageSizeIsoCheck->isChecked(), - pageSizeUsCheck->isChecked(), - pageSizeOtherCheck->isChecked(), - allCategoriesRadio->isChecked(), - mCategoryIdList ); - - - Settings::setSearchCategoryList( mCategoryIdList ); -} - - -/// -/// Template Picker Selection Changed Slot -/// -void SelectProductDialog::onTemplatePickerSelectionChanged() -{ - // Delay close. This should make the selection more apparent to the user. - mTimer.start( 125, this ); -} - - -/// -/// Cancel Button Clicked Slot -/// -void SelectProductDialog::onCancelButtonClicked() -{ - mCanceled = true; - close(); -} - - -/// -/// Cancel Button Clicked Slot -/// -void SelectProductDialog::timerEvent( QTimerEvent *event ) -{ - mTimer.stop(); - close(); -} - - -/// -/// Load category list -/// -void SelectProductDialog::loadCategoryList() -{ - mCategoryIdList.clear(); - - foreach( QCheckBox* check, mCheckToCategoryMap.keys() ) - { - if ( check->isChecked() ) + categoriesCheckContainer->setEnabled( !Settings::searchAllCategories() ); + mCategoryIdList = Settings::searchCategoryList(); + + QList categories = Db::categories(); + foreach ( Category *category, categories ) { - mCategoryIdList.append( mCheckToCategoryMap[check] ); + QCheckBox* check = new QCheckBox( category->name() ); + check->setChecked( mCategoryIdList.contains( category->id() ) ); + categoriesLayout->addWidget( check ); + + mCheckToCategoryMap[check] = category->id(); + + connect( check, SIGNAL(clicked()), this, SLOT(onCategoryCheckClicked()) ); + } + + QList tmplates = Db::templates(); + templatePicker->setTemplates( tmplates ); + + if ( Settings::recentTemplateList().count() > 0 ) + { + modeNotebook->setCurrentIndex(1); + } + + onModeTabChanged(); + } + + + /// + /// Get selected template + /// + const Template* SelectProductDialog::tmplate() const + { + if ( !mCanceled ) + { + return templatePicker->selectedTemplate(); + } + else + { + return 0; } } + + + /// + /// Mode Notebook Tab Changed Slot + /// + void SelectProductDialog::onModeTabChanged() + { + switch (modeNotebook->currentIndex()) + { + case 0: + // Search Tab + templatePicker->applyFilter( searchEntry->text(), + pageSizeIsoCheck->isChecked(), + pageSizeUsCheck->isChecked(), + pageSizeOtherCheck->isChecked(), + allCategoriesRadio->isChecked(), + mCategoryIdList ); + break; + case 1: + // Recent Tab + templatePicker->applyFilter( Settings::recentTemplateList() ); + break; + default: + qDebug() << "onModeTabChanged(): unknown tab!"; + } + } + + + /// + /// Search Entry Text Changed Slot + /// + void SelectProductDialog::onSearchEntryTextChanged() + { + templatePicker->applyFilter( searchEntry->text(), + pageSizeIsoCheck->isChecked(), + pageSizeUsCheck->isChecked(), + pageSizeOtherCheck->isChecked(), + allCategoriesRadio->isChecked(), + mCategoryIdList ); + } + + + /// + /// Search Entry Text Changed Slot + /// + void SelectProductDialog::onSearchClearButtonClicked() + { + searchEntry->setText( "" ); + } + + + /// + /// Page Size Check Clicked Slot + /// + void SelectProductDialog::onPageSizeCheckClicked() + { + Settings::setSearchIsoPaperSizes( pageSizeIsoCheck->isChecked() ); + Settings::setSearchUsPaperSizes( pageSizeUsCheck->isChecked() ); + Settings::setSearchOtherPaperSizes( pageSizeOtherCheck->isChecked() ); + + templatePicker->applyFilter( searchEntry->text(), + pageSizeIsoCheck->isChecked(), + pageSizeUsCheck->isChecked(), + pageSizeOtherCheck->isChecked(), + allCategoriesRadio->isChecked(), + mCategoryIdList ); + } + + + /// + /// Category Radio Clicked Slot + /// + void SelectProductDialog::onCategoryRadioClicked() + { + categoriesCheckContainer->setEnabled( selectedCategoriesRadio->isChecked() ); + loadCategoryList(); + + templatePicker->applyFilter( searchEntry->text(), + pageSizeIsoCheck->isChecked(), + pageSizeUsCheck->isChecked(), + pageSizeOtherCheck->isChecked(), + allCategoriesRadio->isChecked(), + mCategoryIdList ); + + Settings::setSearchAllCategories( allCategoriesRadio->isChecked() ); + } + + + /// + /// Category Check Clicked Slot + /// + void SelectProductDialog::onCategoryCheckClicked() + { + loadCategoryList(); + + templatePicker->applyFilter( searchEntry->text(), + pageSizeIsoCheck->isChecked(), + pageSizeUsCheck->isChecked(), + pageSizeOtherCheck->isChecked(), + allCategoriesRadio->isChecked(), + mCategoryIdList ); + + + Settings::setSearchCategoryList( mCategoryIdList ); + } + + + /// + /// Template Picker Selection Changed Slot + /// + void SelectProductDialog::onTemplatePickerSelectionChanged() + { + // Delay close. This should make the selection more apparent to the user. + mTimer.start( 125, this ); + } + + + /// + /// Cancel Button Clicked Slot + /// + void SelectProductDialog::onCancelButtonClicked() + { + mCanceled = true; + close(); + } + + + /// + /// Cancel Button Clicked Slot + /// + void SelectProductDialog::timerEvent( QTimerEvent *event ) + { + mTimer.stop(); + close(); + } + + + /// + /// Load category list + /// + void SelectProductDialog::loadCategoryList() + { + mCategoryIdList.clear(); + + foreach( QCheckBox* check, mCheckToCategoryMap.keys() ) + { + if ( check->isChecked() ) + { + mCategoryIdList.append( mCheckToCategoryMap[check] ); + } + } + } + } diff --git a/glabels/SelectProductDialog.h b/glabels/SelectProductDialog.h index 0dc7804..8434606 100644 --- a/glabels/SelectProductDialog.h +++ b/glabels/SelectProductDialog.h @@ -27,67 +27,72 @@ #include "ui_SelectProductDialog.h" -/// -/// New Label Dialog Widget -/// -class SelectProductDialog : public QDialog, public Ui_SelectProductDialog +namespace glabels { - Q_OBJECT + + /// + /// New Label Dialog Widget + /// + class SelectProductDialog : public QDialog, public Ui_SelectProductDialog + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - SelectProductDialog( QWidget *parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + SelectProductDialog( QWidget *parent = 0 ); - ///////////////////////////////// - // Accessors - ///////////////////////////////// - const glabels::Template* tmplate() const; + ///////////////////////////////// + // Accessors + ///////////////////////////////// + const Template* tmplate() const; - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onModeTabChanged(); - void onSearchEntryTextChanged(); - void onSearchClearButtonClicked(); - void onPageSizeCheckClicked(); - void onCategoryRadioClicked(); - void onCategoryCheckClicked(); - void onTemplatePickerSelectionChanged(); - void onCancelButtonClicked(); + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onModeTabChanged(); + void onSearchEntryTextChanged(); + void onSearchClearButtonClicked(); + void onPageSizeCheckClicked(); + void onCategoryRadioClicked(); + void onCategoryCheckClicked(); + void onTemplatePickerSelectionChanged(); + void onCancelButtonClicked(); - ///////////////////////////////// - // Events - ///////////////////////////////// -protected: - void timerEvent(QTimerEvent *event); + ///////////////////////////////// + // Events + ///////////////////////////////// + protected: + void timerEvent(QTimerEvent *event); - ///////////////////////////////// - // Private methods - ///////////////////////////////// -private: - void loadCategoryList(); + ///////////////////////////////// + // Private methods + ///////////////////////////////// + private: + void loadCategoryList(); - ///////////////////////////////// - // Private data - ///////////////////////////////// -private: - QBasicTimer mTimer; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + QBasicTimer mTimer; - QMap mCheckToCategoryMap; - QStringList mCategoryIdList; + QMap mCheckToCategoryMap; + QStringList mCategoryIdList; - bool mCanceled; + bool mCanceled; -}; + }; + +} #endif // SelectProductDialog_h diff --git a/glabels/Settings.cpp b/glabels/Settings.cpp index dd96ab4..b11214f 100644 --- a/glabels/Settings.cpp +++ b/glabels/Settings.cpp @@ -26,228 +26,237 @@ #include -Settings* Settings::mInstance = 0; - - -Settings::Settings() +namespace glabels { -} + + // + // Static data + // + Settings* Settings::mInstance = 0; -void Settings::init() -{ - if ( mInstance == 0 ) + Settings::Settings() { - mInstance = new Settings(); - } -} - - -Settings* Settings::instance() -{ - init(); - - return mInstance; -} - - -glabels::Units Settings::units() -{ - // Guess at a suitable default - QString defaultIdString; - if ( QLocale::system().measurementSystem() == QLocale::ImperialSystem ) - { - defaultIdString = glabels::Units(glabels::Units::IN).toIdString(); - } - else - { - defaultIdString = glabels::Units(glabels::Units::MM).toIdString(); - } - - mInstance->beginGroup( "Locale" ); - QString idString = mInstance->value( "units", defaultIdString ).toString(); - mInstance->endGroup(); - - return glabels::Units( idString ); -} - - -void Settings::setUnits( const glabels::Units& units ) -{ - QString idString = units.toIdString(); - - mInstance->beginGroup( "Locale" ); - mInstance->setValue( "units", idString ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -bool Settings::searchIsoPaperSizes() -{ - // Guess at a suitable default - bool defaultValue; - switch (QLocale::system().country()) - { - case QLocale::UnitedStates: - case QLocale::Canada: - defaultValue = false; - break; - - default: - defaultValue = true; - break; - } - - mInstance->beginGroup( "Search" ); - bool returnValue = mInstance->value( "isoPaperSizes", defaultValue ).toBool(); - mInstance->endGroup(); - - return returnValue; -} - - -void Settings::setSearchIsoPaperSizes( bool searchIsoPaperSizes ) -{ - mInstance->beginGroup( "Search" ); - mInstance->setValue( "isoPaperSizes", searchIsoPaperSizes ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -bool Settings::searchUsPaperSizes() -{ - // Guess at a suitable default - bool defaultValue; - switch (QLocale::system().country()) - { - case QLocale::UnitedStates: - case QLocale::Canada: - defaultValue = true; - break; - - default: - defaultValue = false; - break; - } - - mInstance->beginGroup( "Search" ); - bool returnValue = mInstance->value( "usPaperSizes", defaultValue ).toBool(); - mInstance->endGroup(); - - return returnValue; -} - - -void Settings::setSearchUsPaperSizes( bool searchUsPaperSizes ) -{ - mInstance->beginGroup( "Search" ); - mInstance->setValue( "usPaperSizes", searchUsPaperSizes ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -bool Settings::searchOtherPaperSizes() -{ - // Guess at a suitable default - bool defaultValue = true; - - mInstance->beginGroup( "Search" ); - bool returnValue = mInstance->value( "otherPaperSizes", defaultValue ).toBool(); - mInstance->endGroup(); - - return returnValue; -} - - -void Settings::setSearchOtherPaperSizes( bool searchOtherPaperSizes ) -{ - mInstance->beginGroup( "Search" ); - mInstance->setValue( "otherPaperSizes", searchOtherPaperSizes ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -bool Settings::searchAllCategories() -{ - // Guess at a suitable default - bool defaultValue = true; - - mInstance->beginGroup( "Search" ); - bool returnValue = mInstance->value( "allCategories", defaultValue ).toBool(); - mInstance->endGroup(); - - return returnValue; -} - - -void Settings::setSearchAllCategories( bool searchAllCategories ) -{ - mInstance->beginGroup( "Search" ); - mInstance->setValue( "allCategories", searchAllCategories ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -QStringList Settings::searchCategoryList() -{ - QStringList defaultList; - - mInstance->beginGroup( "Search" ); - QStringList returnList = mInstance->value( "categoryList", defaultList ).toStringList(); - mInstance->endGroup(); - - return returnList; -} - - -void Settings::setSearchCategoryList( const QStringList& searchCategoryList ) -{ - mInstance->beginGroup( "Search" ); - mInstance->setValue( "categoryList", searchCategoryList ); - mInstance->endGroup(); - - emit mInstance->changed(); -} - - -QStringList Settings::recentTemplateList() -{ - QStringList defaultList; - - mInstance->beginGroup( "Recent" ); - QStringList returnList = mInstance->value( "templates", defaultList ).toStringList(); - mInstance->endGroup(); - - return returnList; -} - - -void Settings::addToRecentTemplateList( const QString& name ) -{ - mInstance->beginGroup( "Recent" ); - - QStringList list = mInstance->value( "templates" ).toStringList(); - - list.removeAll( name ); - list.prepend( name ); - while ( list.count() > 10 ) - { - list.removeLast(); + // empty } - mInstance->setValue( "templates", list ); - mInstance->endGroup(); + void Settings::init() + { + if ( mInstance == 0 ) + { + mInstance = new Settings(); + } + } + + + Settings* Settings::instance() + { + init(); + + return mInstance; + } + + + Units Settings::units() + { + // Guess at a suitable default + QString defaultIdString; + if ( QLocale::system().measurementSystem() == QLocale::ImperialSystem ) + { + defaultIdString = Units(Units::IN).toIdString(); + } + else + { + defaultIdString = Units(Units::MM).toIdString(); + } + + mInstance->beginGroup( "Locale" ); + QString idString = mInstance->value( "units", defaultIdString ).toString(); + mInstance->endGroup(); + + return Units( idString ); + } + + + void Settings::setUnits( const Units& units ) + { + QString idString = units.toIdString(); + + mInstance->beginGroup( "Locale" ); + mInstance->setValue( "units", idString ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + bool Settings::searchIsoPaperSizes() + { + // Guess at a suitable default + bool defaultValue; + switch (QLocale::system().country()) + { + case QLocale::UnitedStates: + case QLocale::Canada: + defaultValue = false; + break; + + default: + defaultValue = true; + break; + } + + mInstance->beginGroup( "Search" ); + bool returnValue = mInstance->value( "isoPaperSizes", defaultValue ).toBool(); + mInstance->endGroup(); + + return returnValue; + } + + + void Settings::setSearchIsoPaperSizes( bool searchIsoPaperSizes ) + { + mInstance->beginGroup( "Search" ); + mInstance->setValue( "isoPaperSizes", searchIsoPaperSizes ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + bool Settings::searchUsPaperSizes() + { + // Guess at a suitable default + bool defaultValue; + switch (QLocale::system().country()) + { + case QLocale::UnitedStates: + case QLocale::Canada: + defaultValue = true; + break; + + default: + defaultValue = false; + break; + } + + mInstance->beginGroup( "Search" ); + bool returnValue = mInstance->value( "usPaperSizes", defaultValue ).toBool(); + mInstance->endGroup(); + + return returnValue; + } + + + void Settings::setSearchUsPaperSizes( bool searchUsPaperSizes ) + { + mInstance->beginGroup( "Search" ); + mInstance->setValue( "usPaperSizes", searchUsPaperSizes ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + bool Settings::searchOtherPaperSizes() + { + // Guess at a suitable default + bool defaultValue = true; + + mInstance->beginGroup( "Search" ); + bool returnValue = mInstance->value( "otherPaperSizes", defaultValue ).toBool(); + mInstance->endGroup(); + + return returnValue; + } + + + void Settings::setSearchOtherPaperSizes( bool searchOtherPaperSizes ) + { + mInstance->beginGroup( "Search" ); + mInstance->setValue( "otherPaperSizes", searchOtherPaperSizes ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + bool Settings::searchAllCategories() + { + // Guess at a suitable default + bool defaultValue = true; + + mInstance->beginGroup( "Search" ); + bool returnValue = mInstance->value( "allCategories", defaultValue ).toBool(); + mInstance->endGroup(); + + return returnValue; + } + + + void Settings::setSearchAllCategories( bool searchAllCategories ) + { + mInstance->beginGroup( "Search" ); + mInstance->setValue( "allCategories", searchAllCategories ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + QStringList Settings::searchCategoryList() + { + QStringList defaultList; + + mInstance->beginGroup( "Search" ); + QStringList returnList = mInstance->value( "categoryList", defaultList ).toStringList(); + mInstance->endGroup(); + + return returnList; + } + + + void Settings::setSearchCategoryList( const QStringList& searchCategoryList ) + { + mInstance->beginGroup( "Search" ); + mInstance->setValue( "categoryList", searchCategoryList ); + mInstance->endGroup(); + + emit mInstance->changed(); + } + + + QStringList Settings::recentTemplateList() + { + QStringList defaultList; + + mInstance->beginGroup( "Recent" ); + QStringList returnList = mInstance->value( "templates", defaultList ).toStringList(); + mInstance->endGroup(); + + return returnList; + } + + + void Settings::addToRecentTemplateList( const QString& name ) + { + mInstance->beginGroup( "Recent" ); + + QStringList list = mInstance->value( "templates" ).toStringList(); + + list.removeAll( name ); + list.prepend( name ); + while ( list.count() > 10 ) + { + list.removeLast(); + } + + mInstance->setValue( "templates", list ); + + mInstance->endGroup(); + + emit mInstance->changed(); + } - emit mInstance->changed(); } diff --git a/glabels/Settings.h b/glabels/Settings.h index a06ce07..efb0391 100644 --- a/glabels/Settings.h +++ b/glabels/Settings.h @@ -28,65 +28,70 @@ #include "Distance.h" -/// -/// Settings Singleton Class -/// -class Settings : public QSettings +namespace glabels { - Q_OBJECT + + /// + /// Settings Singleton Class + /// + class Settings : public QSettings + { + Q_OBJECT -public: - enum class PageSizeFamilty { ISO, US, }; + public: + enum class PageSizeFamilty { ISO, US, }; - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -private: - Settings(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + private: + Settings(); -public: - static void init(); - static Settings* instance(); + public: + static void init(); + static Settings* instance(); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void changed(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void changed(); - ///////////////////////////////// - // Accessors - ///////////////////////////////// -public: - static glabels::Units units(); - static void setUnits( const glabels::Units& units ); + ///////////////////////////////// + // Accessors + ///////////////////////////////// + public: + static Units units(); + static void setUnits( const Units& units ); - static bool searchIsoPaperSizes(); - static void setSearchIsoPaperSizes( bool searchIsoPaperSizes ); + static bool searchIsoPaperSizes(); + static void setSearchIsoPaperSizes( bool searchIsoPaperSizes ); - static bool searchUsPaperSizes(); - static void setSearchUsPaperSizes( bool searchUsPaperSizes ); + static bool searchUsPaperSizes(); + static void setSearchUsPaperSizes( bool searchUsPaperSizes ); - static bool searchOtherPaperSizes(); - static void setSearchOtherPaperSizes( bool searchOtherPaperSizes ); + static bool searchOtherPaperSizes(); + static void setSearchOtherPaperSizes( bool searchOtherPaperSizes ); - static bool searchAllCategories(); - static void setSearchAllCategories( bool searchAllCategories ); + static bool searchAllCategories(); + static void setSearchAllCategories( bool searchAllCategories ); - static QStringList searchCategoryList(); - static void setSearchCategoryList( const QStringList& searchCategoryList ); + static QStringList searchCategoryList(); + static void setSearchCategoryList( const QStringList& searchCategoryList ); - static QStringList recentTemplateList(); - static void addToRecentTemplateList( const QString& name ); + static QStringList recentTemplateList(); + static void addToRecentTemplateList( const QString& name ); -private: - static Settings* mInstance; + private: + static Settings* mInstance; -}; + }; + +} #endif // Settings_h diff --git a/glabels/SimplePreview.cpp b/glabels/SimplePreview.cpp index 4e58537..addb305 100644 --- a/glabels/SimplePreview.cpp +++ b/glabels/SimplePreview.cpp @@ -26,228 +26,233 @@ #include -// -// Private Configuration Data -// -namespace +namespace glabels { - const QColor paperColor( 255, 255, 255 ); - const QColor paperOutlineColor( 0, 0, 0 ); - const double paperOutlineWidthPixels = 1; - const QColor shadowColor( 64, 64, 64 ); - const double shadowOffsetPixels = 3; - const double shadowRadiusPixels = 12; - - const QColor labelColor( 255, 255, 255 ); - const QColor labelOutlineColor( 128, 128, 255 ); - const double labelOutlineWidthPixels = 2; - - const QColor arrowColor( 192, 192, 255, 128 ); - const double arrowScale = 0.35; - - const QColor upColor( 192, 192, 255, 128 ); - const double upScale = 0.15; - const QString upFontFamily( "Sans" ); -} - - -/// -/// Constructor -/// -SimplePreview::SimplePreview( QWidget *parent ) - : mTmplate(NULL), mRotateFlag(false), QGraphicsView(parent) -{ - mScene = new QGraphicsScene(); - setScene( mScene ); - - setAttribute(Qt::WA_TranslucentBackground); - viewport()->setAutoFillBackground(false); - - setFrameStyle( QFrame::NoFrame ); - setRenderHints( QPainter::Antialiasing ); -} - - -/// -/// Template Property Setter -/// -void SimplePreview::setTemplate( const glabels::Template *tmplate ) -{ - mTmplate = tmplate; - update(); -} - - -/// -/// Rotate Property Setter -/// -void SimplePreview::setRotate( bool rotateFlag ) -{ - mRotateFlag = rotateFlag; - update(); -} - - -/// -/// Resize Event Handler -/// -void SimplePreview::resizeEvent( QResizeEvent* event ) -{ - fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); -} - - -/// -/// Update View -/// -void SimplePreview::update() -{ - clearScene(); - - if ( mTmplate != NULL ) + // + // Private + // + namespace { - // Set scene up with a 5% margin around paper - glabels::Distance x = -0.05 * mTmplate->pageWidth(); - glabels::Distance y = -0.05 * mTmplate->pageHeight(); - glabels::Distance w = 1.10 * mTmplate->pageWidth(); - glabels::Distance h = 1.10 * mTmplate->pageHeight(); + const QColor paperColor( 255, 255, 255 ); + const QColor paperOutlineColor( 0, 0, 0 ); + const double paperOutlineWidthPixels = 1; - mScene->setSceneRect( x.pt(), y.pt(), w.pt(), h.pt() ); + const QColor shadowColor( 64, 64, 64 ); + const double shadowOffsetPixels = 3; + const double shadowRadiusPixels = 12; + + const QColor labelColor( 255, 255, 255 ); + const QColor labelOutlineColor( 128, 128, 255 ); + const double labelOutlineWidthPixels = 2; + + const QColor arrowColor( 192, 192, 255, 128 ); + const double arrowScale = 0.35; + + const QColor upColor( 192, 192, 255, 128 ); + const double upScale = 0.15; + const QString upFontFamily( "Sans" ); + } + + + /// + /// Constructor + /// + SimplePreview::SimplePreview( QWidget *parent ) + : mTmplate(NULL), mRotateFlag(false), QGraphicsView(parent) + { + mScene = new QGraphicsScene(); + setScene( mScene ); + + setAttribute(Qt::WA_TranslucentBackground); + viewport()->setAutoFillBackground(false); + + setFrameStyle( QFrame::NoFrame ); + setRenderHints( QPainter::Antialiasing ); + } + + + /// + /// Template Property Setter + /// + void SimplePreview::setTemplate( const Template *tmplate ) + { + mTmplate = tmplate; + update(); + } + + + /// + /// Rotate Property Setter + /// + void SimplePreview::setRotate( bool rotateFlag ) + { + mRotateFlag = rotateFlag; + update(); + } + + + /// + /// Resize Event Handler + /// + void SimplePreview::resizeEvent( QResizeEvent* event ) + { fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); - - drawPaper( mTmplate->pageWidth(), mTmplate->pageHeight() ); - drawLabels(); - drawArrow(); } -} -/// -/// Clear View -/// -void SimplePreview::clearScene() -{ - foreach ( QGraphicsItem *item, mScene->items() ) + /// + /// Update View + /// + void SimplePreview::update() { - mScene->removeItem( item ); - delete item; + clearScene(); + + if ( mTmplate != NULL ) + { + // Set scene up with a 5% margin around paper + Distance x = -0.05 * mTmplate->pageWidth(); + Distance y = -0.05 * mTmplate->pageHeight(); + Distance w = 1.10 * mTmplate->pageWidth(); + Distance h = 1.10 * mTmplate->pageHeight(); + + mScene->setSceneRect( x.pt(), y.pt(), w.pt(), h.pt() ); + fitInView( mScene->sceneRect(), Qt::KeepAspectRatio ); + + drawPaper( mTmplate->pageWidth(), mTmplate->pageHeight() ); + drawLabels(); + drawArrow(); + } } -} -/// -/// Draw Paper -/// -void SimplePreview::drawPaper( const glabels::Distance& pw, const glabels::Distance& ph ) -{ - QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(); - shadowEffect->setColor( shadowColor ); - shadowEffect->setOffset( shadowOffsetPixels ); - shadowEffect->setBlurRadius( shadowRadiusPixels ); + /// + /// Clear View + /// + void SimplePreview::clearScene() + { + foreach ( QGraphicsItem *item, mScene->items() ) + { + mScene->removeItem( item ); + delete item; + } + } - QBrush brush( paperColor ); - QPen pen( paperOutlineColor ); - pen.setCosmetic( true ); - pen.setWidthF( paperOutlineWidthPixels ); - QGraphicsRectItem *pageItem = new QGraphicsRectItem( 0, 0, pw.pt(), ph.pt() ); - pageItem->setBrush( brush ); - pageItem->setPen( pen ); - pageItem->setGraphicsEffect( shadowEffect ); + /// + /// Draw Paper + /// + void SimplePreview::drawPaper( const Distance& pw, const Distance& ph ) + { + QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(); + shadowEffect->setColor( shadowColor ); + shadowEffect->setOffset( shadowOffsetPixels ); + shadowEffect->setBlurRadius( shadowRadiusPixels ); + + QBrush brush( paperColor ); + QPen pen( paperOutlineColor ); + pen.setCosmetic( true ); + pen.setWidthF( paperOutlineWidthPixels ); + + QGraphicsRectItem *pageItem = new QGraphicsRectItem( 0, 0, pw.pt(), ph.pt() ); + pageItem->setBrush( brush ); + pageItem->setPen( pen ); + pageItem->setGraphicsEffect( shadowEffect ); - mScene->addItem( pageItem ); -} - - -/// -/// Draw Labels on Paper -/// -void SimplePreview::drawLabels() -{ - glabels::Frame *frame = mTmplate->frames().first(); - - foreach (glabels::Point origin, frame->getOrigins() ) - { - drawLabel( origin.x(), origin.y(), frame->path() ); - } -} - - -/// -/// Draw a Single Label at x,y -/// -void SimplePreview::drawLabel( const glabels::Distance& x, - const glabels::Distance& y, - const QPainterPath& path ) -{ - QBrush brush( labelColor ); - QPen pen( labelOutlineColor ); - pen.setCosmetic( true ); - pen.setWidthF( labelOutlineWidthPixels ); - - QGraphicsPathItem *labelItem = new QGraphicsPathItem( path ); - labelItem->setBrush( brush ); - labelItem->setPen( pen ); - labelItem->setPos( x.pt(), y.pt() ); - - mScene->addItem( labelItem ); -} - - -/// -/// Draw Arrow Indicating Top of First Label -/// -void SimplePreview::drawArrow() -{ - glabels::Frame *frame = mTmplate->frames().first(); - - glabels::Distance w = frame->w(); - glabels::Distance h = frame->h(); - - glabels::Distance min = glabels::min( w, h ); - - QPen pen( arrowColor ); - pen.setWidthF( 0.25*min.pt()*arrowScale ); - pen.setCapStyle( Qt::FlatCap ); - pen.setJoinStyle( Qt::MiterJoin ); - - QBrush brush( upColor ); - - glabels::Point origin = frame->getOrigins().first(); - glabels::Distance x0 = origin.x(); - glabels::Distance y0 = origin.y(); - - QPainterPath path; - path.moveTo( 0, min.pt()*arrowScale/3 ); - path.lineTo( 0, -min.pt()*arrowScale ); - path.moveTo( -min.pt()*arrowScale/2, -min.pt()*arrowScale/2 ); - path.lineTo( 0, -min.pt()*arrowScale ); - path.lineTo( min.pt()*arrowScale/2, -min.pt()*arrowScale/2 ); - - QGraphicsPathItem *arrowItem = new QGraphicsPathItem( path ); - arrowItem->setPen( pen ); - arrowItem->setPos( (x0+w/2).pt(), (y0+h/2).pt() ); - if ( mRotateFlag ) - { - arrowItem->setRotation( -90 ); + mScene->addItem( pageItem ); } - QGraphicsSimpleTextItem *upItem = new QGraphicsSimpleTextItem( tr("Up") ); - upItem->setBrush( brush ); - upItem->setFont( QFont( upFontFamily, min.pt()*upScale, QFont::Bold ) ); - upItem->setPos( (x0+w/2).pt(), (y0+h/2).pt() ); - QRectF rect = upItem->boundingRect(); - if ( mRotateFlag ) + + /// + /// Draw Labels on Paper + /// + void SimplePreview::drawLabels() { - upItem->setPos( upItem->x()+min.pt()/8, upItem->y()+rect.width()/2 ); - upItem->setRotation( -90 ); - } - else - { - upItem->setPos( upItem->x()-rect.width()/2, upItem->y()+min.pt()/8 ); + Frame *frame = mTmplate->frames().first(); + + foreach (Point origin, frame->getOrigins() ) + { + drawLabel( origin.x(), origin.y(), frame->path() ); + } + } + + + /// + /// Draw a Single Label at x,y + /// + void SimplePreview::drawLabel( const Distance& x, + const Distance& y, + const QPainterPath& path ) + { + QBrush brush( labelColor ); + QPen pen( labelOutlineColor ); + pen.setCosmetic( true ); + pen.setWidthF( labelOutlineWidthPixels ); + + QGraphicsPathItem *labelItem = new QGraphicsPathItem( path ); + labelItem->setBrush( brush ); + labelItem->setPen( pen ); + labelItem->setPos( x.pt(), y.pt() ); + + mScene->addItem( labelItem ); + } + + + /// + /// Draw Arrow Indicating Top of First Label + /// + void SimplePreview::drawArrow() + { + Frame *frame = mTmplate->frames().first(); + + Distance w = frame->w(); + Distance h = frame->h(); + + Distance minWH = min( w, h ); + + QPen pen( arrowColor ); + pen.setWidthF( 0.25*minWH.pt()*arrowScale ); + pen.setCapStyle( Qt::FlatCap ); + pen.setJoinStyle( Qt::MiterJoin ); + + QBrush brush( upColor ); + + Point origin = frame->getOrigins().first(); + Distance x0 = origin.x(); + Distance y0 = origin.y(); + + QPainterPath path; + path.moveTo( 0, minWH.pt()*arrowScale/3 ); + path.lineTo( 0, -minWH.pt()*arrowScale ); + path.moveTo( -minWH.pt()*arrowScale/2, -minWH.pt()*arrowScale/2 ); + path.lineTo( 0, -minWH.pt()*arrowScale ); + path.lineTo( minWH.pt()*arrowScale/2, -minWH.pt()*arrowScale/2 ); + + QGraphicsPathItem *arrowItem = new QGraphicsPathItem( path ); + arrowItem->setPen( pen ); + arrowItem->setPos( (x0+w/2).pt(), (y0+h/2).pt() ); + if ( mRotateFlag ) + { + arrowItem->setRotation( -90 ); + } + + QGraphicsSimpleTextItem *upItem = new QGraphicsSimpleTextItem( tr("Up") ); + upItem->setBrush( brush ); + upItem->setFont( QFont( upFontFamily, minWH.pt()*upScale, QFont::Bold ) ); + upItem->setPos( (x0+w/2).pt(), (y0+h/2).pt() ); + QRectF rect = upItem->boundingRect(); + if ( mRotateFlag ) + { + upItem->setPos( upItem->x()+minWH.pt()/8, upItem->y()+rect.width()/2 ); + upItem->setRotation( -90 ); + } + else + { + upItem->setPos( upItem->x()-rect.width()/2, upItem->y()+minWH.pt()/8 ); + } + + mScene->addItem( arrowItem ); + mScene->addItem( upItem ); } - mScene->addItem( arrowItem ); - mScene->addItem( upItem ); } diff --git a/glabels/SimplePreview.h b/glabels/SimplePreview.h index 9482c7a..9aa2f3c 100644 --- a/glabels/SimplePreview.h +++ b/glabels/SimplePreview.h @@ -29,60 +29,63 @@ #include "Template.h" -/// -/// Simple Preview Widget -/// -class SimplePreview : public QGraphicsView +namespace glabels { - Q_OBJECT + + /// + /// Simple Preview Widget + /// + class SimplePreview : public QGraphicsView + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - SimplePreview( QWidget *parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + SimplePreview( QWidget *parent = 0 ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - void setTemplate( const glabels::Template *tmplate ); - void setRotate( bool rotateFlag ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + void setTemplate( const Template *tmplate ); + void setRotate( bool rotateFlag ); - ///////////////////////////////////// - // Event handlers - ///////////////////////////////////// -protected: - void resizeEvent( QResizeEvent* event ); + ///////////////////////////////////// + // Event handlers + ///////////////////////////////////// + protected: + void resizeEvent( QResizeEvent* event ); - ///////////////////////////////// - // Internal Methods - ///////////////////////////////// -private: - void update(); - void clearScene(); - void drawPaper( const glabels::Distance& pw, const glabels::Distance& ph ); - void drawLabels(); - void drawLabel( const glabels::Distance& x, - const glabels::Distance& y, - const QPainterPath& path ); - void drawArrow(); + ///////////////////////////////// + // Internal Methods + ///////////////////////////////// + private: + void update(); + void clearScene(); + void drawPaper( const Distance& pw, const Distance& ph ); + void drawLabels(); + void drawLabel( const Distance& x, const Distance& y, const QPainterPath& path ); + void drawArrow(); - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - const glabels::Template *mTmplate; - bool mRotateFlag; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + const Template *mTmplate; + bool mRotateFlag; - QGraphicsScene *mScene; + QGraphicsScene *mScene; -}; + }; + +} #endif // SimplePreview_h diff --git a/glabels/Size.cpp b/glabels/Size.cpp index a1090a2..c173b2e 100644 --- a/glabels/Size.cpp +++ b/glabels/Size.cpp @@ -21,67 +21,74 @@ #include "Size.h" -/// -/// Constructor -/// -Size::Size() : mW(0), mH(0) +namespace glabels { -} - - -/// -/// Constructor -/// -Size::Size( const glabels::Distance& w, const glabels::Distance& h ) : mW(w), mH(h) -{ -} - - -/// -/// Get w -/// -glabels::Distance Size::w( void ) const -{ - return mW; -} - - -/// -/// Set w -/// -void Size::setW( const glabels::Distance& value ) -{ - mW = value; -} - - -/// -/// Get h -/// -glabels::Distance Size::h( void ) const -{ - return mH; -} - - -/// -/// Set h -/// -void Size::setH( const glabels::Distance& value ) -{ - mH = value; -} - - -/// -/// Convert to a QSizeF -/// -QSizeF Size::qSizeF() const -{ - QSizeF s; - - s.setWidth( mW.pt() ); - s.setHeight( mH.pt() ); - - return s; + + /// + /// Constructor + /// + Size::Size() : mW(0), mH(0) + { + // empty + } + + + /// + /// Constructor + /// + Size::Size( const Distance& w, const Distance& h ) : mW(w), mH(h) + { + // empty + } + + + /// + /// Get w + /// + Distance Size::w( void ) const + { + return mW; + } + + + /// + /// Set w + /// + void Size::setW( const Distance& value ) + { + mW = value; + } + + + /// + /// Get h + /// + Distance Size::h( void ) const + { + return mH; + } + + + /// + /// Set h + /// + void Size::setH( const Distance& value ) + { + mH = value; + } + + + /// + /// Convert to a QSizeF + /// + QSizeF Size::qSizeF() const + { + QSizeF s; + + s.setWidth( mW.pt() ); + s.setHeight( mH.pt() ); + + return s; + } + } diff --git a/glabels/Size.h b/glabels/Size.h index c2f56de..0087cf7 100644 --- a/glabels/Size.h +++ b/glabels/Size.h @@ -27,53 +27,58 @@ #include "Distance.h" -/// -/// Size Type -/// -class Size +namespace glabels { - ///////////////////////////////// - // Constructors - ///////////////////////////////// -public: - Size(); - Size( const glabels::Distance& w, const glabels::Distance& h ); + /// + /// Size Type + /// + class Size + { + + ///////////////////////////////// + // Constructors + ///////////////////////////////// + public: + Size(); + Size( const Distance& w, const Distance& h ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - // - // w Property - // - glabels::Distance w( void ) const; - void setW( const glabels::Distance& value ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + // + // w Property + // + Distance w( void ) const; + void setW( const Distance& value ); - // - // H Property - // - glabels::Distance h( void ) const; - void setH( const glabels::Distance& value ); + // + // H Property + // + Distance h( void ) const; + void setH( const Distance& value ); - ///////////////////////////////// - // Methods - ///////////////////////////////// -public: - QSizeF qSizeF() const; + ///////////////////////////////// + // Methods + ///////////////////////////////// + public: + QSizeF qSizeF() const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - glabels::Distance mW; - glabels::Distance mH; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + Distance mW; + Distance mH; -}; + }; + +} #endif // Size_h diff --git a/glabels/StartupView.cpp b/glabels/StartupView.cpp index efc40e9..7098bed 100644 --- a/glabels/StartupView.cpp +++ b/glabels/StartupView.cpp @@ -27,32 +27,37 @@ #include "MainWindow.h" -/// -/// Constructor -/// -StartupView::StartupView( MainWindow* window ) - : QWidget(window), mWindow(window) +namespace glabels { - setupUi( this ); - QString titleImage = ":images/glabels-label-designer.png"; - titleLabel->setPixmap( QPixmap( titleImage ) ); -} - - -/// -/// "New Project" Button Clicked Slot -/// -void StartupView::onNewProjectButtonClicked() -{ - File::newLabel( mWindow ); -} - - -/// -/// "Open Project" Button Clicked Slot -/// -void StartupView::onOpenProjectButtonClicked() -{ - File::open( mWindow ); + /// + /// Constructor + /// + StartupView::StartupView( MainWindow* window ) + : QWidget(window), mWindow(window) + { + setupUi( this ); + + QString titleImage = ":images/glabels-label-designer.png"; + titleLabel->setPixmap( QPixmap( titleImage ) ); + } + + + /// + /// "New Project" Button Clicked Slot + /// + void StartupView::onNewProjectButtonClicked() + { + File::newLabel( mWindow ); + } + + + /// + /// "Open Project" Button Clicked Slot + /// + void StartupView::onOpenProjectButtonClicked() + { + File::open( mWindow ); + } + } diff --git a/glabels/StartupView.h b/glabels/StartupView.h index 15fbad7..164197f 100644 --- a/glabels/StartupView.h +++ b/glabels/StartupView.h @@ -24,40 +24,46 @@ #include "ui_StartupView.h" -// Forward references -class MainWindow; - -/// -/// Startup View Widget -/// -class StartupView : public QWidget, public Ui_StartupView +namespace glabels { - Q_OBJECT + + // Forward references + class MainWindow; - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - StartupView( MainWindow* window ); + /// + /// Startup View Widget + /// + class StartupView : public QWidget, public Ui_StartupView + { + Q_OBJECT - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onNewProjectButtonClicked(); - void onOpenProjectButtonClicked(); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + StartupView( MainWindow* window ); + + + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onNewProjectButtonClicked(); + void onOpenProjectButtonClicked(); - ///////////////////////////////// - // Private data - ///////////////////////////////// -private: - MainWindow* mWindow; + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + MainWindow* mWindow; -}; + }; + +} #endif // StartupView_h diff --git a/glabels/StrUtil.cpp b/glabels/StrUtil.cpp index b4a742e..48f3493 100644 --- a/glabels/StrUtil.cpp +++ b/glabels/StrUtil.cpp @@ -24,21 +24,24 @@ #include -namespace -{ - const double FRAC_EPSILON = 0.00005; - const double denom[] = { 1.0, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0, 0.0 }; - const char* denom_string[] = { "1", "₂", "₃", "₄", "₈", "₁₆", "₃₂", NULL }; - const char* num_string[] = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹", - "¹⁰", "¹¹", "¹²", "¹³", "¹⁴", "¹⁵", "¹⁶", "¹⁷", "¹⁸", "¹⁹", - "²⁰", "²¹", "²²", "²³", "²⁴", "²⁵", "²⁶", "²⁷", "²⁸", "²⁹", - "³⁰", "³¹" }; -} - - namespace glabels { + // + // Private + // + namespace + { + const double FRAC_EPSILON = 0.00005; + const double denom[] = { 1.0, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0, 0.0 }; + const char* denom_string[] = { "1", "₂", "₃", "₄", "₈", "₁₆", "₃₂", NULL }; + const char* num_string[] = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹", + "¹⁰", "¹¹", "¹²", "¹³", "¹⁴", "¹⁵", "¹⁶", "¹⁷", "¹⁸", "¹⁹", + "²⁰", "²¹", "²²", "²³", "²⁴", "²⁵", "²⁶", "²⁷", "²⁸", "²⁹", + "³⁰", "³¹" }; + } + + namespace StrUtil { diff --git a/glabels/TemplatePicker.cpp b/glabels/TemplatePicker.cpp index 20d5344..fad858d 100644 --- a/glabels/TemplatePicker.cpp +++ b/glabels/TemplatePicker.cpp @@ -26,123 +26,128 @@ #include "TemplatePickerItem.h" -/// -/// Constructor -/// -TemplatePicker::TemplatePicker( QWidget *parent ) : QListWidget(parent) +namespace glabels { - setViewMode( QListView::IconMode ); - setResizeMode( QListView::Adjust ); - setSpacing( 24 ); - setWordWrap( true ); - setUniformItemSizes( true ); - setIconSize( QSize(glabels::TEMPLATE_PREVIEW_SIZE, glabels::TEMPLATE_PREVIEW_SIZE) ); -} - -/// -/// Set List of Templates to Pick From -/// -void TemplatePicker::setTemplates( const QList &tmplates ) -{ - foreach (glabels::Template *tmplate, tmplates) + /// + /// Constructor + /// + TemplatePicker::TemplatePicker( QWidget *parent ) : QListWidget(parent) { - TemplatePickerItem *item = new TemplatePickerItem( tmplate, this ); + setViewMode( QListView::IconMode ); + setResizeMode( QListView::Adjust ); + setSpacing( 24 ); + setWordWrap( true ); + setUniformItemSizes( true ); + setIconSize( QSize(TEMPLATE_PREVIEW_SIZE, TEMPLATE_PREVIEW_SIZE) ); } -} -/// -/// Apply Filter to Narrow Template Choices by search criteria -/// -void TemplatePicker::applyFilter( const QString& searchString, - bool isoMask, bool usMask, bool otherMask, - bool anyCategory, const QStringList& categoryIds ) -{ - foreach ( QListWidgetItem *item, findItems( "*", Qt::MatchWildcard ) ) + /// + /// Set List of Templates to Pick From + /// + void TemplatePicker::setTemplates( const QList &tmplates ) { - TemplatePickerItem *tItem = dynamic_cast(item); + foreach (Template *tmplate, tmplates) + { + TemplatePickerItem *item = new TemplatePickerItem( tmplate, this ); + } + } - bool nameMask = tItem->tmplate()->name().contains( searchString, Qt::CaseInsensitive ); + + /// + /// Apply Filter to Narrow Template Choices by search criteria + /// + void TemplatePicker::applyFilter( const QString& searchString, + bool isoMask, bool usMask, bool otherMask, + bool anyCategory, const QStringList& categoryIds ) + { + foreach ( QListWidgetItem *item, findItems( "*", Qt::MatchWildcard ) ) + { + TemplatePickerItem *tItem = dynamic_cast(item); + + bool nameMask = tItem->tmplate()->name().contains( searchString, Qt::CaseInsensitive ); - bool sizeMask = - (isoMask && tItem->tmplate()->isSizeIso()) || - (usMask && tItem->tmplate()->isSizeUs()) || - (otherMask && tItem->tmplate()->isSizeOther()); + bool sizeMask = + (isoMask && tItem->tmplate()->isSizeIso()) || + (usMask && tItem->tmplate()->isSizeUs()) || + (otherMask && tItem->tmplate()->isSizeOther()); - bool categoryMask; - if ( anyCategory ) - { - categoryMask = true; - } - else - { - categoryMask = false; - foreach ( QString id, categoryIds ) + bool categoryMask; + if ( anyCategory ) { - categoryMask = categoryMask || tItem->tmplate()->hasCategory( id ); + categoryMask = true; + } + else + { + categoryMask = false; + foreach ( QString id, categoryIds ) + { + categoryMask = categoryMask || tItem->tmplate()->hasCategory( id ); + } } - } - if ( nameMask && sizeMask && categoryMask ) - { - item->setHidden( false ); - } - else - { - item->setHidden( true ); - item->setSelected( false ); - } - } -} - - -/// -/// Apply Filter to Narrow Template Choices by a list of names -/// -void TemplatePicker::applyFilter( const QStringList& names ) -{ - foreach ( QListWidgetItem *item, findItems( "*", Qt::MatchWildcard ) ) - { - TemplatePickerItem *tItem = dynamic_cast(item); - - bool match = false; - foreach ( QString name, names ) - { - if ( tItem->tmplate()->name() == name ) + if ( nameMask && sizeMask && categoryMask ) { - match = true; - break; + item->setHidden( false ); + } + else + { + item->setHidden( true ); + item->setSelected( false ); } } + } - if ( match ) + + /// + /// Apply Filter to Narrow Template Choices by a list of names + /// + void TemplatePicker::applyFilter( const QStringList& names ) + { + foreach ( QListWidgetItem *item, findItems( "*", Qt::MatchWildcard ) ) { - item->setHidden( false ); + TemplatePickerItem *tItem = dynamic_cast(item); + + bool match = false; + foreach ( QString name, names ) + { + if ( tItem->tmplate()->name() == name ) + { + match = true; + break; + } + } + + if ( match ) + { + item->setHidden( false ); + } + else + { + item->setHidden( true ); + item->setSelected( false ); + } + } + } + + + /// + /// Get Currently Selected Template + /// + const Template *TemplatePicker::selectedTemplate() + { + QList items = selectedItems(); + if ( items.isEmpty() ) + { + return NULL; } else { - item->setHidden( true ); - item->setSelected( false ); + TemplatePickerItem *tItem = dynamic_cast(items.first()); + return tItem->tmplate(); } } -} - -/// -/// Get Currently Selected Template -/// -const glabels::Template *TemplatePicker::selectedTemplate() -{ - QList items = selectedItems(); - if ( items.isEmpty() ) - { - return NULL; - } - else - { - TemplatePickerItem *tItem = dynamic_cast(items.first()); - return tItem->tmplate(); - } } diff --git a/glabels/TemplatePicker.h b/glabels/TemplatePicker.h index c0779c4..2cc1767 100644 --- a/glabels/TemplatePicker.h +++ b/glabels/TemplatePicker.h @@ -28,40 +28,45 @@ #include "Template.h" -/// -/// Template Picker Widget -/// -class TemplatePicker : public QListWidget +namespace glabels { - Q_OBJECT + + /// + /// Template Picker Widget + /// + class TemplatePicker : public QListWidget + { + Q_OBJECT - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - TemplatePicker( QWidget *parent = 0 ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + TemplatePicker( QWidget *parent = 0 ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - void setTemplates( const QList &tmplates ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + void setTemplates( const QList &tmplates ); - ///////////////////////////////// - // Methods - ///////////////////////////////// - void applyFilter( const QString& searchString, - bool isoMask, bool usMask, bool otherMask, - bool anyCategory, const QStringList& categoryIds ); + ///////////////////////////////// + // Methods + ///////////////////////////////// + void applyFilter( const QString& searchString, + bool isoMask, bool usMask, bool otherMask, + bool anyCategory, const QStringList& categoryIds ); - void applyFilter( const QStringList& names ); + void applyFilter( const QStringList& names ); - const glabels::Template *selectedTemplate(); + const Template *selectedTemplate(); -}; + }; + +} #endif // TemplatePicker_h diff --git a/glabels/TemplatePickerItem.cpp b/glabels/TemplatePickerItem.cpp index 24d8187..9b65967 100644 --- a/glabels/TemplatePickerItem.cpp +++ b/glabels/TemplatePickerItem.cpp @@ -26,27 +26,30 @@ #include -/// -/// Constructor -/// -TemplatePickerItem::TemplatePickerItem( glabels::Template *tmplate, - QListWidget *parent ) - : QListWidgetItem(parent) +namespace glabels { - mTmplate = tmplate; - setIcon( QIcon(tmplate->preview()) ); - setText( tmplate->name() ); + /// + /// Constructor + /// + TemplatePickerItem::TemplatePickerItem( Template *tmplate, QListWidget *parent ) + : QListWidgetItem(parent) + { + mTmplate = tmplate; + + setIcon( QIcon(tmplate->preview()) ); + setText( tmplate->name() ); + + setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); + } + + + /// + /// Template Property Getter + /// + const Template *TemplatePickerItem::tmplate() const + { + return mTmplate; + } - setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); } - - -/// -/// Template Property Getter -/// -const glabels::Template *TemplatePickerItem::tmplate() const -{ - return mTmplate; -} - diff --git a/glabels/TemplatePickerItem.h b/glabels/TemplatePickerItem.h index 2c7167a..fe4c216 100644 --- a/glabels/TemplatePickerItem.h +++ b/glabels/TemplatePickerItem.h @@ -28,33 +28,38 @@ #include "Template.h" -/// -/// Template Picker Item Widget -/// -class TemplatePickerItem : public QListWidgetItem +namespace glabels { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - TemplatePickerItem( glabels::Template *tmplate, QListWidget *parent = 0 ); + /// + /// Template Picker Item Widget + /// + class TemplatePickerItem : public QListWidgetItem + { + + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + TemplatePickerItem( Template *tmplate, QListWidget *parent = 0 ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - const glabels::Template *tmplate() const; + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + const Template *tmplate() const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: - glabels::Template *mTmplate; + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: + Template *mTmplate; -}; + }; + +} #endif // TemplatePickerItem_h diff --git a/glabels/TextNode.cpp b/glabels/TextNode.cpp index 0254fbe..e5d8ca4 100644 --- a/glabels/TextNode.cpp +++ b/glabels/TextNode.cpp @@ -21,122 +21,129 @@ #include "TextNode.h" -/// -/// Default Constructor -/// -TextNode::TextNode() - : mIsField(false), mData("") +namespace glabels { -} - -/// -/// Constructor from Data -/// -TextNode::TextNode( bool isField, const QString &data ) - : mIsField(isField), mData(data) -{ -} - - -/// -/// == Operator -/// -bool TextNode::operator==( const TextNode& other ) -{ - return (mIsField == other.mIsField) && - (mData == other.mData); -} - - -/// -/// != Operator -/// -bool TextNode::operator!=( const TextNode& other ) -{ - return (mIsField != other.mIsField) || - (mData != other.mData); -} - - -/// -/// isField? Property Getter -/// -bool TextNode::isField() const -{ - return mIsField; -} - - -/// -/// isField Flag Property Setter -/// -void TextNode::setField( bool isField ) -{ - mIsField = isField; -} - - -/// -/// Data Property Getter -/// -const QString& TextNode::data() const -{ - return mData; -} - - -/// -/// Data Property Setter -/// -void TextNode::setData( const QString& data ) -{ - mData = data; -} - - -/// -/// Get text, expand if necessary -/// -QString TextNode::text( merge::Record* record ) const -{ - if ( mIsField ) + /// + /// Default Constructor + /// + TextNode::TextNode() + : mIsField(false), mData("") { - if ( !record ) - { - return QString("${%1}").arg( mData ); - } - else - { - if ( record->contains( mData ) ) - { - return (*record)[ mData ]; - } - else - { - return ""; - } - } + // empty } - else + + + /// + /// Constructor from Data + /// + TextNode::TextNode( bool isField, const QString &data ) + : mIsField(isField), mData(data) + { + // empty + } + + + /// + /// == Operator + /// + bool TextNode::operator==( const TextNode& other ) + { + return (mIsField == other.mIsField) && + (mData == other.mData); + } + + + /// + /// != Operator + /// + bool TextNode::operator!=( const TextNode& other ) + { + return (mIsField != other.mIsField) || + (mData != other.mData); + } + + + /// + /// isField? Property Getter + /// + bool TextNode::isField() const + { + return mIsField; + } + + + /// + /// isField Flag Property Setter + /// + void TextNode::setField( bool isField ) + { + mIsField = isField; + } + + + /// + /// Data Property Getter + /// + const QString& TextNode::data() const { return mData; } -} -/// -/// Is it an empty field -/// -bool TextNode::isEmptyField( merge::Record* record ) const -{ - if ( record && mIsField ) + /// + /// Data Property Setter + /// + void TextNode::setData( const QString& data ) { - if ( record->contains( mData ) ) + mData = data; + } + + + /// + /// Get text, expand if necessary + /// + QString TextNode::text( merge::Record* record ) const + { + if ( mIsField ) { - return (*record)[mData].isEmpty(); + if ( !record ) + { + return QString("${%1}").arg( mData ); + } + else + { + if ( record->contains( mData ) ) + { + return (*record)[ mData ]; + } + else + { + return ""; + } + } + } + else + { + return mData; } } - return false; + + /// + /// Is it an empty field + /// + bool TextNode::isEmptyField( merge::Record* record ) const + { + if ( record && mIsField ) + { + if ( record->contains( mData ) ) + { + return (*record)[mData].isEmpty(); + } + } + + return false; + } + } diff --git a/glabels/TextNode.h b/glabels/TextNode.h index 26b7599..522b9e4 100644 --- a/glabels/TextNode.h +++ b/glabels/TextNode.h @@ -27,63 +27,68 @@ #include "Merge/Record.h" -/// -/// Text Node Type -/// -struct TextNode +namespace glabels { - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - TextNode(); + /// + /// Text Node Type + /// + struct TextNode + { - TextNode( bool isField, const QString &data ); + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + TextNode(); + + TextNode( bool isField, const QString &data ); - ///////////////////////////////// - // Operators - ///////////////////////////////// -public: - bool operator==( const TextNode& other ); + ///////////////////////////////// + // Operators + ///////////////////////////////// + public: + bool operator==( const TextNode& other ); - bool operator!=( const TextNode& other ); + bool operator!=( const TextNode& other ); - ///////////////////////////////// - // Properties - ///////////////////////////////// -public: - // - // is field? Property - // - bool isField() const; - void setField( bool isField ); + ///////////////////////////////// + // Properties + ///////////////////////////////// + public: + // + // is field? Property + // + bool isField() const; + void setField( bool isField ); - // - // Data Property - // - const QString& data() const; - void setData( const QString& data ); + // + // Data Property + // + const QString& data() const; + void setData( const QString& data ); - ///////////////////////////////// - // Misc. Methods - ///////////////////////////////// - QString text( merge::Record* record ) const; - bool isEmptyField( merge::Record* record ) const; + ///////////////////////////////// + // Misc. Methods + ///////////////////////////////// + QString text( merge::Record* record ) const; + bool isEmptyField( merge::Record* record ) const; - ///////////////////////////////// - // Private Data - ///////////////////////////////// -private: + ///////////////////////////////// + // Private Data + ///////////////////////////////// + private: - bool mIsField; - QString mData; + bool mIsField; + QString mData; -}; + }; + +} #endif // TextNode_h diff --git a/glabels/UndoRedoModel.cpp b/glabels/UndoRedoModel.cpp index 7eab0cc..219e442 100644 --- a/glabels/UndoRedoModel.cpp +++ b/glabels/UndoRedoModel.cpp @@ -24,233 +24,240 @@ #include "LabelModel.h" -/// -/// Constructor -/// -UndoRedoModel::UndoRedoModel( LabelModel* model ) +namespace glabels { - mModel = model; - mNewSelection = true; - connect( model, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()) ); -} - - -/// -/// Destructor -/// -UndoRedoModel::~UndoRedoModel() -{ -} - - -/// -/// Checkpoint -/// -void UndoRedoModel::checkpoint( const QString& description ) -{ - // - // Do not perform consecutive checkpoints that are identical. - // E.g. moving an object by dragging, would produce a large number - // of incremental checkpoints -- what we really want is a single - // checkpoint so that we can undo the entire dragging effort with - // one "undo" - // - if ( mNewSelection || (description != mLastDescription) ) + /// + /// Constructor + /// + UndoRedoModel::UndoRedoModel( LabelModel* model ) { + mModel = model; + mNewSelection = true; - /* Sever old redo "thread" */ - mRedoStack.clear(); + connect( model, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()) ); + } - /* Save state onto undo stack. */ - State* stateNow = new State( mModel, description ); - mUndoStack.push( stateNow ); - /* Track consecutive checkpoints. */ - mNewSelection = false; - mLastDescription = description; + /// + /// Destructor + /// + UndoRedoModel::~UndoRedoModel() + { + // empty + } + + + /// + /// Checkpoint + /// + void UndoRedoModel::checkpoint( const QString& description ) + { + // + // Do not perform consecutive checkpoints that are identical. + // E.g. moving an object by dragging, would produce a large number + // of incremental checkpoints -- what we really want is a single + // checkpoint so that we can undo the entire dragging effort with + // one "undo" + // + if ( mNewSelection || (description != mLastDescription) ) + { + + /* Sever old redo "thread" */ + mRedoStack.clear(); + + /* Save state onto undo stack. */ + State* stateNow = new State( mModel, description ); + mUndoStack.push( stateNow ); + + /* Track consecutive checkpoints. */ + mNewSelection = false; + mLastDescription = description; + + emit changed(); + } + } + + + /// + /// Undo + /// + void UndoRedoModel::undo() + { + State* oldState = mUndoStack.pop(); + State* stateNow = new State( mModel, oldState->description ); + + mRedoStack.push( stateNow ); + + mModel->restore( oldState->model ); + delete oldState; + + mNewSelection = true; emit changed(); } -} - - -/// -/// Undo -/// -void UndoRedoModel::undo() -{ - State* oldState = mUndoStack.pop(); - State* stateNow = new State( mModel, oldState->description ); - - mRedoStack.push( stateNow ); - - mModel->restore( oldState->model ); - delete oldState; - - mNewSelection = true; - - emit changed(); -} -/// -/// Redo -/// -void UndoRedoModel::redo() -{ - State* oldState = mRedoStack.pop(); - State* stateNow = new State( mModel, oldState->description ); - - mUndoStack.push( stateNow ); - - mModel->restore( oldState->model ); - delete oldState; - - mNewSelection = true; - - emit changed(); -} - - -/// -/// Can we undo? -/// -bool UndoRedoModel::canUndo() const -{ - return !mUndoStack.isEmpty(); -} - - -/// -/// Can we redo? -/// -bool UndoRedoModel::canRedo() const -{ - return !mRedoStack.isEmpty(); -} - - -/// -/// Undo description -/// -QString UndoRedoModel::undoDescription() const -{ - if ( canUndo() ) + /// + /// Redo + /// + void UndoRedoModel::redo() { - return mUndoStack.topState()->description; - } - else - { - return ""; - } -} + State* oldState = mRedoStack.pop(); + State* stateNow = new State( mModel, oldState->description ); + mUndoStack.push( stateNow ); + + mModel->restore( oldState->model ); + delete oldState; -/// -/// Redo description -/// -QString UndoRedoModel::redoDescription() const -{ - if ( canRedo() ) - { - return mRedoStack.topState()->description; + mNewSelection = true; + + emit changed(); } - else - { - return ""; - } -} - - -/// -/// Selection changed handler -/// -void UndoRedoModel::onSelectionChanged() -{ - mNewSelection = true; -} - - -/// -/// State constructor -/// -UndoRedoModel::State::State( LabelModel* model, const QString& description ) -{ - this->model = model->save(); - this->description = description; -} - - -/// -/// State destructor -/// -UndoRedoModel::State::~State() -{ - delete model; -} - - -/// -/// Stack constructor -/// -UndoRedoModel::Stack::Stack() -{ -} - - -/// -/// Stack destructor -/// -UndoRedoModel::Stack::~Stack() -{ - clear(); -} - - -/// -/// Push state onto stack -/// -void UndoRedoModel::Stack::push( UndoRedoModel::State* state ) -{ - list.push_front( state ); -} -/// -/// Pop state from stack -/// -UndoRedoModel::State* UndoRedoModel::Stack::pop() -{ - return list.takeFirst(); -} - - -/// -/// Peek at state at top of stack -/// -const UndoRedoModel::State* UndoRedoModel::Stack::topState() const -{ - return list.first(); -} - - -/// -/// Is stack empty? -/// -bool UndoRedoModel::Stack::isEmpty() const -{ - return list.isEmpty(); -} - - -/// -/// Clear stack -/// -void UndoRedoModel::Stack::clear() -{ - while ( !isEmpty() ) + /// + /// Can we undo? + /// + bool UndoRedoModel::canUndo() const { - delete pop(); + return !mUndoStack.isEmpty(); } + + + /// + /// Can we redo? + /// + bool UndoRedoModel::canRedo() const + { + return !mRedoStack.isEmpty(); + } + + + /// + /// Undo description + /// + QString UndoRedoModel::undoDescription() const + { + if ( canUndo() ) + { + return mUndoStack.topState()->description; + } + else + { + return ""; + } + } + + + /// + /// Redo description + /// + QString UndoRedoModel::redoDescription() const + { + if ( canRedo() ) + { + return mRedoStack.topState()->description; + } + else + { + return ""; + } + } + + + /// + /// Selection changed handler + /// + void UndoRedoModel::onSelectionChanged() + { + mNewSelection = true; + } + + + /// + /// State constructor + /// + UndoRedoModel::State::State( LabelModel* model, const QString& description ) + { + this->model = model->save(); + this->description = description; + } + + + /// + /// State destructor + /// + UndoRedoModel::State::~State() + { + delete model; + } + + + /// + /// Stack constructor + /// + UndoRedoModel::Stack::Stack() + { + // empty + } + + + /// + /// Stack destructor + /// + UndoRedoModel::Stack::~Stack() + { + clear(); + } + + + /// + /// Push state onto stack + /// + void UndoRedoModel::Stack::push( UndoRedoModel::State* state ) + { + list.push_front( state ); + } + + + /// + /// Pop state from stack + /// + UndoRedoModel::State* UndoRedoModel::Stack::pop() + { + return list.takeFirst(); + } + + + /// + /// Peek at state at top of stack + /// + const UndoRedoModel::State* UndoRedoModel::Stack::topState() const + { + return list.first(); + } + + + /// + /// Is stack empty? + /// + bool UndoRedoModel::Stack::isEmpty() const + { + return list.isEmpty(); + } + + + /// + /// Clear stack + /// + void UndoRedoModel::Stack::clear() + { + while ( !isEmpty() ) + { + delete pop(); + } + } + } diff --git a/glabels/UndoRedoModel.h b/glabels/UndoRedoModel.h index 0018d74..12e259f 100644 --- a/glabels/UndoRedoModel.h +++ b/glabels/UndoRedoModel.h @@ -26,96 +26,103 @@ #include #include -// Forward references -class LabelModel; - -/// -/// UndoRedoModel -/// -struct UndoRedoModel : QObject +namespace glabels { - Q_OBJECT + + // Forward references + class LabelModel; - ///////////////////////////////// - // Life Cycle - ///////////////////////////////// -public: - UndoRedoModel( LabelModel* model ); - virtual ~UndoRedoModel(); + /// + /// UndoRedoModel + /// + struct UndoRedoModel : QObject + { + Q_OBJECT - ///////////////////////////////// - // Public Methods - ///////////////////////////////// -public: - void checkpoint( const QString& description ); - void undo(); - void redo(); - bool canUndo() const; - bool canRedo() const; - QString undoDescription() const; - QString redoDescription() const; + ///////////////////////////////// + // Life Cycle + ///////////////////////////////// + public: + UndoRedoModel( LabelModel* model ); + virtual ~UndoRedoModel(); - ///////////////////////////////// - // Slots - ///////////////////////////////// -private slots: - void onSelectionChanged(); + ///////////////////////////////// + // Public Methods + ///////////////////////////////// + public: + void checkpoint( const QString& description ); + void undo(); + void redo(); + bool canUndo() const; + bool canRedo() const; + QString undoDescription() const; + QString redoDescription() const; + + + ///////////////////////////////// + // Slots + ///////////////////////////////// + private slots: + void onSelectionChanged(); - ///////////////////////////////// - // Signals - ///////////////////////////////// -signals: - void changed(); + ///////////////////////////////// + // Signals + ///////////////////////////////// + signals: + void changed(); - ///////////////////////////////// - // Private types - ///////////////////////////////// -private: - class State - { - public: - State( LabelModel* model, const QString& description ); - ~State(); - - LabelModel* model; - QString description; - }; - - class Stack - { - public: - Stack(); - ~Stack(); - - void push( State* state ); - State* pop(); - const State* topState() const; - bool isEmpty() const; - void clear(); - + ///////////////////////////////// + // Private types + ///////////////////////////////// private: - QList list; + class State + { + public: + State( LabelModel* model, const QString& description ); + ~State(); + + LabelModel* model; + QString description; + }; + + class Stack + { + public: + Stack(); + ~Stack(); + + void push( State* state ); + State* pop(); + const State* topState() const; + bool isEmpty() const; + void clear(); + + private: + QList list; + }; + + + ///////////////////////////////// + // Private data + ///////////////////////////////// + private: + LabelModel *mModel; + + Stack mUndoStack; + Stack mRedoStack; + + bool mNewSelection; + QString mLastDescription; + }; - - ///////////////////////////////// - // Private data - ///////////////////////////////// -private: - LabelModel *mModel; +} - Stack mUndoStack; - Stack mRedoStack; - - bool mNewSelection; - QString mLastDescription; - -}; #endif // UndoRedoModel_h diff --git a/glabels/Units.cpp b/glabels/Units.cpp index bde38ff..572a6b4 100644 --- a/glabels/Units.cpp +++ b/glabels/Units.cpp @@ -31,6 +31,7 @@ namespace glabels Units::Units() : mEnumValue(PT) { + // empty } @@ -179,19 +180,19 @@ namespace glabels switch (mEnumValue) { - case glabels::Units::PT: + case Units::PT: value = 0.01; break; - case glabels::Units::IN: + case Units::IN: value = 0.001; break; - case glabels::Units::MM: + case Units::MM: value = 0.01; break; - case glabels::Units::CM: + case Units::CM: value = 0.001; break; - case glabels::Units::PC: + case Units::PC: value = 0.01; break; } @@ -206,19 +207,19 @@ namespace glabels switch (mEnumValue) { - case glabels::Units::PT: + case Units::PT: digits = 2; break; - case glabels::Units::IN: + case Units::IN: digits = 3; break; - case glabels::Units::MM: + case Units::MM: digits = 2; break; - case glabels::Units::CM: + case Units::CM: digits = 3; break; - case glabels::Units::PC: + case Units::PC: digits = 2; break; } diff --git a/glabels/Vendor.cpp b/glabels/Vendor.cpp index 2a663dd..9b81fff 100644 --- a/glabels/Vendor.cpp +++ b/glabels/Vendor.cpp @@ -26,6 +26,7 @@ namespace glabels Vendor::Vendor( const QString &name, const QString &url ) : mName(name), mUrl(url) { + // empty } diff --git a/glabels/XmlLabelCreator.cpp b/glabels/XmlLabelCreator.cpp index 816f40d..efa354c 100644 --- a/glabels/XmlLabelCreator.cpp +++ b/glabels/XmlLabelCreator.cpp @@ -42,419 +42,423 @@ #include "Merge/None.h" -void -XmlLabelCreator::writeFile( const LabelModel* label, const QString& fileName ) +namespace glabels { - QDomDocument doc; - createDoc( doc, label ); - QByteArray buffer = doc.toByteArray( 2 ); - - QFile file( fileName ); - - if ( !file.open( QFile::WriteOnly | QFile::Text) ) + void + XmlLabelCreator::writeFile( const LabelModel* label, const QString& fileName ) { - qWarning() << "Error: Cannot write file " << fileName - << ": " << file.errorString(); + QDomDocument doc; + + createDoc( doc, label ); + QByteArray buffer = doc.toByteArray( 2 ); + + QFile file( fileName ); + + if ( !file.open( QFile::WriteOnly | QFile::Text) ) + { + qWarning() << "Error: Cannot write file " << fileName + << ": " << file.errorString(); + } + + file.write( buffer.data(), buffer.size() ); } - file.write( buffer.data(), buffer.size() ); -} - -void -XmlLabelCreator::writeBuffer( const LabelModel* label, QByteArray& buffer ) -{ - QDomDocument doc; - - createDoc( doc, label ); - buffer = doc.toByteArray( 2 ); -} - - -void -XmlLabelCreator::serializeObjects( const QList& objects, - QByteArray& buffer ) -{ - QDomDocument doc; - - QDomNode xmlNode( doc.createProcessingInstruction( "xml", "version=\"1.0\"" ) ); - doc.appendChild( xmlNode ); - - QDomElement root = doc.createElement( "Glabels-objects" ); - doc.appendChild( root ); - - addObjectsToNode( root, objects ); - - buffer = doc.toByteArray( 2 ); -} - - -void -XmlLabelCreator::createDoc( QDomDocument& doc, const LabelModel* label ) -{ - QDomNode xmlNode( doc.createProcessingInstruction( "xml", "version=\"1.0\"" ) ); - doc.appendChild( xmlNode ); - - QDomElement root = doc.createElement( "Glabels-document" ); - doc.appendChild( root ); - glabels::XmlUtil::setStringAttr( root, "version", "4.0" ); - - glabels::XmlTemplateCreator().createTemplateNode( root, label->tmplate() ); - - createObjectsNode( root, label ); - - if ( label->merge() && !dynamic_cast(label->merge()) ) + void + XmlLabelCreator::writeBuffer( const LabelModel* label, QByteArray& buffer ) { - createMergeNode( root, label ); + QDomDocument doc; + + createDoc( doc, label ); + buffer = doc.toByteArray( 2 ); } - createDataNode( root, label ); -} - -void -XmlLabelCreator::createObjectsNode( QDomElement &parent, const LabelModel* label ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Objects" ); - parent.appendChild( node ); - - glabels::XmlUtil::setStringAttr( node, "id", "0" ); - glabels::XmlUtil::setBoolAttr( node, "rotate", label->rotate() ); - - addObjectsToNode( node, label->objectList() ); -} - - -void -XmlLabelCreator::addObjectsToNode( QDomElement &parent, const QList& objects ) -{ - foreach ( LabelModelObject* object, objects ) + void + XmlLabelCreator::serializeObjects( const QList& objects, + QByteArray& buffer ) { - if ( LabelModelBoxObject* boxObject = dynamic_cast(object) ) + QDomDocument doc; + + QDomNode xmlNode( doc.createProcessingInstruction( "xml", "version=\"1.0\"" ) ); + doc.appendChild( xmlNode ); + + QDomElement root = doc.createElement( "Glabels-objects" ); + doc.appendChild( root ); + + addObjectsToNode( root, objects ); + + buffer = doc.toByteArray( 2 ); + } + + + void + XmlLabelCreator::createDoc( QDomDocument& doc, const LabelModel* label ) + { + QDomNode xmlNode( doc.createProcessingInstruction( "xml", "version=\"1.0\"" ) ); + doc.appendChild( xmlNode ); + + QDomElement root = doc.createElement( "Glabels-document" ); + doc.appendChild( root ); + XmlUtil::setStringAttr( root, "version", "4.0" ); + + XmlTemplateCreator().createTemplateNode( root, label->tmplate() ); + + createObjectsNode( root, label ); + + if ( label->merge() && !dynamic_cast(label->merge()) ) { - createObjectBoxNode( parent, boxObject ); + createMergeNode( root, label ); } - else if ( LabelModelEllipseObject* ellipseObject = dynamic_cast(object) ) + + createDataNode( root, label ); + } + + + void + XmlLabelCreator::createObjectsNode( QDomElement &parent, const LabelModel* label ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Objects" ); + parent.appendChild( node ); + + XmlUtil::setStringAttr( node, "id", "0" ); + XmlUtil::setBoolAttr( node, "rotate", label->rotate() ); + + addObjectsToNode( node, label->objectList() ); + } + + + void + XmlLabelCreator::addObjectsToNode( QDomElement &parent, const QList& objects ) + { + foreach ( LabelModelObject* object, objects ) { - createObjectEllipseNode( parent, ellipseObject ); + if ( LabelModelBoxObject* boxObject = dynamic_cast(object) ) + { + createObjectBoxNode( parent, boxObject ); + } + else if ( LabelModelEllipseObject* ellipseObject = dynamic_cast(object) ) + { + createObjectEllipseNode( parent, ellipseObject ); + } + else if ( LabelModelLineObject* lineObject = dynamic_cast(object) ) + { + createObjectLineNode( parent, lineObject ); + } + else if ( LabelModelImageObject* imageObject = dynamic_cast(object) ) + { + createObjectImageNode( parent, imageObject ); + } + else if ( LabelModelTextObject* textObject = dynamic_cast(object) ) + { + createObjectTextNode( parent, textObject ); + } + // TODO: other object types + else + { + Q_ASSERT_X( false, "XmlLabelCreator::addObjectsToNode", "Invalid object type." ); + } } - else if ( LabelModelLineObject* lineObject = dynamic_cast(object) ) + } + + + void + XmlLabelCreator::createObjectBoxNode( QDomElement &parent, const LabelModelBoxObject* object ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Object-box" ); + parent.appendChild( node ); + + /* position attrs */ + XmlUtil::setLengthAttr( node, "x", object->x0() ); + XmlUtil::setLengthAttr( node, "y", object->y0() ); + + /* size attrs */ + XmlUtil::setLengthAttr( node, "w", object->w() ); + XmlUtil::setLengthAttr( node, "h", object->h() ); + + /* line attrs */ + XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); + if ( object->lineColorNode().isField() ) { - createObjectLineNode( parent, lineObject ); + XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); } - else if ( LabelModelImageObject* imageObject = dynamic_cast(object) ) - { - createObjectImageNode( parent, imageObject ); - } - else if ( LabelModelTextObject* textObject = dynamic_cast(object) ) - { - createObjectTextNode( parent, textObject ); - } - // TODO: other object types else { - Q_ASSERT_X( false, "XmlLabelCreator::addObjectsToNode", "Invalid object type." ); + XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); } - } -} - - -void -XmlLabelCreator::createObjectBoxNode( QDomElement &parent, const LabelModelBoxObject* object ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Object-box" ); - parent.appendChild( node ); - - /* position attrs */ - glabels::XmlUtil::setLengthAttr( node, "x", object->x0() ); - glabels::XmlUtil::setLengthAttr( node, "y", object->y0() ); - - /* size attrs */ - glabels::XmlUtil::setLengthAttr( node, "w", object->w() ); - glabels::XmlUtil::setLengthAttr( node, "h", object->h() ); - - /* line attrs */ - glabels::XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); - if ( object->lineColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); - } - - /* fill attrs */ - if ( object->fillColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "fill_color_field", object->fillColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "fill_color", object->fillColorNode().rgba() ); - } - - /* affine attrs */ - createAffineAttrs( node, object ); - - /* shadow attrs */ - createShadowAttrs( node, object ); -} - - -void -XmlLabelCreator::createObjectEllipseNode( QDomElement &parent, const LabelModelEllipseObject* object ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Object-ellipse" ); - parent.appendChild( node ); - - /* position attrs */ - glabels::XmlUtil::setLengthAttr( node, "x", object->x0() ); - glabels::XmlUtil::setLengthAttr( node, "y", object->y0() ); - - /* size attrs */ - glabels::XmlUtil::setLengthAttr( node, "w", object->w() ); - glabels::XmlUtil::setLengthAttr( node, "h", object->h() ); - - /* line attrs */ - glabels::XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); - if ( object->lineColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); - } - - /* fill attrs */ - if ( object->fillColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "fill_color_field", object->fillColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "fill_color", object->fillColorNode().rgba() ); - } - - /* affine attrs */ - createAffineAttrs( node, object ); - - /* shadow attrs */ - createShadowAttrs( node, object ); -} - - -void -XmlLabelCreator::createObjectLineNode( QDomElement &parent, const LabelModelLineObject* object ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Object-line" ); - parent.appendChild( node ); - - /* position attrs */ - glabels::XmlUtil::setLengthAttr( node, "x", object->x0() ); - glabels::XmlUtil::setLengthAttr( node, "y", object->y0() ); - - /* size attrs */ - glabels::XmlUtil::setLengthAttr( node, "dx", object->w() ); - glabels::XmlUtil::setLengthAttr( node, "dy", object->h() ); - - /* line attrs */ - glabels::XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); - if ( object->lineColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); - } - - /* affine attrs */ - createAffineAttrs( node, object ); - - /* shadow attrs */ - createShadowAttrs( node, object ); -} - - -void -XmlLabelCreator::createObjectImageNode( QDomElement &parent, const LabelModelImageObject* object ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Object-image" ); - parent.appendChild( node ); - - /* position attrs */ - glabels::XmlUtil::setLengthAttr( node, "x", object->x0() ); - glabels::XmlUtil::setLengthAttr( node, "y", object->y0() ); - - /* size attrs */ - glabels::XmlUtil::setLengthAttr( node, "w", object->w() ); - glabels::XmlUtil::setLengthAttr( node, "h", object->h() ); - - /* file attrs */ - glabels::XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); - if ( object->filenameNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "src_field", object->filenameNode().data() ); - } - else - { - glabels::XmlUtil::setStringAttr( node, "src", object->filenameNode().data() ); - } - - /* affine attrs */ - createAffineAttrs( node, object ); - - /* shadow attrs */ - createShadowAttrs( node, object ); -} - - -void -XmlLabelCreator::createObjectBarcodeNode( QDomElement &parent, const LabelModelBarcodeObject* object ) -{ - // TODO -} - - -void -XmlLabelCreator::createObjectTextNode( QDomElement &parent, const LabelModelTextObject* object ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Object-text" ); - parent.appendChild( node ); - - /* position attrs */ - glabels::XmlUtil::setLengthAttr( node, "x", object->x0() ); - glabels::XmlUtil::setLengthAttr( node, "y", object->y0() ); - - /* size attrs */ - glabels::XmlUtil::setLengthAttr( node, "w", object->w() ); - glabels::XmlUtil::setLengthAttr( node, "h", object->h() ); - - /* color attr */ - if ( object->textColorNode().isField() ) - { - glabels::XmlUtil::setStringAttr( node, "color_field", object->textColorNode().key() ); - } - else - { - glabels::XmlUtil::setUIntAttr( node, "color", object->textColorNode().rgba() ); - } - - /* font attrs */ - glabels::XmlUtil::setStringAttr( node, "font_family", object->fontFamily() ); - glabels::XmlUtil::setDoubleAttr( node, "font_size", object->fontSize() ); - glabels::XmlUtil::setStringAttr( node, "font_weight", EnumUtil::weightToString( object->fontWeight() ) ); - glabels::XmlUtil::setBoolAttr( node, "font_italic", object->fontItalicFlag() ); - glabels::XmlUtil::setBoolAttr( node, "font_underline", object->fontUnderlineFlag() ); - - /* text attrs */ - glabels::XmlUtil::setDoubleAttr( node, "line_spacing", object->textLineSpacing() ); - glabels::XmlUtil::setStringAttr( node, "align", EnumUtil::hAlignToString( object->textHAlign() ) ); - glabels::XmlUtil::setStringAttr( node, "valign", EnumUtil::vAlignToString( object->textVAlign() ) ); - - /* affine attrs */ - createAffineAttrs( node, object ); - - /* shadow attrs */ - createShadowAttrs( node, object ); - - /* serialize text contents */ - QTextDocument document( object->text() ); - int nBlocks = document.blockCount(); - for ( int iBlock = 0; iBlock < nBlocks; iBlock++ ) - { - createPNode( node, document.findBlockByNumber(iBlock).text() ); - } -} - - -void -XmlLabelCreator::createPNode( QDomElement &parent, const QString& blockText ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "p" ); - parent.appendChild( node ); - - node.appendChild( doc.createTextNode( blockText ) ); -} - - -void -XmlLabelCreator::createAffineAttrs( QDomElement &node, const LabelModelObject* object ) -{ - QMatrix a = object->matrix(); - - glabels::XmlUtil::setDoubleAttr( node, "a0", a.m11() ); - glabels::XmlUtil::setDoubleAttr( node, "a1", a.m12() ); - glabels::XmlUtil::setDoubleAttr( node, "a2", a.m21() ); - glabels::XmlUtil::setDoubleAttr( node, "a3", a.m22() ); - glabels::XmlUtil::setDoubleAttr( node, "a4", a.dx() ); - glabels::XmlUtil::setDoubleAttr( node, "a5", a.dy() ); -} - - -void -XmlLabelCreator::createShadowAttrs( QDomElement &node, const LabelModelObject* object ) -{ - if ( object->shadow() ) - { - glabels::XmlUtil::setBoolAttr( node, "shadow", object->shadow() ); - - glabels::XmlUtil::setLengthAttr( node, "shadow_x", object->shadowX() ); - glabels::XmlUtil::setLengthAttr( node, "shadow_y", object->shadowY() ); + /* fill attrs */ if ( object->fillColorNode().isField() ) { - glabels::XmlUtil::setStringAttr( node, "shadow_color_field", object->shadowColorNode().key() ); + XmlUtil::setStringAttr( node, "fill_color_field", object->fillColorNode().key() ); } else { - glabels::XmlUtil::setUIntAttr( node, "shadow_color", object->shadowColorNode().rgba() ); + XmlUtil::setUIntAttr( node, "fill_color", object->fillColorNode().rgba() ); } - glabels::XmlUtil::setDoubleAttr( node, "shadow_opacity", object->shadowOpacity() ); + /* affine attrs */ + createAffineAttrs( node, object ); + + /* shadow attrs */ + createShadowAttrs( node, object ); } + + + void + XmlLabelCreator::createObjectEllipseNode( QDomElement &parent, const LabelModelEllipseObject* object ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Object-ellipse" ); + parent.appendChild( node ); + + /* position attrs */ + XmlUtil::setLengthAttr( node, "x", object->x0() ); + XmlUtil::setLengthAttr( node, "y", object->y0() ); + + /* size attrs */ + XmlUtil::setLengthAttr( node, "w", object->w() ); + XmlUtil::setLengthAttr( node, "h", object->h() ); + + /* line attrs */ + XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); + if ( object->lineColorNode().isField() ) + { + XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); + } + else + { + XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); + } + + /* fill attrs */ + if ( object->fillColorNode().isField() ) + { + XmlUtil::setStringAttr( node, "fill_color_field", object->fillColorNode().key() ); + } + else + { + XmlUtil::setUIntAttr( node, "fill_color", object->fillColorNode().rgba() ); + } + + /* affine attrs */ + createAffineAttrs( node, object ); + + /* shadow attrs */ + createShadowAttrs( node, object ); + } + + + void + XmlLabelCreator::createObjectLineNode( QDomElement &parent, const LabelModelLineObject* object ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Object-line" ); + parent.appendChild( node ); + + /* position attrs */ + XmlUtil::setLengthAttr( node, "x", object->x0() ); + XmlUtil::setLengthAttr( node, "y", object->y0() ); + + /* size attrs */ + XmlUtil::setLengthAttr( node, "dx", object->w() ); + XmlUtil::setLengthAttr( node, "dy", object->h() ); + + /* line attrs */ + XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); + if ( object->lineColorNode().isField() ) + { + XmlUtil::setStringAttr( node, "line_color_field", object->lineColorNode().key() ); + } + else + { + XmlUtil::setUIntAttr( node, "line_color", object->lineColorNode().rgba() ); + } + + /* affine attrs */ + createAffineAttrs( node, object ); + + /* shadow attrs */ + createShadowAttrs( node, object ); + } + + + void + XmlLabelCreator::createObjectImageNode( QDomElement &parent, const LabelModelImageObject* object ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Object-image" ); + parent.appendChild( node ); + + /* position attrs */ + XmlUtil::setLengthAttr( node, "x", object->x0() ); + XmlUtil::setLengthAttr( node, "y", object->y0() ); + + /* size attrs */ + XmlUtil::setLengthAttr( node, "w", object->w() ); + XmlUtil::setLengthAttr( node, "h", object->h() ); + + /* file attrs */ + XmlUtil::setLengthAttr( node, "line_width", object->lineWidth() ); + if ( object->filenameNode().isField() ) + { + XmlUtil::setStringAttr( node, "src_field", object->filenameNode().data() ); + } + else + { + XmlUtil::setStringAttr( node, "src", object->filenameNode().data() ); + } + + /* affine attrs */ + createAffineAttrs( node, object ); + + /* shadow attrs */ + createShadowAttrs( node, object ); + } + + + void + XmlLabelCreator::createObjectBarcodeNode( QDomElement &parent, const LabelModelBarcodeObject* object ) + { + // TODO + } + + + void + XmlLabelCreator::createObjectTextNode( QDomElement &parent, const LabelModelTextObject* object ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Object-text" ); + parent.appendChild( node ); + + /* position attrs */ + XmlUtil::setLengthAttr( node, "x", object->x0() ); + XmlUtil::setLengthAttr( node, "y", object->y0() ); + + /* size attrs */ + XmlUtil::setLengthAttr( node, "w", object->w() ); + XmlUtil::setLengthAttr( node, "h", object->h() ); + + /* color attr */ + if ( object->textColorNode().isField() ) + { + XmlUtil::setStringAttr( node, "color_field", object->textColorNode().key() ); + } + else + { + XmlUtil::setUIntAttr( node, "color", object->textColorNode().rgba() ); + } + + /* font attrs */ + XmlUtil::setStringAttr( node, "font_family", object->fontFamily() ); + XmlUtil::setDoubleAttr( node, "font_size", object->fontSize() ); + XmlUtil::setStringAttr( node, "font_weight", EnumUtil::weightToString( object->fontWeight() ) ); + XmlUtil::setBoolAttr( node, "font_italic", object->fontItalicFlag() ); + XmlUtil::setBoolAttr( node, "font_underline", object->fontUnderlineFlag() ); + + /* text attrs */ + XmlUtil::setDoubleAttr( node, "line_spacing", object->textLineSpacing() ); + XmlUtil::setStringAttr( node, "align", EnumUtil::hAlignToString( object->textHAlign() ) ); + XmlUtil::setStringAttr( node, "valign", EnumUtil::vAlignToString( object->textVAlign() ) ); + + /* affine attrs */ + createAffineAttrs( node, object ); + + /* shadow attrs */ + createShadowAttrs( node, object ); + + /* serialize text contents */ + QTextDocument document( object->text() ); + int nBlocks = document.blockCount(); + for ( int iBlock = 0; iBlock < nBlocks; iBlock++ ) + { + createPNode( node, document.findBlockByNumber(iBlock).text() ); + } + } + + + void + XmlLabelCreator::createPNode( QDomElement &parent, const QString& blockText ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "p" ); + parent.appendChild( node ); + + node.appendChild( doc.createTextNode( blockText ) ); + } + + + void + XmlLabelCreator::createAffineAttrs( QDomElement &node, const LabelModelObject* object ) + { + QMatrix a = object->matrix(); + + XmlUtil::setDoubleAttr( node, "a0", a.m11() ); + XmlUtil::setDoubleAttr( node, "a1", a.m12() ); + XmlUtil::setDoubleAttr( node, "a2", a.m21() ); + XmlUtil::setDoubleAttr( node, "a3", a.m22() ); + XmlUtil::setDoubleAttr( node, "a4", a.dx() ); + XmlUtil::setDoubleAttr( node, "a5", a.dy() ); + } + + + void + XmlLabelCreator::createShadowAttrs( QDomElement &node, const LabelModelObject* object ) + { + if ( object->shadow() ) + { + XmlUtil::setBoolAttr( node, "shadow", object->shadow() ); + + XmlUtil::setLengthAttr( node, "shadow_x", object->shadowX() ); + XmlUtil::setLengthAttr( node, "shadow_y", object->shadowY() ); + + if ( object->fillColorNode().isField() ) + { + XmlUtil::setStringAttr( node, "shadow_color_field", object->shadowColorNode().key() ); + } + else + { + XmlUtil::setUIntAttr( node, "shadow_color", object->shadowColorNode().rgba() ); + } + + XmlUtil::setDoubleAttr( node, "shadow_opacity", object->shadowOpacity() ); + } + } + + + void + XmlLabelCreator::createMergeNode( QDomElement &parent, const LabelModel* label ) + { + QDomDocument doc = parent.ownerDocument(); + QDomElement node = doc.createElement( "Merge" ); + parent.appendChild( node ); + + XmlUtil::setStringAttr( node, "type", label->merge()->id() ); + XmlUtil::setStringAttr( node, "src", label->merge()->source() ); + } + + + void + XmlLabelCreator::createDataNode( QDomElement &parent, const LabelModel* label ) + { + // TODO + } + + + void + XmlLabelCreator::createPixdataNode( QDomElement &parent, const LabelModel* label, const QString& name ) + { + // TODO + } + + + void + XmlLabelCreator::createSvgFileNode( QDomElement &parent, const LabelModel* label, const QString& name ) + { + // TODO + } + } - - -void -XmlLabelCreator::createMergeNode( QDomElement &parent, const LabelModel* label ) -{ - QDomDocument doc = parent.ownerDocument(); - QDomElement node = doc.createElement( "Merge" ); - parent.appendChild( node ); - - glabels::XmlUtil::setStringAttr( node, "type", label->merge()->id() ); - glabels::XmlUtil::setStringAttr( node, "src", label->merge()->source() ); -} - - -void -XmlLabelCreator::createDataNode( QDomElement &parent, const LabelModel* label ) -{ - // TODO -} - - -void -XmlLabelCreator::createPixdataNode( QDomElement &parent, const LabelModel* label, const QString& name ) -{ - // TODO -} - - -void -XmlLabelCreator::createSvgFileNode( QDomElement &parent, const LabelModel* label, const QString& name ) -{ - // TODO -} - diff --git a/glabels/XmlLabelCreator.h b/glabels/XmlLabelCreator.h index 6879f22..6b9f25c 100644 --- a/glabels/XmlLabelCreator.h +++ b/glabels/XmlLabelCreator.h @@ -25,49 +25,55 @@ #include #include -// Forward references -class LabelModel; -class LabelModelObject; -class LabelModelBoxObject; -class LabelModelEllipseObject; -class LabelModelLineObject; -class LabelModelImageObject; -class LabelModelBarcodeObject; -class LabelModelTextObject; - -/// -/// XmlLabelCreator -/// -class XmlLabelCreator : public QObject +namespace glabels { - Q_OBJECT -public: - static void writeFile( const LabelModel* label, const QString& fileName ); - static void writeBuffer( const LabelModel* label, QByteArray& buffer ); - static void serializeObjects( const QList& objects, QByteArray& buffer ); + // Forward references + class LabelModel; + class LabelModelObject; + class LabelModelBoxObject; + class LabelModelEllipseObject; + class LabelModelLineObject; + class LabelModelImageObject; + class LabelModelBarcodeObject; + class LabelModelTextObject; -private: - static void createDoc( QDomDocument& doc, const LabelModel* label ); - static void createRootNode( const LabelModel* label ); - static void createObjectsNode( QDomElement &parent, const LabelModel* label ); - static void addObjectsToNode( QDomElement &parent, const QList& objects ); - static void createObjectBoxNode( QDomElement &parent, const LabelModelBoxObject* object ); - static void createObjectEllipseNode( QDomElement &parent, const LabelModelEllipseObject* object ); - static void createObjectLineNode( QDomElement &parent, const LabelModelLineObject* object ); - static void createObjectImageNode( QDomElement &parent, const LabelModelImageObject* object ); - static void createObjectBarcodeNode( QDomElement &parent, const LabelModelBarcodeObject* object ); - static void createObjectTextNode( QDomElement &parent, const LabelModelTextObject* object ); - static void createPNode( QDomElement &parent, const QString& blockText ); - static void createAffineAttrs( QDomElement &node, const LabelModelObject* object ); - static void createShadowAttrs( QDomElement &node, const LabelModelObject* object ); - static void createMergeNode( QDomElement &parent, const LabelModel* label ); - static void createDataNode( QDomElement &parent, const LabelModel* label ); - static void createPixdataNode( QDomElement &parent, const LabelModel* label, const QString& name ); - static void createSvgFileNode( QDomElement &parent, const LabelModel* label, const QString& name ); -}; + /// + /// XmlLabelCreator + /// + class XmlLabelCreator : public QObject + { + Q_OBJECT + + public: + static void writeFile( const LabelModel* label, const QString& fileName ); + static void writeBuffer( const LabelModel* label, QByteArray& buffer ); + static void serializeObjects( const QList& objects, QByteArray& buffer ); + + private: + static void createDoc( QDomDocument& doc, const LabelModel* label ); + static void createRootNode( const LabelModel* label ); + static void createObjectsNode( QDomElement &parent, const LabelModel* label ); + static void addObjectsToNode( QDomElement &parent, const QList& objects ); + static void createObjectBoxNode( QDomElement &parent, const LabelModelBoxObject* object ); + static void createObjectEllipseNode( QDomElement &parent, const LabelModelEllipseObject* object ); + static void createObjectLineNode( QDomElement &parent, const LabelModelLineObject* object ); + static void createObjectImageNode( QDomElement &parent, const LabelModelImageObject* object ); + static void createObjectBarcodeNode( QDomElement &parent, const LabelModelBarcodeObject* object ); + static void createObjectTextNode( QDomElement &parent, const LabelModelTextObject* object ); + static void createPNode( QDomElement &parent, const QString& blockText ); + static void createAffineAttrs( QDomElement &node, const LabelModelObject* object ); + static void createShadowAttrs( QDomElement &node, const LabelModelObject* object ); + static void createMergeNode( QDomElement &parent, const LabelModel* label ); + static void createDataNode( QDomElement &parent, const LabelModel* label ); + static void createPixdataNode( QDomElement &parent, const LabelModel* label, const QString& name ); + static void createSvgFileNode( QDomElement &parent, const LabelModel* label, const QString& name ); + + }; + +} #endif // XmlLabelCreator_h diff --git a/glabels/XmlLabelParser.cpp b/glabels/XmlLabelParser.cpp index d6a4057..e3ad450 100644 --- a/glabels/XmlLabelParser.cpp +++ b/glabels/XmlLabelParser.cpp @@ -44,598 +44,586 @@ #include "Merge/Factory.h" -LabelModel* -XmlLabelParser::readFile( const QString& fileName ) +namespace glabels { - QFile file( fileName ); - if ( !file.open( QFile::ReadOnly ) ) + LabelModel* + XmlLabelParser::readFile( const QString& fileName ) { - qWarning() << "Error: Cannot read file " << qPrintable(fileName) - << ": " << file.errorString(); - return 0; - } + QFile file( fileName ); - QDomDocument doc; - bool success; - QString errorString; - int errorLine; - int errorColumn; - - QByteArray rawData = file.readAll(); - if ( ((rawData[0]&0xFF) == 0x1F) && ((rawData[1]&0xFF) == 0x8b) ) // gzip magic number 0x1F, 0x8B - { - // gzip compressed format - QByteArray unzippedData; - gunzip( rawData, unzippedData ); - success = doc.setContent( unzippedData, false, &errorString, &errorLine, &errorColumn ); - } - else - { - // plain text - success = doc.setContent( rawData, false, &errorString, &errorLine, &errorColumn ); - } - - if ( !success ) - { - qWarning() << "Error: Parse error at line " << errorLine - << "column " << errorColumn - << ": " << errorString; - return 0; - } - - - QDomElement root = doc.documentElement(); - if ( root.tagName() != "Glabels-document" ) - { - qWarning() << "Error: Not a Glabels-document file"; - return 0; - } - - return parseRootNode( root ); -} - - -LabelModel* -XmlLabelParser::readBuffer( const QByteArray& buffer ) -{ - QDomDocument doc; - QString errorString; - int errorLine; - int errorColumn; - - if ( !doc.setContent( buffer, false, &errorString, &errorLine, &errorColumn ) ) - { - qWarning() << "Error: Parse error at line " << errorLine - << "column " << errorColumn - << ": " << errorString; - return 0; - } - - QDomElement root = doc.documentElement(); - if ( root.tagName() != "Glabels-document" ) - { - qWarning() << "Error: Not a Glabels-document file"; - return 0; - } - - return parseRootNode( root ); -} - - -QList -XmlLabelParser::deserializeObjects( const QByteArray& buffer ) -{ - QList list; - - QDomDocument doc; - QString errorString; - int errorLine; - int errorColumn; - - if ( !doc.setContent( buffer, false, &errorString, &errorLine, &errorColumn ) ) - { - qWarning() << "Error: Parse error at line " << errorLine - << "column " << errorColumn - << ": " << errorString; - return list; - } - - QDomElement root = doc.documentElement(); - if ( root.tagName() != "Glabels-objects" ) - { - qWarning() << "Error: Not a Glabels-objects stream"; - return list; - } - - return parseObjects( root ); -} - - -void -XmlLabelParser::gunzip( const QByteArray& data, QByteArray& result ) -{ - result.clear(); - - if (data.size() <= 4) { - qWarning("XmlLabelParser::gunzip: Input data is truncated"); - return; - } - - // setup stream for inflate() - z_stream strm; - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = data.size(); - strm.next_in = (Bytef*)(data.data()); - - int ret = inflateInit2(&strm, MAX_WBITS + 16); // gzip decoding - if (ret != Z_OK) - { - return; - } - - static const int CHUNK_SIZE = 1024; - char out[CHUNK_SIZE]; - - // run inflate(), one chunk at a time - do { - strm.avail_out = CHUNK_SIZE; - strm.next_out = (Bytef*)(out); - - ret = inflate(&strm, Z_NO_FLUSH); - Q_ASSERT(ret != Z_STREAM_ERROR); // state not clobbered - - if ( (ret == Z_NEED_DICT) || (ret == Z_DATA_ERROR) || (ret == Z_MEM_ERROR) ) + if ( !file.open( QFile::ReadOnly ) ) { - // clean up - inflateEnd(&strm); + qWarning() << "Error: Cannot read file " << qPrintable(fileName) + << ": " << file.errorString(); + return 0; + } + + QDomDocument doc; + bool success; + QString errorString; + int errorLine; + int errorColumn; + + QByteArray rawData = file.readAll(); + if ( ((rawData[0]&0xFF) == 0x1F) && ((rawData[1]&0xFF) == 0x8b) ) // gzip magic number 0x1F, 0x8B + { + // gzip compressed format + QByteArray unzippedData; + gunzip( rawData, unzippedData ); + success = doc.setContent( unzippedData, false, &errorString, &errorLine, &errorColumn ); + } + else + { + // plain text + success = doc.setContent( rawData, false, &errorString, &errorLine, &errorColumn ); + } + + if ( !success ) + { + qWarning() << "Error: Parse error at line " << errorLine + << "column " << errorColumn + << ": " << errorString; + return 0; + } + + + QDomElement root = doc.documentElement(); + if ( root.tagName() != "Glabels-document" ) + { + qWarning() << "Error: Not a Glabels-document file"; + return 0; + } + + return parseRootNode( root ); + } + + + LabelModel* + XmlLabelParser::readBuffer( const QByteArray& buffer ) + { + QDomDocument doc; + QString errorString; + int errorLine; + int errorColumn; + + if ( !doc.setContent( buffer, false, &errorString, &errorLine, &errorColumn ) ) + { + qWarning() << "Error: Parse error at line " << errorLine + << "column " << errorColumn + << ": " << errorString; + return 0; + } + + QDomElement root = doc.documentElement(); + if ( root.tagName() != "Glabels-document" ) + { + qWarning() << "Error: Not a Glabels-document file"; + return 0; + } + + return parseRootNode( root ); + } + + + QList + XmlLabelParser::deserializeObjects( const QByteArray& buffer ) + { + QList list; + + QDomDocument doc; + QString errorString; + int errorLine; + int errorColumn; + + if ( !doc.setContent( buffer, false, &errorString, &errorLine, &errorColumn ) ) + { + qWarning() << "Error: Parse error at line " << errorLine + << "column " << errorColumn + << ": " << errorString; + return list; + } + + QDomElement root = doc.documentElement(); + if ( root.tagName() != "Glabels-objects" ) + { + qWarning() << "Error: Not a Glabels-objects stream"; + return list; + } + + return parseObjects( root ); + } + + + void + XmlLabelParser::gunzip( const QByteArray& data, QByteArray& result ) + { + result.clear(); + + if (data.size() <= 4) { + qWarning("XmlLabelParser::gunzip: Input data is truncated"); return; } - result.append(out, CHUNK_SIZE - strm.avail_out); - } while (strm.avail_out == 0); + // setup stream for inflate() + z_stream strm; + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = data.size(); + strm.next_in = (Bytef*)(data.data()); - // clean up - inflateEnd(&strm); -} - - -LabelModel* -XmlLabelParser::parseRootNode( const QDomElement &node ) -{ - using namespace glabels; - - QString version = XmlUtil::getStringAttr( node, "version", "" ); - if ( version != "4.0" ) - { - qWarning() << "TODO: compatability mode."; - } - - LabelModel* label = new LabelModel(); - - /* Pass 1, extract data nodes to pre-load cache. */ - for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) - { - if ( child.toElement().tagName() == "Data" ) + int ret = inflateInit2(&strm, MAX_WBITS + 16); // gzip decoding + if (ret != Z_OK) { - parseDataNode( child.toElement(), label ); + return; } - } - /* Pass 2, now extract everything else. */ - for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) - { - QString tagName = child.toElement().tagName(); - - if ( tagName == "Template" ) - { - Template* tmplate = XmlTemplateParser().parseTemplateNode( child.toElement() ); - if ( tmplate == 0 ) + static const int CHUNK_SIZE = 1024; + char out[CHUNK_SIZE]; + + // run inflate(), one chunk at a time + do { + strm.avail_out = CHUNK_SIZE; + strm.next_out = (Bytef*)(out); + + ret = inflate(&strm, Z_NO_FLUSH); + Q_ASSERT(ret != Z_STREAM_ERROR); // state not clobbered + + if ( (ret == Z_NEED_DICT) || (ret == Z_DATA_ERROR) || (ret == Z_MEM_ERROR) ) { - qWarning() << "Unable to parse template"; - return 0; + // clean up + inflateEnd(&strm); + return; } - label->setTmplate( tmplate ); - } - else if ( tagName == "Objects" ) - { - parseObjectsNode( child.toElement(), label ); - } - else if ( tagName == "Merge" ) - { - parseMergeNode( child.toElement(), label ); - } - else if ( tagName == "Data" ) - { - /* Handled in pass 1. */ - } - else if ( !child.isComment() ) - { - qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; - } + + result.append(out, CHUNK_SIZE - strm.avail_out); + } while (strm.avail_out == 0); + + // clean up + inflateEnd(&strm); } - label->clearModified(); - return label; -} - -QList -XmlLabelParser::parseObjects( const QDomElement &node ) -{ - QList list; - - for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) + LabelModel* + XmlLabelParser::parseRootNode( const QDomElement &node ) { - QString tagName = child.toElement().tagName(); + QString version = XmlUtil::getStringAttr( node, "version", "" ); + if ( version != "4.0" ) + { + qWarning() << "TODO: compatability mode."; + } + + LabelModel* label = new LabelModel(); + + /* Pass 1, extract data nodes to pre-load cache. */ + for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) + { + if ( child.toElement().tagName() == "Data" ) + { + parseDataNode( child.toElement(), label ); + } + } + + /* Pass 2, now extract everything else. */ + for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) + { + QString tagName = child.toElement().tagName(); - if ( tagName == "Object-box" ) - { - list.append( parseObjectBoxNode( child.toElement() ) ); + if ( tagName == "Template" ) + { + Template* tmplate = XmlTemplateParser().parseTemplateNode( child.toElement() ); + if ( tmplate == 0 ) + { + qWarning() << "Unable to parse template"; + return 0; + } + label->setTmplate( tmplate ); + } + else if ( tagName == "Objects" ) + { + parseObjectsNode( child.toElement(), label ); + } + else if ( tagName == "Merge" ) + { + parseMergeNode( child.toElement(), label ); + } + else if ( tagName == "Data" ) + { + /* Handled in pass 1. */ + } + else if ( !child.isComment() ) + { + qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; + } } - else if ( tagName == "Object-ellipse" ) + + label->clearModified(); + return label; + } + + + QList + XmlLabelParser::parseObjects( const QDomElement &node ) + { + QList list; + + for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) { - list.append( parseObjectEllipseNode( child.toElement() ) ); - } - else if ( tagName == "Object-line" ) - { - list.append( parseObjectLineNode( child.toElement() ) ); - } - else if ( tagName == "Object-text" ) - { - list.append( parseObjectTextNode( child.toElement() ) ); - } - else if ( tagName == "Object-image" ) - { - list.append( parseObjectImageNode( child.toElement() ) ); - } + QString tagName = child.toElement().tagName(); + + if ( tagName == "Object-box" ) + { + list.append( parseObjectBoxNode( child.toElement() ) ); + } + else if ( tagName == "Object-ellipse" ) + { + list.append( parseObjectEllipseNode( child.toElement() ) ); + } + else if ( tagName == "Object-line" ) + { + list.append( parseObjectLineNode( child.toElement() ) ); + } + else if ( tagName == "Object-text" ) + { + list.append( parseObjectTextNode( child.toElement() ) ); + } + else if ( tagName == "Object-image" ) + { + list.append( parseObjectImageNode( child.toElement() ) ); + } #if 0 - else if ( tagName == "Object-barcode" ) - { - list.append( parseObjectBarcodeNode( child.toElement() ) ); - } -#endif - else if ( !child.isComment() ) - { - qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; - } - } - - return list; -} - - -void -XmlLabelParser::parseObjectsNode( const QDomElement &node, LabelModel* label ) -{ - QList list = parseObjects( node ); - - foreach ( LabelModelObject* object, list ) - { - label->addObject( object ); - } -} - - -LabelModelBoxObject* -XmlLabelParser::parseObjectBoxNode( const QDomElement &node ) -{ - using namespace glabels; - - LabelModelBoxObject* object = new LabelModelBoxObject(); - - - /* position attrs */ - object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); - object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); - - /* size attrs */ - object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); - object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); - - /* line attrs */ - object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); - { - QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); - - object->setLineColorNode( ColorNode( field_flag, color, key ) ); - } - - /* fill attrs */ - { - QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "fill_color", 0 ); - - object->setFillColorNode( ColorNode( field_flag, color, key ) ); - } - - /* affine attrs */ - parseAffineAttrs( node, object ); - - /* shadow attrs */ - parseShadowAttrs( node, object ); - - return object; -} - - -LabelModelEllipseObject* -XmlLabelParser::parseObjectEllipseNode( const QDomElement &node ) -{ - using namespace glabels; - - LabelModelEllipseObject* object = new LabelModelEllipseObject(); - - - /* position attrs */ - object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); - object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); - - /* size attrs */ - object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); - object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); - - /* line attrs */ - object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); - { - QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); - - object->setLineColorNode( ColorNode( field_flag, color, key ) ); - } - - /* fill attrs */ - { - QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "fill_color", 0 ); - - object->setFillColorNode( ColorNode( field_flag, color, key ) ); - } - - /* affine attrs */ - parseAffineAttrs( node, object ); - - /* shadow attrs */ - parseShadowAttrs( node, object ); - - return object; -} - - -LabelModelLineObject* -XmlLabelParser::parseObjectLineNode( const QDomElement &node ) -{ - using namespace glabels; - - LabelModelLineObject* object = new LabelModelLineObject(); - - - /* position attrs */ - object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); - object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); - - /* size attrs */ - object->setW( XmlUtil::getLengthAttr( node, "dx", 0 ) ); - object->setH( XmlUtil::getLengthAttr( node, "dy", 0 ) ); - - /* line attrs */ - object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); - { - QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); - - object->setLineColorNode( ColorNode( field_flag, color, key ) ); - } - - /* affine attrs */ - parseAffineAttrs( node, object ); - - /* shadow attrs */ - parseShadowAttrs( node, object ); - - return object; -} - - -LabelModelImageObject* -XmlLabelParser::parseObjectImageNode( const QDomElement &node ) -{ - using namespace glabels; - - LabelModelImageObject* object = new LabelModelImageObject(); - - - /* position attrs */ - object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); - object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); - - /* size attrs */ - object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); - object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); - - /* file attrs */ - { - QString key = XmlUtil::getStringAttr( node, "src_field", "" ); - bool field_flag = !key.isEmpty(); - QString filename = XmlUtil::getStringAttr( node, "src", "" ); - - object->setFilenameNode( TextNode( field_flag, field_flag ? key : filename ) ); - } - - /* affine attrs */ - parseAffineAttrs( node, object ); - - /* shadow attrs */ - parseShadowAttrs( node, object ); - - return object; -} - - -LabelModelBarcodeObject* -XmlLabelParser::parseObjectBarcodeNode( const QDomElement &node ) -{ - return 0; -} - - -LabelModelTextObject* -XmlLabelParser::parseObjectTextNode( const QDomElement &node ) -{ - using namespace glabels; - - LabelModelTextObject* object = new LabelModelTextObject(); - - - /* position attrs */ - object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); - object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); - - /* size attrs */ - object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); - object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); - - /* color attr */ - { - QString key = XmlUtil::getStringAttr( node, "color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "color", 0 ); - - object->setTextColorNode( ColorNode( field_flag, color, key ) ); - } - - /* font attrs */ - object->setFontFamily( XmlUtil::getStringAttr( node, "font_family", "Sans" ) ); - object->setFontSize( XmlUtil::getDoubleAttr( node, "font_size", 10 ) ); - object->setFontWeight( EnumUtil::stringToWeight( XmlUtil::getStringAttr( node, "font_weight", "normal" ) ) ); - object->setFontItalicFlag( XmlUtil::getBoolAttr( node, "font_italic", false ) ); - object->setFontUnderlineFlag( XmlUtil::getBoolAttr( node, "font_underline", false ) ); - - /* text attrs */ - object->setTextLineSpacing( XmlUtil::getDoubleAttr( node, "line_spacing", 1 ) ); - object->setTextHAlign( EnumUtil::stringToHAlign( XmlUtil::getStringAttr( node, "align", "left" ) ) ); - object->setTextVAlign( EnumUtil::stringToVAlign( XmlUtil::getStringAttr( node, "valign", "top" ) ) ); - - /* affine attrs */ - parseAffineAttrs( node, object ); - - /* shadow attrs */ - parseShadowAttrs( node, object ); - - /* deserialize contents. */ - QTextDocument document; - QTextCursor cursor( &document ); - bool firstBlock = true; - for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) - { - QString tagName = child.toElement().tagName(); - - if ( tagName == "p" ) - { - if ( !firstBlock ) + else if ( tagName == "Object-barcode" ) { - cursor.insertBlock(); + list.append( parseObjectBarcodeNode( child.toElement() ) ); + } +#endif + else if ( !child.isComment() ) + { + qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; } - firstBlock = false; - cursor.insertText( parsePNode( child.toElement() ) ); - } - else if ( !child.isComment() ) - { - qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; } + + return list; } - object->setText( document.toPlainText() ); - - return object; -} -QString -XmlLabelParser::parsePNode( const QDomElement &node ) -{ - return node.text(); -} - - -void -XmlLabelParser::parseAffineAttrs( const QDomElement &node, LabelModelObject* object ) -{ - using namespace glabels; - - double a[6]; - - a[0] = XmlUtil::getDoubleAttr( node, "a0", 1.0 ); - a[1] = XmlUtil::getDoubleAttr( node, "a1", 0.0 ); - a[2] = XmlUtil::getDoubleAttr( node, "a2", 0.0 ); - a[3] = XmlUtil::getDoubleAttr( node, "a3", 1.0 ); - a[4] = XmlUtil::getDoubleAttr( node, "a4", 0.0 ); - a[5] = XmlUtil::getDoubleAttr( node, "a5", 0.0 ); - - object->setMatrix( QMatrix( a[0], a[1], a[2], a[3], a[4], a[5] ) ); -} - - -void -XmlLabelParser::parseShadowAttrs( const QDomElement &node, LabelModelObject* object ) -{ - using namespace glabels; - - object->setShadow( XmlUtil::getBoolAttr( node, "shadow", false ) ); - - if ( object->shadow() ) + void + XmlLabelParser::parseObjectsNode( const QDomElement &node, LabelModel* label ) { - object->setShadowX( XmlUtil::getLengthAttr( node, "shadow_x", 0.0 ) ); - object->setShadowY( XmlUtil::getLengthAttr( node, "shadow_y", 0.0 ) ); + QList list = parseObjects( node ); - QString key = XmlUtil::getStringAttr( node, "shadow_color_field", "" ); - bool field_flag = !key.isEmpty(); - uint32_t color = XmlUtil::getUIntAttr( node, "shadow_color", 0 ); - - object->setShadowColorNode( ColorNode( field_flag, color, key ) ); - - object->setShadowOpacity( XmlUtil::getDoubleAttr( node, "shadow_opacity", 1.0 ) ); + foreach ( LabelModelObject* object, list ) + { + label->addObject( object ); + } } + + + LabelModelBoxObject* + XmlLabelParser::parseObjectBoxNode( const QDomElement &node ) + { + LabelModelBoxObject* object = new LabelModelBoxObject(); + + + /* position attrs */ + object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); + object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); + + /* size attrs */ + object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); + object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); + + /* line attrs */ + object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); + { + QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); + + object->setLineColorNode( ColorNode( field_flag, color, key ) ); + } + + /* fill attrs */ + { + QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "fill_color", 0 ); + + object->setFillColorNode( ColorNode( field_flag, color, key ) ); + } + + /* affine attrs */ + parseAffineAttrs( node, object ); + + /* shadow attrs */ + parseShadowAttrs( node, object ); + + return object; + } + + + LabelModelEllipseObject* + XmlLabelParser::parseObjectEllipseNode( const QDomElement &node ) + { + LabelModelEllipseObject* object = new LabelModelEllipseObject(); + + + /* position attrs */ + object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); + object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); + + /* size attrs */ + object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); + object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); + + /* line attrs */ + object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); + { + QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); + + object->setLineColorNode( ColorNode( field_flag, color, key ) ); + } + + /* fill attrs */ + { + QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "fill_color", 0 ); + + object->setFillColorNode( ColorNode( field_flag, color, key ) ); + } + + /* affine attrs */ + parseAffineAttrs( node, object ); + + /* shadow attrs */ + parseShadowAttrs( node, object ); + + return object; + } + + + LabelModelLineObject* + XmlLabelParser::parseObjectLineNode( const QDomElement &node ) + { + LabelModelLineObject* object = new LabelModelLineObject(); + + + /* position attrs */ + object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); + object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); + + /* size attrs */ + object->setW( XmlUtil::getLengthAttr( node, "dx", 0 ) ); + object->setH( XmlUtil::getLengthAttr( node, "dy", 0 ) ); + + /* line attrs */ + object->setLineWidth( XmlUtil::getLengthAttr( node, "line_width", 1.0 ) ); + { + QString key = XmlUtil::getStringAttr( node, "line_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "line_color", 0 ); + + object->setLineColorNode( ColorNode( field_flag, color, key ) ); + } + + /* affine attrs */ + parseAffineAttrs( node, object ); + + /* shadow attrs */ + parseShadowAttrs( node, object ); + + return object; + } + + + LabelModelImageObject* + XmlLabelParser::parseObjectImageNode( const QDomElement &node ) + { + LabelModelImageObject* object = new LabelModelImageObject(); + + + /* position attrs */ + object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); + object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); + + /* size attrs */ + object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); + object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); + + /* file attrs */ + { + QString key = XmlUtil::getStringAttr( node, "src_field", "" ); + bool field_flag = !key.isEmpty(); + QString filename = XmlUtil::getStringAttr( node, "src", "" ); + + object->setFilenameNode( TextNode( field_flag, field_flag ? key : filename ) ); + } + + /* affine attrs */ + parseAffineAttrs( node, object ); + + /* shadow attrs */ + parseShadowAttrs( node, object ); + + return object; + } + + + LabelModelBarcodeObject* + XmlLabelParser::parseObjectBarcodeNode( const QDomElement &node ) + { + return 0; + } + + + LabelModelTextObject* + XmlLabelParser::parseObjectTextNode( const QDomElement &node ) + { + LabelModelTextObject* object = new LabelModelTextObject(); + + + /* position attrs */ + object->setX0( XmlUtil::getLengthAttr( node, "x", 0.0 ) ); + object->setY0( XmlUtil::getLengthAttr( node, "y", 0.0 ) ); + + /* size attrs */ + object->setW( XmlUtil::getLengthAttr( node, "w", 0 ) ); + object->setH( XmlUtil::getLengthAttr( node, "h", 0 ) ); + + /* color attr */ + { + QString key = XmlUtil::getStringAttr( node, "color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "color", 0 ); + + object->setTextColorNode( ColorNode( field_flag, color, key ) ); + } + + /* font attrs */ + object->setFontFamily( XmlUtil::getStringAttr( node, "font_family", "Sans" ) ); + object->setFontSize( XmlUtil::getDoubleAttr( node, "font_size", 10 ) ); + object->setFontWeight( EnumUtil::stringToWeight( XmlUtil::getStringAttr( node, "font_weight", "normal" ) ) ); + object->setFontItalicFlag( XmlUtil::getBoolAttr( node, "font_italic", false ) ); + object->setFontUnderlineFlag( XmlUtil::getBoolAttr( node, "font_underline", false ) ); + + /* text attrs */ + object->setTextLineSpacing( XmlUtil::getDoubleAttr( node, "line_spacing", 1 ) ); + object->setTextHAlign( EnumUtil::stringToHAlign( XmlUtil::getStringAttr( node, "align", "left" ) ) ); + object->setTextVAlign( EnumUtil::stringToVAlign( XmlUtil::getStringAttr( node, "valign", "top" ) ) ); + + /* affine attrs */ + parseAffineAttrs( node, object ); + + /* shadow attrs */ + parseShadowAttrs( node, object ); + + /* deserialize contents. */ + QTextDocument document; + QTextCursor cursor( &document ); + bool firstBlock = true; + for ( QDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) + { + QString tagName = child.toElement().tagName(); + + if ( tagName == "p" ) + { + if ( !firstBlock ) + { + cursor.insertBlock(); + } + firstBlock = false; + cursor.insertText( parsePNode( child.toElement() ) ); + } + else if ( !child.isComment() ) + { + qWarning() << "Unexpected" << node.tagName() << "child:" << tagName; + } + } + object->setText( document.toPlainText() ); + + return object; + } + + + QString + XmlLabelParser::parsePNode( const QDomElement &node ) + { + return node.text(); + } + + + void + XmlLabelParser::parseAffineAttrs( const QDomElement &node, LabelModelObject* object ) + { + double a[6]; + + a[0] = XmlUtil::getDoubleAttr( node, "a0", 1.0 ); + a[1] = XmlUtil::getDoubleAttr( node, "a1", 0.0 ); + a[2] = XmlUtil::getDoubleAttr( node, "a2", 0.0 ); + a[3] = XmlUtil::getDoubleAttr( node, "a3", 1.0 ); + a[4] = XmlUtil::getDoubleAttr( node, "a4", 0.0 ); + a[5] = XmlUtil::getDoubleAttr( node, "a5", 0.0 ); + + object->setMatrix( QMatrix( a[0], a[1], a[2], a[3], a[4], a[5] ) ); + } + + + void + XmlLabelParser::parseShadowAttrs( const QDomElement &node, LabelModelObject* object ) + { + object->setShadow( XmlUtil::getBoolAttr( node, "shadow", false ) ); + + if ( object->shadow() ) + { + object->setShadowX( XmlUtil::getLengthAttr( node, "shadow_x", 0.0 ) ); + object->setShadowY( XmlUtil::getLengthAttr( node, "shadow_y", 0.0 ) ); + + QString key = XmlUtil::getStringAttr( node, "shadow_color_field", "" ); + bool field_flag = !key.isEmpty(); + uint32_t color = XmlUtil::getUIntAttr( node, "shadow_color", 0 ); + + object->setShadowColorNode( ColorNode( field_flag, color, key ) ); + + object->setShadowOpacity( XmlUtil::getDoubleAttr( node, "shadow_opacity", 1.0 ) ); + } + } + + + void + XmlLabelParser::parseMergeNode( const QDomElement &node, LabelModel* label ) + { + QString type = XmlUtil::getStringAttr( node, "type", "None" ); + QString src = XmlUtil::getStringAttr( node, "src", "" ); + + merge::Merge* merge = merge::Factory::createMerge( type ); + merge->setSource( src ); + + label->setMerge( merge ); + } + + + void + XmlLabelParser::parseDataNode( const QDomElement &node, LabelModel* label ) + { + // TODO + } + + + void + XmlLabelParser::parsePixdataNode( const QDomElement &node, LabelModel* label ) + { + // TODO + } + + + void + XmlLabelParser::parseFileNode( const QDomElement &node, LabelModel* label ) + { + // TODO + } + } - - -void -XmlLabelParser::parseMergeNode( const QDomElement &node, LabelModel* label ) -{ - using namespace glabels; - - QString type = XmlUtil::getStringAttr( node, "type", "None" ); - QString src = XmlUtil::getStringAttr( node, "src", "" ); - - merge::Merge* merge = merge::Factory::createMerge( type ); - merge->setSource( src ); - - label->setMerge( merge ); -} - - -void -XmlLabelParser::parseDataNode( const QDomElement &node, LabelModel* label ) -{ -} - - -void -XmlLabelParser::parsePixdataNode( const QDomElement &node, LabelModel* label ) -{ -} - - -void -XmlLabelParser::parseFileNode( const QDomElement &node, LabelModel* label ) -{ -} - - diff --git a/glabels/XmlLabelParser.h b/glabels/XmlLabelParser.h index 6ad9449..07b5e7e 100644 --- a/glabels/XmlLabelParser.h +++ b/glabels/XmlLabelParser.h @@ -25,49 +25,55 @@ #include #include -// Forward references -class LabelModel; -class LabelModelObject; -class LabelModelBoxObject; -class LabelModelEllipseObject; -class LabelModelLineObject; -class LabelModelImageObject; -class LabelModelBarcodeObject; -class LabelModelTextObject; - -/// -/// XmlLabelParser -/// -class XmlLabelParser : public QObject +namespace glabels { - Q_OBJECT -public: - static LabelModel* readFile( const QString& fileName ); - static LabelModel* readBuffer( const QByteArray& buffer ); - static QList deserializeObjects( const QByteArray& buffer ); + // Forward references + class LabelModel; + class LabelModelObject; + class LabelModelBoxObject; + class LabelModelEllipseObject; + class LabelModelLineObject; + class LabelModelImageObject; + class LabelModelBarcodeObject; + class LabelModelTextObject; -private: - static void gunzip( const QByteArray& gzippedData, QByteArray& data ); - static LabelModel* parseRootNode( const QDomElement &node ); - static QList parseObjects( const QDomElement &node ); - static void parseObjectsNode( const QDomElement &node, LabelModel* label ); - static LabelModelBoxObject* parseObjectBoxNode( const QDomElement &node ); - static LabelModelEllipseObject* parseObjectEllipseNode( const QDomElement &node ); - static LabelModelLineObject* parseObjectLineNode( const QDomElement &node ); - static LabelModelImageObject* parseObjectImageNode( const QDomElement &node ); - static LabelModelBarcodeObject* parseObjectBarcodeNode( const QDomElement &node ); - static LabelModelTextObject* parseObjectTextNode( const QDomElement &node ); - static QString parsePNode( const QDomElement &node ); - static void parseAffineAttrs( const QDomElement &node, LabelModelObject* object ); - static void parseShadowAttrs( const QDomElement &node, LabelModelObject* object ); - static void parseMergeNode( const QDomElement &node, LabelModel* label ); - static void parseDataNode( const QDomElement &node, LabelModel* label ); - static void parsePixdataNode( const QDomElement &node, LabelModel* label ); - static void parseFileNode( const QDomElement &node, LabelModel* label ); -}; + /// + /// XmlLabelParser + /// + class XmlLabelParser : public QObject + { + Q_OBJECT + + public: + static LabelModel* readFile( const QString& fileName ); + static LabelModel* readBuffer( const QByteArray& buffer ); + static QList deserializeObjects( const QByteArray& buffer ); + + private: + static void gunzip( const QByteArray& gzippedData, QByteArray& data ); + static LabelModel* parseRootNode( const QDomElement &node ); + static QList parseObjects( const QDomElement &node ); + static void parseObjectsNode( const QDomElement &node, LabelModel* label ); + static LabelModelBoxObject* parseObjectBoxNode( const QDomElement &node ); + static LabelModelEllipseObject* parseObjectEllipseNode( const QDomElement &node ); + static LabelModelLineObject* parseObjectLineNode( const QDomElement &node ); + static LabelModelImageObject* parseObjectImageNode( const QDomElement &node ); + static LabelModelBarcodeObject* parseObjectBarcodeNode( const QDomElement &node ); + static LabelModelTextObject* parseObjectTextNode( const QDomElement &node ); + static QString parsePNode( const QDomElement &node ); + static void parseAffineAttrs( const QDomElement &node, LabelModelObject* object ); + static void parseShadowAttrs( const QDomElement &node, LabelModelObject* object ); + static void parseMergeNode( const QDomElement &node, LabelModel* label ); + static void parseDataNode( const QDomElement &node, LabelModel* label ); + static void parsePixdataNode( const QDomElement &node, LabelModel* label ); + static void parseFileNode( const QDomElement &node, LabelModel* label ); + + }; + +} #endif // XmlLabelParser_h diff --git a/glabels/XmlUtil.cpp b/glabels/XmlUtil.cpp index 672c7de..a8387be 100644 --- a/glabels/XmlUtil.cpp +++ b/glabels/XmlUtil.cpp @@ -28,6 +28,9 @@ namespace glabels { + // + // Static data + // Units XmlUtil::mUnits; diff --git a/glabels/glabels_main.cpp b/glabels/glabels_main.cpp index e731fb2..ae24c74 100644 --- a/glabels/glabels_main.cpp +++ b/glabels/glabels_main.cpp @@ -36,9 +36,9 @@ int main( int argc, char **argv ) QCoreApplication::setOrganizationDomain( "glabels.org" ); QCoreApplication::setApplicationName( "glabels-qt" ); - Settings::init(); + glabels::Settings::init(); glabels::Db::init(); - merge::Factory::init(); + glabels::merge::Factory::init(); ////// TEMPORARY TESTING //////// #if 0 glabels::Db::printKnownPapers(); @@ -49,7 +49,7 @@ int main( int argc, char **argv ) ///////////////////////////////// /// @TODO open file(s) from command line if present, otherwise start wizard - MainWindow mainWindow; + glabels::MainWindow mainWindow; mainWindow.show(); return app.exec(); diff --git a/glabels/privateConstants.h b/glabels/privateConstants.h deleted file mode 100644 index f9b3392..0000000 --- a/glabels/privateConstants.h +++ /dev/null @@ -1,40 +0,0 @@ -/* privateConstants.h - * - * Copyright (C) 2013-2016 Jim Evins - * - * This file is part of gLabels-qt. - * - * gLabels-qt is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * gLabels-qt is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with gLabels-qt. If not, see . - */ - -#ifndef glabels_privateConstants_h -#define glabels_privateConstants_h - - -#include "Distance.h" - - -namespace glabels -{ - - namespace Constants - { - - const Distance EPSILON( 0.5, Units::PT ); - - } - -} - -#endif // glabels_privateConstants_h diff --git a/glabels/ui/ObjectEditor.ui b/glabels/ui/ObjectEditor.ui index e0da56f..bfd74fa 100644 --- a/glabels/ui/ObjectEditor.ui +++ b/glabels/ui/ObjectEditor.ui @@ -35,7 +35,7 @@ - 4 + 5 @@ -372,7 +372,7 @@ - + @@ -451,7 +451,7 @@ - + @@ -535,7 +535,7 @@ - + @@ -814,7 +814,7 @@ - + 0 @@ -933,7 +933,7 @@ - + 0 @@ -987,7 +987,7 @@ - + 0 @@ -1199,7 +1199,16 @@ 15 - + + 0 + + + 0 + + + 0 + + 0 @@ -1457,7 +1466,7 @@ - + 0 @@ -1545,20 +1554,14 @@ - ColorButton + glabels::ColorButton QPushButton
ColorButton.h
- - colorChanged() -
- FieldButton + glabels::FieldButton QComboBox
FieldButton.h
- - keySelected(QString) -
diff --git a/glabels/ui/PrintView.ui b/glabels/ui/PrintView.ui index 83c8f5c..187ead0 100644 --- a/glabels/ui/PrintView.ui +++ b/glabels/ui/PrintView.ui @@ -26,7 +26,7 @@ QLayout::SetDefaultConstraint
- + 0 @@ -109,7 +109,16 @@ QLayout::SetDefaultConstraint - + + 12 + + + 12 + + + 12 + + 12 @@ -340,7 +349,7 @@ - Preview + glabels::Preview QWidget
Preview.h
1 diff --git a/glabels/ui/PropertiesView.ui b/glabels/ui/PropertiesView.ui index 496e5db..42669a5 100644 --- a/glabels/ui/PropertiesView.ui +++ b/glabels/ui/PropertiesView.ui @@ -29,7 +29,7 @@ - + 0 @@ -42,7 +42,16 @@ - + + 12 + + + 12 + + + 12 + + 12 @@ -362,10 +371,9 @@
- SimplePreview + glabels::SimplePreview QGraphicsView
SimplePreview.h
- 1
diff --git a/glabels/ui/SelectProductDialog.ui b/glabels/ui/SelectProductDialog.ui index 6855657..bd1379b 100644 --- a/glabels/ui/SelectProductDialog.ui +++ b/glabels/ui/SelectProductDialog.ui @@ -170,7 +170,16 @@ - + + 0 + + + 0 + + + 0 + + 0 @@ -252,7 +261,7 @@ - + false @@ -290,7 +299,7 @@ - TemplatePicker + glabels::TemplatePicker QListWidget
TemplatePicker.h