diff options
Diffstat (limited to 'src/gui')
194 files changed, 8087 insertions, 6541 deletions
diff --git a/src/gui/accessible/accessible.pri b/src/gui/accessible/accessible.pri index 76b6687..ad2fb4c 100644 --- a/src/gui/accessible/accessible.pri +++ b/src/gui/accessible/accessible.pri @@ -14,7 +14,8 @@ contains(QT_CONFIG, accessibility) { mac:!embedded { HEADERS += accessible/qaccessible_mac_p.h - OBJECTIVE_SOURCES += accessible/qaccessible_mac.mm + OBJECTIVE_SOURCES += accessible/qaccessible_mac.mm \ + accessible/qaccessible_mac_cocoa.mm } else:win32 { SOURCES += accessible/qaccessible_win.cpp } else { diff --git a/src/gui/accessible/qaccessible_mac_cocoa.mm b/src/gui/accessible/qaccessible_mac_cocoa.mm index e69de29..1cb2ffa 100644 --- a/src/gui/accessible/qaccessible_mac_cocoa.mm +++ b/src/gui/accessible/qaccessible_mac_cocoa.mm @@ -0,0 +1,234 @@ + +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qaccessible.h" +#include "qaccessible_mac_p.h" +#include "qdebug.h" +#include "qtabwidget.h" + +#include <private/qt_mac_p.h> +#include <private/qcocoaview_mac_p.h> +#include <private/qwidget_p.h> + + +#ifndef QT_NO_ACCESSIBILITY + +#ifdef QT_MAC_USE_COCOA + +QT_BEGIN_NAMESPACE + +//#define MAC_ACCESSIBILTY_DEVELOPER_MODE + +#ifdef MAC_ACCESSIBILTY_DEVELOPER_MODE +#define MAC_ACCESSIBILTY_DEBUG qDebug +#else +#define MAC_ACCESSIBILTY_DEBUG if (0) qDebug +#endif + +typedef QMap<QAccessible::Role, NSString *> QMacAccessibiltyRoleMap; +Q_GLOBAL_STATIC(QMacAccessibiltyRoleMap, qMacAccessibiltyRoleMap); + +static QAInterface interfaceForView(QT_MANGLE_NAMESPACE(QCocoaView) *view) +{ + return QAInterface(QAccessible::queryAccessibleInterface([view qt_qwidget])); +} + +/* + Set up mappings from Qt accessibilty roles to Mac accessibilty roles. +*/ +static void populateRoleMap() +{ + QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap(); + roleMap[QAccessible::MenuItem] = NSAccessibilityMenuItemRole; + roleMap[QAccessible::MenuBar] = NSAccessibilityMenuBarRole; + roleMap[QAccessible::ScrollBar] = NSAccessibilityScrollBarRole; + roleMap[QAccessible::Grip] = NSAccessibilityGrowAreaRole; + roleMap[QAccessible::Window] = NSAccessibilityWindowRole; + roleMap[QAccessible::Dialog] = NSAccessibilityWindowRole; + roleMap[QAccessible::AlertMessage] = NSAccessibilityWindowRole; + roleMap[QAccessible::ToolTip] = NSAccessibilityWindowRole; + roleMap[QAccessible::HelpBalloon] = NSAccessibilityWindowRole; + roleMap[QAccessible::PopupMenu] = NSAccessibilityMenuRole; + roleMap[QAccessible::Application] = NSAccessibilityApplicationRole; + roleMap[QAccessible::Pane] = NSAccessibilityGroupRole; + roleMap[QAccessible::Grouping] = NSAccessibilityGroupRole; + roleMap[QAccessible::Separator] = NSAccessibilitySplitterRole; + roleMap[QAccessible::ToolBar] = NSAccessibilityToolbarRole; + roleMap[QAccessible::PageTab] = NSAccessibilityRadioButtonRole; + roleMap[QAccessible::ButtonMenu] = NSAccessibilityMenuButtonRole; + roleMap[QAccessible::ButtonDropDown] = NSAccessibilityPopUpButtonRole; + roleMap[QAccessible::SpinBox] = NSAccessibilityIncrementorRole; + roleMap[QAccessible::Slider] = NSAccessibilitySliderRole; + roleMap[QAccessible::ProgressBar] = NSAccessibilityProgressIndicatorRole; + roleMap[QAccessible::ComboBox] = NSAccessibilityPopUpButtonRole; + roleMap[QAccessible::RadioButton] = NSAccessibilityRadioButtonRole; + roleMap[QAccessible::CheckBox] = NSAccessibilityCheckBoxRole; + roleMap[QAccessible::StaticText] = NSAccessibilityStaticTextRole; + roleMap[QAccessible::Table] = NSAccessibilityTableRole; + roleMap[QAccessible::StatusBar] = NSAccessibilityStaticTextRole; + roleMap[QAccessible::Column] = NSAccessibilityColumnRole; + roleMap[QAccessible::ColumnHeader] = NSAccessibilityColumnRole; + roleMap[QAccessible::Row] = NSAccessibilityRowRole; + roleMap[QAccessible::RowHeader] = NSAccessibilityRowRole; + roleMap[QAccessible::Cell] = NSAccessibilityTextFieldRole; + roleMap[QAccessible::PushButton] = NSAccessibilityButtonRole; + roleMap[QAccessible::EditableText] = NSAccessibilityTextFieldRole; + roleMap[QAccessible::Link] = NSAccessibilityTextFieldRole; + roleMap[QAccessible::Indicator] = NSAccessibilityValueIndicatorRole; + roleMap[QAccessible::Splitter] = NSAccessibilitySplitGroupRole; + roleMap[QAccessible::List] = NSAccessibilityListRole; + roleMap[QAccessible::ListItem] = NSAccessibilityStaticTextRole; + roleMap[QAccessible::Cell] = NSAccessibilityStaticTextRole; +} + +/* + Returns a Mac accessibility role for the given interface, or + NSAccessibilityUnknownRole if no role mapping is found. +*/ +static NSString *macRoleForInterface(QAInterface interface) +{ + const QAccessible::Role qtRole = interface.role(); + QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap(); + + if (roleMap.isEmpty()) + populateRoleMap(); + + MAC_ACCESSIBILTY_DEBUG() << "role for" << interface.object() << "interface role" << hex << qtRole; + + if (roleMap.contains(qtRole)) { + MAC_ACCESSIBILTY_DEBUG() << "return" << roleMap[qtRole]; + return roleMap[qtRole]; + } + + MAC_ACCESSIBILTY_DEBUG() << "return NSAccessibilityUnknownRole"; + return NSAccessibilityUnknownRole; +} + +/* + Is the interface a QTabBar embedded in a QTabWidget? + (as opposed to a stand-alone tab bar) +*/ +static bool isEmbeddedTabBar(const QAInterface &interface) +{ + QObject *object = interface.object(); + if (interface.role() == QAccessible::PageTabList && object) + return (qobject_cast<QTabWidget *>(object->parent())); + + return false; +} + +static bool isInterfaceIgnored(QAInterface interface) +{ + // Mac accessibility does not have an attribute that corresponds to the + // Invisible/Offscreen state. Use the ignore facility to disable them. + const QAccessible::State state = interface.state(); + if (state & QAccessible::Invisible || + state & QAccessible::Offscreen ) + return false; + + // Hide QTabBars that has a QTabWidget parent (the QTabWidget handles the accessibility) + if (isEmbeddedTabBar(interface)) + return false; + + if (QObject * const object = interface.object()) { + const QString className = QLatin1String(object->metaObject()->className()); + + // Prevent VoiceOver from focusing on tool tips by ignoring those + // interfaces. Shifting VoiceOver focus to the tool tip is confusing + // and the contents of the tool tip is avalible through the description + // attribute anyway. + if (className == QLatin1String("QTipLabel")) + return false; + } + + // Hide interfaces with an unknown role. When developing it's often useful to disable + // this check to see all interfaces in the hierarchy. +#ifndef MAC_ACCESSIBILTY_DEVELOPER_MODE + return [macRoleForInterface(interface) isEqualToString: NSAccessibilityUnknownRole]; +#else + return NO; +#endif +} + +QT_END_NAMESPACE + +@implementation QT_MANGLE_NAMESPACE(QCocoaView) (Accessibility) + +- (BOOL)accessibilityIsIgnored +{ + QAInterface interface = interfaceForView(self); + return isInterfaceIgnored(interface); +} + +- (NSArray *)accessibilityAttributeNames +{ + QAInterface interface = interfaceForView(self); + + static NSArray *attributes = nil; + if (attributes == nil) { + attributes = [super accessibilityAttributeNames]; + + } + return attributes; +} + +- (id)accessibilityAttributeValue:(NSString *)attribute +{ + MAC_ACCESSIBILTY_DEBUG() << "accessibilityAttributeValue" << self << QCFString::toQString(reinterpret_cast<CFStringRef>(attribute)); + + QAInterface interface = interfaceForView(self); + + // Switch on the attribute name and call the appropriate handler function. + // Pass the call on to the NSView class for attributes we don't handle. + if ([attribute isEqualToString:@"AXRole"]) { + return macRoleForInterface(interface); + } else { + return [super accessibilityAttributeValue:attribute]; + } +} + +@end + +#endif // QT_MAC_USE_COCOA + +#endif // QT_NO_ACCESSIBILITY + diff --git a/src/gui/dialogs/qabstractprintdialog.cpp b/src/gui/dialogs/qabstractprintdialog.cpp index 2ffc400..beb6918 100644 --- a/src/gui/dialogs/qabstractprintdialog.cpp +++ b/src/gui/dialogs/qabstractprintdialog.cpp @@ -395,10 +395,8 @@ void QAbstractPrintDialogPrivate::setPrinter(QPrinter *newPrinter) On Windows and Mac OS X, the native print dialog is used, which means that some QWidget and QDialog properties set on the dialog won't be respected. - The native print dialog on - Mac OS X does not support setting printer options, i.e. - QAbstractPrintDialog::setEnabledOptions() and - QAbstractPrintDialog::addEnabledOption() have no effect. + The native print dialog on Mac OS X does not support setting printer options, + i.e. setOptions() and setOption() have no effect. In Qt 4.4, it was possible to use the static functions to show a sheet on Mac OS X. This is no longer supported in Qt 4.5. If you want this diff --git a/src/gui/dialogs/qcolordialog.cpp b/src/gui/dialogs/qcolordialog.cpp index 42d3a9a..0357a7a 100644 --- a/src/gui/dialogs/qcolordialog.cpp +++ b/src/gui/dialogs/qcolordialog.cpp @@ -1583,8 +1583,7 @@ void QColorDialog::setCurrentColor(const QColor &color) #ifdef Q_WS_MAC d->setCurrentQColor(color); - if (d->delegate) - QColorDialogPrivate::setColor(d->delegate, color); + d->setCocoaPanelColor(color); #endif } @@ -1725,19 +1724,16 @@ void QColorDialog::setVisible(bool visible) #if defined(Q_WS_MAC) if (visible) { - if (!d->delegate && QColorDialogPrivate::sharedColorPanelAvailable && - !(testAttribute(Qt::WA_DontShowOnScreen) || (d->opts & DontUseNativeDialog))){ - d->delegate = QColorDialogPrivate::openCocoaColorPanel( - currentColor(), parentWidget(), windowTitle(), options(), d); + if (d->delegate || (QColorDialogPrivate::sharedColorPanelAvailable && + !(testAttribute(Qt::WA_DontShowOnScreen) || (d->opts & DontUseNativeDialog)))){ + d->openCocoaColorPanel(currentColor(), parentWidget(), windowTitle(), options()); QColorDialogPrivate::sharedColorPanelAvailable = false; setAttribute(Qt::WA_DontShowOnScreen); } setWindowFlags(windowModality() == Qt::WindowModal ? Qt::Sheet : DefaultWindowFlags); } else { if (d->delegate) { - QColorDialogPrivate::closeCocoaColorPanel(d->delegate); - d->delegate = 0; - QColorDialogPrivate::sharedColorPanelAvailable = true; + d->closeCocoaColorPanel(); setAttribute(Qt::WA_DontShowOnScreen, false); } } @@ -1840,6 +1836,14 @@ QRgb QColorDialog::getRgba(QRgb initial, bool *ok, QWidget *parent) QColorDialog::~QColorDialog() { +#if defined(Q_WS_MAC) + Q_D(QColorDialog); + if (d->delegate) { + d->releaseCocoaColorPanelDelegate(); + QColorDialogPrivate::sharedColorPanelAvailable = true; + } +#endif + #ifndef QT_NO_SETTINGS if (!customSet) { QSettings settings(QSettings::UserScope, QLatin1String("Trolltech")); diff --git a/src/gui/dialogs/qcolordialog_mac.mm b/src/gui/dialogs/qcolordialog_mac.mm index 1936de5..6cdb7ee 100644 --- a/src/gui/dialogs/qcolordialog_mac.mm +++ b/src/gui/dialogs/qcolordialog_mac.mm @@ -76,6 +76,8 @@ QT_USE_NAMESPACE CGFloat mMinWidth; // currently unused CGFloat mExtraHeight; // currently unused BOOL mHackedPanel; + NSInteger mResultCode; + BOOL mDialogIsExecuting; } - (id)initWithColorPanel:(NSColorPanel *)panel stolenContentView:(NSView *)stolenContentView @@ -90,7 +92,8 @@ QT_USE_NAMESPACE - (NSColorPanel *)colorPanel; - (QColor)qtColor; - (void)finishOffWithCode:(NSInteger)result; -- (void)cleanUpAfterMyself; +- (void)showColorPanel; +- (void)exec; @end @implementation QCocoaColorPanelDelegate @@ -110,6 +113,8 @@ QT_USE_NAMESPACE mMinWidth = 0.0; mExtraHeight = 0.0; mHackedPanel = (okButton != 0); + mResultCode = NSCancelButton; + mDialogIsExecuting = false; if (mHackedPanel) { [self relayout]; @@ -121,19 +126,31 @@ QT_USE_NAMESPACE [cancelButton setTarget:self]; } - if (mPriv) - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(colorChanged:) - name:NSColorPanelColorDidChangeNotification - object:mColorPanel]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(colorChanged:) + name:NSColorPanelColorDidChangeNotification + object:mColorPanel]; + mQtColor = new QColor(); return self; } - (void)dealloc { - if (mPriv) - [[NSNotificationCenter defaultCenter] removeObserver:self]; + QMacCocoaAutoReleasePool pool; + if (mHackedPanel) { + NSView *ourContentView = [mColorPanel contentView]; + + // return stolen stuff to its rightful owner + [mStolenContentView removeFromSuperview]; + [mColorPanel setContentView:mStolenContentView]; + + [mOkButton release]; + [mCancelButton release]; + [ourContentView release]; + } + [mColorPanel setDelegate:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; delete mQtColor; [super dealloc]; } @@ -160,8 +177,7 @@ QT_USE_NAMESPACE - (void)colorChanged:(NSNotification *)notification; { Q_UNUSED(notification); - if (mPriv) - [self updateQtColor]; + [self updateQtColor]; } - (void)relayout @@ -258,8 +274,7 @@ QT_USE_NAMESPACE } } - if (mPriv) - mPriv->setCurrentQColor(*mQtColor); + mPriv->setCurrentQColor(*mQtColor); } - (NSColorPanel *)colorPanel @@ -274,36 +289,42 @@ QT_USE_NAMESPACE - (void)finishOffWithCode:(NSInteger)code { - if (mPriv) { - // Finish the QColorDialog as well. But since a call to accept or reject will - // close down the QEventLoop found in QDialog, we need to make sure that the - // current thread has exited the native dialogs modal session/run loop first. - // We ensure this by posting the call: + mResultCode = code; + if (mDialogIsExecuting) { + // We stop the current modal event loop. The control + // will then return inside -(void)exec below. + // It's important that the modal event loop is stopped before + // we accept/reject QColorDialog, since QColorDialog has its + // own event loop that needs to be stopped last. [NSApp stopModalWithCode:code]; - if (code == NSOKButton) - QMetaObject::invokeMethod(mPriv->colorDialog(), "accept", Qt::QueuedConnection); - else - QMetaObject::invokeMethod(mPriv->colorDialog(), "reject", Qt::QueuedConnection); } else { - [NSApp stopModalWithCode:code]; + // Since we are not in a modal event loop, we can safely close + // down QColorDialog + if (mResultCode == NSCancelButton) + mPriv->colorDialog()->reject(); + else + mPriv->colorDialog()->accept(); } } -- (void)cleanUpAfterMyself +- (void)showColorPanel { - if (mHackedPanel) { - NSView *ourContentView = [mColorPanel contentView]; - - // return stolen stuff to its rightful owner - [mStolenContentView removeFromSuperview]; - [mColorPanel setContentView:mStolenContentView]; + mDialogIsExecuting = false; + [mColorPanel makeKeyAndOrderFront:mColorPanel]; +} - [mOkButton release]; - [mCancelButton release]; - [ourContentView release]; - } - [mColorPanel setDelegate:nil]; +- (void)exec +{ + QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active); + QMacCocoaAutoReleasePool pool; + mDialogIsExecuting = true; + [NSApp runModalForWindow:mColorPanel]; + if (mResultCode == NSCancelButton) + mPriv->colorDialog()->reject(); + else + mPriv->colorDialog()->accept(); } + @end QT_BEGIN_NAMESPACE @@ -312,91 +333,90 @@ extern void macStartInterceptNSPanelCtor(); extern void macStopInterceptNSPanelCtor(); extern NSButton *macCreateButton(const char *text, NSView *superview); -void *QColorDialogPrivate::openCocoaColorPanel(const QColor &initial, - QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options, - QColorDialogPrivate *priv) +void QColorDialogPrivate::openCocoaColorPanel(const QColor &initial, + QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options) { Q_UNUSED(parent); // we would use the parent if only NSColorPanel could be a sheet QMacCocoaAutoReleasePool pool; - /* - The standard Cocoa color panel has no OK or Cancel button and - is created as a utility window, whereas we want something like - the Carbon color panel. We need to take the following steps: + if (!delegate) { + /* + The standard Cocoa color panel has no OK or Cancel button and + is created as a utility window, whereas we want something like + the Carbon color panel. We need to take the following steps: + + 1. Intercept the color panel constructor to turn off the + NSUtilityWindowMask flag. This is done by temporarily + replacing initWithContentRect:styleMask:backing:defer: + in NSPanel by our own method. - 1. Intercept the color panel constructor to turn off the - NSUtilityWindowMask flag. This is done by temporarily - replacing initWithContentRect:styleMask:backing:defer: - in NSPanel by our own method. + 2. Modify the color panel so that its content view is part + of a new content view that contains it as well as two + buttons (OK and Cancel). - 2. Modify the color panel so that its content view is part - of a new content view that contains it as well as two - buttons (OK and Cancel). + 3. Lay out the original content view and the buttons when + the color panel is shown and whenever it is resized. - 3. Lay out the original content view and the buttons when - the color panel is shown and whenever it is resized. + 4. Clean up after ourselves. + */ - 4. Clean up after ourselves. - */ + bool hackColorPanel = !(options & QColorDialog::NoButtons); - bool hackColorPanel = !(options & QColorDialog::NoButtons); + if (hackColorPanel) + macStartInterceptNSPanelCtor(); + NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel]; + if (hackColorPanel) + macStopInterceptNSPanelCtor(); - if (hackColorPanel) - macStartInterceptNSPanelCtor(); - NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel]; - if (hackColorPanel) - macStopInterceptNSPanelCtor(); + [colorPanel setHidesOnDeactivate:false]; - [colorPanel setHidesOnDeactivate:false]; + // set up the Cocoa color panel + [colorPanel setShowsAlpha:options & QColorDialog::ShowAlphaChannel]; + [colorPanel setTitle:(NSString*)(CFStringRef)QCFString(title)]; - // set up the Cocoa color panel - [colorPanel setShowsAlpha:options & QColorDialog::ShowAlphaChannel]; - [colorPanel setTitle:(NSString*)(CFStringRef)QCFString(title)]; + NSView *stolenContentView = 0; + NSButton *okButton = 0; + NSButton *cancelButton = 0; - NSView *stolenContentView = 0; - NSButton *okButton = 0; - NSButton *cancelButton = 0; + if (hackColorPanel) { + // steal the color panel's contents view + stolenContentView = [colorPanel contentView]; + [stolenContentView retain]; + [colorPanel setContentView:0]; - if (hackColorPanel) { - // steal the color panel's contents view - stolenContentView = [colorPanel contentView]; - [stolenContentView retain]; - [colorPanel setContentView:0]; + // create a new content view and add the stolen one as a subview + NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } }; + NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect]; + [ourContentView addSubview:stolenContentView]; - // create a new content view and add the stolen one as a subview - NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } }; - NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect]; - [ourContentView addSubview:stolenContentView]; + // create OK and Cancel buttons and add these as subviews + okButton = macCreateButton("&OK", ourContentView); + cancelButton = macCreateButton("Cancel", ourContentView); - // create OK and Cancel buttons and add these as subviews - okButton = macCreateButton("&OK", ourContentView); - cancelButton = macCreateButton("Cancel", ourContentView); + [colorPanel setContentView:ourContentView]; + [colorPanel setDefaultButtonCell:[okButton cell]]; + } - [colorPanel setContentView:ourContentView]; - [colorPanel setDefaultButtonCell:[okButton cell]]; + delegate = [[QCocoaColorPanelDelegate alloc] initWithColorPanel:colorPanel + stolenContentView:stolenContentView + okButton:okButton + cancelButton:cancelButton + priv:this]; + [colorPanel setDelegate:static_cast<QCocoaColorPanelDelegate *>(delegate)]; } - // create a delegate and set it - QCocoaColorPanelDelegate *delegate = - [[QCocoaColorPanelDelegate alloc] initWithColorPanel:colorPanel - stolenContentView:stolenContentView - okButton:okButton - cancelButton:cancelButton - priv:priv]; - [colorPanel setDelegate:delegate]; - setColor(delegate, initial); - [colorPanel makeKeyAndOrderFront:colorPanel]; - - return delegate; + setCocoaPanelColor(initial); + [static_cast<QCocoaColorPanelDelegate *>(delegate) showColorPanel]; } -void QColorDialogPrivate::closeCocoaColorPanel(void *delegate) +void QColorDialogPrivate::closeCocoaColorPanel() { - QMacCocoaAutoReleasePool pool; - QCocoaColorPanelDelegate *theDelegate = static_cast<QCocoaColorPanelDelegate *>(delegate); - [[theDelegate colorPanel] close]; - [theDelegate cleanUpAfterMyself]; - [theDelegate autorelease]; + [[static_cast<QCocoaColorPanelDelegate *>(delegate) colorPanel] close]; +} + +void QColorDialogPrivate::releaseCocoaColorPanelDelegate() +{ + [static_cast<QCocoaColorPanelDelegate *>(delegate) release]; } void QColorDialogPrivate::mac_nativeDialogModalHelp() @@ -416,13 +436,10 @@ void QColorDialogPrivate::mac_nativeDialogModalHelp() void QColorDialogPrivate::_q_macRunNativeAppModalPanel() { - QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active); - QMacCocoaAutoReleasePool pool; - QCocoaColorPanelDelegate *delegateCasted = static_cast<QCocoaColorPanelDelegate *>(delegate); - [NSApp runModalForWindow:[delegateCasted colorPanel]]; + [static_cast<QCocoaColorPanelDelegate *>(delegate) exec]; } -void QColorDialogPrivate::setColor(void *delegate, const QColor &color) +void QColorDialogPrivate::setCocoaPanelColor(const QColor &color) { QMacCocoaAutoReleasePool pool; QCocoaColorPanelDelegate *theDelegate = static_cast<QCocoaColorPanelDelegate *>(delegate); diff --git a/src/gui/dialogs/qcolordialog_p.h b/src/gui/dialogs/qcolordialog_p.h index ea66d4a..00d40b6 100644 --- a/src/gui/dialogs/qcolordialog_p.h +++ b/src/gui/dialogs/qcolordialog_p.h @@ -116,14 +116,11 @@ public: QByteArray memberToDisconnectOnClose; #ifdef Q_WS_MAC - static void *openCocoaColorPanel(const QColor &initial, - QWidget *parent, const QString &title, - QColorDialog::ColorDialogOptions options, - QColorDialogPrivate *priv = 0); - static void closeCocoaColorPanel(void *delegate); - static QColor execCocoaColorPanel(const QColor &initial, QWidget *parent, - const QString &title, QColorDialog::ColorDialogOptions options); - static void setColor(void *delegate, const QColor &color); + void openCocoaColorPanel(const QColor &initial, + QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options); + void closeCocoaColorPanel(); + void releaseCocoaColorPanelDelegate(); + void setCocoaPanelColor(const QColor &color); inline void done(int result) { q_func()->done(result); } inline QColorDialog *colorDialog() { return q_func(); } diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index 8b4e1b1..f000033 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -394,6 +394,9 @@ QList<QUrl> QFileDialog::sidebarUrls() const static const qint32 QFileDialogMagic = 0xbe; +const char *qt_file_dialog_filter_reg_exp = +"^(.*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$"; + /*! \since 4.3 Saves the state of the dialog's layout, history and current directory. @@ -984,8 +987,13 @@ void QFileDialog::setNameFilters(const QStringList &filters) if (testOption(HideNameFilterDetails)) { QStringList strippedFilters; + QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp)); for (int i = 0; i < cleanedFilters.count(); ++i) { - strippedFilters.append(cleanedFilters[i].mid(0, cleanedFilters[i].indexOf(QLatin1String(" (")))); + QString filterName; + int index = r.indexIn(cleanedFilters[i]); + if (index >= 0) + filterName = r.cap(1); + strippedFilters.append(filterName.simplified()); } d->qFileDialogUi->fileTypeCombo->addItems(strippedFilters); } else { @@ -2837,9 +2845,6 @@ void QFileDialogPrivate::_q_goToDirectory(const QString &path) } } -const char *qt_file_dialog_filter_reg_exp = - "^([^()]*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$"; - // Makes a list of filters from a normal filter string "Image Files (*.png *.jpg)" QStringList qt_clean_filter_list(const QString &filter) { diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp index 9bf82c3..114456d 100644 --- a/src/gui/dialogs/qfiledialog_win.cpp +++ b/src/gui/dialogs/qfiledialog_win.cpp @@ -59,7 +59,10 @@ #endif #include <shlobj.h> - +//At some point we can hope that mingw will support that interface +#if !defined(Q_WS_WINCE) && !defined(Q_CC_MINGW) +#include <shobjidl.h> +#endif #include <objbase.h> #if defined(__IFileDialog_INTERFACE_DEFINED__) \ @@ -173,15 +176,22 @@ static QStringList qt_win_make_filters_list(const QString &filter) } // Makes a NUL-oriented Windows filter from a Qt filter. -static QString qt_win_filter(const QString &filter) +static QString qt_win_filter(const QString &filter, bool hideFiltersDetails) { QStringList filterLst = qt_win_make_filters_list(filter); QStringList::Iterator it = filterLst.begin(); QString winfilters; + QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp)); for (; it != filterLst.end(); ++it) { QString subfilter = *it; if (!subfilter.isEmpty()) { - winfilters += subfilter; + if (hideFiltersDetails) { + int index = r.indexIn(subfilter); + if (index >= 0) + winfilters += r.cap(1); + } else { + winfilters += subfilter; + } winfilters += QChar(); winfilters += qt_win_extract_filter(subfilter); winfilters += QChar(); @@ -295,9 +305,10 @@ QString qt_win_get_open_file_name(const QFileDialogArgs &args, modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); + bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails; OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, args.directory, args.caption, - qt_win_filter(args.filter), + qt_win_filter(args.filter, hideFiltersDetails), QFileDialog::ExistingFile, args.options); if (idx) @@ -354,7 +365,7 @@ QString qt_win_get_save_file_name(const QFileDialogArgs &args, modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); - + bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails; // This block is used below for the lpstrDefExt member. // Note that the current MSDN docs document this member wrong. // It should rather be documented as "the default extension if no extension was given and if the @@ -374,7 +385,7 @@ QString qt_win_get_save_file_name(const QFileDialogArgs &args, OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection, args.directory, args.caption, - qt_win_filter(args.filter), + qt_win_filter(args.filter, hideFiltersDetails), QFileDialog::AnyFile, args.options); @@ -441,6 +452,8 @@ static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd, QString subfilter = *it; if (!subfilter.isEmpty()) { offsets<<currentOffset; + //Here the COMMON_ITEM_DIALOG API always add the details for the filter (e.g. *.txt) + //so we don't need to handle the flag HideNameFilterDetails. winfilters += subfilter; // The name of the filter. winfilters += QChar(); currentOffset += subfilter.size()+1; @@ -638,9 +651,10 @@ QStringList qt_win_get_open_file_names(const QFileDialogArgs &args, modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); + bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails; OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, args.directory, args.caption, - qt_win_filter(args.filter), + qt_win_filter(args.filter, hideFiltersDetails), QFileDialog::ExistingFiles, args.options); if (idx) diff --git a/src/gui/dialogs/qfileinfogatherer.cpp b/src/gui/dialogs/qfileinfogatherer.cpp index 887eb71..467822c 100644 --- a/src/gui/dialogs/qfileinfogatherer.cpp +++ b/src/gui/dialogs/qfileinfogatherer.cpp @@ -44,8 +44,11 @@ #include <qfsfileengine.h> #include <qdiriterator.h> #ifndef Q_OS_WIN -#include <unistd.h> -#include <sys/types.h> +# include <unistd.h> +# include <sys/types.h> +#endif +#if defined(Q_OS_VXWORKS) +# include "qplatformdefs.h" #endif QT_BEGIN_NAMESPACE diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index 5a5d845..b8e12b4 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -872,6 +872,7 @@ QVariant QFileSystemModel::headerData(int section, Qt::Orientation orientation, pixmap.setAlphaChannel(pixmap.createAlphaMask()); return pixmap; } + break; case Qt::TextAlignmentRole: return Qt::AlignLeft; } diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 89d9d1b..ebdac9a 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -400,4 +400,15 @@ void QEglContext::dumpAllConfigs() delete [] configs; } +QString QEglContext::extensions() +{ + const char* exts = eglQueryString(dpy, EGL_EXTENSIONS); + return QString(QLatin1String(exts)); +} + +bool QEglContext::hasExtension(const char* extensionName) +{ + return extensions().contains(QLatin1String(extensionName)); +} + QT_END_NAMESPACE diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index ddf7d27..3ae1489 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -122,6 +122,9 @@ public: void dumpAllConfigs(); + QString extensions(); + bool hasExtension(const char* extensionName); + private: QEgl::API apiType; EGLDisplay dpy; diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index be89efe..6772592 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -39,15 +39,18 @@ ** ****************************************************************************/ +#include <QtCore/qdebug.h> + +#include <private/qt_x11_p.h> +#include <QtGui/qx11info_x11.h> +#include <private/qpixmapdata_p.h> +#include <private/qpixmap_x11_p.h> + #include <QtGui/qpaintdevice.h> #include <QtGui/qpixmap.h> #include <QtGui/qwidget.h> -#include <QtCore/qdebug.h> #include "qegl_p.h" -#include <QtGui/qx11info_x11.h> -#include <X11/Xlib.h> -#include <X11/Xutil.h> QT_BEGIN_NAMESPACE @@ -125,7 +128,17 @@ void QEglProperties::setVisualFormat(const QX11Info *xinfo) setValue(EGL_RED_SIZE, countBits(visual->red_mask)); setValue(EGL_GREEN_SIZE, countBits(visual->green_mask)); setValue(EGL_BLUE_SIZE, countBits(visual->blue_mask)); - setValue(EGL_ALPHA_SIZE, 0); // XXX + + EGLint alphaBits = 0; +#if !defined(QT_NO_XRENDER) + XRenderPictFormat *format; + format = XRenderFindVisualFormat(xinfo->display(), visual); + if (format && (format->type == PictTypeDirect) && format->direct.alphaMask) { + alphaBits = countBits(format->direct.alphaMask); + qDebug("QEglProperties::setVisualFormat() - visual's alphaMask is %d", alphaBits); + } +#endif + setValue(EGL_ALPHA_SIZE, alphaBits); } extern const QX11Info *qt_x11Info(const QPaintDevice *pd); diff --git a/src/gui/egl/qeglproperties.cpp b/src/gui/egl/qeglproperties.cpp index e0ae8a6..358ebcc 100644 --- a/src/gui/egl/qeglproperties.cpp +++ b/src/gui/egl/qeglproperties.cpp @@ -46,12 +46,26 @@ QT_BEGIN_NAMESPACE #include <QtCore/qdebug.h> #include <QtCore/qstringlist.h> +#include "qegl_p.h" + + // Initialize a property block. QEglProperties::QEglProperties() { props.append(EGL_NONE); } +QEglProperties::QEglProperties(EGLConfig cfg) +{ + props.append(EGL_NONE); + for (int name = 0x3020; name <= 0x304F; ++name) { + EGLint value; + if (name != EGL_NONE && eglGetConfigAttrib(QEglContext::defaultDisplay(0), cfg, name, &value)) + setValue(name, value); + } + eglGetError(); // Clear the error state. +} + // Fetch the current value associated with a property. int QEglProperties::value(int name) const { @@ -215,12 +229,21 @@ bool QEglProperties::reduceConfiguration() removeValue(EGL_SAMPLES); return true; } - if (removeValue(EGL_ALPHA_SIZE)) + if (removeValue(EGL_ALPHA_SIZE)) { +#if defined(EGL_BIND_TO_TEXTURE_RGBA) && defined(EGL_BIND_TO_TEXTURE_RGB) + if (removeValue(EGL_BIND_TO_TEXTURE_RGBA)) + setValue(EGL_BIND_TO_TEXTURE_RGB, TRUE); +#endif return true; + } if (removeValue(EGL_STENCIL_SIZE)) return true; if (removeValue(EGL_DEPTH_SIZE)) return true; +#if defined(EGL_BIND_TO_TEXTURE_RGB) + if (removeValue(EGL_BIND_TO_TEXTURE_RGB)) + return true; +#endif return false; } diff --git a/src/gui/egl/qeglproperties_p.h b/src/gui/egl/qeglproperties_p.h index 81af4cd..bcdc657 100644 --- a/src/gui/egl/qeglproperties_p.h +++ b/src/gui/egl/qeglproperties_p.h @@ -107,6 +107,7 @@ class Q_GUI_EXPORT QEglProperties { public: QEglProperties(); + QEglProperties(EGLConfig); QEglProperties(const QEglProperties& other) : props(other.props) {} ~QEglProperties() {} diff --git a/src/gui/embedded/embedded.pri b/src/gui/embedded/embedded.pri index 4a9aa3f..e8eb959 100644 --- a/src/gui/embedded/embedded.pri +++ b/src/gui/embedded/embedded.pri @@ -114,11 +114,18 @@ embedded { SOURCES += embedded/qscreenlinuxfb_qws.cpp } + contains( gfx-drivers, qnx ) { + HEADERS += embedded/qscreenqnx_qws.h + SOURCES += embedded/qscreenqnx_qws.cpp + LIBS += -lgf + } + contains( gfx-drivers, qvfb ) { HEADERS += embedded/qscreenvfb_qws.h SOURCES += embedded/qscreenvfb_qws.cpp } + contains( gfx-drivers, vnc ) { VNCDIR = $$QT_SOURCE_TREE/src/plugins/gfxdrivers/vnc INCLUDEPATH += $$VNCDIR @@ -141,15 +148,7 @@ embedded { !contains( kbd-drivers, qvfb ) { kbd-drivers += qvfb } - } - - contains( kbd-drivers, sl5000 ) { - HEADERS +=embedded/qkbdsl5000_qws.h - SOURCES +=embedded/qkbdsl5000_qws.cpp - !contains( kbd-drivers, tty ) { - kbd-drivers += tty - } - } + } contains( kbd-drivers, tty ) { HEADERS +=embedded/qkbdtty_qws.h @@ -166,15 +165,10 @@ embedded { SOURCES +=embedded/qkbdum_qws.cpp } - contains( kbd-drivers, yopy ) { - HEADERS +=embedded/qkbdyopy_qws.h - SOURCES +=embedded/qkbdyopy_qws.cpp - } - - contains( kbd-drivers, vr41xx ) { - HEADERS +=embedded/qkbdvr41xx_qws.h - SOURCES +=embedded/qkbdvr41xx_qws.cpp - } + contains( kbd-drivers, qnx ) { + HEADERS += embedded/qkbdqnx_qws.h + SOURCES += embedded/qkbdqnx_qws.cpp + } # # Mouse drivers @@ -189,29 +183,24 @@ embedded { SOURCES +=embedded/qmousepc_qws.cpp } - contains( mouse-drivers, bus ) { - HEADERS +=embedded/qmousebus_qws.h - SOURCES +=embedded/qmousebus_qws.cpp - } - contains( mouse-drivers, linuxtp ) { HEADERS +=embedded/qmouselinuxtp_qws.h SOURCES +=embedded/qmouselinuxtp_qws.cpp } - contains( mouse-drivers, vr41xx ) { - HEADERS +=embedded/qmousevr41xx_qws.h - SOURCES +=embedded/qmousevr41xx_qws.cpp - } - - contains( mouse-drivers, yopy ) { - HEADERS +=embedded/qmouseyopy_qws.h - SOURCES +=embedded/qmouseyopy_qws.cpp - } - contains( mouse-drivers, tslib ) { LIBS += -lts HEADERS +=embedded/qmousetslib_qws.h SOURCES +=embedded/qmousetslib_qws.cpp } + + contains( mouse-drivers, linuxinput ) { + HEADERS +=embedded/qmouselinuxinput_qws.h + SOURCES +=embedded/qmouselinuxinput_qws.cpp + } + + contains( mouse-drivers, qnx ) { + HEADERS += embedded/qmouseqnx_qws.h + SOURCES += embedded/qmouseqnx_qws.cpp + } } diff --git a/src/gui/embedded/qdirectpainter_qws.cpp b/src/gui/embedded/qdirectpainter_qws.cpp index e97367c..b3dff06 100644 --- a/src/gui/embedded/qdirectpainter_qws.cpp +++ b/src/gui/embedded/qdirectpainter_qws.cpp @@ -150,14 +150,14 @@ QT_BEGIN_NAMESPACE \value ReservedSynchronous The allocated region will never change and each function that changes the allocated region will be blocking. - \sa reservedRegion(), allocatedRegion() + \sa allocatedRegion() */ /*! \fn QRegion QDirectPainter::region() \obsolete - Use QDirectPainter::reservedRegion() instead. + Use QDirectPainter::allocatedRegion() instead. */ static inline QScreen *getPrimaryScreen() @@ -346,7 +346,7 @@ void QDirectPainter::setRegion(const QRegion ®ion) returned by the allocatedRegion() function. Otherwise they might differ (see \l {Dynamic Allocation} for details). - \sa geometry(), setRegion() + \sa geometry(), setRegion(), allocatedRegion() */ QRegion QDirectPainter::requestedRegion() const { @@ -540,7 +540,7 @@ void QDirectPainter::lower() any. If not released explicitly, the region will be released on application exit. - \sa reservedRegion(), {Static Allocation} + \sa allocatedRegion(), {Static Allocation} \obsolete diff --git a/src/gui/embedded/qkbd_qws.cpp b/src/gui/embedded/qkbd_qws.cpp index 7799339..756a398 100644 --- a/src/gui/embedded/qkbd_qws.cpp +++ b/src/gui/embedded/qkbd_qws.cpp @@ -453,8 +453,9 @@ void QWSKeyboardHandler::endAutoRepeat() Maps \a keycode according to a keymap and sends that key event to the \l{Qt for Embedded Linux} server application. - Please see the QWS_KEYBOARD documentation for a description on how to - create and use keymap files. + Please see the \l{Qt for Embedded Linux Character Input} and the \l + {kmap2qmap} documentations for a description on how to create and use + keymap files. The key event is identified by its \a keycode value and the \a isPress and \a autoRepeat parameters. @@ -475,9 +476,6 @@ void QWSKeyboardHandler::endAutoRepeat() implementation needs to take care of a special action, like console switching or LED handling. - Standard Linux console keymaps can be found at the - \l {http://lct.sourceforege.net}{LCT project} - If standard Linux console keymaps are used, \a keycode must be one of the standardized values defined in \c /usr/include/linux/input.h diff --git a/src/gui/embedded/qkbddriverfactory_qws.cpp b/src/gui/embedded/qkbddriverfactory_qws.cpp index c599396..fb10030 100644 --- a/src/gui/embedded/qkbddriverfactory_qws.cpp +++ b/src/gui/embedded/qkbddriverfactory_qws.cpp @@ -47,10 +47,8 @@ #include "qkbdtty_qws.h" #include "qkbdlinuxinput_qws.h" #include "qkbdum_qws.h" -#include "qkbdsl5000_qws.h" #include "qkbdvfb_qws.h" -#include "qkbdyopy_qws.h" -#include "qkbdvr41xx_qws.h" +#include "qkbdqnx_qws.h" #include <stdlib.h> #include "private/qfactoryloader_p.h" #include "qkbddriverplugin_qws.h" @@ -104,17 +102,9 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, QWSKeyboardHandler *QKbdDriverFactory::create(const QString& key, const QString& device) { QString driver = key.toLower(); -#ifndef QT_NO_QWS_KBD_SL5000 - if (driver == QLatin1String("sl5000") || driver.isEmpty()) - return new QWSSL5000KeyboardHandler(device); -#endif -#ifndef QT_NO_QWS_KBD_YOPY - if (driver == QLatin1String("yopy") || driver.isEmpty()) - return new QWSYopyKeyboardHandler(device); -#endif -#ifndef QT_NO_QWS_KBD_VR41XX - if (driver == QLatin1String("vr41xx") || driver.isEmpty()) - return new QWSVr41xxKeyboardHandler(device); +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_KBD_QNX) + if (driver == QLatin1String("qnx") || driver.isEmpty()) + return new QWSQnxKeyboardHandler(device); #endif #ifndef QT_NO_QWS_KEYBOARD # ifndef QT_NO_QWS_KBD_TTY @@ -158,14 +148,8 @@ QStringList QKbdDriverFactory::keys() { QStringList list; -#ifndef QT_NO_QWS_KBD_SL5000 - list << QLatin1String("SL5000"); -#endif -#ifndef QT_NO_QWS_KBD_YOPY - list << QLatin1String("YOPY"); -#endif -#ifndef QT_NO_QWS_KBD_VR41XX - list << QLatin1String("VR41xx"); +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_KBD_QNX) + list << QLatin1String("QNX"); #endif #ifndef QT_NO_QWS_KBD_TTY list << QLatin1String("TTY"); diff --git a/src/gui/embedded/qkbdlinuxinput_qws.cpp b/src/gui/embedded/qkbdlinuxinput_qws.cpp index e552731..6aa6633 100644 --- a/src/gui/embedded/qkbdlinuxinput_qws.cpp +++ b/src/gui/embedded/qkbdlinuxinput_qws.cpp @@ -76,6 +76,7 @@ private: int m_fd; int m_tty_fd; struct termios m_tty_attr; + int m_orig_kbmode; }; QWSLinuxInputKeyboardHandler::QWSLinuxInputKeyboardHandler(const QString &device) @@ -95,8 +96,7 @@ bool QWSLinuxInputKeyboardHandler::filterInputEvent(quint16 &, qint32 &) } QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(QWSLinuxInputKeyboardHandler *h, const QString &device) - : m_handler(h), m_fd(-1), m_tty_fd(-1) - + : m_handler(h), m_fd(-1), m_tty_fd(-1), m_orig_kbmode(K_XLATE) { setObjectName(QLatin1String("LinuxInputSubsystem Keyboard Handler")); @@ -135,7 +135,10 @@ QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(QWSLinuxInputKeyboardHandler *h, struct ::termios termdata; tcgetattr(m_tty_fd, &termdata); - // setting this tranlation mode is also needed in INPUT mode to prevent + // record the original mode so we can restore it again in the destructor. + ::ioctl(m_tty_fd, KDGKBMODE, &m_orig_kbmode); + + // setting this tranlation mode is even needed in INPUT mode to prevent // the shell from also interpreting codes, if the process has a tty // attached: e.g. Ctrl+C wouldn't copy, but kill the application. ::ioctl(m_tty_fd, KDSKBMODE, K_MEDIUMRAW); @@ -152,7 +155,7 @@ QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(QWSLinuxInputKeyboardHandler *h, tcsetattr(m_tty_fd, TCSANOW, &termdata); } } else { - qWarning("Cannot open input device '%s': %s", qPrintable(dev), strerror(errno)); + qWarning("Cannot open keyboard input device '%s': %s", qPrintable(dev), strerror(errno)); return; } } @@ -160,7 +163,7 @@ QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(QWSLinuxInputKeyboardHandler *h, QWSLinuxInputKbPrivate::~QWSLinuxInputKbPrivate() { if (m_tty_fd >= 0) { - ::ioctl(m_tty_fd, KDSKBMODE, K_XLATE); + ::ioctl(m_tty_fd, KDSKBMODE, m_orig_kbmode); tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr); } if (m_fd >= 0) diff --git a/src/gui/embedded/qkbdqnx_qws.cpp b/src/gui/embedded/qkbdqnx_qws.cpp new file mode 100644 index 0000000..089b868 --- /dev/null +++ b/src/gui/embedded/qkbdqnx_qws.cpp @@ -0,0 +1,231 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qkbdqnx_qws.h" +#include "QtCore/qsocketnotifier.h" +#include "QtCore/qdebug.h" + +#include <sys/dcmd_input.h> +#include <photon/keycodes.h> + +#include "qplatformdefs.h" +#include <errno.h> + +/*! + \class QWSQnxKeyboardHandler + \preliminary + \ingroup qws + \since 4.6 + \internal + + \brief The QWSQnxKeyboardHandler class implements a keyboard driver + for the QNX \c{devi-hid} input manager. + + To be able to compile this mouse handler, \l{Qt for Embedded Linux} + must be configured with the \c -qt-kbd-qnx option, see the + \l{Qt for Embedded Linux Character Input} documentation for details. + + In order to use this keyboard handler, the \c{devi-hid} input manager + must be set up and run with the resource manager interface (option \c{-r}). + Also, Photon must not be running. + + Example invocation from command line: \c{/usr/photon/bin/devi-hid -Pr kbd mouse} + Note that after running \c{devi-hid}, you will not be able to use the local + shell anymore. It is suggested to run the command in a shell scrip, that launches + a Qt application after invocation of \c{devi-hid}. + + To make \l{Qt for Embedded Linux} explicitly choose the qnx keyboard + handler, set the QWS_KEYBOARD environment variable to \c{qnx}. By default, + the first keyboard device (\c{/dev/devi/keyboard0}) is used. To override, pass a device + name as the first and only parameter, for example + \c{QWS_KEYBOARD=qnx:/dev/devi/keyboard1; export QWS_KEYBOARD}. + + \sa {Qt for Embedded Linux Character Input}, {Qt for Embedded Linux} +*/ + +/*! + Constructs a keyboard handler for the specified \a device, defaulting to + \c{/dev/devi/keyboard0}. + + Note that you should never instanciate this class, instead let QKbdDriverFactory + handle the keyboard handlers. + + \sa QKbdDriverFactory + */ +QWSQnxKeyboardHandler::QWSQnxKeyboardHandler(const QString &device) +{ + // open the keyboard device + keyboardFD = QT_OPEN(device.isEmpty() ? "/dev/devi/keyboard0" : device.toLatin1().constData(), + QT_OPEN_RDONLY); + if (keyboardFD == -1) { + qErrnoWarning(errno, "QWSQnxKeyboardHandler: Unable to open device"); + return; + } + + // create a socket notifier so we'll wake up whenever keyboard input is detected. + QSocketNotifier *notifier = new QSocketNotifier(keyboardFD, QSocketNotifier::Read, this); + connect(notifier, SIGNAL(activated(int)), SLOT(socketActivated())); + + qDebug() << "QWSQnxKeyboardHandler: connected."; + +} + +/*! + Destroys this keyboard handler and closes the connection to the keyboard device. + */ +QWSQnxKeyboardHandler::~QWSQnxKeyboardHandler() +{ + QT_CLOSE(keyboardFD); +} + +/*! \internal + Translates the QNX keyboard events to Qt keyboard events + */ +void QWSQnxKeyboardHandler::socketActivated() +{ + _keyboard_packet packet; + + // read one keyboard event + int bytesRead = QT_READ(keyboardFD, &packet, sizeof(_keyboard_packet)); + if (bytesRead == -1) { + qErrnoWarning(errno, "QWSQnxKeyboardHandler::socketActivated(): Unable to read data."); + return; + } + + // the bytes read must be the size of a keyboard packet + Q_ASSERT(bytesRead == sizeof(_keyboard_packet)); + +#if 0 + qDebug() << "keyboard got scancode" + << hex << packet.data.modifiers + << packet.data.flags + << packet.data.key_cap + << packet.data.key_sym + << packet.data.key_scan; +#endif + + // QNX is nice enough to translate the raw keyboard data into a QNX data structure + // Now we just have to translate it into a format Qt understands. + + // figure out whether it's a press + bool isPress = packet.data.key_cap & KEY_DOWN; + // figure out wheter the key is still pressed and the key event is repeated + bool isRepeat = packet.data.key_cap & KEY_REPEAT; + + Qt::Key key = Qt::Key_unknown; + int unicode = 0xffff; + + // TODO - this switch is not complete! + switch (packet.data.key_scan) { + case KEYCODE_SPACE: key = Qt::Key_Space; unicode = 0x20; break; + case KEYCODE_F1: key = Qt::Key_F1; break; + case KEYCODE_F2: key = Qt::Key_F2; break; + case KEYCODE_F3: key = Qt::Key_F3; break; + case KEYCODE_F4: key = Qt::Key_F4; break; + case KEYCODE_F5: key = Qt::Key_F5; break; + case KEYCODE_F6: key = Qt::Key_F6; break; + case KEYCODE_F7: key = Qt::Key_F7; break; + case KEYCODE_F8: key = Qt::Key_F8; break; + case KEYCODE_F9: key = Qt::Key_F9; break; + case KEYCODE_F10: key = Qt::Key_F10; break; + case KEYCODE_F11: key = Qt::Key_F11; break; + case KEYCODE_F12: key = Qt::Key_F12; break; + case KEYCODE_BACKSPACE: key = Qt::Key_Backspace; break; + case KEYCODE_TAB: key = Qt::Key_Tab; break; + case KEYCODE_RETURN: key = Qt::Key_Return; break; + case KEYCODE_KP_ENTER: key = Qt::Key_Enter; break; + case KEYCODE_UP: + case KEYCODE_KP_UP: + key = Qt::Key_Up; break; + case KEYCODE_DOWN: + case KEYCODE_KP_DOWN: + key = Qt::Key_Down; break; + case KEYCODE_LEFT: + case KEYCODE_KP_LEFT: + key = Qt::Key_Left; break; + case KEYCODE_RIGHT: + case KEYCODE_KP_RIGHT: + key = Qt::Key_Right; break; + case KEYCODE_HOME: + case KEYCODE_KP_HOME: + key = Qt::Key_Home; break; + case KEYCODE_END: + case KEYCODE_KP_END: + key = Qt::Key_End; break; + case KEYCODE_PG_UP: + case KEYCODE_KP_PG_UP: + key = Qt::Key_PageUp; break; + case KEYCODE_PG_DOWN: + case KEYCODE_KP_PG_DOWN: + key = Qt::Key_PageDown; break; + case KEYCODE_INSERT: + case KEYCODE_KP_INSERT: + key = Qt::Key_Insert; break; + case KEYCODE_DELETE: + case KEYCODE_KP_DELETE: + key = Qt::Key_Delete; break; + case KEYCODE_ESCAPE: + key = Qt::Key_Escape; break; + default: // none of the above, try the key_scan directly + unicode = packet.data.key_scan; + break; + } + + // figure out the modifiers that are currently pressed + Qt::KeyboardModifiers modifiers = Qt::NoModifier; + if (packet.data.flags & KEYMOD_SHIFT) + modifiers |= Qt::ShiftModifier; + if (packet.data.flags & KEYMOD_CTRL) + modifiers |= Qt::ControlModifier; + if (packet.data.flags & KEYMOD_ALT) + modifiers |= Qt::AltModifier; + + // if the unicode value is not ascii, we ignore it. + // TODO - do a complete mapping between all QNX scan codes and Qt codes + if (unicode != 0xffff && !isascii(unicode)) + return; // unprintable character + + // call processKeyEvent. This is where all the magic happens to insert a + // key event into Qt's event loop. + // Note that for repeated key events, isPress must be true + // (on QNX, isPress is not set when the key event is repeated). + processKeyEvent(unicode, key, modifiers, isPress || isRepeat, isRepeat); +} diff --git a/src/gui/embedded/qkbdyopy_qws.h b/src/gui/embedded/qkbdqnx_qws.h index b4e45bd..fa3ae56 100644 --- a/src/gui/embedded/qkbdyopy_qws.h +++ b/src/gui/embedded/qkbdqnx_qws.h @@ -39,9 +39,10 @@ ** ****************************************************************************/ -#ifndef QKBDYOPY_QWS_H -#define QKBDYOPY_QWS_H +#ifndef QKBDQNX_QWS_H +#define QKBDQNX_QWS_H +#include <QtGui/qapplication.h> #include <QtGui/qkbd_qws.h> QT_BEGIN_HEADER @@ -50,24 +51,26 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -#ifndef QT_NO_QWS_KBD_YOPY +#if !defined(QT_NO_QWS_KEYBOARD) && !defined(QT_NO_QWS_KBD_QNX) -class QWSYopyKbPrivate; - -class QWSYopyKeyboardHandler : public QWSKeyboardHandler +class Q_GUI_EXPORT QWSQnxKeyboardHandler : public QObject, public QWSKeyboardHandler { + Q_OBJECT public: - explicit QWSYopyKeyboardHandler(const QString&); - virtual ~QWSYopyKeyboardHandler(); + QWSQnxKeyboardHandler(const QString &device); + ~QWSQnxKeyboardHandler(); + +private Q_SLOTS: + void socketActivated(); private: - QWSYopyKbPrivate *d; + int keyboardFD; }; -#endif // QT_NO_QWS_KBD_YOPY +#endif // QT_NO_QWS_KEYBOARD QT_END_NAMESPACE QT_END_HEADER -#endif // QKBDYOPY_QWS_H +#endif // QKBDQNX_QWS_H diff --git a/src/gui/embedded/qkbdsl5000_qws.cpp b/src/gui/embedded/qkbdsl5000_qws.cpp deleted file mode 100644 index cf82c10..0000000 --- a/src/gui/embedded/qkbdsl5000_qws.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qkbdsl5000_qws.h" - -#ifndef QT_NO_QWS_KBD_SL5000 - -#include "qwindowsystem_qws.h" -#include "qwsutils_qws.h" -#include "qscreen_qws.h" - -#include "qapplication.h" -#include "qnamespace.h" -#include "qtimer.h" - -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -#include <unistd.h> -#include <sys/ioctl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <errno.h> -#include <signal.h> - -#include <asm/sharp_char.h> - -#include <string.h> - -QT_BEGIN_NAMESPACE - -static const QWSKeyMap sl5000KeyMap[] = { - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 00 - { Qt::Key_A, 'a' , 'A' , 'A'-64 }, // 01 - { Qt::Key_B, 'b' , 'B' , 'B'-64 }, // 02 - { Qt::Key_C, 'c' , 'C' , 'C'-64 }, // 03 - { Qt::Key_D, 'd' , 'D' , 'D'-64 }, // 04 - { Qt::Key_E, 'e' , 'E' , 'E'-64 }, // 05 - { Qt::Key_F, 'f' , 'F' , 'F'-64 }, // 06 - { Qt::Key_G, 'g' , 'G' , 'G'-64 }, // 07 - { Qt::Key_H, 'h' , 'H' , 'H'-64 }, // 08 - { Qt::Key_I, 'i' , 'I' , 'I'-64 }, // 09 - { Qt::Key_J, 'j' , 'J' , 'J'-64 }, // 0a 10 - { Qt::Key_K, 'k' , 'K' , 'K'-64 }, // 0b - { Qt::Key_L, 'l' , 'L' , 'L'-64 }, // 0c - { Qt::Key_M, 'm' , 'M' , 'M'-64 }, // 0d - { Qt::Key_N, 'n' , 'N' , 'N'-64 }, // 0e - { Qt::Key_O, 'o' , 'O' , 'O'-64 }, // 0f - { Qt::Key_P, 'p' , 'P' , 'P'-64 }, // 10 - { Qt::Key_Q, 'q' , 'Q' , 'Q'-64 }, // 11 - { Qt::Key_R, 'r' , 'R' , 'R'-64 }, // 12 - { Qt::Key_S, 's' , 'S' , 'S'-64 }, // 13 - { Qt::Key_T, 't' , 'T' , 'T'-64 }, // 14 20 - { Qt::Key_U, 'u' , 'U' , 'U'-64 }, // 15 - { Qt::Key_V, 'v' , 'V' , 'V'-64 }, // 16 - { Qt::Key_W, 'w' , 'W' , 'W'-64 }, // 17 - { Qt::Key_X, 'x' , 'X' , 'X'-64 }, // 18 - { Qt::Key_Y, 'y' , 'Y' , 'Y'-64 }, // 19 - { Qt::Key_Z, 'z' , 'Z' , 'Z'-64 }, // 1a - { Qt::Key_Shift, 0xffff , 0xffff , 0xffff }, // 1b - { Qt::Key_Return, 13 , 13 , 0xffff }, // 1c - { Qt::Key_F11, 0xffff , 0xffff , 0xffff }, // 1d todo - { Qt::Key_F22, 0xffff , 0xffff , 0xffff }, // 1e 30 - { Qt::Key_Backspace, 8 , 8 , 0xffff }, // 1f - { Qt::Key_F31, 0xffff , 0xffff , 0xffff }, // 20 - { Qt::Key_F35, 0xffff , 0xffff , 0xffff }, // 21 light - { Qt::Key_Escape, 0xffff , 0xffff , 0xffff }, // 22 - - // Direction key code are for *UNROTATED* display. - { Qt::Key_Up, 0xffff , 0xffff , 0xffff }, // 23 - { Qt::Key_Right, 0xffff , 0xffff , 0xffff }, // 24 - { Qt::Key_Left, 0xffff , 0xffff , 0xffff }, // 25 - { Qt::Key_Down, 0xffff , 0xffff , 0xffff }, // 26 - - { Qt::Key_F33, 0xffff , 0xffff , 0xffff }, // 27 OK - { Qt::Key_F12, 0xffff , 0xffff , 0xffff }, // 28 40 home - { Qt::Key_1, '1' , 'q' , 'Q'-64 }, // 29 - { Qt::Key_2, '2' , 'w' , 'W'-64 }, // 2a - { Qt::Key_3, '3' , 'e' , 'E'-64 }, // 2b - { Qt::Key_4, '4' , 'r' , 'R'-64 }, // 2c - { Qt::Key_5, '5' , 't' , 'T'-64 }, // 2d - { Qt::Key_6, '6' , 'y' , 'Y'-64 }, // 2e - { Qt::Key_7, '7' , 'u' , 'U'-64 }, // 2f - { Qt::Key_8, '8' , 'i' , 'I'-64 }, // 30 - { Qt::Key_9, '9' , 'o' , 'O'-64 }, // 31 - { Qt::Key_0, '0' , 'p' , 'P'-64 }, // 32 50 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 33 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 34 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 35 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 36 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 37 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 38 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 39 - { Qt::Key_Minus, '-' , 'b' , 'B'-64 }, // 3a - { Qt::Key_Plus, '+' , 'n' , 'N'-64 }, // 3b - { Qt::Key_CapsLock, 0xffff , 0xffff , 0xffff }, // 3c 60 - { Qt::Key_At, '@' , 's' , 'S'-64 }, // 3d - { Qt::Key_Question, '?' , '?' , 0xffff }, // 3e - { Qt::Key_Comma, ',' , ',' , 0xffff }, // 3f - { Qt::Key_Period, '.' , '.' , 0xffff }, // 40 - { Qt::Key_Tab, 9 , '\\' , 0xffff }, // 41 - { Qt::Key_X, 0xffff , 'x' , 'X'-64 }, // 42 - { Qt::Key_C, 0xffff , 'c' , 'C'-64 }, // 43 - { Qt::Key_V, 0xffff , 'v' , 'V'-64 }, // 44 - { Qt::Key_Slash, '/' , '/' , 0xffff }, // 45 - { Qt::Key_Apostrophe, '\'' , '\'' , 0xffff }, // 46 70 - { Qt::Key_Semicolon, ';' , ';' , 0xffff }, // 47 - { Qt::Key_QuoteDbl, '\"' , '\"' , 0xffff }, // 48 - { Qt::Key_Colon, ':' , ':' , 0xffff }, // 49 - { Qt::Key_NumberSign, '#' , 'd' , 'D'-64 }, // 4a - { Qt::Key_Dollar, '$' , 'f' , 'F'-64 }, // 4b - { Qt::Key_Percent, '%' , 'g' , 'G'-64 }, // 4c - { Qt::Key_Underscore, '_' , 'h' , 'H'-64 }, // 4d - { Qt::Key_Ampersand, '&' , 'j' , 'J'-64 }, // 4e - { Qt::Key_Asterisk, '*' , 'k' , 'K'-64 }, // 4f - { Qt::Key_ParenLeft, '(' , 'l' , 'L'-64 }, // 50 80 - { Qt::Key_Delete, '[' , '[' , '[' }, // 51 - { Qt::Key_Z, 0xffff , 'z' , 'Z'-64 }, // 52 - { Qt::Key_Equal, '=' , 'm' , 'M'-64 }, // 53 - { Qt::Key_ParenRight, ')' , ']' , ']' }, // 54 - { Qt::Key_AsciiTilde, '~' , '^' , '^' }, // 55 - { Qt::Key_Less, '<' , '{' , '{' }, // 56 - { Qt::Key_Greater, '>' , '}' , '}' }, // 57 - { Qt::Key_F9, 0xffff , 0xffff , 0xffff }, // 58 datebook - { Qt::Key_F10, 0xffff , 0xffff , 0xffff }, // 59 address - { Qt::Key_F13, 0xffff , 0xffff , 0xffff }, // 5a 90 email - { Qt::Key_F30, ' ' , ' ' , 0xffff }, // 5b select - { Qt::Key_Space, ' ' , '|' , '`' }, // 5c - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 5d - { Qt::Key_Exclam, '!' , 'a' , 'A'-64 }, // 5e - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 5f - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 60 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 61 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 62 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 63 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 64 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 65 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 66 - { Qt::Key_Meta, 0xffff , 0xffff , 0xffff }, // 67 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 68 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 69 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 6a - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 6b - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 6c - { Qt::Key_F34, 0xffff , 0xffff , 0xffff }, // 6d power - { Qt::Key_F13, 0xffff , 0xffff , 0xffff }, // 6e mail long - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 6f - { Qt::Key_NumLock, 0xffff , 0xffff , 0xffff }, // 70 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 71 - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 72 - { 0x20ac, 0xffff , 0x20ac , 0x20ac }, // 73 Euro sign - { Qt::Key_unknown, 0xffff , 0xffff , 0xffff }, // 74 - { Qt::Key_F32, 0xffff , 0xffff , 0xffff }, // 75 Sync - { 0, 0xffff , 0xffff , 0xffff } -}; - -static const int keyMSize = sizeof(sl5000KeyMap)/sizeof(QWSKeyMap)-1; - -QWSSL5000KeyboardHandler::QWSSL5000KeyboardHandler(const QString &device) - : QWSTtyKeyboardHandler(device) -{ - shift = false; - alt = false; - ctrl = false; - extended = 0; - prevuni = 0; - prevkey = 0; - caps = false; - meta = false; - fn = false; - numLock = false; - - sharp_kbdctl_modifstat st; - int dev = QT_OPEN(device.isEmpty()?"/dev/sharp_kbdctl":device.toLocal8Bit().constData(), O_RDWR); - if (dev >= 0) { - memset(&st, 0, sizeof(st)); - st.which = 3; - int ret = ioctl(dev, SHARP_KBDCTL_GETMODIFSTAT, (char*)&st); - if(!ret) - numLock = (bool)st.stat; - QT_CLOSE(dev); - } -} - -QWSSL5000KeyboardHandler::~QWSSL5000KeyboardHandler() -{ -} - -const QWSKeyMap *QWSSL5000KeyboardHandler::keyMap() const -{ - return sl5000KeyMap; -} - -bool QWSSL5000KeyboardHandler::filterKeycode(char &code) -{ - int keyCode = Qt::Key_unknown; - bool release = false; - - if (code & 0x80) { - release = true; - code &= 0x7f; - } - - if (fn && !meta && (code >= 0x42 && code <= 0x52)) { - ushort unicode=0; - int scan=0; - if (code == 0x42) { unicode='X'-'@'; scan=Qt::Key_X; } // Cut - else if (code == 0x43) { unicode='C'-'@'; scan=Qt::Key_C; } // Copy - else if (code == 0x44) { unicode='V'-'@'; scan=Qt::Key_V; } // Paste - else if (code == 0x52) { unicode='Z'-'@'; scan=Qt::Key_Z; } // Undo - if (scan) { - processKeyEvent(unicode, scan, Qt::ControlModifier, !release, false); - return true; - } - } - - if (code < keyMSize) { - keyCode = keyMap()[int(code)].key_code; - } - - bool repeatable = true; - - if (release && (keyCode == Qt::Key_F34 || keyCode == Qt::Key_F35)) - return true; // no release for power and light keys - if ((keyCode >= Qt::Key_F1 && keyCode <= Qt::Key_F35) - || keyCode == Qt::Key_Escape || keyCode == Qt::Key_Home - || keyCode == Qt::Key_Shift || keyCode == Qt::Key_Meta) - repeatable = false; - - if (qt_screen->isTransformed() - && keyCode >= Qt::Key_Left && keyCode <= Qt::Key_Down) - { - keyCode = transformDirKey(keyCode); - } - - // Ctrl-Alt-Delete exits qws - if (ctrl && alt && keyCode == Qt::Key_Delete) { - qApp->quit(); - } - - if (keyCode == Qt::Key_F22) { /* Fn key */ - fn = !release; - } else if (keyCode == Qt::Key_NumLock) { - if (release) - numLock = !numLock; - } else if (keyCode == Qt::AltModifier) { - alt = !release; - } else if (keyCode == Qt::ControlModifier) { - ctrl = !release; - } else if (keyCode == Qt::ShiftModifier) { - shift = !release; - } else if (keyCode == Qt::MetaModifier) { - meta = !release; - } else if (keyCode == Qt::Key_CapsLock && release) { - caps = !caps; - } - if (keyCode != Qt::Key_unknown) { - bool bAlt = alt; - bool bCtrl = ctrl; - bool bShift = shift; - int unicode = 0; - if (code < keyMSize) { - bool bCaps = caps ^ shift; - if (fn) { - if (shift) { - bCaps = bShift = false; - bCtrl = true; - } - if (meta) { - bCaps = bShift = true; - bAlt = true; - } - } else if (meta) { - bCaps = bShift = true; - } - if (code > 40 && caps) { - // fn-keys should only react to shift, not caps - bCaps = bShift = shift; - } - if (numLock) { - if (keyCode != Qt::Key_Space && keyCode != Qt::Key_Tab) - bCaps = bShift = false; - } - if (keyCode == Qt::Key_Delete && (bAlt || bCtrl)) { - keyCode = Qt::Key_BraceLeft; - unicode = '['; - bCaps = bShift = bAlt = bCtrl = false; - } else if (keyCode == Qt::Key_F31 && bCtrl) { - keyCode = Qt::Key_QuoteLeft; - unicode = '`'; - } else if (bCtrl) - unicode = keyMap()[int(code)].ctrl_unicode ? keyMap()[int(code)].ctrl_unicode : 0xffff; - else if (bCaps) - unicode = keyMap()[int(code)].shift_unicode ? keyMap()[int(code)].shift_unicode : 0xffff; - else - unicode = keyMap()[int(code)].unicode ? keyMap()[int(code)].unicode : 0xffff; - } - - modifiers = 0; - if (bAlt) modifiers |= Qt::AltModifier; - if (bCtrl) modifiers |= Qt::ControlModifier; - if (bShift) modifiers |= Qt::ShiftModifier; - - // looks wrong -- WWA - bool repeat = false; - if (prevuni == unicode && prevkey == keyCode && !release) - repeat = true; - - processKeyEvent(unicode, keyCode, modifiers, !release, repeat); - - if (!release) { - prevuni = unicode; - prevkey = keyCode; - } else { - prevkey = prevuni = 0; - } - } - - if (repeatable && !release) - beginAutoRepeat(prevuni, prevkey, modifiers); - else - endAutoRepeat(); - - return true; -} - -QT_END_NAMESPACE - -#endif // QT_NO_QWS_KBD_SL5000 diff --git a/src/gui/embedded/qkbdtty_qws.cpp b/src/gui/embedded/qkbdtty_qws.cpp index 8c1e79b..f107567 100644 --- a/src/gui/embedded/qkbdtty_qws.cpp +++ b/src/gui/embedded/qkbdtty_qws.cpp @@ -90,7 +90,7 @@ private: struct termios m_tty_attr; char m_last_keycode; int m_vt_qws; - int m_originalKbdMode; + int m_orig_kbmode; }; @@ -111,7 +111,7 @@ bool QWSTtyKeyboardHandler::filterKeycode(char &) } QWSTtyKbPrivate::QWSTtyKbPrivate(QWSTtyKeyboardHandler *h, const QString &device) - : m_handler(h), m_tty_fd(-1), m_last_keycode(0), m_vt_qws(0) + : m_handler(h), m_tty_fd(-1), m_last_keycode(0), m_vt_qws(0), m_orig_kbmode(K_XLATE) { setObjectName(QLatin1String("TTY Keyboard Handler")); #ifndef QT_NO_QWS_SIGNALHANDLER @@ -152,15 +152,15 @@ QWSTtyKbPrivate::QWSTtyKbPrivate(QWSTtyKeyboardHandler *h, const QString &device tcgetattr(m_tty_fd, &termdata); #if defined(Q_OS_LINUX) - // record the original mode so we can restore it again in the constructor - ::ioctl(m_tty_fd, KDGKBMODE, m_originalKbdMode); + // record the original mode so we can restore it again in the destructor. + ::ioctl(m_tty_fd, KDGKBMODE, &m_orig_kbmode); // PLEASE NOTE: - // The tty keycode interface can only report keycodes 0x01 .. 0x7f + // the tty keycode interface can only report keycodes 0x01 .. 0x7f // KEY_MAX is however defined to 0x1ff. In practice this is sufficient // for a PC style keyboard though. - // we don't support K_RAW anymore - if you need, you habe to add a - // scan- to keycode converter. + // we don't support K_RAW anymore - if you need that, you have to add + // a scan- to keycode converter yourself. ::ioctl(m_tty_fd, KDSKBMODE, K_MEDIUMRAW); #endif @@ -211,12 +211,10 @@ QWSTtyKbPrivate::~QWSTtyKbPrivate() { if (m_tty_fd >= 0) { #if defined(Q_OS_LINUX) - ::ioctl(m_tty_fd, KDSKBMODE, m_originalKbdMode); + ::ioctl(m_tty_fd, KDSKBMODE, m_orig_kbmode); #endif tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr); - - // we're leaking m_tty_fd here? - //QT_CLOSE(m_tty_fd); + QT_CLOSE(m_tty_fd); } } diff --git a/src/gui/embedded/qkbdvr41xx_qws.cpp b/src/gui/embedded/qkbdvr41xx_qws.cpp deleted file mode 100644 index 6d8299b..0000000 --- a/src/gui/embedded/qkbdvr41xx_qws.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qkbdvr41xx_qws.h" - -#if !defined(QT_NO_QWS_KEYBOARD) && !defined(QT_NO_QWS_KBD_VR41XX) - -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/ioctl.h> -#include <fcntl.h> -#include <termios.h> -#include <unistd.h> -#include <errno.h> - -#include <qsocketnotifier.h> -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -QT_BEGIN_NAMESPACE - -class QWSVr41xxKbPrivate : public QObject -{ - Q_OBJECT -public: - QWSVr41xxKbPrivate(QWSVr41xxKeyboardHandler *h, const QString&); - virtual ~QWSVr41xxKbPrivate(); - - bool isOpen() { return buttonFD > 0; } - -private slots: - void readKeyboardData(); - -private: - QString terminalName; - int buttonFD; - int kbdIdx; - int kbdBufferLen; - unsigned char *kbdBuffer; - QSocketNotifier *notifier; - QWSVr41xxKeyboardHandler *handler; -}; - -QWSVr41xxKeyboardHandler::QWSVr41xxKeyboardHandler(const QString &device) -{ - d = new QWSVr41xxKbPrivate(this, device); -} - -QWSVr41xxKeyboardHandler::~QWSVr41xxKeyboardHandler() -{ - delete d; -} - -QWSVr41xxKbPrivate::QWSVr41xxKbPrivate(QWSVr41xxKeyboardHandler *h, const QString &device) : handler(h) -{ - terminalName = device; - if (terminalName.isEmpty()) - terminalName = QLatin1String("/dev/buttons"); - buttonFD = -1; - notifier = 0; - - buttonFD = QT_OPEN(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0);; - if (buttonFD < 0) { - qWarning("Cannot open %s\n", qPrintable(terminalName)); - return; - } - - if (buttonFD >= 0) { - notifier = new QSocketNotifier(buttonFD, QSocketNotifier::Read, this); - connect(notifier, SIGNAL(activated(int)),this, - SLOT(readKeyboardData())); - } - - kbdBufferLen = 80; - kbdBuffer = new unsigned char [kbdBufferLen]; - kbdIdx = 0; -} - -QWSVr41xxKbPrivate::~QWSVr41xxKbPrivate() -{ - if (buttonFD > 0) { - QT_CLOSE(buttonFD); - buttonFD = -1; - } - delete notifier; - notifier = 0; - delete [] kbdBuffer; -} - -void QWSVr41xxKbPrivate::readKeyboardData() -{ - int n = 0; - do { - n = QT_READ(buttonFD, kbdBuffer+kbdIdx, kbdBufferLen - kbdIdx); - if (n > 0) - kbdIdx += n; - } while (n > 0); - - int idx = 0; - while (kbdIdx - idx >= 2) { - unsigned char *next = kbdBuffer + idx; - unsigned short *code = (unsigned short *)next; - int keycode = Qt::Key_unknown; - switch ((*code) & 0x0fff) { - case 0x7: - keycode = Qt::Key_Up; - break; - case 0x9: - keycode = Qt::Key_Right; - break; - case 0x8: - keycode = Qt::Key_Down; - break; - case 0xa: - keycode = Qt::Key_Left; - break; - case 0x3: - keycode = Qt::Key_Up; - break; - case 0x4: - keycode = Qt::Key_Down; - break; - case 0x1: - keycode = Qt::Key_Return; - break; - case 0x2: - keycode = Qt::Key_F4; - break; - default: - qDebug("Unrecognised key sequence %d", *code); - } - if ((*code) & 0x8000) - handler->processKeyEvent(0, keycode, 0, false, false); - else - handler->processKeyEvent(0, keycode, 0, true, false); - idx += 2; - } - - int surplus = kbdIdx - idx; - for (int i = 0; i < surplus; i++) - kbdBuffer[i] = kbdBuffer[idx+i]; - kbdIdx = surplus; -} - -QT_END_NAMESPACE - -#include "qkbdvr41xx_qws.moc" - -#endif // QT_NO_QWS_KBD_VR41XX diff --git a/src/gui/embedded/qkbdyopy_qws.cpp b/src/gui/embedded/qkbdyopy_qws.cpp deleted file mode 100644 index edb732c..0000000 --- a/src/gui/embedded/qkbdyopy_qws.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - * YOPY buttons driver - * Contributed by Ron Victorelli (victorrj at icubed.com) - */ - -#include "qkbdyopy_qws.h" - -#ifndef QT_NO_QWS_KBD_YOPY - -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/ioctl.h> -#include <fcntl.h> -#include <termios.h> -#include <unistd.h> -#include <errno.h> - -#include <linux/kd.h> -#include <linux/fb.h> -#include <linux/yopy_button.h> - -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -extern "C" { - int getpgid(int); -} - -#include <qwidget.h> -#include <qsocketnotifier.h> - -QT_BEGIN_NAMESPACE - -class QWSYopyKbPrivate : public QObject -{ - Q_OBJECT -public: - QWSYopyKbPrivate(QWSYopyKeyboardHandler *h, const QString&); - virtual ~QWSYopyKbPrivate(); - - bool isOpen() { return buttonFD > 0; } - -private slots: - void readKeyboardData(); - -private: - QString terminalName; - int buttonFD; - struct termios newT, oldT; - QSocketNotifier *notifier; - QWSYopyKeyboardHandler *handler; -}; - -QWSYopyKeyboardHandler::QWSYopyKeyboardHandler(const QString &device) -{ - d = new QWSYopyKbPrivate(this, device); -} - -QWSYopyKeyboardHandler::~QWSYopyKeyboardHandler() -{ - delete d; -} - -QWSYopyKbPrivate::QWSYopyKbPrivate(QWSYopyKeyboardHandler *h, const QString &device) : handler(h) -{ - terminalName = device.isEmpty()?"/dev/tty1":device.toLatin1().constData(); - buttonFD = -1; - notifier = 0; - - buttonFD = QT_OPEN(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0); - if (buttonFD < 0) { - qWarning("Cannot open %s\n", qPrintable(terminalName)); - return; - } else { - - tcsetpgrp(buttonFD, getpgid(0)); - - /* put tty into "straight through" mode. - */ - if (tcgetattr(buttonFD, &oldT) < 0) { - qFatal("Linux-kbd: tcgetattr failed"); - } - - newT = oldT; - newT.c_lflag &= ~(ICANON | ECHO | ISIG); - newT.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); - newT.c_iflag |= IGNBRK; - newT.c_cc[VMIN] = 0; - newT.c_cc[VTIME] = 0; - - - if (tcsetattr(buttonFD, TCSANOW, &newT) < 0) { - qFatal("Linux-kbd: TCSANOW tcsetattr failed"); - } - - if (ioctl(buttonFD, KDSKBMODE, K_MEDIUMRAW) < 0) { - qFatal("Linux-kbd: KDSKBMODE tcsetattr failed"); - } - - notifier = new QSocketNotifier(buttonFD, QSocketNotifier::Read, this); - connect(notifier, SIGNAL(activated(int)),this, - SLOT(readKeyboardData())); - } -} - -QWSYopyKbPrivate::~QWSYopyKbPrivate() -{ - if (buttonFD > 0) { - ::close(buttonFD); - buttonFD = -1; - } -} - -void QWSYopyKbPrivate::readKeyboardData() -{ - uchar buf[1]; - char c='1'; - int fd; - - int n=read(buttonFD,buf,1); - if (n<0) { - qDebug("Keyboard read error %s",strerror(errno)); - } else { - uint code = buf[0]&YPBUTTON_CODE_MASK; - bool press = !(buf[0]&0x80); - // printf("Key=%d/%d/%d\n",buf[1],code,press); - int k=(-1); - switch(code) { - case 39: k=Qt::Key_Up; break; - case 44: k=Qt::Key_Down; break; - case 41: k=Qt::Key_Left; break; - case 42: k=Qt::Key_Right; break; - case 56: k=Qt::Key_F1; break; //windows - case 29: k=Qt::Key_F2; break; //cycle - case 24: k=Qt::Key_F3; break; //record - case 23: k=Qt::Key_F4; break; //mp3 - case 4: k=Qt::Key_F5; break; // PIMS - case 1: k=Qt::Key_Escape; break; // Escape - case 40: k=Qt::Key_Up; break; // prev - case 45: k=Qt::Key_Down; break; // next - case 35: if(!press) { - fd = QT_OPEN("/proc/sys/pm/sleep",O_RDWR,0); - if(fd >= 0) { - QT_WRITE(fd,&c,sizeof(c)); - QT_CLOSE(fd); - // - // Updates all widgets. - // - QWidgetList list = QApplication::allWidgets(); - for (int i = 0; i < list.size(); ++i) { - QWidget *w = list.at(i); - w->update(); - } - } - } - break; - - default: k=(-1); break; - } - - if (k >= 0) { - handler->processKeyEvent(0, k, 0, press, false); - } - } -} - -QT_END_NAMESPACE - -#include "qkbdyopy_qws.moc" - -#endif // QT_NO_QWS_KBD_YOPY diff --git a/src/gui/embedded/qlock.cpp b/src/gui/embedded/qlock.cpp index 305832c..9592a4d 100644 --- a/src/gui/embedded/qlock.cpp +++ b/src/gui/embedded/qlock.cpp @@ -41,9 +41,46 @@ #include "qlock_p.h" -#ifndef QT_NO_QWS_MULTIPROCESS +QT_BEGIN_NAMESPACE + +#ifdef QT_NO_QWS_MULTIPROCESS + +/* no multiprocess - use a dummy */ + +QLock::QLock(const QString & /*filename*/, char /*id*/, bool /*create*/) + : type(Read), data(0) +{ +} + +QLock::~QLock() +{ +} + +bool QLock::isValid() const +{ + return true; +} + +void QLock::lock(Type t) +{ + data = (QLockData *)-1; + type = t; +} + +void QLock::unlock() +{ + data = 0; +} + +bool QLock::locked() const +{ + return data; +} + +#else // QT_NO_QWS_MULTIPROCESS #include "qwssignalhandler_p.h" + #include <unistd.h> #include <sys/types.h> #if defined(Q_OS_DARWIN) @@ -71,16 +108,10 @@ union semun { #include <qdebug.h> #include <signal.h> -#endif // QT_NO_QWS_MULTIPROCESS - #include <private/qcore_unix_p.h> // overrides QT_OPEN #define MAX_LOCKS 200 // maximum simultaneous read locks -QT_BEGIN_NAMESPACE - - -#ifndef QT_NO_QWS_MULTIPROCESS class QLockData { public: @@ -91,7 +122,6 @@ public: int count; bool owned; }; -#endif // QT_NO_QWS_MULTIPROCESS /*! \class QLock @@ -126,11 +156,6 @@ public: QLock::QLock(const QString &filename, char id, bool create) { -#ifdef QT_NO_QWS_MULTIPROCESS - Q_UNUSED(filename); - Q_UNUSED(id); - Q_UNUSED(create); -#else data = new QLockData; data->count = 0; #ifdef Q_NO_SEMAPHORE @@ -163,7 +188,6 @@ QLock::QLock(const QString &filename, char id, bool create) qPrintable(filename), id); qDebug() << "Error" << eno << strerror(eno); } -#endif } /*! @@ -174,7 +198,6 @@ QLock::QLock(const QString &filename, char id, bool create) QLock::~QLock() { -#ifndef QT_NO_QWS_MULTIPROCESS if (locked()) unlock(); #ifdef Q_NO_SEMAPHORE @@ -188,7 +211,6 @@ QLock::~QLock() QWSSignalHandler::instance()->removeSemaphore(data->id); #endif delete data; -#endif } /*! @@ -200,11 +222,7 @@ QLock::~QLock() bool QLock::isValid() const { -#ifndef QT_NO_QWS_MULTIPROCESS return (data->id != -1); -#else - return true; -#endif } /*! @@ -221,9 +239,6 @@ bool QLock::isValid() const void QLock::lock(Type t) { -#ifdef QT_NO_QWS_MULTIPROCESS - Q_UNUSED(t); -#else if (!data->count) { #ifdef Q_NO_SEMAPHORE int op = LOCK_SH; @@ -256,7 +271,6 @@ void QLock::lock(Type t) #endif } data->count++; -#endif } /*! @@ -269,7 +283,6 @@ void QLock::lock(Type t) void QLock::unlock() { -#ifndef QT_NO_QWS_MULTIPROCESS if(data->count) { data->count--; if(!data->count) { @@ -298,7 +311,6 @@ void QLock::unlock() } else { qDebug("Unlock without corresponding lock"); } -#endif } /*! @@ -310,11 +322,9 @@ void QLock::unlock() bool QLock::locked() const { -#ifndef QT_NO_QWS_MULTIPROCESS return (data->count > 0); -#else - return false; -#endif } +#endif // QT_NO_QWS_MULTIPROCESS + QT_END_NAMESPACE diff --git a/src/gui/embedded/qmousebus_qws.cpp b/src/gui/embedded/qmousebus_qws.cpp deleted file mode 100644 index 0b674b6..0000000 --- a/src/gui/embedded/qmousebus_qws.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qmousebus_qws.h" - -#ifndef QT_NO_QWS_MOUSE_BUS - -#include "qwindowsystem_qws.h" -#include "qsocketnotifier.h" - -#include "qapplication.h" -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -#include <unistd.h> -#include <stdlib.h> -#include <stdio.h> -#include <sys/ioctl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <errno.h> -#include <termios.h> - -QT_BEGIN_NAMESPACE - -/* - * bus mouse driver (a.k.a. Logitech busmouse) - */ - -class QWSBusMouseHandlerPrivate : public QObject -{ - Q_OBJECT -public: - QWSBusMouseHandlerPrivate(QWSBusMouseHandler *h, const QString &driver, const QString &device); - ~QWSBusMouseHandlerPrivate(); - - void suspend(); - void resume(); - -private slots: - void readMouseData(); - -protected: - enum { mouseBufSize = 128 }; - QWSBusMouseHandler *handler; - QSocketNotifier *mouseNotifier; - int mouseFD; - int mouseIdx; - int obstate; - uchar mouseBuf[mouseBufSize]; -}; - -QWSBusMouseHandler::QWSBusMouseHandler(const QString &driver, const QString &device) - : QWSMouseHandler(driver, device) -{ - d = new QWSBusMouseHandlerPrivate(this, driver, device); -} - -QWSBusMouseHandler::~QWSBusMouseHandler() -{ - delete d; -} - -void QWSBusMouseHandler::suspend() -{ - d->suspend(); -} - -void QWSBusMouseHandler::resume() -{ - d->resume(); -} - - -QWSBusMouseHandlerPrivate::QWSBusMouseHandlerPrivate(QWSBusMouseHandler *h, - const QString &, const QString &device) - : handler(h) - -{ - QString mouseDev = device; - if (mouseDev.isEmpty()) - mouseDev = QLatin1String("/dev/mouse"); - obstate = -1; - mouseFD = -1; - mouseFD = QT_OPEN(mouseDev.toLocal8Bit(), O_RDWR | O_NDELAY); - if (mouseFD < 0) - mouseFD = QT_OPEN(mouseDev.toLocal8Bit(), O_RDONLY | O_NDELAY); - if (mouseFD < 0) - qDebug("Cannot open %s (%s)", qPrintable(mouseDev), strerror(errno)); - - // Clear pending input - tcflush(mouseFD,TCIFLUSH); - usleep(50000); - - char buf[100]; // busmouse driver will not read if bufsize < 3, YYD - while (QT_READ(mouseFD, buf, 100) > 0) { } // eat unwanted replies - - mouseIdx = 0; - - mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this); - connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData())); -} - -QWSBusMouseHandlerPrivate::~QWSBusMouseHandlerPrivate() -{ - if (mouseFD >= 0) { - tcflush(mouseFD,TCIFLUSH); // yyd. - QT_CLOSE(mouseFD); - } -} - - -void QWSBusMouseHandlerPrivate::suspend() -{ - mouseNotifier->setEnabled(false); -} - - -void QWSBusMouseHandlerPrivate::resume() -{ - mouseIdx = 0; - obstate = -1; - mouseNotifier->setEnabled(true); -} - -void QWSBusMouseHandlerPrivate::readMouseData() -{ - int n; - // It'll only read 3 bytes a time and return all other buffer zeroed, thus cause protocol errors - for (;;) { - if (mouseBufSize - mouseIdx < 3) - break; - n = QT_READ(mouseFD, mouseBuf+mouseIdx, 3); - if (n != 3) - break; - mouseIdx += 3; - } - - static const int accel_limit = 5; - static const int accel = 2; - - int idx = 0; - int bstate = 0; - int dx = 0, dy = 0; - bool sendEvent = false; - int tdx = 0, tdy = 0; - - while (mouseIdx-idx >= 3) { -#if 0 // debug - qDebug("Got mouse data"); -#endif - uchar *mb = mouseBuf+idx; - bstate = 0; - dx = 0; - dy = 0; - sendEvent = false; - if (((mb[0] & 0x04))) - bstate |= Qt::LeftButton; - if (((mb[0] & 0x01))) - bstate |= Qt::RightButton; - - dx=(signed char)mb[1]; - dy=(signed char)mb[2]; - sendEvent=true; - - if (sendEvent) { - if (qAbs(dx) > accel_limit || qAbs(dy) > accel_limit) { - dx *= accel; - dy *= accel; - } - tdx += dx; - tdy += dy; - if (bstate != obstate) { - QPoint pos = handler->pos() + QPoint(tdx,-tdy); - handler->limitToScreen(pos); - handler->mouseChanged(pos,bstate); - sendEvent = false; - tdx = 0; - tdy = 0; - obstate = bstate; - } - } - idx += 3; - } - if (sendEvent) { - QPoint pos = handler->pos() + QPoint(tdx,-tdy); - handler->limitToScreen(pos); - handler->mouseChanged(pos,bstate); - } - - int surplus = mouseIdx - idx; - for (int i = 0; i < surplus; i++) - mouseBuf[i] = mouseBuf[idx+i]; - mouseIdx = surplus; -} - -QT_END_NAMESPACE - -#include "qmousebus_qws.moc" - -#endif // QT_NO_QWS_MOUSE_BUS diff --git a/src/gui/embedded/qmousedriverfactory_qws.cpp b/src/gui/embedded/qmousedriverfactory_qws.cpp index 7e51818..6d71750 100644 --- a/src/gui/embedded/qmousedriverfactory_qws.cpp +++ b/src/gui/embedded/qmousedriverfactory_qws.cpp @@ -43,12 +43,11 @@ #include "qapplication.h" #include "qmousepc_qws.h" -#include "qmousebus_qws.h" -#include "qmousevr41xx_qws.h" -#include "qmouseyopy_qws.h" #include "qmouselinuxtp_qws.h" +#include "qmouselinuxinput_qws.h" #include "qmousevfb_qws.h" #include "qmousetslib_qws.h" +#include "qmouseqnx_qws.h" #include <stdlib.h> #include "private/qfactoryloader_p.h" #include "qmousedriverplugin_qws.h" @@ -104,18 +103,14 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, QWSMouseHandler *QMouseDriverFactory::create(const QString& key, const QString &device) { QString driver = key.toLower(); +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_MOUSE_QNX) + if (driver == QLatin1String("qnx") || driver.isEmpty()) + return new QQnxMouseHandler(key, device); +#endif #ifndef QT_NO_QWS_MOUSE_LINUXTP if (driver == QLatin1String("linuxtp") || driver.isEmpty()) return new QWSLinuxTPMouseHandler(key, device); #endif -#ifndef QT_NO_QWS_MOUSE_YOPY - if (driver == QLatin1String("yopy") || driver.isEmpty()) - return new QWSYopyMouseHandler(key, device); -#endif -#ifndef QT_NO_QWS_MOUSE_VR41XX - if (driver == QLatin1String("vr41xx") || driver.isEmpty()) - return new QWSVr41xxMouseHandler(key, device); -#endif #ifndef QT_NO_QWS_MOUSE_PC if (driver == QLatin1String("auto") || driver == QLatin1String("intellimouse") @@ -126,14 +121,16 @@ QWSMouseHandler *QMouseDriverFactory::create(const QString& key, const QString & return new QWSPcMouseHandler(key, device); } #endif -#ifndef QT_NO_QWS_MOUSE_BUS - if (driver == QLatin1String("bus")) - return new QWSBusMouseHandler(key, device); -#endif #ifndef QT_NO_QWS_MOUSE_TSLIB if (driver == QLatin1String("tslib") || driver.isEmpty()) return new QWSTslibMouseHandler(key, device); #endif +# ifndef QT_NO_QWS_MOUSE_LINUXINPUT + if (driver == QLatin1String("linuxinput") || \ + driver == QLatin1String("usb") || \ + driver == QLatin1String("linuxis")) + return new QWSLinuxInputMouseHandler(device); +# endif #ifndef QT_NO_QWS_MOUSE_QVFB if (driver == QLatin1String("qvfbmouse") || driver == QLatin1String("qvfb")) return new QVFbMouseHandler(key, device); @@ -157,15 +154,12 @@ QStringList QMouseDriverFactory::keys() { QStringList list; +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_MOUSE_QNX) + list << QLatin1String("QNX"); +#endif #ifndef QT_NO_QWS_MOUSE_LINUXTP list << QLatin1String("LinuxTP"); #endif -#ifndef QT_NO_QWS_MOUSE_YOPY - list << QLatin1String("Yopy"); -#endif -#ifndef QT_NO_QWS_MOUSE_VR41XX - list << QLatin1String("VR41xx"); -#endif #ifndef QT_NO_QWS_MOUSE_PC list << QLatin1String("Auto") << QLatin1String("IntelliMouse") @@ -173,12 +167,12 @@ QStringList QMouseDriverFactory::keys() << QLatin1String("MouseSystems") << QLatin1String("MouseMan"); #endif -#ifndef QT_NO_QWS_MOUSE_BUS - list << QLatin1String("Bus"); -#endif #ifndef QT_NO_QWS_MOUSE_TSLIB list << QLatin1String("Tslib"); #endif +#ifndef QT_NO_QWS_MOUSE_LINUXINPUT + list << QLatin1String("LinuxInput"); +#endif #if !defined(Q_OS_WIN32) || defined(QT_MAKEDLL) #ifndef QT_NO_LIBRARY diff --git a/src/gui/embedded/qmouselinuxinput_qws.cpp b/src/gui/embedded/qmouselinuxinput_qws.cpp new file mode 100644 index 0000000..6ea8807 --- /dev/null +++ b/src/gui/embedded/qmouselinuxinput_qws.cpp @@ -0,0 +1,205 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmouselinuxinput_qws.h" + +#include <QScreen> +#include <QSocketNotifier> + +#include <qplatformdefs.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN + +#include <errno.h> + +#include <linux/input.h> + +QT_BEGIN_NAMESPACE + + +class QWSLinuxInputMousePrivate : public QObject +{ + Q_OBJECT +public: + QWSLinuxInputMousePrivate(QWSLinuxInputMouseHandler *, const QString &); + ~QWSLinuxInputMousePrivate(); + + void enable(bool on); + +private Q_SLOTS: + void readMouseData(); + +private: + QWSLinuxInputMouseHandler *m_handler; + QSocketNotifier * m_notify; + int m_fd; + int m_x, m_y; + int m_buttons; +}; + +QWSLinuxInputMouseHandler::QWSLinuxInputMouseHandler(const QString &device) + : QWSCalibratedMouseHandler(device) +{ + d = new QWSLinuxInputMousePrivate(this, device); +} + +QWSLinuxInputMouseHandler::~QWSLinuxInputMouseHandler() +{ + delete d; +} + +void QWSLinuxInputMouseHandler::suspend() +{ + d->enable(false); +} + +void QWSLinuxInputMouseHandler::resume() +{ + d->enable(true); +} + +QWSLinuxInputMousePrivate::QWSLinuxInputMousePrivate(QWSLinuxInputMouseHandler *h, const QString &device) + : m_handler(h), m_notify(0), m_x(0), m_y(0), m_buttons(0) +{ + setObjectName(QLatin1String("LinuxInputSubsystem Mouse Handler")); + + QString dev = QLatin1String("/dev/input/event0"); + if (device.startsWith(QLatin1String("/dev/"))) + dev = device; + + m_fd = QT_OPEN(dev.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0); + if (m_fd >= 0) { + m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this); + connect(m_notify, SIGNAL(activated(int)), this, SLOT(readMouseData())); + } else { + qWarning("Cannot open mouse input device '%s': %s", qPrintable(dev), strerror(errno)); + return; + } +} + +QWSLinuxInputMousePrivate::~QWSLinuxInputMousePrivate() +{ + if (m_fd >= 0) + QT_CLOSE(m_fd); +} + +void QWSLinuxInputMousePrivate::enable(bool on) +{ + if (m_notify) + m_notify->setEnabled(on); +} + +void QWSLinuxInputMousePrivate::readMouseData() +{ + if (!qt_screen) + return; + + struct ::input_event buffer[32]; + int n = 0; + + forever { + n = QT_READ(m_fd, reinterpret_cast<char *>(buffer) + n, sizeof(buffer) - n); + + if (n == 0) { + qWarning("Got EOF from the input device."); + return; + } else if (n < 0 && (errno != EINTR && errno != EAGAIN)) { + qWarning("Could not read from input device: %s", strerror(errno)); + return; + } else if (n % sizeof(buffer[0]) == 0) { + break; + } + } + + n /= sizeof(buffer[0]); + + for (int i = 0; i < n; ++i) { + struct ::input_event *data = &buffer[i]; + + bool unknown = false; + if (data->type == EV_ABS) { + if (data->code == ABS_X) { + m_x = data->value; + } else if (data->code == ABS_Y) { + m_y = data->value; + } else { + unknown = true; + } + } else if (data->type == EV_REL) { + if (data->code == REL_X) { + m_x += data->value; + } else if (data->code == REL_Y) { + m_y += data->value; + } else { + unknown = true; + } + } else if (data->type == EV_KEY && data->code == BTN_TOUCH) { + m_buttons = data->value ? Qt::LeftButton : 0; + } else if (data->type == EV_KEY) { + int button = 0; + switch (data->code) { + case BTN_LEFT: button = Qt::LeftButton; break; + case BTN_MIDDLE: button = Qt::MidButton; break; + case BTN_RIGHT: button = Qt::RightButton; break; + } + if (data->value) + m_buttons |= button; + else + m_buttons &= ~button; + } else if (data->type == EV_SYN && data->code == SYN_REPORT) { + QPoint pos(m_x, m_y); + pos = m_handler->transform(pos); + m_handler->limitToScreen(pos); + m_handler->mouseChanged(pos, m_buttons); + } else if (data->type == EV_MSC && data->code == MSC_SCAN) { + // kernel encountered an unmapped key - just ignore it + continue; + } else { + unknown = true; + } + if (unknown) { + qWarning("unknown mouse event type=%x, code=%x, value=%x", data->type, data->code, data->value); + } + } +} + +QT_END_NAMESPACE + +#include "qmouselinuxinput_qws.moc" diff --git a/src/gui/embedded/qmousevr41xx_qws.h b/src/gui/embedded/qmouselinuxinput_qws.h index 46d07e0..25e351f 100644 --- a/src/gui/embedded/qmousevr41xx_qws.h +++ b/src/gui/embedded/qmouselinuxinput_qws.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** -** This file is part of the QtGui module of the Qt Toolkit. +** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage @@ -39,10 +39,10 @@ ** ****************************************************************************/ -#ifndef QMOUSEVR41XX_QWS_H -#define QMOUSEVR41XX_QWS_H +#ifndef QMOUSELINUXINPUT_QWS_H +#define QMOUSELINUXINPUT_QWS_H -#include <QtGui/qmouse_qws.h> +#include <QtGui/QWSCalibratedMouseHandler> QT_BEGIN_HEADER @@ -50,31 +50,29 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -#ifndef QT_NO_QWS_MOUSE_VR41XX +#ifndef QT_NO_QWS_MOUSE_LINUXINPUT -class QWSVr41xxMouseHandlerPrivate; +class QWSLinuxInputMousePrivate; -class QWSVr41xxMouseHandler : public QWSCalibratedMouseHandler +class QWSLinuxInputMouseHandler : public QWSCalibratedMouseHandler { public: - explicit QWSVr41xxMouseHandler(const QString & = QString(), - const QString & = QString()); - ~QWSVr41xxMouseHandler(); + QWSLinuxInputMouseHandler(const QString &); + ~QWSLinuxInputMouseHandler(); - void resume(); void suspend(); - -protected: - QWSVr41xxMouseHandlerPrivate *d; + void resume(); private: - friend class QWSVr41xxMouseHandlerPrivate; + QWSLinuxInputMousePrivate *d; + + friend class QWSLinuxInputMousePrivate; }; -#endif // QT_NO_QWS_MOUSE_VR41XX +#endif // QT_NO_QWS_MOUSE_LINUXINPUT QT_END_NAMESPACE QT_END_HEADER -#endif // QMOUSEVR41XX_QWS_H +#endif // QMOUSELINUXINPUT_QWS_H diff --git a/src/gui/embedded/qmousepc_qws.cpp b/src/gui/embedded/qmousepc_qws.cpp index 317bb8a..2d62772 100644 --- a/src/gui/embedded/qmousepc_qws.cpp +++ b/src/gui/embedded/qmousepc_qws.cpp @@ -332,7 +332,7 @@ protected: tty.c_oflag = 0; tty.c_lflag = 0; tty.c_cflag = f | CREAD | CLOCAL | HUPCL; -#if !defined(Q_OS_DARWIN) && !defined(Q_OS_SOLARIS) && !defined(Q_OS_INTEGRITY) +#ifdef Q_OS_LINUX tty.c_line = 0; #endif tty.c_cc[VTIME] = 0; diff --git a/src/gui/embedded/qmouseqnx_qws.cpp b/src/gui/embedded/qmouseqnx_qws.cpp new file mode 100644 index 0000000..59cd5be --- /dev/null +++ b/src/gui/embedded/qmouseqnx_qws.cpp @@ -0,0 +1,190 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qplatformdefs.h" +#include "qmouseqnx_qws.h" + +#include "qsocketnotifier.h" +#include "qdebug.h" + +#include <sys/dcmd_input.h> + +#include <errno.h> + +QT_BEGIN_NAMESPACE + +/*! + \class QQnxMouseHandler + \preliminary + \ingroup qws + \internal + \since 4.6 + + \brief The QQnxMouseHandler class implements a mouse driver + for the QNX \c{devi-hid} input manager. + + To be able to compile this mouse handler, \l{Qt for Embedded Linux} + must be configured with the \c -qt-mouse-qnx option, see the + \l{Qt for Embedded Linux Pointer Handling}{Pointer Handling} documentation for details. + + In order to use this mouse handler, the \c{devi-hid} input manager + must be set up and run with the resource manager interface (option \c{-r}). + Also, Photon must not be running. + + Example invocation from command line: \c{/usr/photon/bin/devi-hid -Pr kbd mouse} + Note that after running \c{devi-hid}, you will not be able to use the local + shell anymore. It is suggested to run the command in a shell scrip, that launches + a Qt application after invocation of \c{devi-hid}. + + To make \l{Qt for Embedded Linux} explicitly choose the qnx mouse + handler, set the QWS_MOUSE_PROTO environment variable to \c{qnx}. By default, + the first mouse device (\c{/dev/devi/mouse0}) is used. To override, pass a device + name as the first and only parameter, for example + \c{QWS_MOUSE_PROTO=qnx:/dev/devi/mouse1; export QWS_MOUSE_PROTO}. + + \sa {Qt for Embedded Linux Pointer Handling}{Pointer Handling}, {Qt for Embedded Linux} +*/ + +/*! + Constructs a mouse handler for the specified \a device, defaulting to \c{/dev/devi/mouse0}. + The \a driver parameter must be \c{"qnx"}. + + Note that you should never instanciate this class, instead let QMouseDriverFactory + handle the mouse handlers. + + \sa QMouseDriverFactory + */ +QQnxMouseHandler::QQnxMouseHandler(const QString & /*driver*/, const QString &device) +{ + // open the mouse device with O_NONBLOCK so reading won't block when there's no data + mouseFD = QT_OPEN(device.isEmpty() ? "/dev/devi/mouse0" : device.toLatin1().constData(), + QT_OPEN_RDONLY | O_NONBLOCK); + if (mouseFD == -1) { + qErrnoWarning(errno, "QQnxMouseHandler: Unable to open mouse device"); + return; + } + + // register a socket notifier on the file descriptor so we'll wake up whenever + // there's a mouse move waiting for us. + mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this); + connect(mouseNotifier, SIGNAL(activated(int)), SLOT(socketActivated())); + + qDebug() << "QQnxMouseHandler: connected."; +} + +/*! + Destroys this mouse handler and closes the connection to the mouse device. + */ +QQnxMouseHandler::~QQnxMouseHandler() +{ + QT_CLOSE(mouseFD); +} + +/*! \reimp */ +void QQnxMouseHandler::resume() +{ + if (mouseNotifier) + mouseNotifier->setEnabled(true); +} + +/*! \reimp */ +void QQnxMouseHandler::suspend() +{ + if (mouseNotifier) + mouseNotifier->setEnabled(false); +} + +/*! \internal + + This function is called whenever there is activity on the mouse device. + By default, it reads up to 10 mouse move packets and calls mouseChanged() + for each of them. +*/ +void QQnxMouseHandler::socketActivated() +{ + // _mouse_packet is a QNX structure. devi-hid is nice enough to translate + // the raw byte data from mouse devices into generic format for us. + _mouse_packet packet; + + int iteration = 0; + + // read mouse events in batches of 10. Since we're getting quite a lot + // of mouse events, it's better to do them in batches than to return to the + // event loop every time. + do { + int bytesRead = QT_READ(mouseFD, &packet, sizeof(packet)); + if (bytesRead == -1) { + // EAGAIN means that there are no more mouse events to read + if (errno != EAGAIN) + qErrnoWarning(errno, "QQnxMouseHandler: Unable to read from socket"); + return; + } + + // bytes read should always be equal to the size of a packet. + Q_ASSERT(bytesRead == sizeof(packet)); + + // translate the coordinates from the QNX data structure to Qt coordinates + // note the swapped y axis + QPoint pos = mousePos; + pos += QPoint(packet.dx, -packet.dy); + + // QNX only tells us relative mouse movements, not absolute ones, so limit the + // cursor position manually to the screen + limitToScreen(pos); + + // translate the QNX mouse button bitmask to Qt buttons + int buttons = Qt::NoButton; + + if (packet.hdr.buttons & _POINTER_BUTTON_LEFT) + buttons |= Qt::LeftButton; + if (packet.hdr.buttons & _POINTER_BUTTON_MIDDLE) + buttons |= Qt::MidButton; + if (packet.hdr.buttons & _POINTER_BUTTON_RIGHT) + buttons |= Qt::RightButton; + + // call mouseChanged() - this does all the magic to actually move the on-screen + // mouse cursor. + mouseChanged(pos, buttons, 0); + } while (++iteration < 11); +} + +QT_END_NAMESPACE + diff --git a/src/gui/embedded/qmousebus_qws.h b/src/gui/embedded/qmouseqnx_qws.h index 407da98..f8cad4a 100644 --- a/src/gui/embedded/qmousebus_qws.h +++ b/src/gui/embedded/qmouseqnx_qws.h @@ -39,9 +39,10 @@ ** ****************************************************************************/ -#ifndef QMOUSEBUS_QWS_H -#define QMOUSEBUS_QWS_H +#ifndef QMOUSE_QNX_H +#define QMOUSE_QNX_H +#include <QtCore/qobject.h> #include <QtGui/qmouse_qws.h> QT_BEGIN_HEADER @@ -50,27 +51,29 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -#ifndef QT_NO_QWS_MOUSE_BUS +class QSocketNotifier; -class QWSBusMouseHandlerPrivate; - -class QWSBusMouseHandler : public QWSMouseHandler +class Q_GUI_EXPORT QQnxMouseHandler : public QObject, public QWSMouseHandler { + Q_OBJECT public: - explicit QWSBusMouseHandler(const QString & = QString(), - const QString & = QString()); - ~QWSBusMouseHandler(); + explicit QQnxMouseHandler(const QString &driver = QString(), + const QString &device = QString()); + ~QQnxMouseHandler(); - void suspend(); void resume(); -protected: - QWSBusMouseHandlerPrivate *d; -}; + void suspend(); + +private Q_SLOTS: + void socketActivated(); -#endif // QT_NO_QWS_MOUSE_BUS +private: + QSocketNotifier *mouseNotifier; + int mouseFD; +}; QT_END_NAMESPACE QT_END_HEADER -#endif // QMOUSEBUS_QWS_H +#endif // QMOUSE_QWS_H diff --git a/src/gui/embedded/qmousevr41xx_qws.cpp b/src/gui/embedded/qmousevr41xx_qws.cpp deleted file mode 100644 index b7491d9..0000000 --- a/src/gui/embedded/qmousevr41xx_qws.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qmousevr41xx_qws.h" - -#ifndef QT_NO_QWS_MOUSE_VR41XX -#include "qwindowsystem_qws.h" -#include "qsocketnotifier.h" -#include "qtimer.h" -#include "qapplication.h" -#include "qscreen_qws.h" -#include <qstringlist.h> -#include <qvarlengtharray.h> -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -#include <unistd.h> -#include <stdlib.h> -#include <stdio.h> -#include <sys/ioctl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <errno.h> -#include <termios.h> - -QT_BEGIN_NAMESPACE - -static const int defaultFilterSize = 3; - -class QWSVr41xxMouseHandlerPrivate : public QObject -{ - Q_OBJECT -public: - QWSVr41xxMouseHandlerPrivate(QWSVr41xxMouseHandler *, const QString &, const QString &); - ~QWSVr41xxMouseHandlerPrivate(); - - void resume(); - void suspend(); - -private slots: - void sendRelease(); - void readMouseData(); - -private: - bool getSample(); - ushort currSample[6]; - uint currLength; - - int mouseFD; - int mouseIdx; - QTimer *rtimer; - QSocketNotifier *mouseNotifier; - QWSVr41xxMouseHandler *handler; - QPoint lastPos; - bool isPressed; - int filterSize; - int pressLimit; -}; - -QWSVr41xxMouseHandler::QWSVr41xxMouseHandler(const QString &drv, const QString &dev) - : QWSCalibratedMouseHandler(drv, dev) -{ - d = new QWSVr41xxMouseHandlerPrivate(this, drv, dev); -} - -QWSVr41xxMouseHandler::~QWSVr41xxMouseHandler() -{ - delete d; -} - -void QWSVr41xxMouseHandler::resume() -{ - d->resume(); -} - -void QWSVr41xxMouseHandler::suspend() -{ - d->suspend(); -} - -QWSVr41xxMouseHandlerPrivate::QWSVr41xxMouseHandlerPrivate(QWSVr41xxMouseHandler *h, const QString &, const QString &device) - : currLength(0), handler(h) -{ - QStringList options = device.split(QLatin1String(":")); - int index = -1; - - filterSize = defaultFilterSize; - QRegExp filterRegExp(QLatin1String("filter=(\\d+)")); - index = options.indexOf(filterRegExp); - if (index != -1) { - filterSize = qMax(1, filterRegExp.cap(1).toInt()); - options.removeAt(index); - } - handler->setFilterSize(filterSize); - - pressLimit = 750; - QRegExp pressRegExp(QLatin1String("press=(\\d+)")); - index = options.indexOf(pressRegExp); - if (index != -1) { - pressLimit = filterRegExp.cap(1).toInt(); - options.removeAt(index); - } - - QString dev; - if (options.isEmpty()) - dev = QLatin1String("/dev/vrtpanel"); - else - dev = options.first(); - - if ((mouseFD = QT_OPEN(dev.toLocal8Bit().constData(), O_RDONLY)) < 0) { - qWarning("Cannot open %s (%s)", qPrintable(dev), strerror(errno)); - return; - } - sleep(1); - - if (fcntl(mouseFD, F_SETFL, O_NONBLOCK) < 0) { - qWarning("Error initializing touch panel."); - return; - } - - mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this); - connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData())); - - rtimer = new QTimer(this); - rtimer->setSingleShot(true); - connect(rtimer, SIGNAL(timeout()), this, SLOT(sendRelease())); - mouseIdx = 0; -} - -QWSVr41xxMouseHandlerPrivate::~QWSVr41xxMouseHandlerPrivate() -{ - if (mouseFD >= 0) - QT_CLOSE(mouseFD); -} - -void QWSVr41xxMouseHandlerPrivate::suspend() -{ - mouseNotifier->setEnabled(false); -} - - -void QWSVr41xxMouseHandlerPrivate::resume() -{ - mouseIdx = 0; - mouseNotifier->setEnabled(true); -} - -void QWSVr41xxMouseHandlerPrivate::sendRelease() -{ - handler->sendFiltered(lastPos, Qt::NoButton); - isPressed = false; -} - -bool QWSVr41xxMouseHandlerPrivate::getSample() -{ - const int n = QT_READ(mouseFD, - reinterpret_cast<uchar*>(currSample) + currLength, - sizeof(currSample) - currLength); - - if (n > 0) - currLength += n; - - if (currLength < sizeof(currSample)) - return false; - - currLength = 0; - return true; -} - -void QWSVr41xxMouseHandlerPrivate::readMouseData() -{ - const int sampleLength = sizeof(currSample) / sizeof(ushort); - QVarLengthArray<ushort, sampleLength * defaultFilterSize> samples(sampleLength * filterSize); - - // Only return last 'filterSize' samples - int head = 0; - int tail = 0; - int nSamples = 0; - while (getSample()) { - if (!(currSample[0] & 0x8000) || (currSample[5] < pressLimit)) - continue; - - ushort *data = samples.data() + head * sampleLength; - memcpy(data, currSample, sizeof(currSample)); - ++nSamples; - head = (head + 1) % filterSize; - if (nSamples >= filterSize) - tail = (tail + 1) % filterSize; - } - - if (nSamples == 0) - return; - - // send mouse events - while (tail != head || filterSize == 1) { - const ushort *data = samples.data() + tail * sampleLength; - lastPos = QPoint(data[3] - data[4], data[2] - data[1]); - handler->sendFiltered(lastPos, Qt::LeftButton); - isPressed = true; - tail = (tail + 1) % filterSize; - if (filterSize == 1) - break; - } - - if (isPressed) - rtimer->start(50); // release unreliable -} - -QT_END_NAMESPACE - -#include "qmousevr41xx_qws.moc" - -#endif //QT_NO_QWS_MOUSE_VR41 diff --git a/src/gui/embedded/qmouseyopy_qws.cpp b/src/gui/embedded/qmouseyopy_qws.cpp deleted file mode 100644 index 3a541d3..0000000 --- a/src/gui/embedded/qmouseyopy_qws.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qmouseyopy_qws.h" - -#ifndef QT_NO_QWS_MOUSE_YOPY -#include "qwindowsystem_qws.h" -#include "qsocketnotifier.h" -#include "qapplication.h" -#include "qscreen_qws.h" -#include <private/qcore_unix_p.h> // overrides QT_OPEN - -#include <unistd.h> -#include <stdlib.h> -#include <stdio.h> -#include <sys/ioctl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <errno.h> -#include <termios.h> - -QT_BEGIN_NAMESPACE - -class QWSYopyMouseHandlerPrivate : public QObject -{ - Q_OBJECT -public: - QWSYopyMouseHandlerPrivate(QWSYopyMouseHandler *h); - ~QWSYopyMouseHandlerPrivate(); - - void suspend(); - void resume(); - -private slots: - void readMouseData(); - -private: - int mouseFD; - int prevstate; - QSocketNotifier *mouseNotifier; - QWSYopyMouseHandler *handler; -}; - -QWSYopyMouseHandler::QWSYopyMouseHandler(const QString &driver, const QString &device) - : QWSMouseHandler(driver, device) -{ - d = new QWSYopyMouseHandlerPrivate(this); -} - -QWSYopyMouseHandler::~QWSYopyMouseHandler() -{ - delete d; -} - -void QWSYopyMouseHandler::resume() -{ - d->resume(); -} - -void QWSYopyMouseHandler::suspend() -{ - d->suspend(); -} - -QWSYopyMouseHandlerPrivate::QWSYopyMouseHandlerPrivate(QWSYopyMouseHandler *h) - : handler(h) -{ - if ((mouseFD = QT_OPEN("/dev/ts", O_RDONLY)) < 0) { - qWarning("Cannot open /dev/ts (%s)", strerror(errno)); - return; - } else { - sleep(1); - } - prevstate=0; - mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, - this); - connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData())); -} - -QWSYopyMouseHandlerPrivate::~QWSYopyMouseHandlerPrivate() -{ - if (mouseFD >= 0) - QT_CLOSE(mouseFD); -} - -#define YOPY_XPOS(d) (d[1]&0x3FF) -#define YOPY_YPOS(d) (d[2]&0x3FF) -#define YOPY_PRES(d) (d[0]&0xFF) -#define YOPY_STAT(d) (d[3]&0x01) - -struct YopyTPdata { - - unsigned char status; - unsigned short xpos; - unsigned short ypos; - -}; - -void QWSYopyMouseHandlerPrivate::suspend() -{ - mouseNotifier->setEnabled(false); -} - - -void QWSYopyMouseHandlerPrivate::resume() -{ - prevstate = 0; - mouseNotifier->setEnabled(true); -} - -void QWSYopyMouseHandlerPrivate::readMouseData() -{ - if(!qt_screen) - return; - YopyTPdata data; - - unsigned int yopDat[4]; - - int ret; - - ret=QT_READ(mouseFD,&yopDat,sizeof(yopDat)); - - if(ret) { - data.status= (YOPY_PRES(yopDat)) ? 1 : 0; - data.xpos=YOPY_XPOS(yopDat); - data.ypos=YOPY_YPOS(yopDat); - QPoint q; - q.setX(data.xpos); - q.setY(data.ypos); - if (data.status && !prevstate) { - handler->mouseChanged(q,Qt::LeftButton); - } else if(!data.status && prevstate) { - handler->mouseChanged(q,0); - } - prevstate = data.status; - } - if(ret<0) { - qDebug("Error %s",strerror(errno)); - } -} - -QT_END_NAMESPACE - -#include "qmouseyopy_qws.moc" - -#endif //QT_NO_QWS_MOUSE_YOPY diff --git a/src/gui/embedded/qmouseyopy_qws.h b/src/gui/embedded/qmouseyopy_qws.h deleted file mode 100644 index 0d24a8f..0000000 --- a/src/gui/embedded/qmouseyopy_qws.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QMOUSEYOPY_QWS_H -#define QMOUSEYOPY_QWS_H - -#include <QtGui/qmouse_qws.h> - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -#ifndef QT_NO_QWS_MOUSE_YOPY - -// YOPY touch panel support based on changes contributed by Ron Victorelli -// (victorrj at icubed.com) to Custom TP driver. - -class QWSYopyMouseHandlerPrivate; - -class QWSYopyMouseHandler : public QWSMouseHandler -{ -public: - explicit QWSYopyMouseHandler(const QString & = QString(), - const QString & = QString()); - ~QWSYopyMouseHandler(); - - void resume(); - void suspend(); - -protected: - QWSYopyMouseHandlerPrivate *d; -}; - -#endif // QT_NO_QWS_MOUSE_YOPY - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QMOUSEYOPY_QWS_H diff --git a/src/gui/embedded/qscreendriverfactory_qws.cpp b/src/gui/embedded/qscreendriverfactory_qws.cpp index 2290627..b531798 100644 --- a/src/gui/embedded/qscreendriverfactory_qws.cpp +++ b/src/gui/embedded/qscreendriverfactory_qws.cpp @@ -47,6 +47,7 @@ #include "qscreentransformed_qws.h" #include "qscreenvfb_qws.h" #include "qscreenmulti_qws_p.h" +#include "qscreenqnx_qws.h" #include <stdlib.h> #include "private/qfactoryloader_p.h" #include "qscreendriverplugin_qws.h" @@ -105,6 +106,10 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, QScreen *QScreenDriverFactory::create(const QString& key, int displayId) { QString driver = key.toLower(); +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_QNX) + if (driver == QLatin1String("qnx") || driver.isEmpty()) + return new QQnxScreen(displayId); +#endif #ifndef QT_NO_QWS_QVFB if (driver == QLatin1String("qvfb") || driver.isEmpty()) return new QVFbScreen(displayId); @@ -146,6 +151,9 @@ QStringList QScreenDriverFactory::keys() { QStringList list; +#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_QNX) + list << QLatin1String("QNX"); +#endif #ifndef QT_NO_QWS_QVFB list << QLatin1String("QVFb"); #endif diff --git a/src/gui/embedded/qscreenqnx_qws.cpp b/src/gui/embedded/qscreenqnx_qws.cpp new file mode 100644 index 0000000..c79ee59 --- /dev/null +++ b/src/gui/embedded/qscreenqnx_qws.cpp @@ -0,0 +1,447 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qscreenqnx_qws.h" +#include "qdebug.h" + +#include <gf/gf.h> + +// This struct holds all the pointers to QNX's internals +struct QQnxScreenContext +{ + inline QQnxScreenContext() + : device(0), display(0), layer(0), hwSurface(0), memSurface(0), context(0) + {} + + gf_dev_t device; + gf_dev_info_t deviceInfo; + gf_display_t display; + gf_display_info_t displayInfo; + gf_layer_t layer; + gf_surface_t hwSurface; + gf_surface_t memSurface; + gf_surface_info_t memSurfaceInfo; + gf_context_t context; +}; + +/*! + \class QQnxScreen + \preliminary + \ingroup qws + \since 4.6 + \internal + + \brief The QQnxScreen class implements a screen driver + for QNX io-display based devices. + + Note - you never have to instanciate this class, the QScreenDriverFactory + does that for us based on the \c{QWS_DISPLAY} environment variable. + + To activate this driver, set \c{QWS_DISPLAY} to \c{qnx}. + + Example: + \c{QWS_DISPLAY=qnx; export QWS_DISPLAY} + + By default, the main layer of the first display of the first device is used. + If you have multiple graphic cards, multiple displays or multiple layers and + don't want to connect to the default, you can override that with setting + the corresponding options \c{device}, \c{display} or \c{layer} in the \c{QWS_DISPLAY} variable: + + \c{QWS_DISPLAY=qnx:device=3:display=4:layer=5} + + In addition, it is suggested to set the physical width and height of the display. + QQnxScreen will use that information to compute the dots per inch (DPI) in order to render + fonts correctly. If this informaiton is omitted, QQnxScreen defaults to 72 dpi. + + \c{QWS_DISPLAY=qnx:mmWidth=120:mmHeight=80} + + \c{mmWidth} and \c{mmHeight} are the physical width/height of the screen in millimeters. + + \sa QScreen, QScreenDriverPlugin, {Running Qt for Embedded Linux Applications}{Running Applications} +*/ + +/*! + Constructs a QQnxScreen object. The \a display_id argument + identifies the Qt for Embedded Linux server to connect to. +*/ +QQnxScreen::QQnxScreen(int display_id) + : QScreen(display_id), d(new QQnxScreenContext) +{ +} + +/*! + Destroys this QQnxScreen object. +*/ +QQnxScreen::~QQnxScreen() +{ + delete d; +} + +/*! \reimp +*/ +bool QQnxScreen::initDevice() +{ + // implement this if you have multiple processes that want to access the display + // (not required if QT_NO_QWS_MULTIPROCESS is set) + return true; +} + +/*! \internal + Attaches to the named device \a name. +*/ +static bool attachDevice(QQnxScreenContext * const d, const char *name) +{ + int ret = gf_dev_attach(&d->device, name, &d->deviceInfo); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_dev_attach(%s) failed with error code %d", name, ret); + return false; + } + return true; +} + +/*! \internal + Attaches to the display at index \a displayIndex. + */ +static bool attachDisplay(QQnxScreenContext * const d, int displayIndex) +{ + int ret = gf_display_attach(&d->display, d->device, displayIndex, &d->displayInfo); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_display_attach(%d) failed with error code %d", + displayIndex, ret); + return false; + } + return true; +} + +/*! \internal + Attaches to the layer \a layerIndex. + */ +static bool attachLayer(QQnxScreenContext * const d, int layerIndex) +{ + int ret = gf_layer_attach(&d->layer, d->display, layerIndex, 0); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_layer_attach(%d) failed with error code %d", layerIndex, + ret); + return false; + } + gf_layer_enable(d->layer); + + return true; +} + +/*! \internal + Creates a new hardware surface (usually on the Gfx card memory) with the dimensions \a w * \a h. + */ +static bool createHwSurface(QQnxScreenContext * const d, int w, int h) +{ + int ret = gf_surface_create_layer(&d->hwSurface, &d->layer, 1, 0, + w, h, GF_FORMAT_ARGB8888, 0, 0); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_surface_create_layer(%dx%d) failed with error code %d", + w, h, ret); + return false; + } + + gf_layer_set_surfaces(d->layer, &d->hwSurface, 1); + + ret = gf_layer_update(d->layer, 0); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_layer_update() failed with error code %d\n", ret); + return false; + } + + return true; +} + +/*! \internal + Creates an in-memory, linear accessible surface of dimensions \a w * \a h. + This is the main surface that QWS blits to. + */ +static bool createMemSurface(QQnxScreenContext * const d, int w, int h) +{ + // Note: gf_surface_attach() could also be used, so we'll create the buffer + // and let the surface point to it. Here, we use surface_create instead. + + int ret = gf_surface_create(&d->memSurface, d->device, w, h, + GF_FORMAT_ARGB8888, 0, + GF_SURFACE_CREATE_CPU_FAST_ACCESS | GF_SURFACE_CREATE_CPU_LINEAR_ACCESSIBLE + | GF_SURFACE_PHYS_CONTIG); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_surface_create(%dx%d) failed with error code %d", + w, h, ret); + return false; + } + + gf_surface_get_info(d->memSurface, &d->memSurfaceInfo); + + if (d->memSurfaceInfo.sid == unsigned(GF_SID_INVALID)) { + qWarning("QQnxScreen: gf_surface_get_info() failed."); + return false; + } + + return true; +} + +/* \internal + Creates a QNX gf context and sets our memory surface on it. + */ +static bool createContext(QQnxScreenContext * const d) +{ + int ret = gf_context_create(&d->context); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_context_create() failed with error code %d", ret); + return false; + } + + ret = gf_context_set_surface(d->context, d->memSurface); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_context_set_surface() failed with error code %d", ret); + return false; + } + + return true; +} + +/*! \reimp + Connects to QNX's io-display based device based on the \a displaySpec parameters + from the \c{QWS_DISPLAY} environment variable. See the QQnxScreen class documentation + for possible parameters. + + \sa QQnxScreen + */ +bool QQnxScreen::connect(const QString &displaySpec) +{ + const QStringList params = displaySpec.split(QLatin1Char(':'), QString::SkipEmptyParts); + + bool isOk = false; + QRegExp deviceRegExp(QLatin1String("^device=(.+)$")); + if (params.indexOf(deviceRegExp) != -1) { + isOk = attachDevice(d, deviceRegExp.cap(1).toLocal8Bit().constData()); + } else { + // no device specified - attach to device 0 (the default) + isOk = attachDevice(d, GF_DEVICE_INDEX(0)); + } + + if (!isOk) + return false; + + qDebug("QQnxScreen: Attached to Device, number of displays: %d", d->deviceInfo.ndisplays); + + // default to display 0 + int displayIndex = 0; + QRegExp displayRegexp(QLatin1String("^display=(\\d+)$")); + if (params.indexOf(displayRegexp) != -1) { + displayIndex = displayRegexp.cap(1).toInt(); + } + + if (!attachDisplay(d, displayIndex)) + return false; + + qDebug("QQnxScreen: Attached to Display %d, resolution %dx%d, refresh %d Hz", + displayIndex, d->displayInfo.xres, d->displayInfo.yres, + d->displayInfo.refresh); + + + // default to main_layer_index from the displayInfo struct + int layerIndex = 0; + QRegExp layerRegexp(QLatin1String("^layer=(\\d+)$")); + if (params.indexOf(layerRegexp) != -1) { + layerIndex = layerRegexp.cap(1).toInt(); + } else { + layerIndex = d->displayInfo.main_layer_index; + } + + if (!attachLayer(d, layerIndex)) + return false; + + // tell QWSDisplay the width and height of the display + w = dw = d->displayInfo.xres; + h = dh = d->displayInfo.yres; + + // we only support 32 bit displays for now. + QScreen::d = 32; + + // assume 72 dpi as default, to calculate the physical dimensions if not specified + const int defaultDpi = 72; + + // Handle display physical size spec. + QRegExp mmWidthRegexp(QLatin1String("^mmWidth=(\\d+)$")); + if (params.indexOf(mmWidthRegexp) == -1) { + physWidth = qRound(dw * 25.4 / defaultDpi); + } else { + physWidth = mmWidthRegexp.cap(1).toInt(); + } + + QRegExp mmHeightRegexp(QLatin1String("^mmHeight=(\\d+)$")); + if (params.indexOf(mmHeightRegexp) == -1) { + physHeight = qRound(dh * 25.4 / defaultDpi); + } else { + physHeight = mmHeightRegexp.cap(1).toInt(); + } + + // create a hardware surface with our dimensions. In the old days, it was possible + // to get a pointer directly to the hw surface, so we could blit directly. Now, we + // have to use one indirection more, because it's not guaranteed that the hw surface + // is mappable into our process. + if (!createHwSurface(d, w, h)) + return false; + + // create an in-memory linear surface that is used by QWS. QWS will blit directly in here. + if (!createMemSurface(d, w, h)) + return false; + + // set the address of the in-memory buffer that QWS is blitting to + data = d->memSurfaceInfo.vaddr; + // set the line stepping + lstep = d->memSurfaceInfo.stride; + + // the overall size of the in-memory buffer is linestep * height + size = mapsize = lstep * h; + + // create a QNX drawing context + if (!createContext(d)) + return false; + + // we're always using a software cursor for now. Initialize it here. + QScreenCursor::initSoftwareCursor(); + + // done, the driver should be connected to the display now. + return true; +} + +/*! \reimp + */ +void QQnxScreen::disconnect() +{ + if (d->context) + gf_context_free(d->context); + + if (d->memSurface) + gf_surface_free(d->memSurface); + + if (d->hwSurface) + gf_surface_free(d->hwSurface); + + if (d->layer) + gf_layer_detach(d->layer); + + if (d->display) + gf_display_detach(d->display); + + if (d->device) + gf_dev_detach(d->device); + + d->memSurface = 0; + d->hwSurface = 0; + d->context = 0; + d->layer = 0; + d->display = 0; + d->device = 0; +} + +/*! \reimp + */ +void QQnxScreen::shutdownDevice() +{ +} + + +/*! \reimp + QQnxScreen doesn't support setting the mode, use io-display instead. + */ +void QQnxScreen::setMode(int,int,int) +{ + qWarning("QQnxScreen: Unable to change mode, use io-display instead."); +} + +/*! \reimp + */ +bool QQnxScreen::supportsDepth(int depth) const +{ + // only 32-bit for the moment + return depth == 32; +} + +/*! \reimp + */ +void QQnxScreen::exposeRegion(QRegion r, int changing) +{ + // here is where the actual magic happens. QWS will call exposeRegion whenever + // a region on the screen is dirty and needs to be updated on the actual screen. + + // first, call the parent implementation. The parent implementation will update + // the region on our in-memory surface + QScreen::exposeRegion(r, changing); + + // now our in-memory surface should be up to date with the latest changes. + // the code below copies the region from the in-memory surface to the hardware. + + // just get the bounding rectangle of the region. Most screen updates are rectangular + // anyways. Code could be optimized to blit each and every member of the region + // individually, but in real life, the speed-up is neglectable + const QRect br = r.boundingRect(); + if (br.isEmpty()) + return; // ignore empty regions because gf_draw_blit2 doesn't like 0x0 dimensions + + // start drawing. + int ret = gf_draw_begin(d->context); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_draw_begin() failed with error code %d", ret); + return; + } + + // blit the changed region from the memory surface to the hardware surface + ret = gf_draw_blit2(d->context, d->memSurface, d->hwSurface, + br.x(), br.y(), br.right(), br.bottom(), br.x(), br.y()); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_draw_blit2() failed with error code %d", ret); + } + + // flush all drawing commands (in our case, a single blit) + ret = gf_draw_flush(d->context); + if (ret != GF_ERR_OK) { + qWarning("QQnxScreen: gf_draw_flush() failed with error code %d", ret); + } + + // tell QNX that we're done drawing. + gf_draw_end(d->context); +} + diff --git a/src/gui/embedded/qkbdvr41xx_qws.h b/src/gui/embedded/qscreenqnx_qws.h index 1a657b9..30312fe 100644 --- a/src/gui/embedded/qkbdvr41xx_qws.h +++ b/src/gui/embedded/qscreenqnx_qws.h @@ -39,10 +39,12 @@ ** ****************************************************************************/ -#ifndef QKBDVR41XX_QWS_H -#define QKBDVR41XX_QWS_H +#ifndef QSCREENQNX_QWS_H +#define QSCREENQNX_QWS_H -#include <QtGui/qkbd_qws.h> +#include <QtGui/qscreen_qws.h> + +#ifndef QT_NO_QWS_QNX QT_BEGIN_HEADER @@ -50,24 +52,31 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -#if !defined(QT_NO_QWS_KEYBOARD) && !defined(QT_NO_QWS_KBD_VR41XX) - -class QWSVr41xxKbPrivate; +struct QQnxScreenContext; -class QWSVr41xxKeyboardHandler : public QWSKeyboardHandler +class QQnxScreen : public QScreen { public: - explicit QWSVr41xxKeyboardHandler(const QString&); - virtual ~QWSVr41xxKeyboardHandler(); + explicit QQnxScreen(int display_id); + ~QQnxScreen(); + + bool initDevice(); + bool connect(const QString &displaySpec); + void disconnect(); + void shutdownDevice(); + void setMode(int,int,int); + bool supportsDepth(int) const; + + void exposeRegion(QRegion r, int changing); private: - QWSVr41xxKbPrivate *d; + QQnxScreenContext * const d; }; -#endif // QT_NO_QWS_KBD_VR41XX - QT_END_NAMESPACE QT_END_HEADER -#endif // QKBDVR41XX_QWS_H +#endif // QT_NO_QWS_QNX + +#endif diff --git a/src/gui/embedded/qwindowsystem_qws.cpp b/src/gui/embedded/qwindowsystem_qws.cpp index 0580198..624ba84 100644 --- a/src/gui/embedded/qwindowsystem_qws.cpp +++ b/src/gui/embedded/qwindowsystem_qws.cpp @@ -39,6 +39,8 @@ ** ****************************************************************************/ +#include "qplatformdefs.h" + #include "qwindowsystem_qws.h" #include "qwsevent_qws.h" #include "qwscommand_qws_p.h" @@ -71,24 +73,26 @@ #include <qdebug.h> -#include <unistd.h> +#include "qkbddriverfactory_qws.h" +#include "qmousedriverfactory_qws.h" + +#include <qbuffer.h> +#include <qdir.h> + +#include <private/qwindowsurface_qws_p.h> +#include <private/qfontengine_qpf_p.h> + +#include "qwindowsystem_p.h" + + #include <stdlib.h> #include <stdio.h> #include <errno.h> #ifndef QT_NO_QWS_MULTIPROCESS -#include <sys/types.h> -#include <sys/socket.h> -#include <sys/ipc.h> -#include <sys/shm.h> -#ifndef Q_OS_DARWIN -# include <sys/sem.h> -#endif #include <sys/param.h> #include <sys/mount.h> #endif -#include <signal.h> -#include <fcntl.h> #if !defined(QT_NO_SOUND) && !defined(Q_OS_DARWIN) #ifdef QT_USE_OLD_QWS_SOUND @@ -101,17 +105,6 @@ #endif #endif -#include "qkbddriverfactory_qws.h" -#include "qmousedriverfactory_qws.h" - -#include <qbuffer.h> -#include <qdir.h> - -#include <private/qwindowsurface_qws_p.h> -#include <private/qfontengine_qpf_p.h> - -#include "qwindowsystem_p.h" - //#define QWS_DEBUG_FONTCLEANUP QT_BEGIN_NAMESPACE @@ -1400,7 +1393,7 @@ void QWSServerPrivate::initServer(int flags) #ifndef QT_NO_QWS_MULTIPROCESS if (!geteuid()) { -#if !defined(Q_OS_FREEBSD) && !defined(Q_OS_SOLARIS) && !defined(Q_OS_DARWIN) && !defined(QT_LINUXBASE) +#if defined(Q_OS_LINUX) && !defined(QT_LINUXBASE) if(mount(0,"/var/shm", "shm", 0, 0)) { /* This just confuses people with 2.2 kernels if (errno != EBUSY) diff --git a/src/gui/graphicsview/graphicsview.pri b/src/gui/graphicsview/graphicsview.pri index 55bb9e0..a3095e7 100644 --- a/src/gui/graphicsview/graphicsview.pri +++ b/src/gui/graphicsview/graphicsview.pri @@ -16,13 +16,15 @@ HEADERS += graphicsview/qgraphicsgridlayout.h \ graphicsview/qgraphicssceneevent.h \ graphicsview/qgraphicssceneindex_p.h \ graphicsview/qgraphicsscenelinearindex_p.h \ + graphicsview/qgraphicstransform.h \ + graphicsview/qgraphicstransform_p.h \ graphicsview/qgraphicsview.h \ graphicsview/qgraphicsview_p.h \ graphicsview/qgraphicswidget.h \ graphicsview/qgraphicswidget_p.h \ - graphicsview/qgridlayoutengine_p.h \ graphicsview/qgraphicseffect.h \ graphicsview/qgraphicseffect_p.h \ + graphicsview/qgridlayoutengine_p.h SOURCES += graphicsview/qgraphicsgridlayout.cpp \ graphicsview/qgraphicsitem.cpp \ @@ -38,6 +40,7 @@ SOURCES += graphicsview/qgraphicsgridlayout.cpp \ graphicsview/qgraphicssceneevent.cpp \ graphicsview/qgraphicssceneindex.cpp \ graphicsview/qgraphicsscenelinearindex.cpp \ + graphicsview/qgraphicstransform.cpp \ graphicsview/qgraphicsview.cpp \ graphicsview/qgraphicswidget.cpp \ graphicsview/qgraphicswidget_p.cpp \ diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 9cb49af..38b80fc 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -135,38 +135,39 @@ \section1 Transformation - QGraphicsItem supports affine transformations in addition to its base - position, pos(). To change the item's transformation, you can pass - a transformation matrix to setTransform() - - Item transformations accumulate from parent to child, so if both a - parent and child item are rotated 90 degrees, the child's total - transformation will be 180 degrees. Similarly, if the item's - parent is scaled to 2x its original size, its children will also - be twice as large. An item's transformation does not affect its - own local geometry; all geometry functions (e.g., contains(), - update(), and all the mapping functions) still operate in local - coordinates. For convenience, QGraphicsItem provides the functions - sceneTransform(), which returns the item's total transformation + QGraphicsItem supports projective transformations in addition to its base + position, pos(). There are several ways to change an item's transformation. + For simple transformations, you can call either of the convenience + functions setRotation() or setScale(), or you can pass any transformation + matrix to setTransform(). For advanced transformation control you also have + the option of setting several combined transformations by calling + setTransformations(). + + Item transformations accumulate from parent to child, so if both a parent + and child item are rotated 90 degrees, the child's total transformation + will be 180 degrees. Similarly, if the item's parent is scaled to 2x its + original size, its children will also be twice as large. An item's + transformation does not affect its own local geometry; all geometry + functions (e.g., contains(), update(), and all the mapping functions) still + operate in local coordinates. For convenience, QGraphicsItem provides the + functions sceneTransform(), which returns the item's total transformation matrix (including its position and all parents' positions and - transformations), and scenePos(), which returns its position in - scene coordinates. To reset an item's matrix, call - resetTransform(). + transformations), and scenePos(), which returns its position in scene + coordinates. To reset an item's matrix, call resetTransform(). - Another way to apply transformation to an item is to use the , or - set the different transformation properties (transformOrigin, - x/y/zRotation, x/yScale, horizontal/verticalShear). Those - properties come in addition to the base transformation + Certain transformation operations produce a different outcome depending on + the order in which they are applied. For example, if you scale an + transform, and then rotate it, you may get a different result than if the + transform was rotated first. However, the order you set the transformation + properties on QGraphicsItem does not affect the resulting transformation; + QGraphicsItem always applies the properties in a fixed, defined order: - The order you set the transformation properties does not affect - the resulting transformation The resulting transformation is - always computed in the following order - - \code - [Origin] [Base] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] - \endcode - - Where [Base] is the stransformation set by setTransform + \list + \o The item's base transform is applied (transform()) + \o The item's transformations list is applied in order (transformations()) + \o The item is rotated relative to its transform origin point (rotation(), transformOriginPoint()) + \o The item is scaled relative to its transform origin point (scale(), transformOriginPoint()) + \endlist \section1 Painting @@ -303,13 +304,12 @@ drop shadow effects and for decoration objects that follow the parent item's geometry without drawing on top of it. - \value ItemUsesExtendedStyleOption The item makes use of either - QStyleOptionGraphicsItem::exposedRect or QStyleOptionGraphicsItem::matrix. + \value ItemUsesExtendedStyleOption The item makes use of either the + exposedRect or matrix member of the QStyleOptionGraphicsItem. Implementers + of QGraphicsItem subclasses should set that flag if this data is required. By default, the exposedRect is initialized to the item's boundingRect and the matrix is untransformed. Enable this flag for more fine-grained values. - Note that QStyleOptionGraphicsItem::levelOfDetail is unaffected by this flag - and is always initialized to 1. - Use QStyleOptionGraphicsItem::levelOfDetailFromTransform for a more + Use QStyleOptionGraphicsItem::levelOfDetailFromTransform() for a more fine-grained value. \value ItemHasNoContents The item does not paint anything (i.e., calling @@ -327,6 +327,10 @@ \value ItemAcceptsInputMethod The item supports input methods typically used for Asian languages. This flag was introduced in Qt 4.6. + + \value ItemAutoDetectsFocusProxy The item will assign any child that + gains input focus as its focus proxy. See also focusProxy(). + This flag was introduced in Qt 4.6. */ /*! @@ -671,19 +675,22 @@ void QGraphicsItemPrivate::updateAncestorFlag(QGraphicsItem::GraphicsItemFlag ch return; } - // Inherit the enabled-state from our parents. - if ((parent && ((parent->d_ptr->ancestorFlags & flag) - || (int(parent->d_ptr->flags & childFlag) == childFlag) + if (parent) { + // Inherit the enabled-state from our parents. + if ((parent->d_ptr->ancestorFlags & flag) + || (int(parent->d_ptr->flags & childFlag) == childFlag) || (childFlag == -1 && parent->d_ptr->handlesChildEvents) - || (childFlag == -2 && parent->d_ptr->filtersDescendantEvents)))) { - enabled = true; - ancestorFlags |= flag; - } - - // Top-level root items don't have any ancestors, so there are no - // ancestor flags either. - if (!parent) + || (childFlag == -2 && parent->d_ptr->filtersDescendantEvents)) { + enabled = true; + ancestorFlags |= flag; + } else { + ancestorFlags &= ~flag; + } + } else { + // Top-level root items don't have any ancestors, so there are no + // ancestor flags either. ancestorFlags = 0; + } } else { // Don't set or propagate the ancestor flag if it's already correct. if (((ancestorFlags & flag) && enabled) || (!(ancestorFlags & flag) && !enabled)) @@ -909,12 +916,12 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent) scene->d_func()->index->itemChange(q, QGraphicsItem::ItemParentChange, newParentVariant); } - if (QGraphicsWidget *w = isWidget ? static_cast<QGraphicsWidget *>(q) : q->parentWidget()) { - // Update the child focus chain; when reparenting a widget that has a + QGraphicsItem *lastSubFocusItem = subFocusItem; + if (subFocusItem) { + // Update the child focus chain; when reparenting an item that has a // focus child, ensure that that focus child clears its focus child // chain from our parents before it's reparented. - if (QGraphicsWidget *focusChild = w->focusWidget()) - focusChild->clearFocus(); + subFocusItem->clearFocus(); } // We anticipate geometry changes. If the item is deleted, it will be @@ -1002,6 +1009,21 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent) resolveDepth(parent ? parent->d_ptr->depth : -1); dirtySceneTransform = 1; + // Restore the sub focus chain. + if (lastSubFocusItem) + lastSubFocusItem->d_ptr->setSubFocus(); + + // Auto-update focus proxy. The closest parent that detects + // focus proxies is updated as the proxy gains or loses focus. + QGraphicsItem *p = newParent; + while (p) { + if (p->d_ptr->flags & QGraphicsItem::ItemAutoDetectsFocusProxy) { + p->setFocusProxy(q); + break; + } + p = p->d_ptr->parent; + } + // Deliver post-change notification q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); @@ -1176,6 +1198,13 @@ QGraphicsItem::~QGraphicsItem() d_ptr->setParentItemHelper(0); delete d_ptr->graphicsEffect; + if (d_ptr->transformData) { + for(int i = 0; i < d_ptr->transformData->graphicsTransforms.size(); ++i) { + QGraphicsTransform *t = d_ptr->transformData->graphicsTransforms.at(i); + static_cast<QGraphicsTransformPrivate *>(t->d_ptr)->item = 0; + delete t; + } + } delete d_ptr->transformData; delete d_ptr; @@ -1234,7 +1263,7 @@ void QGraphicsItem::setGroup(QGraphicsItemGroup *group) Returns a pointer to this item's parent item. If this item does not have a parent, 0 is returned. - \sa setParentItem(), children() + \sa setParentItem(), childItems() */ QGraphicsItem *QGraphicsItem::parentItem() const { @@ -1350,7 +1379,7 @@ const QGraphicsObject *QGraphicsItem::toGraphicsObject() const the parent. You should not \l{QGraphicsScene::addItem()}{add} the item to the scene yourself. - \sa parentItem(), children() + \sa parentItem(), childItems() */ void QGraphicsItem::setParentItem(QGraphicsItem *parent) { @@ -2408,10 +2437,10 @@ bool QGraphicsItem::acceptsHoverEvents() const stays "hovered" until the cursor leaves its area, including its children's areas. - If a parent item handles child events (setHandlesChildEvents()), it will - receive hover move, drag move, and drop events as the cursor passes - through its children, but it does not receive hover enter and hover leave, - nor drag enter and drag leave events on behalf of its children. + If a parent item handles child events, it will receive hover move, + drag move, and drop events as the cursor passes through its + children, but it does not receive hover enter and hover leave, nor + drag enter and drag leave events on behalf of its children. A QGraphicsWidget with window decorations will accept hover events regardless of the value of acceptHoverEvents(). @@ -2558,10 +2587,10 @@ void QGraphicsItem::setHandlesChildEvents(bool enabled) } /*! - Returns true if this item has keyboard input focus; otherwise, returns - false. + Returns true if this item or its \l{focusProxy()}{focus proxy} has keyboard + input focus; otherwise, returns false. - \sa QGraphicsScene::focusItem(), setFocus(), QGraphicsScene::setFocusItem() + \sa focusItem(), setFocus(), QGraphicsScene::setFocusItem() */ bool QGraphicsItem::hasFocus() const { @@ -2572,58 +2601,68 @@ bool QGraphicsItem::hasFocus() const /*! Gives keyboard input focus to this item. The \a focusReason argument will - be passed into any focus event generated by this function; it is used to - give an explanation of what caused the item to get focus. + be passed into any \l{QFocusEvent}{focus event} generated by this function; + it is used to give an explanation of what caused the item to get focus. - Only items that set the ItemIsFocusable flag can accept keyboard focus. + Only enabled items that set the ItemIsFocusable flag can accept keyboard + focus. - If this item is not visible (i.e., isVisible() returns false), not - enabled, not associated with a scene, or if it already has input focus, - this function will do nothing. + If this item is not visible, or not associated with a scene, it will not + gain immediate input focus. However, it will be registered as the preferred + focus item for its subtree of items, should it later become visible. - As a result of calling this function, this item will receive a focus in - event with \a focusReason. If another item already has focus, that item - will first receive a focus out event indicating that it has lost input - focus. + As a result of calling this function, this item will receive a + \l{focusInEvent()}{focus in event} with \a focusReason. If another item + already has focus, that item will first receive a \l{focusOutEvent()} + {focus out event} indicating that it has lost input focus. - \sa clearFocus(), hasFocus() + \sa clearFocus(), hasFocus(), focusItem(), focusProxy() */ void QGraphicsItem::setFocus(Qt::FocusReason focusReason) { - if (!d_ptr->scene || !isEnabled() || hasFocus() || !(d_ptr->flags & ItemIsFocusable)) + // Disabled / unfocusable items cannot accept focus. + if (!isEnabled() || !(d_ptr->flags & QGraphicsItem::ItemIsFocusable)) return; - QGraphicsItem *item = this; - QGraphicsItem *f; - while ((f = item->d_ptr->focusProxy)) - item = f; - if (item->isVisible()) { - // Visible items immediately gain focus from scene. - d_ptr->scene->d_func()->setFocusItemHelper(item, focusReason); - } else if (item->d_ptr->isWidget) { - // Just set up subfocus. - static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget(); + + // Find focus proxy. + QGraphicsItem *f = this; + while (f->d_ptr->focusProxy) + f = f->d_ptr->focusProxy; + + // Return if it already has focus. + if (d_ptr->scene && d_ptr->scene->focusItem() == f) + return; + + // Update the child focus chain. + d_ptr->setSubFocus(); + + // Update the scene's focus item. + if (d_ptr->scene) { + QGraphicsWidget *w = window(); + if (!w || w->isActiveWindow()) { + // Visible items immediately gain focus from scene. + d_ptr->scene->d_func()->setFocusItemHelper(f, focusReason); + } } } /*! Takes keyboard input focus from the item. - If it has focus, a focus out event is sent to this item to tell it that it - is about to lose the focus. + If it has focus, a \l{focusOutEvent()}{focus out event} is sent to this item + to tell it that it is about to lose the focus. Only items that set the ItemIsFocusable flag, or widgets that set an appropriate focus policy, can accept keyboard focus. - \sa setFocus(), QGraphicsWidget::focusPolicy + \sa setFocus(), hasFocus(), QGraphicsWidget::focusPolicy */ void QGraphicsItem::clearFocus() { if (!d_ptr->scene) return; - if (d_ptr->isWidget) { - // Invisible widget items with focus must explicitly clear subfocus. - static_cast<QGraphicsWidget *>(this)->d_func()->clearFocusWidget(); - } + // Invisible items with focus must explicitly clear subfocus. + d_ptr->clearSubFocus(); if (hasFocus()) { // If this item has the scene's input focus, clear it. d_ptr->scene->setFocusItem(0); @@ -2633,10 +2672,10 @@ void QGraphicsItem::clearFocus() /*! \since 4.6 - Returns this item's focus proxy, or 0 if the item - does not have any focus proxy. + Returns this item's focus proxy, or 0 if this item has no + focus proxy. - \sa setFocusProxy() + \sa setFocusProxy(), ItemAutoDetectsFocusProxy, setFocus(), hasFocus() */ QGraphicsItem *QGraphicsItem::focusProxy() const { @@ -2657,7 +2696,10 @@ QGraphicsItem *QGraphicsItem::focusProxy() const such case, keyboard input will be handled by the outermost focus proxy. - \sa focusProxy() + The focus proxy \a item must belong to the same scene as + this item. + + \sa focusProxy(), ItemAutoDetectsFocusProxy, setFocus(), hasFocus() */ void QGraphicsItem::setFocusProxy(QGraphicsItem *item) { @@ -2691,6 +2733,20 @@ void QGraphicsItem::setFocusProxy(QGraphicsItem *item) } /*! + \since 4.6 + + If this item, a child or descendant of this item currently has input + focus, this function will return a pointer to that item. If + no descendant has input focus, 0 is returned. + + \sa hasFocus(), setFocus(), QWidget::focusWidget() +*/ +QGraphicsItem *QGraphicsItem::focusItem() const +{ + return d_ptr->subFocusItem; +} + +/*! \since 4.4 Grabs the mouse input. @@ -2825,7 +2881,7 @@ void QGraphicsItem::ungrabKeyboard() For convenience, you can also call scenePos() to determine the item's position in scene coordinates, regardless of its parent. - \sa x(), y(), setPos(), matrix(), {The Graphics View Coordinate System} + \sa x(), y(), setPos(), transform(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::pos() const { @@ -3027,11 +3083,10 @@ QMatrix QGraphicsItem::matrix() const Returns this item's transformation matrix. - Either the one set by setTransform, or the resulting transformation from - all the transfmation properties - - If no matrix or transformation property has been set, the - identity matrix is returned. + The transformation matrix is combined with the item's rotation(), scale() + and transformations() into a combined transformations for the item. + + The default transformation matrix is an identity matrix. \sa setTransform(), sceneTransform() */ @@ -3045,321 +3100,170 @@ QTransform QGraphicsItem::transform() const /*! \since 4.6 - Returns the rotation around the X axis. - - The default is 0 + Returns the clockwise rotation, in degrees, around the Z axis. The default + value is 0 (i.e., the item is not rotated). - \warning The value doesn't take in account any rotation set with - the setTransform() method. + The rotation is combined with the item's scale(), transform() and + transformations() to map the item's coordinate system to the parent item. - \sa setXRotation(), {Transformations} + \sa setRotation(), transformOriginPoint(), {Transformations} */ -qreal QGraphicsItem::xRotation() const +qreal QGraphicsItem::rotation() const { if (!d_ptr->transformData) return 0; - return d_ptr->transformData->xRotation; -} - -/*! - \since 4.6 - - Sets the rotation around the X axis to \a angle degrees. - - \warning The value doesn't take in account any rotation set with the setTransform() method. - - \sa xRotation(), setTransformOrigin(), {Transformations} -*/ -void QGraphicsItem::setXRotation(qreal angle) -{ - prepareGeometryChange(); - if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->xRotation = angle; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; + return d_ptr->transformData->rotation; } /*! \since 4.6 - Returns the rotation around the Y axis. + Sets the clockwise rotation \a angle, in degrees, around the Z axis. The + default value is 0 (i.e., the item is not rotated). Assigning a negative + value will rotate the item counter-clockwise. Normally the rotation angle + is in the range (-360, 360), but it's also possible to assign values + outside of this range (e.g., a rotation of 370 degrees is the same as a + rotation of 10 degrees). - The default is 0 + The item is rotated around its transform origin point, which by default + is (0, 0). You can select a different transformation origin by calling + setTransformOriginPoint(). - \warning The value doesn't take in account any rotation set with the setTransform() method. + The rotation is combined with the item's scale(), transform() and + transformations() to map the item's coordinate system to the parent item. - \sa setYRotation(), {Transformations} + \sa rotation(), setTransformOriginPoint(), {Transformations} */ -qreal QGraphicsItem::yRotation() const -{ - if (!d_ptr->transformData) - return 0; - return d_ptr->transformData->yRotation; -} - -/*! - \since 4.6 - - Sets the rotation around the Y axis to \a angle degrees. - - \warning The value doesn't take in account any rotation set with the setTransform() method. - - \sa yRotation(), setTransformOrigin() {Transformations} -*/ -void QGraphicsItem::setYRotation(qreal angle) +void QGraphicsItem::setRotation(qreal angle) { prepareGeometryChange(); if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->yRotation = angle; + d_ptr->transformData->rotation = angle; d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; -} - -/*! - \since 4.6 - Returns the rotation around the Z axis. - - The default is 0 - - \warning The value doesn't take in account any rotation set with the setTransform() method. - - \sa setZRotation(), {Transformations} -*/ -qreal QGraphicsItem::zRotation() const -{ - if (!d_ptr->transformData) - return 0; - return d_ptr->transformData->zRotation; + if (d_ptr->isObject) + emit static_cast<QGraphicsObject *>(this)->rotationChanged(); } /*! \since 4.6 - Sets the rotation around the Z axis to \a angle degrees. - - \warning The value doesn't take in account any rotation set with the setTransform() method. - - \sa zRotation(), setTransformOrigin(), {Transformations} -*/ -void QGraphicsItem::setZRotation(qreal angle) -{ - prepareGeometryChange(); - if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->zRotation = angle; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; -} - -/*! - \since 4.6 + Returns the scale factor of the item. The default scale factor is 1.0 + (i.e., the item is not scaled). - This convenience function set the rotation angles around the 3 axes - to \a x, \a y and \a z. + The scale is combined with the item's rotation(), transform() and + transformations() to map the item's coordinate system to the parent item. - \sa setXRotation(), setYRotation(), setZRotation(), {Transformations} + \sa setScale(), rotation(), {Transformations} */ -void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) +qreal QGraphicsItem::scale() const { - prepareGeometryChange(); if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->xRotation = x; - d_ptr->transformData->yRotation = y; - d_ptr->transformData->zRotation = z; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; + return 1.; + return d_ptr->transformData->scale; } /*! \since 4.6 - Returns the scale factor on the X axis. + Sets the scale \a factor of the item. The default scale factor is 1.0 + (i.e., the item is not scaled). A scale factor of 0.0 will collapse the + item to a single point. If you provide a negative scale factor, the + item will be flipped and mirrored (i.e., rotated 180 degrees). - The default is 1 + The item is scaled around its transform origin point, which by default + is (0, 0). You can select a different transformation origin by calling + setTransformOriginPoint(). - \warning The value doesn't take in account any scaling set with the setTransform() method. + The scale is combined with the item's rotation(), transform() and + transformations() to map the item's coordinate system to the parent item. - \sa setXScale(), {Transformations} + \sa scale(), setTransformOriginPoint(), {Transformations} */ -qreal QGraphicsItem::xScale() const -{ - if (!d_ptr->transformData) - return 1; - return d_ptr->transformData->xScale; -} - -/*! - \since 4.6 - - Sets the scale factor on the X axis to \a factor. - - \warning The value doesn't take in account any scaling set with the setTransform() method. - - \sa xScale(), setTransformOrigin(), {Transformations} -*/ -void QGraphicsItem::setXScale(qreal factor) +void QGraphicsItem::setScale(qreal factor) { prepareGeometryChange(); if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->xScale = factor; + d_ptr->transformData->scale = factor; d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; -} - -/*! - \since 4.6 - - Returns the scale factor on the Y axis. - The default is 1 - - \warning The value doesn't take in account any scaling set with the setTransform() method. - - \sa setYScale(), {Transformations} -*/ -qreal QGraphicsItem::yScale() const -{ - if (!d_ptr->transformData) - return 1; - return d_ptr->transformData->yScale; + if (d_ptr->isObject) + emit static_cast<QGraphicsObject *>(this)->scaleChanged(); } -/*! - \since 4.6 - - Sets the scale factor on the Y axis to \a factor. - - \warning The value doesn't take in account any scaling set with the setTransform() method. - - \sa yScale(), setTransformOrigin(), {Transformations} -*/ -void QGraphicsItem::setYScale(qreal factor) -{ - prepareGeometryChange(); - if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->yScale = factor; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; -} /*! \since 4.6 - This convenience function set the scaling factors on X and Y axis to \a sx and \a sy. + Returns a list of graphics transforms that currently apply to this item. - \warning The value doesn't take in account any scaling set with the setTransform() method. + QGraphicsTransform is for applying and controlling a chain of individual + transformation operations on an item. It's particularily useful in + animations, where each transform operation needs to be interpolated + independently, or differently. - \sa setXScale(), setYScale(), {Transformations} -*/ -void QGraphicsItem::setScale(qreal sx, qreal sy) -{ - prepareGeometryChange(); - if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->xScale = sx; - d_ptr->transformData->yScale = sy; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; -} - -/*! - \since 4.6 - - Returns the horizontal shear. - - The default is 0 - - \warning The value doesn't take in account any shearing set with the setTransform() method. - - \sa setHorizontalShear(), {Transformations} -*/ -qreal QGraphicsItem::horizontalShear() const -{ - if (!d_ptr->transformData) - return 0; - return d_ptr->transformData->horizontalShear; -} - -/*! - \since 4.6 - - Sets the horizontal shear to \a shear. - - \warning The value doesn't take in account any shearing set with the setTransform() method. + The transformations are combined with the item's rotation(), scale() and + transform() to map the item's coordinate system to the parent item. - \sa horizontalShear(), {Transformations} + \sa scale(), rotation(), transformOriginPoint(), {Transformations} */ -void QGraphicsItem::setHorizontalShear(qreal shear) +QList<QGraphicsTransform *> QGraphicsItem::transformations() const { - prepareGeometryChange(); if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->horizontalShear = shear; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; + return QList<QGraphicsTransform *>(); + return d_ptr->transformData->graphicsTransforms; } /*! \since 4.6 - Returns the vertical shear. - - The default is 0 - - \warning The value doesn't take in account any shearing set with the setTransform() method. - - \sa setHorizontalShear(), {Transformations} -*/ -qreal QGraphicsItem::verticalShear() const -{ - if (!d_ptr->transformData) - return 0; - return d_ptr->transformData->verticalShear; -} + Sets a list of graphics \a transformations (QGraphicsTransform) that + currently apply to this item. -/*! - \since 4.6 + If all you want is to rotate or scale an item, you should call setRotation() + or setScale() instead. If you want to set an arbitrary transformation on + an item, you can call setTransform(). - Sets the vertical shear to \a shear. + QGraphicsTransform is for applying and controlling a chain of individual + transformation operations on an item. It's particularily useful in + animations, where each transform operation needs to be interpolated + independently, or differently. - \warning The value doesn't take in account any shearing set with the setTransform() method. + The transformations are combined with the item's rotation(), scale() and + transform() to map the item's coordinate system to the parent item. - \sa verticalShear(), {Transformations} + \sa scale(), setTransformOriginPoint(), {Transformations} */ -void QGraphicsItem::setVerticalShear(qreal shear) +void QGraphicsItem::setTransformations(const QList<QGraphicsTransform *> &transformations) { prepareGeometryChange(); if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->verticalShear = shear; + d_ptr->transformData->graphicsTransforms = transformations; + for (int i = 0; i < transformations.size(); ++i) + transformations.at(i)->d_func()->setItem(this); d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; } /*! - \since 4.6 - - This convenience function sets the horizontal shear to \a sh and the vertical shear to \a sv. - - \warning The value doesn't take in account any shearing set with the setTransform() method. - - \sa setHorizontalShear(), setVerticalShear() + \internal */ -void QGraphicsItem::setShear(qreal sh, qreal sv) +void QGraphicsItemPrivate::appendGraphicsTransform(QGraphicsTransform *t) { - prepareGeometryChange(); - if (!d_ptr->transformData) - d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->transformData->horizontalShear = sh; - d_ptr->transformData->verticalShear = sv; - d_ptr->transformData->onlyTransform = false; - d_ptr->dirtySceneTransform = 1; + if (!transformData) + transformData = new QGraphicsItemPrivate::TransformData; + if (!transformData->graphicsTransforms.contains(t)) + transformData->graphicsTransforms.append(t); + + Q_Q(QGraphicsItem); + t->d_func()->setItem(q); + transformData->onlyTransform = false; + dirtySceneTransform = 1; } /*! @@ -3369,9 +3273,9 @@ void QGraphicsItem::setShear(qreal sh, qreal sv) The default is QPointF(0,0). - \sa setTransformOrigin(), {Transformations} + \sa setTransformOriginPoint(), {Transformations} */ -QPointF QGraphicsItem::transformOrigin() const +QPointF QGraphicsItem::transformOriginPoint() const { if (!d_ptr->transformData) return QPointF(0,0); @@ -3383,9 +3287,9 @@ QPointF QGraphicsItem::transformOrigin() const Sets the \a origin point for the transformation in item coordinates. - \sa transformOrigin(), {Transformations} + \sa transformOriginPoint(), {Transformations} */ -void QGraphicsItem::setTransformOrigin(const QPointF &origin) +void QGraphicsItem::setTransformOriginPoint(const QPointF &origin) { prepareGeometryChange(); if (!d_ptr->transformData) @@ -3397,15 +3301,15 @@ void QGraphicsItem::setTransformOrigin(const QPointF &origin) } /*! - \fn void QGraphicsItem::setTransformOrigin(qreal x, qreal y) + \fn void QGraphicsItem::setTransformOriginPoint(qreal x, qreal y) \since 4.6 \overload Sets the origin point for the transformation in item coordinates. - This is equivalent to calling setTransformOrigin(QPointF(\a x, \a y)). + This is equivalent to calling setTransformOriginPoint(QPointF(\a x, \a y)). - \sa setTransformOrigin(), {Transformations} + \sa setTransformOriginPoint(), {Transformations} */ @@ -3682,9 +3586,11 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) to map an item coordiate to a scene coordinate, or mapFromScene() to map from scene coordinates to item coordinates. - \warning using this function doesnt affect the value of the transformation properties + The transformation matrix is combined with the item's rotation(), scale() + and transformations() into a combined transformation that maps the item's + coordinate system to its parent. - \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin(), {The Graphics View Coordinate System}, {Transformations} + \sa transform(), setRotation(), setScale(), setTransformOriginPoint(), {The Graphics View Coordinate System}, {Transformations} */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { @@ -3741,7 +3647,14 @@ void QGraphicsItem::resetTransform() /*! \obsolete - Use setZRotation() instead + + Use + + \code + setRotation(rotation() + angle); + \endcode + + instead. Rotates the current item transformation \a angle degrees clockwise around its origin. To translate around an arbitrary point (x, y), you need to @@ -3751,8 +3664,6 @@ void QGraphicsItem::resetTransform() \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6 - \warning using this functionhas no effect on the zRotation value - \sa setTransform(), transform(), scale(), shear(), translate() */ void QGraphicsItem::rotate(qreal angle) @@ -3762,7 +3673,14 @@ void QGraphicsItem::rotate(qreal angle) /*! \obsolete - Use setScale() instead + + Use + + \code + setTransform(QTransform::fromScale(sx, sy), true); + \endcode + + instead. Scales the current item transformation by (\a sx, \a sy) around its origin. To scale from an arbitrary point (x, y), you need to combine @@ -3772,8 +3690,6 @@ void QGraphicsItem::rotate(qreal angle) \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7 - \warning using this function has no effect on the xScale or yScale value - \sa setTransform(), transform() */ void QGraphicsItem::scale(qreal sx, qreal sy) @@ -3783,11 +3699,16 @@ void QGraphicsItem::scale(qreal sx, qreal sy) /*! \obsolete - Use setShear instead. - Shears the current item transformation by (\a sh, \a sv). + Use - \warning using this function has no effect on the horizontalShear or verticalShear value + \code + setTransform(QTransform().shear(sh, sv), true); + \endcode + + instead. + + Shears the current item transformation by (\a sh, \a sv). \sa setTransform(), transform() */ @@ -3798,7 +3719,13 @@ void QGraphicsItem::shear(qreal sh, qreal sv) /*! \obsolete - Use setPos() or setTransformOrigin() instead. + + Use setPos() or setTransformOriginPoint() instead. For identical + behavior, use + + \code + setTransform(QTransform::fromTranslate(dx, dy), true); + \endcode Translates the current item transformation by (\a dx, \a dy). @@ -4780,6 +4707,34 @@ void QGraphicsItemPrivate::ensureSceneTransform() /*! \internal +*/ +void QGraphicsItemPrivate::setSubFocus() +{ + // Update focus child chain. + QGraphicsItem *item = q_ptr; + QGraphicsItem *parent = item; + bool hidden = !visible; + do { + parent->d_func()->subFocusItem = item; + } while (!parent->isWindow() && (parent = parent->d_ptr->parent) && (!hidden || !parent->d_func()->visible)); +} + +/*! + \internal +*/ +void QGraphicsItemPrivate::clearSubFocus() +{ + // Reset focus child chain. + QGraphicsItem *parent = q_ptr; + do { + if (parent->d_ptr->subFocusItem != q_ptr) + break; + parent->d_ptr->subFocusItem = 0; + } while (!parent->isWindow() && (parent = parent->d_ptr->parent)); +} + +/*! + \internal Tells us if it is a proxy widget */ @@ -6152,7 +6107,7 @@ void QGraphicsItem::dropEvent(QGraphicsSceneDragDropEvent *event) focus in events for this item. The default implementation calls ensureVisible(). - \sa focusOutEvent(), sceneEvent() + \sa focusOutEvent(), sceneEvent(), setFocus() */ void QGraphicsItem::focusInEvent(QFocusEvent *event) { @@ -6164,7 +6119,7 @@ void QGraphicsItem::focusInEvent(QFocusEvent *event) This event handler, for event \a event, can be reimplemented to receive focus out events for this item. The default implementation does nothing. - \sa focusInEvent(), sceneEvent() + \sa focusInEvent(), sceneEvent(), setFocus() */ void QGraphicsItem::focusOutEvent(QFocusEvent *event) { @@ -6549,7 +6504,7 @@ void QGraphicsItem::inputMethodEvent(QInputMethodEvent *event) surrounding text and reconversions. \a query specifies which property is queried. - \sa inputMethodEvent() + \sa inputMethodEvent(), QInputMethodEvent, QInputContext */ QVariant QGraphicsItem::inputMethodQuery(Qt::InputMethodQuery query) const { @@ -6565,6 +6520,39 @@ QVariant QGraphicsItem::inputMethodQuery(Qt::InputMethodQuery query) const } /*! + Returns the current input method hints of this item. + + Input method hints are only relevant for input items. + The hints are used by the input method to indicate how it should operate. + For example, if the Qt::ImhNumbersOnly flag is set, the input method may change + its visual components to reflect that only numbers can be entered. + + The effect may vary between input method implementations. + + \since 4.6 + + \sa setInputMethodHints(), inputMethodQuery(), QInputContext +*/ +Qt::InputMethodHints QGraphicsItem::inputMethodHints() const +{ + Q_D(const QGraphicsItem); + return d->imHints; +} + +/*! + Sets the current input method hints of this item to \a hints. + + \since 4.6 + + \sa inputMethodHints(), inputMethodQuery(), QInputContext +*/ +void QGraphicsItem::setInputMethodHints(Qt::InputMethodHints hints) +{ + Q_D(QGraphicsItem); + d->imHints = hints; +} + +/*! This virtual function is called by QGraphicsItem to notify custom items that some part of the item's state changes. By reimplementing this function, your can react to a change, and in some cases, (depending on \a @@ -6692,7 +6680,7 @@ void QGraphicsItem::prepareGeometryChange() // if someone is connected to the changed signal or the scene has no views. // Note that this has to be done *after* markDirty to ensure that // _q_processDirtyItems is called before _q_emitUpdated. - if ((scenePrivate->connectedSignals & scenePrivate->changedSignalMask) + if ((scenePrivate->connectedSignals[0] & scenePrivate->changedSignalMask) || scenePrivate->views.isEmpty()) { if (d_ptr->hasTranslateOnlySceneTransform()) { d_ptr->scene->update(boundingRect().translated(d_ptr->sceneTransform.dx(), @@ -6905,6 +6893,41 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent \sa pos() */ +/*! + \property QGraphicsObject::rotation + This property holds the rotation of the item in degrees. + + This specifies how many degrees to rotate the item around its transformOrigin. + The default rotation is 0 degrees (i.e. not rotated at all). +*/ + +/*! + \fn QGraphicsObject::rotationChanged() + + This signal gets emitted whenever the roation of the item changes. +*/ + +/*! + \property QGraphicsObject::scale + This property holds the scale of the item. + + A scale of less than 1 means the item will be displayed smaller than + normal, and a scale of greater than 1 means the item will be + displayed larger than normal. A negative scale means the item will + be mirrored. + + By default, items are displayed at a scale of 1 (i.e. at their + normal size). + + Scaling is from the item's transformOrigin. +*/ + +/*! + \fn void QGraphicsObject::scaleChanged() + + This signal is emitted when the scale of the item changes. +*/ + /*! \property QGraphicsObject::enabled @@ -6944,6 +6967,25 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent \sa visible */ +/*! + \fn const QObjectList &QGraphicsObject::children() const + \internal + + This function returns the same value as QObject::children(). It's + provided to differentiate between the obsolete member + QGraphicsItem::children() and QObject::children(). QGraphicsItem now + provides childItems() instead. +*/ + +/*! + \property QGraphicsObject::transformOriginPoint + \brief the transformation origin + + This property sets a specific point in the items coordiante system as the + origin for scale and rotation. + + \sa scale, rotation, QGraphicsItem::transformOriginPoint() +*/ /*! @@ -9827,13 +9869,10 @@ QVariant QGraphicsSimpleTextItem::extension(const QVariant &variant) const setParentItem(). The boundingRect() function of QGraphicsItemGroup returns the - bounding rectangle of all items in the item group. In addition, - item groups have handlesChildEvents() enabled by default, so all - events sent to a member of the group go to the item group (i.e., - selecting one item in a group will select them all). - QGraphicsItemGroup ignores the ItemIgnoresTransformations flag on its - children (i.e., with respect to the geometry of the group item, the - children are treated as if they were transformable). + bounding rectangle of all items in the item group. + QGraphicsItemGroup ignores the ItemIgnoresTransformations flag on + its children (i.e., with respect to the geometry of the group + item, the children are treated as if they were transformable). There are two ways to construct an item group. The easiest and most common approach is to pass a list of items (e.g., all @@ -9919,20 +9958,25 @@ void QGraphicsItemGroup::addToGroup(QGraphicsItem *item) } // COMBINE - // ### Use itemTransform() instead. - QTransform oldSceneMatrix = item->sceneTransform(); + bool ok; + QTransform itemTransform = item->itemTransform(this, &ok); + + if (!ok) { + qWarning("QGraphicsItemGroup::addToGroup: could not find a valid transformation from item to group coordinates"); + return; + } + + QTransform newItemTransform(itemTransform); item->setPos(mapFromItem(item, 0, 0)); item->setParentItem(this); - QTransform newItemTransform(oldSceneMatrix); - newItemTransform *= sceneTransform().inverted(); + + // removing position from translation component of the new transform if (!item->pos().isNull()) newItemTransform *= QTransform::fromTranslate(-item->x(), -item->y()); + item->setTransform(newItemTransform); item->d_func()->setIsMemberOfGroup(true); prepareGeometryChange(); - QTransform itemTransform(item->transform()); - if (!item->pos().isNull()) - itemTransform *= QTransform::fromTranslate(item->x(), item->y()); d->itemsBoundingRect |= itemTransform.mapRect(item->boundingRect() | item->childrenBoundingRect()); update(); } @@ -10283,6 +10327,9 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) case QGraphicsItem::ItemAcceptsInputMethod: str = "ItemAcceptsInputMethod"; break; + case QGraphicsItem::ItemAutoDetectsFocusProxy: + str = "ItemAutoDetectsFocusProxy"; + break; } debug << str; return debug; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index afbaf24..58f1c36 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -72,6 +72,7 @@ class QGraphicsSceneHoverEvent; class QGraphicsSceneMouseEvent; class QGraphicsSceneWheelEvent; class QGraphicsScene; +class QGraphicsTransform; class QGraphicsWidget; class QInputMethodEvent; class QKeyEvent; @@ -100,7 +101,8 @@ public: ItemUsesExtendedStyleOption = 0x200, ItemHasNoContents = 0x400, ItemSendsGeometryChanges = 0x800, - ItemAcceptsInputMethod = 0x1000 + ItemAcceptsInputMethod = 0x1000, + ItemAutoDetectsFocusProxy = 0x2000 // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag. }; Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag) @@ -236,6 +238,8 @@ public: QGraphicsItem *focusProxy() const; void setFocusProxy(QGraphicsItem *item); + QGraphicsItem *focusItem() const; + void grabMouse(); void ungrabMouse(); void grabKeyboard(); @@ -272,34 +276,19 @@ public: void shear(qreal sh, qreal sv); // ### obsolete void translate(qreal dx, qreal dy); // ### obsolete - qreal xRotation() const; - void setXRotation(qreal angle); - - qreal yRotation() const; - void setYRotation(qreal angle); - - qreal zRotation() const; - void setZRotation(qreal angle); - void setRotation(qreal x, qreal y, qreal z); - - qreal xScale() const; - void setXScale(qreal factor); + void setRotation(qreal angle); + qreal rotation() const; - qreal yScale() const; - void setYScale(qreal factor); - void setScale(qreal sx, qreal sy); + void setScale(qreal scale); + qreal scale() const; - qreal horizontalShear() const; - void setHorizontalShear(qreal shear); + QList<QGraphicsTransform *> transformations() const; + void setTransformations(const QList<QGraphicsTransform *> &transformations); - qreal verticalShear() const; - void setVerticalShear(qreal shear); - void setShear(qreal sh, qreal sv); - - QPointF transformOrigin() const; - void setTransformOrigin(const QPointF &origin); - inline void setTransformOrigin(qreal x, qreal y) - { setTransformOrigin(QPointF(x,y)); } + QPointF transformOriginPoint() const; + void setTransformOriginPoint(const QPointF &origin); + inline void setTransformOriginPoint(qreal x, qreal y) + { setTransformOriginPoint(QPointF(x,y)); } virtual void advance(int phase); @@ -393,6 +382,9 @@ public: QVariant data(int key) const; void setData(int key, const QVariant &value); + Qt::InputMethodHints inputMethodHints() const; + void setInputMethodHints(Qt::InputMethodHints hints); + enum { Type = 1, UserType = 65536 @@ -461,6 +453,7 @@ private: friend class QGraphicsSceneBspTreeIndex; friend class QGraphicsSceneBspTreeIndexPrivate; friend class QGraphicsItemEffectSourcePrivate; + friend class QGraphicsTransformPrivate; friend class ::tst_QGraphicsItem; friend bool qt_closestLeaf(const QGraphicsItem *, const QGraphicsItem *); friend bool qt_closestItemFirst(const QGraphicsItem *, const QGraphicsItem *); @@ -526,9 +519,19 @@ class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged) Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged) Q_PROPERTY(qreal z READ zValue WRITE setZValue NOTIFY zChanged) + Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged) + Q_PROPERTY(qreal scale READ scale WRITE setScale NOTIFY scaleChanged) + Q_PROPERTY(QPointF transformOriginPoint READ transformOriginPoint WRITE setTransformOriginPoint) public: QGraphicsObject(QGraphicsItem *parent = 0); + // ### Qt 5: Disambiguate +#ifdef Q_NO_USING_KEYWORD + const QObjectList &children() const { return QObject::children(); } +#else + using QObject::children; +#endif + Q_SIGNALS: void parentChanged(); void opacityChanged(); @@ -537,6 +540,8 @@ Q_SIGNALS: void xChanged(); void yChanged(); void zChanged(); + void rotationChanged(); + void scaleChanged(); protected: QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 310d9ef..4763a4f 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -58,6 +58,8 @@ #include "qpixmapcache.h" #include "qgraphicsview_p.h" #include "qgraphicseffect_p.h" +#include "qgraphicstransform.h" +#include "qgraphicstransform_p.h" #include <QtCore/qpoint.h> @@ -126,6 +128,8 @@ public: siblingIndex(-1), depth(0), focusProxy(0), + subFocusItem(0), + imHints(Qt::ImhNone), acceptedMouseButtons(0x1f), visible(1), explicitlyHidden(0), @@ -196,7 +200,7 @@ public: void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const; void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const; - void updateSceneTransformFromParent(); + virtual void updateSceneTransformFromParent(); // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4. virtual QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const; @@ -204,6 +208,7 @@ public: void setPosHelper(const QPointF &pos); void setTransformHelper(const QTransform &transform); + void appendGraphicsTransform(QGraphicsTransform *t); void setVisibleHelper(bool newVisible, bool explicitly, bool update = true); void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true); bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, @@ -396,6 +401,9 @@ public: || (childrenCombineOpacity() && isFullyTransparent()); } + void setSubFocus(); + void clearSubFocus(); + inline QTransform transformToParent() const; inline void ensureSortedChildren(); @@ -417,8 +425,10 @@ public: int siblingIndex; int depth; QGraphicsItem *focusProxy; + QGraphicsItem *subFocusItem; + Qt::InputMethodHints imHints; - // Packed 32 bytes + // Packed 32 bits quint32 acceptedMouseButtons : 5; quint32 visible : 1; quint32 explicitlyHidden : 1; @@ -446,7 +456,7 @@ public: // New 32 bits quint32 fullUpdatePending : 1; - quint32 flags : 12; + quint32 flags : 14; quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; @@ -461,54 +471,45 @@ public: quint32 sceneTransformTranslateOnly : 1; quint32 notifyBoundingRectChanged : 1; quint32 notifyInvalidated : 1; - quint32 unused : 4; // feel free to use + quint32 unused : 3; // feel free to use // Optional stacking order int globalStackingOrder; QGraphicsItem *q_ptr; }; -struct QGraphicsItemPrivate::TransformData { +struct QGraphicsItemPrivate::TransformData +{ QTransform transform; - qreal xScale; - qreal yScale; - qreal xRotation; - qreal yRotation; - qreal zRotation; - qreal horizontalShear; - qreal verticalShear; + qreal scale; + qreal rotation; qreal xOrigin; qreal yOrigin; + QList<QGraphicsTransform *> graphicsTransforms; bool onlyTransform; TransformData() : - xScale(1.0), yScale(1.0), xRotation(0.0), yRotation(0.0), zRotation(0.0), - horizontalShear(0.0), verticalShear(0.0), xOrigin(0.0), yOrigin(0.0), + scale(1.0), rotation(0.0), + xOrigin(0.0), yOrigin(0.0), onlyTransform(true) - {} + { } QTransform computedFullTransform(QTransform *postmultiplyTransform = 0) const { if (onlyTransform) { - if (!postmultiplyTransform) - return transform; - if (postmultiplyTransform->isIdentity()) + if (!postmultiplyTransform || postmultiplyTransform->isIdentity()) return transform; if (transform.isIdentity()) return *postmultiplyTransform; - QTransform x(transform); - x *= *postmultiplyTransform; - return x; + return transform * *postmultiplyTransform; } QTransform x(transform); - if (xOrigin != 0 || yOrigin != 0) - x *= QTransform::fromTranslate(xOrigin, yOrigin); - x.rotate(xRotation, Qt::XAxis); - x.rotate(yRotation, Qt::YAxis); - x.rotate(zRotation, Qt::ZAxis); - x.shear(horizontalShear, verticalShear); - x.scale(xScale, yScale); + for (int i = 0; i < graphicsTransforms.size(); ++i) + graphicsTransforms.at(i)->applyTo(&x); + x.translate(xOrigin, yOrigin); + x.rotate(rotation, Qt::ZAxis); + x.scale(scale, scale); x.translate(-xOrigin, -yOrigin); if (postmultiplyTransform) x *= *postmultiplyTransform; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 5f214c9..7d0876f 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -345,7 +345,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() // the optimization that items send updates directly to the views, but it // needs to happen in order to keep compatibility with the behavior from // Qt 4.4 and backward. - if (connectedSignals & changedSignalMask) { + if (connectedSignals[0] & changedSignalMask) { for (int i = 0; i < views.size(); ++i) { QGraphicsView *view = views.at(i); if (!view->d_func()->connectedToScene) { @@ -485,6 +485,8 @@ void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item) index->removeItem(item); } + item->d_ptr->clearSubFocus(); + if (!item->d_ptr->inDestructor && item == tabFocusFirst) { QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item); widget->d_func()->fixFocusChainBeforeReparenting(0, 0); @@ -573,17 +575,34 @@ void QGraphicsScenePrivate::setFocusItemHelper(QGraphicsItem *item, Q_Q(QGraphicsScene); if (item == focusItem) return; + + // Clear focus if asked to set focus on something that can't + // accept input focus. if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable) || !item->isVisible() || !item->isEnabled())) { item = 0; } + // Set focus on the scene if an item requests focus. if (item) { q->setFocus(focusReason); if (item == focusItem) return; } + // Auto-update focus proxy. The closest parent that detects + // focus proxies is updated as the proxy gains or loses focus. + if (item) { + QGraphicsItem *p = item->d_ptr->parent; + while (p) { + if (p->d_ptr->flags & QGraphicsItem::ItemAutoDetectsFocusProxy) { + p->setFocusProxy(item); + break; + } + p = p->d_ptr->parent; + } + } + if (focusItem) { QFocusEvent event(QEvent::FocusOut, focusReason); lastFocusItem = focusItem; @@ -603,11 +622,6 @@ void QGraphicsScenePrivate::setFocusItemHelper(QGraphicsItem *item, } if (item) { - if (item->isWidget()) { - // Update focus child chain. - static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget(); - } - focusItem = item; QFocusEvent event(QEvent::FocusIn, focusReason); sendEvent(item, &event); @@ -2343,6 +2357,15 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // Deliver post-change notification item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); + // Auto-activate the first inactive window if the scene is active. + if (d->activationRefCount > 0 && !d->activeWindow && item->isWindow()) + setActiveWindow(static_cast<QGraphicsWidget *>(item)); + + // Ensure that newly added items that have subfocus set, gain + // focus automatically if there isn't a focus item already. + if (!d->focusItem && item->focusItem()) + item->focusItem()->setFocus(); + d->updateInputMethodSensitivityInViews(); } @@ -2877,7 +2900,7 @@ void QGraphicsScene::update(const QRectF &rect) // Check if anyone's connected; if not, we can send updates directly to // the views. Otherwise or if there are no views, use old behavior. - bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty(); + bool directUpdates = !(d->connectedSignals[0] & d->changedSignalMask) && !d->views.isEmpty(); if (rect.isNull()) { d->updateAll = true; d->updatedRects.clear(); @@ -3458,7 +3481,7 @@ void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent) text = toolTipItem->toolTip(); point = helpEvent->screenPos(); } - QToolTip::showText(point, text); + QToolTip::showText(point, text, helpEvent->widget()); helpEvent->setAccepted(!text.isEmpty()); #endif } @@ -3557,8 +3580,7 @@ void QGraphicsScenePrivate::leaveScene() { Q_Q(QGraphicsScene); #ifndef QT_NO_TOOLTIP - // Remove any tooltips - QToolTip::showText(QPoint(), QString()); + QToolTip::hideText(); #endif // Send HoverLeave events to all existing hover items, topmost first. QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender()); @@ -3661,6 +3683,13 @@ void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent) void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { Q_D(QGraphicsScene); + if (d->mouseGrabberItems.isEmpty()) { + // Dispatch hover events + QGraphicsSceneHoverEvent hover; + _q_hoverFromMouseEvent(&hover, mouseEvent); + d->dispatchHoverEvent(&hover); + } + d->mousePressEventHandler(mouseEvent); } @@ -4491,7 +4520,7 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b if (removingItemFromScene) { // Note that this function can be called from the item's destructor, so // do NOT call any virtual functions on it within this block. - if ((connectedSignals & changedSignalMask) || views.isEmpty()) { + if ((connectedSignals[0] & changedSignalMask) || views.isEmpty()) { // This block of code is kept for compatibility. Since 4.5, by default // QGraphicsView does not connect the signal and we use the below // method of delivering updates. @@ -4641,7 +4670,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool // Process item. if (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint) { - const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); + const bool useCompatUpdate = views.isEmpty() || (connectedSignals[0] & changedSignalMask); const QRectF itemBoundingRect = adjustedItemEffectiveBoundingRect(item); if (useCompatUpdate && !itemIsUntransformable && qFuzzyIsNull(item->boundingRegionGranularity())) { @@ -4745,7 +4774,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool background has been drawn, and before the foreground has been drawn. All painting is done in \e scene coordinates. Before drawing each item, the painter must be transformed using - QGraphicsItem::sceneMatrix(). + QGraphicsItem::sceneTransform(). The \a options parameter is the list of style option objects for each item in \a items. The \a numItems parameter is the number of diff --git a/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp b/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp index 78a77aa..55a493d 100644 --- a/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp +++ b/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp @@ -525,7 +525,7 @@ QGraphicsSceneBspTreeIndex::~QGraphicsSceneBspTreeIndex() } /*! - \reimp + \internal Clear the all the BSP index. */ void QGraphicsSceneBspTreeIndex::clear() @@ -566,7 +566,7 @@ void QGraphicsSceneBspTreeIndex::removeItem(QGraphicsItem *item) } /*! - \reimp + \internal Update the BSP when the \a item 's bounding rect has changed. */ void QGraphicsSceneBspTreeIndex::prepareBoundingRectChange(const QGraphicsItem *item) @@ -682,7 +682,7 @@ void QGraphicsSceneBspTreeIndex::setBspTreeDepth(int depth) } /*! - \reimp + \internal This method react to the \a rect change of the scene and reset the BSP tree index. @@ -695,11 +695,10 @@ void QGraphicsSceneBspTreeIndex::updateSceneRect(const QRectF &rect) } /*! - \reimp + \internal This method react to the \a change of the \a item and use the \a value to update the BSP tree if necessary. - */ void QGraphicsSceneBspTreeIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value) { diff --git a/src/gui/graphicsview/qgraphicssceneevent.cpp b/src/gui/graphicsview/qgraphicssceneevent.cpp index 53019f2..92af0cc 100644 --- a/src/gui/graphicsview/qgraphicssceneevent.cpp +++ b/src/gui/graphicsview/qgraphicssceneevent.cpp @@ -1476,7 +1476,7 @@ void QGraphicsSceneDragDropEvent::acceptProposedAction() /*! Returns the action that was performed in this drag and drop. This should be set by the receiver of the drop and is - returned by QDrag::start(). + returned by QDrag::exec(). \sa setDropAction(), acceptProposedAction() */ diff --git a/src/gui/graphicsview/qgraphicstransform.cpp b/src/gui/graphicsview/qgraphicstransform.cpp new file mode 100644 index 0000000..778cd94 --- /dev/null +++ b/src/gui/graphicsview/qgraphicstransform.cpp @@ -0,0 +1,573 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QGraphicsTransform + \brief The QGraphicsTransform class is an abstract base class for building + advanced transformations on QGraphicsItems. + \since 4.6 + + As an alternative to QGraphicsItem::transform, QGraphicsTransform lets you + create and control advanced transformations that can be configured + independently using specialized properties. + + QGraphicsItem allows you to assign any number of QGraphicsTransform + instances to one QGraphicsItem. Each QGraphicsTransform is applied in + order, one at a time, to the QGraphicsItem it's assigned to. + + QGraphicsTransform is particularily useful for animations. Whereas + QGraphicsItem::setTransform() lets you assign any transform directly to an + item, there is no direct way to interpolate between two different + transformations (e.g., when transitioning between two states, each for + which the item has a different arbitrary transform assigned). Using + QGraphicsTransform you can interpolate the property values of each + independent transformation. The resulting operation is then combined into a + single transform which is applied to QGraphicsItem. + + If you want to create your own configurable transformation, you can create + a subclass of QGraphicsTransform (or any or the existing subclasses), and + reimplement the pure virtual applyTo() function, which takes a pointer to a + QTransform. Each operation you would like to apply should be exposed as + properties (e.g., customTransform->setVerticalShear(2.5)). Inside you + reimplementation of applyTo(), you can modify the provided transform + respectively. + + QGraphicsTransform can be used together with QGraphicsItem::setTransform(), + QGraphicsItem::setRotation(), and QGraphicsItem::setScale(). + + \sa QGraphicsItem::transform(), QGraphicsScale, QGraphicsRotation, QGraphicsRotation3D +*/ + +#include "qgraphicstransform.h" +#include "qgraphicsitem_p.h" +#include "qgraphicstransform_p.h" +#include <QDebug> + +#include <math.h> +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +QT_BEGIN_NAMESPACE + +void QGraphicsTransformPrivate::setItem(QGraphicsItem *i) +{ + if (item == i) + return; + + if (item) { + Q_Q(QGraphicsTransform); + QGraphicsItemPrivate *d_ptr = item->d_ptr; + + item->prepareGeometryChange(); + Q_ASSERT(d_ptr->transformData); + d_ptr->transformData->graphicsTransforms.removeAll(q); + d_ptr->dirtySceneTransform = 1; + item = 0; + } + + item = i; +} + +void QGraphicsTransformPrivate::updateItem(QGraphicsItem *item) +{ + item->prepareGeometryChange(); + item->d_ptr->dirtySceneTransform = 1; +} + +/*! + Constructs a new QGraphicsTransform with the given \a parent. +*/ +QGraphicsTransform::QGraphicsTransform(QObject *parent) + : QObject(*new QGraphicsTransformPrivate, parent) +{ +} + +/*! + Destroys the graphics transform. +*/ +QGraphicsTransform::~QGraphicsTransform() +{ + Q_D(QGraphicsTransform); + d->setItem(0); +} + +/*! + \internal +*/ +QGraphicsTransform::QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent) + : QObject(p, parent) +{ +} + +/*! + Applies this transformation to an identity transform, and returns the + resulting transform. + + This is equivalent to passing an identity transform to applyTo(). + + \sa applyTo() +*/ +QTransform QGraphicsTransform::transform() const +{ + QTransform t; + applyTo(&t); + return t; +} + +/*! + \fn void QGraphicsTransform::applyTo(QTransform *transform) const + + This pure virtual method has to be reimplemented in derived classes. + + It applies this transformation to \a transform. + + \sa QGraphicsItem::transform() +*/ + +/*! + Notifies that this transform operation has changed its parameters in such a + way that applyTo() will return a different result than before. + + When implementing you own custom graphics transform, you must call this + function every time you change a parameter, to let QGraphicsItem know that + its transformation needs to be updated. + + \sa applyTo() +*/ +void QGraphicsTransform::update() +{ + Q_D(QGraphicsTransform); + if (d->item) + d->updateItem(d->item); +} + +/*! + \class QGraphicsScale + \brief The QGraphicsScale class provides a scale transformation. + \since 4.6 + + QGraphicsScene provides certain parameters to help control how the scale + should be applied. + + The origin is the point that the item is scaled from (i.e., it stays fixed + relative to the parent as the rest of the item grows). By default the + origin is QPointF(0, 0). + + The two parameters xScale and yScale describe the scale factors to apply in + horizontal and vertical direction. They can take on any value, including 0 + (to collapse the item to a point) or negativate value. A negative xScale + value will mirror the item horizontally. A negative yScale value will flip + the item vertically. + + \sa QGraphicsTransform, QGraphicsItem::setScale(), QTransform::scale() +*/ + +class QGraphicsScalePrivate : public QGraphicsTransformPrivate +{ +public: + QGraphicsScalePrivate() + : xScale(1), yScale(1) {} + QPointF origin; + qreal xScale; + qreal yScale; +}; + +/*! + Constructs an empty QGraphicsScale object with the given \a parent. +*/ +QGraphicsScale::QGraphicsScale(QObject *parent) + : QGraphicsTransform(*new QGraphicsScalePrivate, parent) +{ +} + +/*! + Destroys the graphics scale. +*/ +QGraphicsScale::~QGraphicsScale() +{ +} + +/*! + \property QGraphicsScale::origin + \brief The QGraphicsScene class provides the origin of the scale. + + All scaling will be done relative to this point (i.e., this point + will stay fixed, relative to the parent, when the item is scaled). + + \sa xScale, yScale +*/ +QPointF QGraphicsScale::origin() const +{ + Q_D(const QGraphicsScale); + return d->origin; +} +void QGraphicsScale::setOrigin(const QPointF &point) +{ + Q_D(QGraphicsScale); + d->origin = point; + update(); + emit originChanged(); +} + +/*! + \property QGraphicsScale::xScale + \brief the horizontal scale factor. + + The scale factor can be any real number; the default value is 1.0. If you + set the factor to 0.0, the item will be collapsed to a single point. If you + provide a negative value, the item will be mirrored horizontally around its + origin. + + \sa yScale, origin +*/ +qreal QGraphicsScale::xScale() const +{ + Q_D(const QGraphicsScale); + return d->xScale; +} +void QGraphicsScale::setXScale(qreal scale) +{ + Q_D(QGraphicsScale); + if (d->xScale == scale) + return; + d->xScale = scale; + update(); + emit scaleChanged(); +} + +/*! + \property QGraphicsScale::yScale + \brief the vertical scale factor. + + The scale factor can be any real number; the default value is 1.0. If you + set the factor to 0.0, the item will be collapsed to a single point. If you + provide a negative value, the item will be flipped vertically around its + origin. + + \sa xScale, origin +*/ +qreal QGraphicsScale::yScale() const +{ + Q_D(const QGraphicsScale); + return d->yScale; +} +void QGraphicsScale::setYScale(qreal scale) +{ + Q_D(QGraphicsScale); + if (d->yScale == scale) + return; + d->yScale = scale; + update(); + emit scaleChanged(); +} + +/*! + \reimp +*/ +void QGraphicsScale::applyTo(QTransform *transform) const +{ + Q_D(const QGraphicsScale); + transform->translate(d->origin.x(), d->origin.y()); + transform->scale(d->xScale, d->yScale); + transform->translate(-d->origin.x(), -d->origin.y()); +} + +/*! + \fn QGraphicsScale::originChanged() + + QGraphicsScale emits this signal when its origin changes. + + \sa QGraphicsScale::origin +*/ + +/*! + \fn QGraphicsScale::scaleChanged() + + This signal is emitted whenever the xScale or yScale of the object + changes. + + \sa QGraphicsScale::xScale, QGraphicsScale::yScale +*/ + +/*! + \class QGraphicsRotation + \brief The QGraphicsRotation class provides a rotation transformation. + \since 4.6 + + QGraphicsRotation provides certain parameters to help control how the + rotation should be applied. + + The origin is the point that the item is rotated around (i.e., it stays + fixed relative to the parent as the rest of the item is rotated). By + default the origin is QPointF(0, 0). + + The angle property provides the number of degrees to rotate the item + clockwise around the origin. This value also be negative, indicating a + counter-clockwise rotation. For animation purposes it may also be useful to + provide rotation angles exceeding (-360, 360) degrees, for instance to + animate how an item rotates several times. + + \sa QGraphicsTransform, QGraphicsItem::setRotation(), QTransform::rotate() +*/ + +class QGraphicsRotationPrivate : public QGraphicsTransformPrivate +{ +public: + QGraphicsRotationPrivate() + : angle(0) {} + QPointF origin; + qreal originY; + qreal angle; +}; + +/*! + Constructs a new QGraphicsRotation with the given \a parent. +*/ +QGraphicsRotation::QGraphicsRotation(QObject *parent) + : QGraphicsTransform(*new QGraphicsRotationPrivate, parent) +{ +} + +/*! + \internal +*/ +QGraphicsRotation::QGraphicsRotation(QGraphicsRotationPrivate &p, QObject *parent) + : QGraphicsTransform(p, parent) +{ +} + +/*! + Destroys the graphics rotation. +*/ +QGraphicsRotation::~QGraphicsRotation() +{ +} + +/*! + \property QGraphicsRotation::origin + \brief the origin of the rotation. + + All rotations will be done relative to this point (i.e., this point + will stay fixed, relative to the parent, when the item is rotated). + + \sa angle +*/ +QPointF QGraphicsRotation::origin() const +{ + Q_D(const QGraphicsRotation); + return d->origin; +} +void QGraphicsRotation::setOrigin(const QPointF &point) +{ + Q_D(QGraphicsRotation); + d->origin = point; + update(); + emit originChanged(); +} + +/*! + \property QGraphicsRotation::angle + \brief the angle for clockwise rotation, in degrees. + + The angle can be any real number; the default value is 0.0. A value of 180 + will rotate 180 degrees, clockwise. If you provide a negative number, the + item will be rotated counter-clockwise. Normally the rotation angle will be + in the range (-360, 360), but you can also provide numbers outside of this + range (e.g., a angle of 370 degrees gives the same result as 10 degrees). + + \sa origin +*/ +qreal QGraphicsRotation::angle() const +{ + Q_D(const QGraphicsRotation); + return d->angle; +} +void QGraphicsRotation::setAngle(qreal angle) +{ + Q_D(QGraphicsRotation); + if (d->angle == angle) + return; + d->angle = angle; + update(); + emit angleChanged(); +} + +/*! + \reimp +*/ +void QGraphicsRotation::applyTo(QTransform *t) const +{ + Q_D(const QGraphicsRotation); + if (d->angle) { + t->translate(d->origin.x(), d->origin.y()); + t->rotate(d->angle); + t->translate(-d->origin.x(), -d->origin.y()); + } +} + +/*! + \fn QGraphicsRotation::originChanged() + + This signal is emitted whenever the origin has changed. + + \sa QGraphicsRotation::origin +*/ + +/*! + \fn void QGraphicsRotation::angleChanged() + + This signal is emitted whenever the angle has changed. + + \sa QGraphicsRotation::angle +*/ + +/*! + \class QGraphicsRotation3D + \brief The QGraphicsRotation3D class provides rotation in 3 dimensions. + \since 4.6 + + QGraphicsRotation3D extends QGraphicsRotation with the ability to rotate + around a given axis. + + You can provide the desired axis by assigning a QVector3D to the axis + property. The angle property, which is provided by QGraphicsRotation, now + describes the number of degrees to rotate around this axis. + + By default the axis is (0, 0, 1), giving QGraphicsRotation3D the same + default behavior as QGraphicsRotation (i.e., rotation around the Z axis). + + \sa QGraphicsTransform, QGraphicsItem::setRotation(), QTransform::rotate() +*/ + +class QGraphicsRotation3DPrivate : public QGraphicsRotationPrivate +{ +public: + QGraphicsRotation3DPrivate() {} + + QVector3D axis; +}; + +/*! + Constructs a new QGraphicsRotation3D with the given \a parent. +*/ +QGraphicsRotation3D::QGraphicsRotation3D(QObject *parent) + : QGraphicsRotation(*new QGraphicsRotation3DPrivate, parent) +{ +} + +/*! + Destroys the 3D graphics rotation. +*/ +QGraphicsRotation3D::~QGraphicsRotation3D() +{ +} + +/*! + \property QGraphicsRotation3D::axis + \brief a rotation axis, specified by a vector in 3D space. + + This can be any axis in 3D space. By default the axis is (0, 0, 1), + which is aligned with the Z axis and provides the same behavior + for the rotation angle as QGraphicsRotation. If you provide another + axis, QGraphicsRotation3D will provide a transformation that rotates + around this axis. For example, if you would like to rotate an item + around its X axis, you could pass (1, 0, 0) as the axis. + + \sa QTransform, QGraphicsRotation::angle +*/ +QVector3D QGraphicsRotation3D::axis() +{ + Q_D(QGraphicsRotation3D); + return d->axis; +} +void QGraphicsRotation3D::setAxis(const QVector3D &axis) +{ + Q_D(QGraphicsRotation3D); + d->axis = axis; + update(); +} + +static const qreal inv_dist_to_plane = 1. / 1024.; + +/*! + \reimp +*/ +void QGraphicsRotation3D::applyTo(QTransform *t) const +{ + Q_D(const QGraphicsRotation3D); + + if (d->angle == 0. || + (d->axis.z() == 0. && d->axis.y() == 0 && d->axis.x() == 0)) + return; + + qreal rad = d->angle * 2. * M_PI / 360.; + qreal c = ::cos(rad); + qreal s = ::sin(rad); + + qreal x = d->axis.x(); + qreal y = d->axis.y(); + qreal z = d->axis.z(); + + qreal len = x * x + y * y + z * z; + if (len != 1.) { + len = 1./::sqrt(len); + x *= len; + y *= len; + z *= len; + } + + t->translate(d->origin.x(), d->origin.y()); + *t = QTransform(x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s*inv_dist_to_plane, + y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s*inv_dist_to_plane, + 0, 0, 1) * *t; + t->translate(-d->origin.x(), -d->origin.y()); +} + +/*! + \fn void QGraphicsRotation3D::axisChanged() + + This signal is emitted whenever the axis of the object changes. +*/ + +#include "moc_qgraphicstransform.cpp" + +QT_END_NAMESPACE diff --git a/src/gui/graphicsview/qgraphicstransform.h b/src/gui/graphicsview/qgraphicstransform.h new file mode 100644 index 0000000..d7c07d0 --- /dev/null +++ b/src/gui/graphicsview/qgraphicstransform.h @@ -0,0 +1,169 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QGRAPHICSTRANSFORM_H +#define QGRAPHICSTRANSFORM_H + +#include <QtCore/QObject> +#include <QtGui/QTransform> +#include <QtGui/QVector3D> + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class QGraphicsItem; +class QGraphicsTransformPrivate; + +class Q_GUI_EXPORT QGraphicsTransform : public QObject +{ + Q_OBJECT +public: + QGraphicsTransform(QObject *parent = 0); + ~QGraphicsTransform(); + + QTransform transform() const; + virtual void applyTo(QTransform *transform) const = 0; + +protected Q_SLOTS: + void update(); + +protected: + QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent); + +private: + friend class QGraphicsItem; + friend class QGraphicsItemPrivate; + Q_DECLARE_PRIVATE(QGraphicsTransform) +}; + +class QGraphicsScalePrivate; + +class Q_GUI_EXPORT QGraphicsScale : public QGraphicsTransform +{ + Q_OBJECT + + Q_PROPERTY(QPointF origin READ origin WRITE setOrigin NOTIFY originChanged) + Q_PROPERTY(qreal xScale READ xScale WRITE setXScale NOTIFY scaleChanged) + Q_PROPERTY(qreal yScale READ yScale WRITE setYScale NOTIFY scaleChanged) +public: + QGraphicsScale(QObject *parent = 0); + ~QGraphicsScale(); + + QPointF origin() const; + void setOrigin(const QPointF &point); + + qreal xScale() const; + void setXScale(qreal); + + qreal yScale() const; + void setYScale(qreal); + + void applyTo(QTransform *transform) const; + +Q_SIGNALS: + void originChanged(); + void scaleChanged(); + +private: + Q_DECLARE_PRIVATE(QGraphicsScale) +}; + +class QGraphicsRotationPrivate; + +class Q_GUI_EXPORT QGraphicsRotation : public QGraphicsTransform +{ + Q_OBJECT + + Q_PROPERTY(QPointF origin READ origin WRITE setOrigin NOTIFY originChanged) + Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged) +public: + QGraphicsRotation(QObject *parent = 0); + ~QGraphicsRotation(); + + QPointF origin() const; + void setOrigin(const QPointF &point); + + qreal angle() const; + void setAngle(qreal); + + void applyTo(QTransform *transform) const; + +Q_SIGNALS: + void originChanged(); + void angleChanged(); + +protected: + QGraphicsRotation(QGraphicsRotationPrivate &p, QObject *parent); +private: + Q_DECLARE_PRIVATE(QGraphicsRotation) +}; + +class QGraphicsRotation3DPrivate; + +class Q_GUI_EXPORT QGraphicsRotation3D : public QGraphicsRotation +{ + Q_OBJECT + + Q_PROPERTY(QVector3D axis READ axis WRITE setAxis NOTIFY axisChanged) +public: + QGraphicsRotation3D(QObject *parent = 0); + ~QGraphicsRotation3D(); + + QVector3D axis(); + void setAxis(const QVector3D &axis); + + void applyTo(QTransform *transform) const; + +Q_SIGNALS: + void axisChanged(); + +private: + Q_DECLARE_PRIVATE(QGraphicsRotation3D) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QFXTRANSFORM_H diff --git a/src/gui/graphicsview/qgraphicstransform_p.h b/src/gui/graphicsview/qgraphicstransform_p.h new file mode 100644 index 0000000..2d36eda --- /dev/null +++ b/src/gui/graphicsview/qgraphicstransform_p.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QGRAPHICSTRANSFORM_P_H +#define QGRAPHICSTRANSFORM_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. This header +// file may change from version to version without notice, or even be removed. +// +// We mean it. +// + +#include "private/qobject_p.h" + +class QGraphicsItem; + +class QGraphicsTransformPrivate : public QObjectPrivate { +public: + Q_DECLARE_PUBLIC(QGraphicsTransform) + + QGraphicsTransformPrivate() + : QObjectPrivate(), item(0) {} + + QGraphicsItem *item; + + void setItem(QGraphicsItem *item); + static void updateItem(QGraphicsItem *item); +}; + +#endif // QGRAPHICSTRANSFORM_P_H diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 53b044c..ca55f2e 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -97,8 +97,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < setViewport(new QGLWidget). QGraphicsView takes ownership of the viewport widget. - QGraphicsView supports affine transformations, using QMatrix. You can - either pass a matrix to setMatrix(), or you can call one of the + QGraphicsView supports affine transformations, using QTransform. You can + either pass a matrix to setTransform(), or you can call one of the convenience functions rotate(), scale(), translate() or shear(). The most two common transformations are scaling, which is used to implement zooming, and rotation. QGraphicsView keeps the center of the view fixed @@ -1583,7 +1583,7 @@ void QGraphicsView::setSceneRect(const QRectF &rect) Returns the current transformation matrix for the view. If no current transformation is set, the identity matrix is returned. - \sa setMatrix(), rotate(), scale(), shear(), translate() + \sa setMatrix(), transform(), rotate(), scale(), shear(), translate() */ QMatrix QGraphicsView::matrix() const { @@ -1615,7 +1615,7 @@ QMatrix QGraphicsView::matrix() const a view coordinate to a floating point scene coordinate, or mapFromScene() to map from floating point scene coordinates to view coordinates. - \sa matrix(), rotate(), scale(), shear(), translate() + \sa matrix(), setTransform(), rotate(), scale(), shear(), translate() */ void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine) { @@ -1624,6 +1624,8 @@ void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine) /*! Resets the view transformation matrix to the identity matrix. + + \sa resetTransform() */ void QGraphicsView::resetMatrix() { @@ -1633,7 +1635,7 @@ void QGraphicsView::resetMatrix() /*! Rotates the current view transformation \a angle degrees clockwise. - \sa setMatrix(), matrix(), scale(), shear(), translate() + \sa setTransform(), transform(), scale(), shear(), translate() */ void QGraphicsView::rotate(qreal angle) { @@ -1646,7 +1648,7 @@ void QGraphicsView::rotate(qreal angle) /*! Scales the current view transformation by (\a sx, \a sy). - \sa setMatrix(), matrix(), rotate(), shear(), translate() + \sa setTransform(), transform(), rotate(), shear(), translate() */ void QGraphicsView::scale(qreal sx, qreal sy) { @@ -1659,7 +1661,7 @@ void QGraphicsView::scale(qreal sx, qreal sy) /*! Shears the current view transformation by (\a sh, \a sv). - \sa setMatrix(), matrix(), rotate(), scale(), translate() + \sa setTransform(), transform(), rotate(), scale(), translate() */ void QGraphicsView::shear(qreal sh, qreal sv) { @@ -1672,7 +1674,7 @@ void QGraphicsView::shear(qreal sh, qreal sv) /*! Translates the current view transformation by (\a dx, \a dy). - \sa setMatrix(), matrix(), rotate(), shear() + \sa setTransform(), transform(), rotate(), shear() */ void QGraphicsView::translate(qreal dx, qreal dy) { @@ -1830,7 +1832,7 @@ void QGraphicsView::ensureVisible(const QGraphicsItem *item, int xmargin, int ym If \a rect is empty, or if the viewport is too small, this function will do nothing. - \sa setMatrix(), ensureVisible(), centerOn() + \sa setTransform(), ensureVisible(), centerOn() */ void QGraphicsView::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode) { diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 86c0b48..3ea80ce 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -1716,49 +1716,18 @@ void QGraphicsWidget::setFocusPolicy(Qt::FocusPolicy policy) /*! If this widget, a child or descendant of this widget currently has input focus, this function will return a pointer to that widget. If - no descendant has input focus, 0 is returned. + no descendant widget has input focus, 0 is returned. - \sa QWidget::focusWidget() + \sa QGraphicsItem::focusItem(), QWidget::focusWidget() */ QGraphicsWidget *QGraphicsWidget::focusWidget() const { Q_D(const QGraphicsWidget); - return d->focusChild; + if (d->subFocusItem && d->subFocusItem->d_ptr->isWidget) + return static_cast<QGraphicsWidget *>(d->subFocusItem); + return 0; } -/*! \property QGraphicsWidget::horizontalShear - \brief This property holds the horizontal shear value for the item. - */ - -/*! \property QGraphicsWidget::transformOrigin - \brief This property holds the origin point used for transformations - in item coordinates. - */ - -/*! \property QGraphicsWidget::verticalShear - \brief This property holds the vertical shear value for the item. - */ - -/*! \property QGraphicsWidget::xRotation - \brief This property holds the value for rotation around the x axis. - */ - -/*! \property QGraphicsWidget::xScale - \brief This property holds the scale factor for the x axis. - */ - -/*! \property QGraphicsWidget::yRotation - \brief This property holds the value for rotation around the y axis. - */ - -/*! \property QGraphicsWidget::yScale - \brief This property holds the scale factor for the y axis. - */ - -/*! \property QGraphicsWidget::zRotation - \brief This property holds the value for rotation around the z axis. - */ - #ifndef QT_NO_SHORTCUT /*! \since 4.5 @@ -2284,6 +2253,7 @@ bool QGraphicsWidget::close() #ifdef Q_NO_USING_KEYWORD /*! \fn const QObjectList &QGraphicsWidget::children() const + \internal This function returns the same value as QObject::children(). It's provided to differentiate between the obsolete member diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index b72ec9f..d03a637 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -77,14 +77,6 @@ class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLay Q_PROPERTY(Qt::WindowFlags windowFlags READ windowFlags WRITE setWindowFlags) Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle) Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) - Q_PROPERTY(QPointF transformOrigin READ transformOrigin WRITE setTransformOrigin) - Q_PROPERTY(qreal xRotation READ xRotation WRITE setXRotation) - Q_PROPERTY(qreal yRotation READ yRotation WRITE setYRotation) - Q_PROPERTY(qreal zRotation READ zRotation WRITE setZRotation) - Q_PROPERTY(qreal xScale READ xScale WRITE setXScale) - Q_PROPERTY(qreal yScale READ yScale WRITE setYScale) - Q_PROPERTY(qreal horizontalShear READ horizontalShear WRITE setHorizontalShear) - Q_PROPERTY(qreal verticalShear READ verticalShear WRITE setVerticalShear) public: QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); ~QGraphicsWidget(); diff --git a/src/gui/graphicsview/qgraphicswidget_p.cpp b/src/gui/graphicsview/qgraphicswidget_p.cpp index c9212f7..8eac063 100644 --- a/src/gui/graphicsview/qgraphicswidget_p.cpp +++ b/src/gui/graphicsview/qgraphicswidget_p.cpp @@ -626,34 +626,6 @@ bool QGraphicsWidgetPrivate::hasDecoration() const return (windowFlags & Qt::Window) && (windowFlags & Qt::WindowTitleHint); } -/*! - \internal -*/ -void QGraphicsWidgetPrivate::setFocusWidget() -{ - // Update focus child chain. - QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(q_ptr); - QGraphicsWidget *parent = widget; - bool hidden = !visible; - do { - parent->d_func()->focusChild = widget; - } while (!parent->isWindow() && (parent = parent->parentWidget()) && (!hidden || !parent->d_func()->visible)); -} - -/*! - \internal -*/ -void QGraphicsWidgetPrivate::clearFocusWidget() -{ - // Reset focus child chain. - QGraphicsWidget *parent = static_cast<QGraphicsWidget *>(q_ptr); - do { - if (parent->d_func()->focusChild != q_ptr) - break; - parent->d_func()->focusChild = 0; - } while (!parent->isWindow() && (parent = parent->parentWidget())); -} - /** * is called after a reparent has taken place to fix up the focus chain(s) */ @@ -670,12 +642,6 @@ void QGraphicsWidgetPrivate::fixFocusChainBeforeReparenting(QGraphicsWidget *new QGraphicsWidget *firstOld = 0; bool wasPreviousNew = true; - - if (focusChild) { - // Ensure that the current focus child doesn't leave pointers around - // before reparenting. - focusChild->clearFocus(); - } while (w != q) { bool isCurrentNew = q->isAncestorOf(w); diff --git a/src/gui/graphicsview/qgraphicswidget_p.h b/src/gui/graphicsview/qgraphicswidget_p.h index 0c34baa..92e520a 100644 --- a/src/gui/graphicsview/qgraphicswidget_p.h +++ b/src/gui/graphicsview/qgraphicswidget_p.h @@ -83,7 +83,6 @@ public: focusPolicy(Qt::NoFocus), focusNext(0), focusPrev(0), - focusChild(0), windowFlags(0), windowData(0), setWindowFrameMargins(false), @@ -178,9 +177,6 @@ public: Qt::FocusPolicy focusPolicy; QGraphicsWidget *focusNext; QGraphicsWidget *focusPrev; - QGraphicsWidget *focusChild; - void setFocusWidget(); - void clearFocusWidget(); // Windows Qt::WindowFlags windowFlags; diff --git a/src/gui/image/image.pri b/src/gui/image/image.pri index bf348af..b9c36dc 100644 --- a/src/gui/image/image.pri +++ b/src/gui/image/image.pri @@ -25,7 +25,9 @@ HEADERS += \ image/qpixmapcache_p.h \ image/qpixmapdata_p.h \ image/qpixmapdatafactory_p.h \ - image/qpixmapfilter_p.h + image/qpixmapfilter_p.h \ + image/qimagepixmapcleanuphooks_p.h \ + SOURCES += \ image/qbitmap.cpp \ @@ -47,6 +49,8 @@ SOURCES += \ image/qmovie.cpp \ image/qpixmap_raster.cpp \ image/qnativeimage.cpp \ + image/qimagepixmapcleanuphooks.cpp \ + win32 { SOURCES += image/qpixmap_win.cpp diff --git a/src/gui/image/qbitmap.cpp b/src/gui/image/qbitmap.cpp index 6bca504..78c3396 100644 --- a/src/gui/image/qbitmap.cpp +++ b/src/gui/image/qbitmap.cpp @@ -78,7 +78,7 @@ QT_BEGIN_NAMESPACE 0 for black and 1 for white. The QBitmap class provides the transformed() function returning a - transformed copy of the bitmap; use the QMatrix argument to + transformed copy of the bitmap; use the QTransform argument to translate, scale, shear, and rotate the bitmap. In addition, QBitmap provides the static fromData() function which returns a bitmap constructed from the given \c uchar data, and the static @@ -318,6 +318,7 @@ QBitmap QBitmap::transformed(const QTransform &matrix) const /*! \overload + \obsolete This convenience function converts the \a matrix to a QTransform and calls the overloaded function. diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp index 7d7dde1..bb77fb5 100644 --- a/src/gui/image/qimage.cpp +++ b/src/gui/image/qimage.cpp @@ -49,6 +49,7 @@ #include "qimagewriter.h" #include "qstringlist.h" #include "qvariant.h" +#include "qimagepixmapcleanuphooks_p.h" #include <ctype.h> #include <stdlib.h> #include <limits.h> @@ -106,14 +107,6 @@ static inline bool checkPixelSize(const QImage::Format format) } -// ### Qt 5: remove -typedef void (*_qt_image_cleanup_hook)(int); -Q_GUI_EXPORT _qt_image_cleanup_hook qt_image_cleanup_hook = 0; - -// ### Qt 5: rename -typedef void (*_qt_image_cleanup_hook_64)(qint64); -Q_GUI_EXPORT _qt_image_cleanup_hook_64 qt_image_cleanup_hook_64 = 0; - static QImage rotated90(const QImage &src); static QImage rotated180(const QImage &src); static QImage rotated270(const QImage &src); @@ -257,8 +250,8 @@ QImageData * QImageData::create(const QSize &size, QImage::Format format, int nu QImageData::~QImageData() { - if (is_cached && qt_image_cleanup_hook_64) - qt_image_cleanup_hook_64((((qint64) ser_no) << 32) | ((qint64) detach_no)); + if (is_cached) + QImagePixmapCleanupHooks::executeImageHooks((((qint64) ser_no) << 32) | ((qint64) detach_no)); delete paintEngine; if (data && own_data) free(data); @@ -590,9 +583,8 @@ bool QImageData::checkForAlphaPixels() const The mirrored() function returns a mirror of the image in the desired direction, the scaled() returns a copy of the image scaled - to a rectangle of the desired measures, the rgbSwapped() function - constructs a BGR image from a RGB image, and the alphaChannel() - function constructs an image from this image's alpha channel. + to a rectangle of the desired measures, and the rgbSwapped() function + constructs a BGR image from a RGB image. The scaledToWidth() and scaledToHeight() functions return scaled copies of the image. @@ -1343,8 +1335,8 @@ QImage::operator QVariant() const void QImage::detach() { if (d) { - if (d->is_cached && qt_image_cleanup_hook_64 && d->ref == 1) - qt_image_cleanup_hook_64(cacheKey()); + if (d->is_cached && d->ref == 1) + QImagePixmapCleanupHooks::executeImageHooks(cacheKey()); if (d->ref != 1 || d->ro_data) *this = copy(); @@ -4629,12 +4621,19 @@ bool QImage::loadFromData(const uchar *data, int len, const char *format) binary \a data. The loader attempts to read the image using the specified \a format. If \a format is not specified (which is the default), the loader probes the file for a header to guess the file format. + binary \a data. The loader attempts to read the image, either using the + optional image \a format specified or by determining the image format from + the data. - If the loading of the image failed, this object is a null image. + If \a format is not specified (which is the default), the loader probes the + file for a header to determine the file format. If \a format is specified, + it must be one of the values returned by QImageReader::supportedImageFormats(). + + If the loading of the image fails, the image returned will be a null image. + + \sa load(), save(), {QImage#Reading and Writing Image Files}{Reading and Writing Image Files} + */ - \sa load(), save(), {QImage#Reading and Writing Image - Files}{Reading and Writing Image Files} -*/ QImage QImage::fromData(const uchar *data, int size, const char *format) { QByteArray a = QByteArray::fromRawData(reinterpret_cast<const char *>(data), size); diff --git a/src/gui/painting/qregion_wince.cpp b/src/gui/image/qimagepixmapcleanuphooks.cpp index 9c33123..7d1c5fb 100644 --- a/src/gui/painting/qregion_wince.cpp +++ b/src/gui/image/qimagepixmapcleanuphooks.cpp @@ -39,81 +39,72 @@ ** ****************************************************************************/ -#include "qatomic.h" -#include "qbitmap.h" -#include "qbuffer.h" -#include "qimage.h" -#include "qpolygon.h" -#include "qregion.h" -#include "qt_windows.h" -#include "qpainterpath.h" -#include "qguifunctions_wince.h" +#include "qimagepixmapcleanuphooks_p.h" +#include "qpixmapdata_p.h" -QT_BEGIN_NAMESPACE -QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 }; +// Legacy, single instance hooks: ### Qt 5: remove +typedef void (*_qt_pixmap_cleanup_hook)(int); +typedef void (*_qt_pixmap_cleanup_hook_64)(qint64); +typedef void (*_qt_image_cleanup_hook)(int); +Q_GUI_EXPORT _qt_pixmap_cleanup_hook qt_pixmap_cleanup_hook = 0; +Q_GUI_EXPORT _qt_pixmap_cleanup_hook_64 qt_pixmap_cleanup_hook_64 = 0; +Q_GUI_EXPORT _qt_image_cleanup_hook qt_image_cleanup_hook = 0; +Q_GUI_EXPORT _qt_image_cleanup_hook_64 qt_image_cleanup_hook_64 = 0; -HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom) + +QImagePixmapCleanupHooks* qt_image_and_pixmap_cleanup_hooks = 0; + + +QImagePixmapCleanupHooks::QImagePixmapCleanupHooks() +{ + qt_image_and_pixmap_cleanup_hooks = this; +} + +QImagePixmapCleanupHooks *QImagePixmapCleanupHooks::instance() +{ + if (!qt_image_and_pixmap_cleanup_hooks) + qt_image_and_pixmap_cleanup_hooks = new QImagePixmapCleanupHooks; + return qt_image_and_pixmap_cleanup_hooks; +} + +void QImagePixmapCleanupHooks::addPixmapHook(_qt_pixmap_cleanup_hook_pm hook) { - const int tries = 10; - for (int i = 0; i < tries; ++i) { - HRGN region; - switch (type) { - case QRegion::Rectangle: - region = CreateRectRgn(left, top, right, bottom); - break; - case QRegion::Ellipse: -#ifndef Q_OS_WINCE - region = CreateEllipticRgn(left, top, right, bottom); -#endif - break; - } - if (region) { - if (GetRegionData(region, 0, 0)) - return region; - else - DeleteObject(region); - } - } - return 0; + pixmapHooks.append(hook); } -void qt_win_dispose_rgn(HRGN r) +void QImagePixmapCleanupHooks::addImageHook(_qt_image_cleanup_hook_64 hook) { - if (r) - DeleteObject(r); + imageHooks.append(hook); } -static void qt_add_rect(HRGN &winRegion, QRect r) +void QImagePixmapCleanupHooks::removePixmapHook(_qt_pixmap_cleanup_hook_pm hook) { - HRGN rgn = CreateRectRgn(r.left(), r.top(), r.x() + r.width(), r.y() + r.height()); - if (rgn) { - HRGN dest = CreateRectRgn(0,0,0,0); - int result = CombineRgn(dest, winRegion, rgn, RGN_OR); - if (result) { - DeleteObject(winRegion); - winRegion = dest; - } - } + pixmapHooks.removeAll(hook); } -void QRegion::ensureHandle() const +void QImagePixmapCleanupHooks::removeImageHook(_qt_image_cleanup_hook_64 hook) { - if (d->rgn) - DeleteObject(d->rgn); - d->rgn = CreateRectRgn(0,0,0,0); - if (d->qt_rgn) { - if (d->qt_rgn->numRects == 1) { - QRect r = d->qt_rgn->extents; - qt_add_rect(d->rgn, r); - return; - } - for (int i = 0;i < d->qt_rgn->numRects;i++) { - QRect r = d->qt_rgn->rects.at(i); - qt_add_rect(d->rgn, r); - } - } + imageHooks.removeAll(hook); } -QT_END_NAMESPACE +void QImagePixmapCleanupHooks::executePixmapHooks(QPixmap* pm) +{ + for (int i = 0; i < qt_image_and_pixmap_cleanup_hooks->pixmapHooks.count(); ++i) + qt_image_and_pixmap_cleanup_hooks->pixmapHooks[i](pm); + + if (qt_pixmap_cleanup_hook_64) + qt_pixmap_cleanup_hook_64(pm->cacheKey()); +} + + +void QImagePixmapCleanupHooks::executeImageHooks(qint64 key) +{ + for (int i = 0; i < qt_image_and_pixmap_cleanup_hooks->imageHooks.count(); ++i) + qt_image_and_pixmap_cleanup_hooks->imageHooks[i](key); + + if (qt_image_cleanup_hook_64) + qt_image_cleanup_hook_64(key); +} + diff --git a/src/gui/embedded/qkbdsl5000_qws.h b/src/gui/image/qimagepixmapcleanuphooks_p.h index 42afbe1..e765e69 100644 --- a/src/gui/embedded/qkbdsl5000_qws.h +++ b/src/gui/image/qimagepixmapcleanuphooks_p.h @@ -39,54 +39,51 @@ ** ****************************************************************************/ -#ifndef QKBDSL5000_QWS_H -#define QKBDSL5000_QWS_H +#ifndef QIMAGEPIXMAP_CLEANUPHOOKS_P_H +#define QIMAGEPIXMAP_CLEANUPHOOKS_P_H -#include <QtGui/qkbdtty_qws.h> +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// -QT_BEGIN_HEADER +#include <QtGui/qpixmap.h> QT_BEGIN_NAMESPACE -QT_MODULE(Gui) +typedef void (*_qt_image_cleanup_hook_64)(qint64); +typedef void (*_qt_pixmap_cleanup_hook_pm)(QPixmap*); -#ifndef QT_NO_QWS_KBD_SL5000 +class QImagePixmapCleanupHooks; +extern QImagePixmapCleanupHooks* qt_image_and_pixmap_cleanup_hooks; -struct QWSKeyMap { - uint key_code; - ushort unicode; - ushort shift_unicode; - ushort ctrl_unicode; -}; - - -class QWSSL5000KeyboardHandler : public QWSTtyKeyboardHandler +class Q_GUI_EXPORT QImagePixmapCleanupHooks { public: - explicit QWSSL5000KeyboardHandler(const QString&); - virtual ~QWSSL5000KeyboardHandler(); + QImagePixmapCleanupHooks(); + + static QImagePixmapCleanupHooks *instance(); - bool filterKeycode(char &keycode); - virtual const QWSKeyMap *keyMap() const; + void addPixmapHook(_qt_pixmap_cleanup_hook_pm); + void addImageHook(_qt_image_cleanup_hook_64); + + void removePixmapHook(_qt_pixmap_cleanup_hook_pm); + void removeImageHook(_qt_image_cleanup_hook_64); + + static void executePixmapHooks(QPixmap*); + static void executeImageHooks(qint64 key); private: - bool shift; - bool alt; - bool ctrl; - bool caps; - uint extended:2; - Qt::KeyboardModifiers modifiers; - int prevuni; - int prevkey; - bool meta; - bool fn; - bool numLock; + QList<_qt_image_cleanup_hook_64> imageHooks; + QList<_qt_pixmap_cleanup_hook_pm> pixmapHooks; }; -#endif // QT_NO_QWS_KBD_SL5000 - QT_END_NAMESPACE -QT_END_HEADER - -#endif // QKBDSL5000_QWS_H +#endif // QIMAGEPIXMAP_CLEANUPHOOKS_P_H diff --git a/src/gui/image/qpixmap.cpp b/src/gui/image/qpixmap.cpp index 3e5c9b7..82835d5 100644 --- a/src/gui/image/qpixmap.cpp +++ b/src/gui/image/qpixmap.cpp @@ -43,6 +43,7 @@ #include "qpixmap.h" #include "qpixmapdata_p.h" +#include "qimagepixmapcleanuphooks_p.h" #include "qbitmap.h" #include "qcolormap.h" @@ -81,14 +82,6 @@ QT_BEGIN_NAMESPACE // ### Qt 5: remove -typedef void (*_qt_pixmap_cleanup_hook)(int); -Q_GUI_EXPORT _qt_pixmap_cleanup_hook qt_pixmap_cleanup_hook = 0; - -// ### Qt 5: rename -typedef void (*_qt_pixmap_cleanup_hook_64)(qint64); -Q_GUI_EXPORT _qt_pixmap_cleanup_hook_64 qt_pixmap_cleanup_hook_64 = 0; - -// ### Qt 5: remove Q_GUI_EXPORT qint64 qt_pixmap_id(const QPixmap &pixmap) { return pixmap.cacheKey(); @@ -656,7 +649,7 @@ void QPixmap::resize_helper(const QSize &s) QX11PixmapData *x11Data = data->classId() == QPixmapData::X11Class ? static_cast<QX11PixmapData*>(data) : 0; if (x11Data) { pm.x11SetScreen(x11Data->xinfo.screen()); - uninit = x11Data->uninit; + uninit = x11Data->flags & QX11PixmapData::Uninitialized; } #elif defined(Q_WS_MAC) QMacPixmapData *macData = data->classId() == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(data) : 0; @@ -671,12 +664,7 @@ void QPixmap::resize_helper(const QSize &s) p.drawPixmap(0, 0, *this, 0, 0, qMin(width(), w), qMin(height(), h)); } -#if defined(Q_WS_MAC) -#ifndef QT_MAC_NO_QUICKDRAW - if(macData && macData->qd_alpha) - macData->macQDUpdateAlpha(); -#endif -#elif defined(Q_WS_X11) +#if defined(Q_WS_X11) if (x11Data && x11Data->x11_mask) { QX11PixmapData *pmData = static_cast<QX11PixmapData*>(pm.data); pmData->x11_mask = (Qt::HANDLE)XCreatePixmap(X11->display, @@ -1362,8 +1350,8 @@ bool QPixmap::isDetached() const void QPixmap::deref() { if (data && !data->ref.deref()) { // Destroy image if last ref - if (data->is_cached && qt_pixmap_cleanup_hook_64) - qt_pixmap_cleanup_hook_64(cacheKey()); + if (data->is_cached) + QImagePixmapCleanupHooks::executePixmapHooks(this); delete data; data = 0; } @@ -1902,9 +1890,6 @@ int QPixmap::defaultDepth() #endif } -typedef void (*_qt_pixmap_cleanup_hook_64)(qint64); -extern _qt_pixmap_cleanup_hook_64 qt_pixmap_cleanup_hook_64; - /*! Detaches the pixmap from shared pixmap data. @@ -1930,8 +1915,8 @@ void QPixmap::detach() rasterData->image.detach(); } - if (data->is_cached && qt_pixmap_cleanup_hook_64 && data->ref == 1) - qt_pixmap_cleanup_hook_64(cacheKey()); + if (data->is_cached && data->ref == 1) + QImagePixmapCleanupHooks::executePixmapHooks(this); #if defined(Q_WS_MAC) QMacPixmapData *macData = id == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(data) : 0; @@ -1945,18 +1930,13 @@ void QPixmap::detach() if (data->ref != 1) { *this = copy(); -#if defined(Q_WS_MAC) && !defined(QT_MAC_NO_QUICKDRAW) - if (id == QPixmapData::MacClass) { - macData->qd_alpha = 0; - } -#endif } ++data->detach_no; #if defined(Q_WS_X11) if (data->classId() == QPixmapData::X11Class) { QX11PixmapData *d = static_cast<QX11PixmapData*>(data); - d->uninit = false; + d->flags &= ~QX11PixmapData::Uninitialized; // reset the cache data if (d->hd2) { diff --git a/src/gui/image/qpixmap_mac.cpp b/src/gui/image/qpixmap_mac.cpp index 25ef8ba..5568898 100644 --- a/src/gui/image/qpixmap_mac.cpp +++ b/src/gui/image/qpixmap_mac.cpp @@ -166,9 +166,6 @@ QMacPixmapData::QMacPixmapData(PixelType type) : QPixmapData(type, MacClass), has_alpha(0), has_mask(0), uninit(true), pixels(0), pixelsToFree(0), bytesPerRow(0), cg_data(0), cg_dataBeingReleased(0), cg_mask(0), -#ifndef QT_MAC_NO_QUICKDRAW - qd_data(0), qd_alpha(0), -#endif pengine(0) { } @@ -494,13 +491,6 @@ int QMacPixmapData::metric(QPaintDevice::PaintDeviceMetric theMetric) const QMacPixmapData::~QMacPixmapData() { validDataPointers.remove(this); -#ifndef QT_MAC_NO_QUICKDRAW - macQDDisposeAlpha(); - if (qd_data) { - DisposeGWorld(qd_data); - qd_data = 0; - } -#endif if (cg_mask) { CGImageRelease(cg_mask); cg_mask = 0; @@ -589,48 +579,9 @@ void QMacPixmapData::macGetAlphaChannel(QMacPixmapData *pix, bool asMask) const void QMacPixmapData::macSetHasAlpha(bool b) { has_alpha = b; -#ifndef QT_MAC_NO_QUICKDRAW - macQDDisposeAlpha(); //let it get created lazily -#endif macReleaseCGImageRef(); } -#ifndef QT_MAC_NO_QUICKDRAW -void QMacPixmapData::macQDDisposeAlpha() -{ - if (qd_alpha) { - DisposeGWorld(qd_alpha); - qd_alpha = 0; - } -} - -void QMacPixmapData::macQDUpdateAlpha() -{ - macQDDisposeAlpha(); // get rid of alpha pixmap - if (!has_alpha && !has_mask) - return; - - //setup - Rect rect; - SetRect(&rect, 0, 0, w, h); - const int params = alignPix | stretchPix | newDepth; - NewGWorld(&qd_alpha, 32, &rect, 0, 0, params); - int *dptr = (int *)GetPixBaseAddr(GetGWorldPixMap(qd_alpha)), *drow; - unsigned short dbpr = GetPixRowBytes(GetGWorldPixMap(qd_alpha)); - const int *sptr = (int*)pixels, *srow; - const uint sbpr = bytesPerRow; - uchar clr; - for (int y = 0; y < h; ++y) { - drow = (int*)((char *)dptr + (y * dbpr)); - srow = (int*)((char *)sptr + (y * sbpr)); - for (int x=0; x < w; x++) { - clr = qAlpha(*(srow + x)); - *(drow + x) = qRgba(~clr, ~clr, ~clr, 0); - } - } -} -#endif - void QMacPixmapData::macCreateCGImageRef() { Q_ASSERT(cg_data == 0); @@ -979,31 +930,12 @@ QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h) relocated. \warning This function is only available on Mac OS X. + \warning As of Qt 4.6, this function \e{always} returns zero. */ Qt::HANDLE QPixmap::macQDHandle() const { -#ifndef QT_MAC_NO_QUICKDRAW - QMacPixmapData *d = static_cast<QMacPixmapData*>(data); - if (!d->qd_data) { //create the qd data - Rect rect; - SetRect(&rect, 0, 0, d->w, d->h); - unsigned long qdformat = k32ARGBPixelFormat; - GWorldFlags qdflags = 0; - //we play such games so we can use the same buffer in CG as QD this - //makes our merge much simpler, at some point the hacks will go away - //because QD will be removed, but until that day this keeps them coexisting - if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) - qdformat = k32BGRAPixelFormat; - - if(NewGWorldFromPtr(&d->qd_data, qdformat, &rect, 0, 0, qdflags, - (char*)d->pixels, d->bytesPerRow) != noErr) - qWarning("Qt: internal: QPixmap::init error (%d %d %d %d)", rect.left, rect.top, rect.right, rect.bottom); - } - return d->qd_data; -#else return 0; -#endif } /*! \internal @@ -1013,18 +945,11 @@ Qt::HANDLE QPixmap::macQDHandle() const long as it can be relocated. \warning This function is only available on Mac OS X. + \warning As of Qt 4.6, this function \e{always} returns zero. */ Qt::HANDLE QPixmap::macQDAlphaHandle() const { -#ifndef QT_MAC_NO_QUICKDRAW - QMacPixmapData *d = static_cast<QMacPixmapData*>(data); - if (d->has_alpha || d->has_mask) { - if (!d->qd_alpha) //lazily created - d->macQDUpdateAlpha(); - return d->qd_alpha; - } -#endif return 0; } @@ -1094,7 +1019,6 @@ IconRef qt_mac_create_iconref(const QPixmap &px) if (px.isNull()) return 0; - QMacSavedPortInfo pi; //save the current state //create icon IconFamilyHandle iconFamily = reinterpret_cast<IconFamilyHandle>(NewHandle(0)); //create data @@ -1254,6 +1178,7 @@ QPixmap QPixmap::fromMacCGImageRef(CGImageRef image) const size_t w = CGImageGetWidth(image), h = CGImageGetHeight(image); QPixmap ret(w, h); + ret.fill(Qt::transparent); CGRect rect = CGRectMake(0, 0, w, h); CGContextRef ctx = qt_mac_cg_context(&ret); qt_mac_drawCGImage(ctx, &rect, image); diff --git a/src/gui/image/qpixmap_mac_p.h b/src/gui/image/qpixmap_mac_p.h index a3ff0d3..ea6fe60 100644 --- a/src/gui/image/qpixmap_mac_p.h +++ b/src/gui/image/qpixmap_mac_p.h @@ -109,11 +109,6 @@ private: uint bytesPerRow; QRectF cg_mask_rect; CGImageRef cg_data, cg_dataBeingReleased, cg_mask; -#ifndef QT_MAC_NO_QUICKDRAW - GWorldPtr qd_data, qd_alpha; - void macQDDisposeAlpha(); - void macQDUpdateAlpha(); -#endif static QSet<QMacPixmapData*> validDataPointers; QPaintEngine *pengine; diff --git a/src/gui/image/qpixmap_x11.cpp b/src/gui/image/qpixmap_x11.cpp index 86cf515..be3d070 100644 --- a/src/gui/image/qpixmap_x11.cpp +++ b/src/gui/image/qpixmap_x11.cpp @@ -313,7 +313,7 @@ int Q_GUI_EXPORT qt_x11_preferred_pixmap_depth = 0; QX11PixmapData::QX11PixmapData(PixelType type) : QPixmapData(type, X11Class), hd(0), - uninit(true), read_only(false), x11_mask(0), picture(0), mask_picture(0), hd2(0), + flags(Uninitialized), x11_mask(0), picture(0), mask_picture(0), hd2(0), gl_surface(0), share_mode(QPixmap::ImplicitlyShared), pengine(0) { } @@ -1217,7 +1217,7 @@ void QX11PixmapData::release() XFreePixmap(xinfo.display(), hd2); hd2 = 0; } - if (!read_only) + if (!(flags & Readonly)) XFreePixmap(xinfo.display(), hd); hd = 0; } @@ -1876,7 +1876,7 @@ QPixmap QX11PixmapData::transformed(const QTransform &transform, } else { // color pixmap QPixmap pm; QX11PixmapData *x11Data = static_cast<QX11PixmapData*>(pm.data); - x11Data->uninit = false; + x11Data->flags &= ~QX11PixmapData::Uninitialized; x11Data->xinfo = xinfo; x11Data->d = d; x11Data->w = w; @@ -2018,7 +2018,7 @@ QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h) QPixmap pm(data); - data->uninit = false; + data->flags &= ~QX11PixmapData::Uninitialized; pm.x11SetScreen(scr); GC gc = XCreateGC(dpy, pm.handle(), 0, 0); @@ -2060,7 +2060,7 @@ QPaintEngine* QX11PixmapData::paintEngine() const { QX11PixmapData *that = const_cast<QX11PixmapData*>(this); - if (read_only && share_mode == QPixmap::ImplicitlyShared) { + if ((flags & Readonly) && share_mode == QPixmap::ImplicitlyShared) { // if someone wants to draw onto us, copy the shared contents // and turn it into a fully fledged QPixmap ::Pixmap hd_copy = XCreatePixmap(X11->display, RootWindow(X11->display, xinfo.screen()), @@ -2082,7 +2082,7 @@ QPaintEngine* QX11PixmapData::paintEngine() const XFreeGC(X11->display, gc); } that->hd = hd_copy; - that->read_only = false; + that->flags &= ~QX11PixmapData::Readonly; } if (!that->pengine) @@ -2133,7 +2133,7 @@ void QX11PixmapData::copy(const QPixmapData *data, const QRect &rect) setSerialNumber(++qt_pixmap_serial); - uninit = false; + flags &= ~Uninitialized; xinfo = x11Data->xinfo; d = x11Data->d; w = rect.width(); @@ -2201,7 +2201,7 @@ void QX11PixmapData::convertToARGB32(bool preserveContents) return; // Q_ASSERT(count == 1); - if (read_only && share_mode == QPixmap::ExplicitlyShared) + if ((flags & Readonly) && share_mode == QPixmap::ExplicitlyShared) return; Pixmap pm = XCreatePixmap(X11->display, RootWindow(X11->display, xinfo.screen()), @@ -2211,10 +2211,10 @@ void QX11PixmapData::convertToARGB32(bool preserveContents) if (picture) { if (preserveContents) XRenderComposite(X11->display, PictOpSrc, picture, 0, p, 0, 0, 0, 0, 0, 0, w, h); - if (!read_only) + if (!(flags & Readonly)) XRenderFreePicture(X11->display, picture); } - if (hd && !read_only) + if (hd && !(flags & Readonly)) XFreePixmap(X11->display, hd); if (x11_mask) { XFreePixmap(X11->display, x11_mask); @@ -2252,9 +2252,8 @@ QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode) QX11PixmapData *data = new QX11PixmapData(depth == 1 ? QPixmapData::BitmapType : QPixmapData::PixmapType); data->setSerialNumber(++qt_pixmap_serial); - data->read_only = true; + data->flags = QX11PixmapData::Readonly; data->share_mode = mode; - data->uninit = false; data->w = width; data->h = height; data->is_null = (width <= 0 || height <= 0); diff --git a/src/gui/image/qpixmap_x11_p.h b/src/gui/image/qpixmap_x11_p.h index 3de9a0f..835fea4 100644 --- a/src/gui/image/qpixmap_x11_p.h +++ b/src/gui/image/qpixmap_x11_p.h @@ -99,6 +99,7 @@ private: friend class QX11PaintEngine; friend class QX11WindowSurface; friend class QRasterWindowSurface; + friend class QGLContextPrivate; // Needs to access xinfo, gl_surface & flags void release(); @@ -108,14 +109,21 @@ private: Qt::HANDLE hd; - uint uninit : 1; - uint read_only : 1; + enum Flag { + NoFlags = 0x0, + Uninitialized = 0x1, + Readonly = 0x2, + InvertedWhenBoundToTexture = 0x4, + GlSurfaceCreatedWithAlpha = 0x8 + }; + uint flags; QX11Info xinfo; Qt::HANDLE x11_mask; Qt::HANDLE picture; Qt::HANDLE mask_picture; Qt::HANDLE hd2; // sorted in the default display depth + Qt::HANDLE gl_surface; #ifndef QT_NO_XRENDER void convertToARGB32(bool preserveContents = true); #endif diff --git a/src/gui/image/qpixmapcache.h b/src/gui/image/qpixmapcache.h index c86f3fa..de589fc 100644 --- a/src/gui/image/qpixmapcache.h +++ b/src/gui/image/qpixmapcache.h @@ -54,7 +54,7 @@ class Q_GUI_EXPORT QPixmapCache { public: class KeyData; - class Key + class Q_GUI_EXPORT Key { public: Key(); diff --git a/src/gui/image/qpixmapdata_p.h b/src/gui/image/qpixmapdata_p.h index 29dafaf..32b419e 100644 --- a/src/gui/image/qpixmapdata_p.h +++ b/src/gui/image/qpixmapdata_p.h @@ -116,6 +116,7 @@ private: friend class QPixmap; friend class QGLContextPrivate; friend class QX11PixmapData; + friend class QGLTextureCache; //Needs to check the reference count QAtomicInt ref; int detach_no; diff --git a/src/gui/inputmethod/qinputcontextplugin.h b/src/gui/inputmethod/qinputcontextplugin.h index 8ab8f84..c0c127b 100644 --- a/src/gui/inputmethod/qinputcontextplugin.h +++ b/src/gui/inputmethod/qinputcontextplugin.h @@ -66,7 +66,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -#if !defined(QT_NO_IM) && !defined(QT_NO_LIBRARY) +#if !defined(QT_NO_IM) class QInputContext; class QInputContextPluginPrivate; diff --git a/src/gui/inputmethod/qximinputcontext_x11.cpp b/src/gui/inputmethod/qximinputcontext_x11.cpp index 9b21163..074b189 100644 --- a/src/gui/inputmethod/qximinputcontext_x11.cpp +++ b/src/gui/inputmethod/qximinputcontext_x11.cpp @@ -53,6 +53,7 @@ ** ****************************************************************************/ +#include "qplatformdefs.h" #include "qdebug.h" #include "qximinputcontext_p.h" diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index 8887977..421d511 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -851,8 +851,8 @@ QAbstractItemDelegate *QAbstractItemView::itemDelegateForColumn(int column) cons } /*! - Returns the item delegate used by this view and model for - the given \a index. + Returns the item delegate used by this view and model for + the given \a index. */ QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const { @@ -861,14 +861,14 @@ QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) } /*! - \property QAbstractItemView::selectionMode - \brief which selection mode the view operates in + \property QAbstractItemView::selectionMode + \brief which selection mode the view operates in - This property controls whether the user can select one or many items - and, in many-item selections, whether the selection must be a - continuous range of items. + This property controls whether the user can select one or many items + and, in many-item selections, whether the selection must be a + continuous range of items. - \sa SelectionMode SelectionBehavior + \sa SelectionMode SelectionBehavior */ void QAbstractItemView::setSelectionMode(SelectionMode mode) { @@ -883,13 +883,13 @@ QAbstractItemView::SelectionMode QAbstractItemView::selectionMode() const } /*! - \property QAbstractItemView::selectionBehavior - \brief which selection behavior the view uses + \property QAbstractItemView::selectionBehavior + \brief which selection behavior the view uses - This property holds whether selections are done - in terms of single items, rows or columns. + This property holds whether selections are done + in terms of single items, rows or columns. - \sa SelectionMode SelectionBehavior + \sa SelectionMode SelectionBehavior */ void QAbstractItemView::setSelectionBehavior(QAbstractItemView::SelectionBehavior behavior) @@ -960,6 +960,8 @@ void QAbstractItemView::reset() d->currentIndexSet = false; setState(NoState); setRootIndex(QModelIndex()); + if (d->selectionModel) + d->selectionModel->reset(); } /*! @@ -990,11 +992,11 @@ QModelIndex QAbstractItemView::rootIndex() const } /*! - Selects all item in the view. - This function wil use the selection selection behavior - set on the view when selecting. + Selects all items in the view. + This function will use the selection behavior + set on the view when selecting. - \sa setSelection(), selectedIndexes(), clearSelection() + \sa setSelection(), selectedIndexes(), clearSelection() */ void QAbstractItemView::selectAll() { @@ -1223,10 +1225,10 @@ bool QAbstractItemView::tabKeyNavigation() const #ifndef QT_NO_DRAGANDDROP /*! - \property QAbstractItemView::showDropIndicator - \brief whether the drop indicator is shown when dragging items and dropping. + \property QAbstractItemView::showDropIndicator + \brief whether the drop indicator is shown when dragging items and dropping. - \sa dragEnabled DragDropMode dragDropOverwriteMode acceptDrops + \sa dragEnabled DragDropMode dragDropOverwriteMode acceptDrops */ void QAbstractItemView::setDropIndicatorShown(bool enable) @@ -1242,10 +1244,10 @@ bool QAbstractItemView::showDropIndicator() const } /*! - \property QAbstractItemView::dragEnabled - \brief whether the view supports dragging of its own items + \property QAbstractItemView::dragEnabled + \brief whether the view supports dragging of its own items - \sa showDropIndicator DragDropMode dragDropOverwriteMode acceptDrops + \sa showDropIndicator DragDropMode dragDropOverwriteMode acceptDrops */ void QAbstractItemView::setDragEnabled(bool enable) @@ -1281,11 +1283,11 @@ bool QAbstractItemView::dragEnabled() const */ /*! - \property QAbstractItemView::dragDropMode - \brief the drag and drop event the view will act upon + \property QAbstractItemView::dragDropMode + \brief the drag and drop event the view will act upon - \since 4.2 - \sa showDropIndicator dragDropOverwriteMode + \since 4.2 + \sa showDropIndicator dragDropOverwriteMode */ void QAbstractItemView::setDragDropMode(DragDropMode behavior) { @@ -1321,14 +1323,14 @@ QAbstractItemView::DragDropMode QAbstractItemView::dragDropMode() const #endif // QT_NO_DRAGANDDROP /*! - \property QAbstractItemView::alternatingRowColors - \brief whether to draw the background using alternating colors + \property QAbstractItemView::alternatingRowColors + \brief whether to draw the background using alternating colors - If this property is true, the item background will be drawn using - QPalette::Base and QPalette::AlternateBase; otherwise the background - will be drawn using the QPalette::Base color. + If this property is true, the item background will be drawn using + QPalette::Base and QPalette::AlternateBase; otherwise the background + will be drawn using the QPalette::Base color. - By default, this property is false. + By default, this property is false. */ void QAbstractItemView::setAlternatingRowColors(bool enable) { @@ -2257,8 +2259,8 @@ void QAbstractItemView::inputMethodEvent(QInputMethodEvent *event) \value BelowItem The item will be dropped below the index. \value OnViewport The item will be dropped onto a region of the viewport with -no items. The way each view handles items dropped onto the viewport depends on -the behavior of the underlying model in use. + no items. The way each view handles items dropped onto the viewport depends on + the behavior of the underlying model in use. */ @@ -2275,11 +2277,11 @@ QAbstractItemView::DropIndicatorPosition QAbstractItemView::dropIndicatorPositio #endif /*! - This convenience function returns a list of all selected and - non-hidden item indexes in the view. The list contains no - duplicates, and is not sorted. + This convenience function returns a list of all selected and + non-hidden item indexes in the view. The list contains no + duplicates, and is not sorted. - \sa QItemSelectionModel::selectedIndexes() + \sa QItemSelectionModel::selectedIndexes() */ QModelIndexList QAbstractItemView::selectedIndexes() const { @@ -2361,8 +2363,8 @@ bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEve } /*! - \internal - Updates the data shown in the open editor widgets in the view. + \internal + Updates the data shown in the open editor widgets in the view. */ void QAbstractItemView::updateEditorData() { @@ -2371,8 +2373,8 @@ void QAbstractItemView::updateEditorData() } /*! - \internal - Updates the geometry of the open editor widgets in the view. + \internal + Updates the geometry of the open editor widgets in the view. */ void QAbstractItemView::updateEditorGeometries() { @@ -2421,7 +2423,7 @@ void QAbstractItemView::updateGeometries() } /*! - \internal + \internal */ void QAbstractItemView::verticalScrollbarValueChanged(int value) { @@ -2432,7 +2434,7 @@ void QAbstractItemView::verticalScrollbarValueChanged(int value) } /*! - \internal + \internal */ void QAbstractItemView::horizontalScrollbarValueChanged(int value) { @@ -2534,9 +2536,9 @@ void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndE } /*! - Commit the data in the \a editor to the model. + Commit the data in the \a editor to the model. - \sa closeEditor() + \sa closeEditor() */ void QAbstractItemView::commitData(QWidget *editor) { @@ -2555,9 +2557,9 @@ void QAbstractItemView::commitData(QWidget *editor) } /*! - This function is called when the given \a editor has been destroyed. + This function is called when the given \a editor has been destroyed. - \sa closeEditor() + \sa closeEditor() */ void QAbstractItemView::editorDestroyed(QObject *editor) { @@ -2628,12 +2630,12 @@ int QAbstractItemView::verticalStepsPerItem() const } /*! - Moves to and selects the item best matching the string \a search. - If no item is found nothing happens. + Moves to and selects the item best matching the string \a search. + If no item is found nothing happens. - In the default implementation, the search is reset if \a search is empty, or - the time interval since the last search has exceeded - QApplication::keyboardInputInterval(). + In the default implementation, the search is reset if \a search is empty, or + the time interval since the last search has exceeded + QApplication::keyboardInputInterval(). */ void QAbstractItemView::keyboardSearch(const QString &search) { @@ -2648,7 +2650,7 @@ void QAbstractItemView::keyboardSearch(const QString &search) if (search.isEmpty() || (d->keyboardInputTime.msecsTo(now) > QApplication::keyboardInputInterval())) { d->keyboardInput = search; - skipRow = true; + skipRow = currentIndex().isValid(); //if it is not valid we should really start at QModelIndex(0,0) } else { d->keyboardInput += search; } @@ -2675,6 +2677,7 @@ void QAbstractItemView::keyboardSearch(const QString &search) QModelIndex current = start; QModelIndexList match; QModelIndex firstMatch; + QModelIndex startMatch; QModelIndexList previous; do { match = d->model->match(current, Qt::DisplayRole, searchString); @@ -2687,10 +2690,16 @@ void QAbstractItemView::keyboardSearch(const QString &search) setCurrentIndex(firstMatch); break; } - int row = firstMatch.row() + 1; - if (row >= d->model->rowCount(firstMatch.parent())) - row = 0; + int row = firstMatch.row() + 1; + if (row >= d->model->rowCount(firstMatch.parent())) + row = 0; current = firstMatch.sibling(row, firstMatch.column()); + + //avoid infinite loop if all the matching items are disabled. + if (!startMatch.isValid()) + startMatch = firstMatch; + else if (startMatch == firstMatch) + break; } } while (current != start && firstMatch.isValid()); } @@ -2796,9 +2805,9 @@ void QAbstractItemView::openPersistentEditor(const QModelIndex &index) } /*! - Closes the persistent editor for the item at the given \a index. + Closes the persistent editor for the item at the given \a index. - \sa openPersistentEditor() + \sa openPersistentEditor() */ void QAbstractItemView::closePersistentEditor(const QModelIndex &index) { @@ -3333,14 +3342,14 @@ void QAbstractItemView::setDirtyRegion(const QRegion ®ion) } /*! - Prepares the view for scrolling by (\a{dx},\a{dy}) pixels by moving the dirty regions in the - opposite direction. You only need to call this function if you are implementing a scrolling - viewport in your view subclass. + Prepares the view for scrolling by (\a{dx},\a{dy}) pixels by moving the dirty regions in the + opposite direction. You only need to call this function if you are implementing a scrolling + viewport in your view subclass. - If you implement scrollContentsBy() in a subclass of QAbstractItemView, call this function - before you call QWidget::scroll() on the viewport. Alternatively, just call update(). + If you implement scrollContentsBy() in a subclass of QAbstractItemView, call this function + before you call QWidget::scroll() on the viewport. Alternatively, just call update(). - \sa scrollContentsBy(), dirtyRegionOffset(), setDirtyRegion() + \sa scrollContentsBy(), dirtyRegionOffset(), setDirtyRegion() */ void QAbstractItemView::scrollDirtyRegion(int dx, int dy) { @@ -3349,13 +3358,13 @@ void QAbstractItemView::scrollDirtyRegion(int dx, int dy) } /*! - Returns the offset of the dirty regions in the view. + Returns the offset of the dirty regions in the view. - If you use scrollDirtyRegion() and implement a paintEvent() in a subclass of - QAbstractItemView, you should translate the area given by the paint event with - the offset returned from this function. + If you use scrollDirtyRegion() and implement a paintEvent() in a subclass of + QAbstractItemView, you should translate the area given by the paint event with + the offset returned from this function. - \sa scrollDirtyRegion(), setDirtyRegion() + \sa scrollDirtyRegion(), setDirtyRegion() */ QPoint QAbstractItemView::dirtyRegionOffset() const { @@ -3527,7 +3536,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC const bool shiftKeyPressed = modifiers & Qt::ShiftModifier; const bool controlKeyPressed = modifiers & Qt::ControlModifier; if (((index == pressedIndex && selectionModel->isSelected(index)) - || !index.isValid()) && state != QAbstractItemView::DragSelectingState + || !index.isValid()) && state != QAbstractItemView::DragSelectingState && !shiftKeyPressed && !controlKeyPressed && !rightButtonPressed) return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags(); return QItemSelectionModel::NoUpdate; @@ -3759,7 +3768,7 @@ void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QMo but the behavior is view dependant (table just clears the selected indexes for example). Either remove the selected rows or clear them - */ +*/ void QAbstractItemViewPrivate::clearOrRemove() { #ifndef QT_NO_DRAGANDDROP @@ -3795,7 +3804,7 @@ void QAbstractItemViewPrivate::clearOrRemove() When persistent aeditor gets/loses focus, we need to check and setcorrectly the current index. - */ +*/ void QAbstractItemViewPrivate::checkPersistentEditorFocus() { Q_Q(QAbstractItemView); @@ -3882,10 +3891,10 @@ bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *even } /* - \internal + \internal - returns the pair QRect/QModelIndex that should be painted on the viewports's rect - */ + returns the pair QRect/QModelIndex that should be painted on the viewports's rect +*/ QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const { diff --git a/src/gui/itemviews/qitemdelegate.cpp b/src/gui/itemviews/qitemdelegate.cpp index 336ca79..bd6dc62 100644 --- a/src/gui/itemviews/qitemdelegate.cpp +++ b/src/gui/itemviews/qitemdelegate.cpp @@ -1226,21 +1226,19 @@ bool QItemDelegate::eventFilter(QObject *object, QEvent *event) } else if (event->type() == QEvent::FocusOut || (event->type() == QEvent::Hide && editor->isWindow())) { //the Hide event will take care of he editors that are in fact complete dialogs if (!editor->isActiveWindow() || (QApplication::focusWidget() != editor)) { - if (editor->isAncestorOf(QApplication::focusWidget())) - return false; // don't worry about focus changes internally in the editor - + QWidget *w = QApplication::focusWidget(); + while (w) { // don't worry about focus changes internally in the editor + if (w == editor) + return false; + w = w->parentWidget(); + } #ifndef QT_NO_DRAGANDDROP // The window may lose focus during an drag operation. // i.e when dragging involves the taskbar on Windows. if (QDragManager::self() && QDragManager::self()->object != 0) return false; #endif - // Opening a modal dialog will start a new eventloop - // that will process the deleteLater event. - if (QApplication::activeModalWidget() - && !QApplication::activeModalWidget()->isAncestorOf(editor) - && qobject_cast<QDialog*>(QApplication::activeModalWidget())) - return false; + emit commitData(editor); emit closeEditor(editor, NoHint); } @@ -1298,8 +1296,14 @@ bool QItemDelegate::editorEvent(QEvent *event, return false; } - Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked + Qt::CheckState state; + if ( flags & Qt::ItemIsTristate ) { + state = static_cast<Qt::CheckState>( (value.toInt() + 1) % 3 ); + } else { + state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked ? Qt::Unchecked : Qt::Checked); + } + return model->setData(index, state, Qt::CheckStateRole); } diff --git a/src/gui/itemviews/qitemselectionmodel.cpp b/src/gui/itemviews/qitemselectionmodel.cpp index 87825d9..9dad95f 100644 --- a/src/gui/itemviews/qitemselectionmodel.cpp +++ b/src/gui/itemviews/qitemselectionmodel.cpp @@ -303,45 +303,44 @@ QModelIndexList QItemSelectionRange::indexes() const } /*! - \class QItemSelection + \class QItemSelection - \brief The QItemSelection class manages information about selected items in a model. + \brief The QItemSelection class manages information about selected items in a model. - \ingroup model-view - - A QItemSelection describes the items in a model that have been - selected by the user. A QItemSelection is basically a list of - selection ranges, see QItemSelectionRange. It provides functions for - creating and manipulating selections, and selecting a range of items - from a model. + \ingroup model-view - The QItemSelection class is one of the \l{Model/View Classes} - and is part of Qt's \l{Model/View Programming}{model/view framework}. + A QItemSelection describes the items in a model that have been + selected by the user. A QItemSelection is basically a list of + selection ranges, see QItemSelectionRange. It provides functions for + creating and manipulating selections, and selecting a range of items + from a model. - An item selection can be constructed and initialized to contain a - range of items from an existing model. The following example constructs - a selection that contains a range of items from the given \c model, - beginning at the \c topLeft, and ending at the \c bottomRight. + The QItemSelection class is one of the \l{Model/View Classes} + and is part of Qt's \l{Model/View Programming}{model/view framework}. - \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 0 + An item selection can be constructed and initialized to contain a + range of items from an existing model. The following example constructs + a selection that contains a range of items from the given \c model, + beginning at the \c topLeft, and ending at the \c bottomRight. - An empty item selection can be constructed, and later populated as - required. So, if the model is going to be unavailable when we construct - the item selection, we can rewrite the above code in the following way: + \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 0 - \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 1 + An empty item selection can be constructed, and later populated as + required. So, if the model is going to be unavailable when we construct + the item selection, we can rewrite the above code in the following way: - QItemSelection saves memory, and avoids unnecessary work, by working with - selection ranges rather than recording the model item index for each - item in the selection. Generally, an instance of this class will contain - a list of non-overlapping selection ranges. + \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 1 - Use merge() to merge one item selection into another without making - overlapping ranges. Use split() to split one selection range into - smaller ranges based on a another selection range. + QItemSelection saves memory, and avoids unnecessary work, by working with + selection ranges rather than recording the model item index for each + item in the selection. Generally, an instance of this class will contain + a list of non-overlapping selection ranges. - \sa {Model/View Programming}, QItemSelectionModel + Use merge() to merge one item selection into another without making + overlapping ranges. Use split() to split one selection range into + smaller ranges based on a another selection range. + \sa {Model/View Programming}, QItemSelectionModel */ /*! @@ -420,14 +419,14 @@ QModelIndexList QItemSelection::indexes() const } /*! - Merges the \a other selection with this QItemSelection using the - \a command given. This method guarantees that no ranges are overlapping. + Merges the \a other selection with this QItemSelection using the + \a command given. This method guarantees that no ranges are overlapping. - Note that only QItemSelectionModel::Select, - QItemSelectionModel::Deselect, and QItemSelectionModel::Toggle are - supported. + Note that only QItemSelectionModel::Select, + QItemSelectionModel::Deselect, and QItemSelectionModel::Toggle are + supported. - \sa split() + \sa split() */ void QItemSelection::merge(const QItemSelection &other, QItemSelectionModel::SelectionFlags command) { @@ -479,10 +478,10 @@ void QItemSelection::merge(const QItemSelection &other, QItemSelectionModel::Sel } /*! - Splits the selection \a range using the selection \a other range. - Removes all items in \a other from \a range and puts the result in \a result. - This can be compared with the semantics of the \e subtract operation of a set. - \sa merge() + Splits the selection \a range using the selection \a other range. + Removes all items in \a other from \a range and puts the result in \a result. + This can be compared with the semantics of the \e subtract operation of a set. + \sa merge() */ void QItemSelection::split(const QItemSelectionRange &range, @@ -529,11 +528,11 @@ void QItemSelection::split(const QItemSelectionRange &range, } /*! - \internal + \internal - returns a QItemSelection where all ranges have been expanded to: - Rows: left: 0 and right: columnCount()-1 - Columns: top: 0 and bottom: rowCount()-1 + returns a QItemSelection where all ranges have been expanded to: + Rows: left: 0 and right: columnCount()-1 + Columns: top: 0 and bottom: rowCount()-1 */ QItemSelection QItemSelectionModelPrivate::expandSelection(const QItemSelection &selection, @@ -568,7 +567,7 @@ QItemSelection QItemSelectionModelPrivate::expandSelection(const QItemSelection } /*! - \internal + \internal */ void QItemSelectionModelPrivate::_q_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) @@ -599,7 +598,7 @@ void QItemSelectionModelPrivate::_q_rowsAboutToBeRemoved(const QModelIndex &pare } /*! - \internal + \internal */ void QItemSelectionModelPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end) @@ -630,9 +629,9 @@ void QItemSelectionModelPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &p } /*! - \internal + \internal - Split selection ranges if columns are about to be inserted in the middle. + Split selection ranges if columns are about to be inserted in the middle. */ void QItemSelectionModelPrivate::_q_columnsAboutToBeInserted(const QModelIndex &parent, int start, int end) @@ -659,9 +658,9 @@ void QItemSelectionModelPrivate::_q_columnsAboutToBeInserted(const QModelIndex & } /*! - \internal + \internal - Split selection ranges if rows are about to be inserted in the middle. + Split selection ranges if rows are about to be inserted in the middle. */ void QItemSelectionModelPrivate::_q_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) @@ -688,11 +687,11 @@ void QItemSelectionModelPrivate::_q_rowsAboutToBeInserted(const QModelIndex &par } /*! - \internal + \internal - Split selection into individual (persistent) indexes. This is done in - preparation for the layoutChanged() signal, where the indexes can be - merged again. + Split selection into individual (persistent) indexes. This is done in + preparation for the layoutChanged() signal, where the indexes can be + merged again. */ void QItemSelectionModelPrivate::_q_layoutAboutToBeChanged() { @@ -726,10 +725,10 @@ void QItemSelectionModelPrivate::_q_layoutAboutToBeChanged() } /*! - \internal + \internal - Merges \a indexes into an item selection made up of ranges. - Assumes that the indexes are sorted. + Merges \a indexes into an item selection made up of ranges. + Assumes that the indexes are sorted. */ static QItemSelection mergeIndexes(const QList<QPersistentModelIndex> &indexes) { @@ -774,9 +773,9 @@ static QItemSelection mergeIndexes(const QList<QPersistentModelIndex> &indexes) } /*! - \internal + \internal - Merge the selected indexes into selection ranges again. + Merge the selected indexes into selection ranges again. */ void QItemSelectionModelPrivate::_q_layoutChanged() { @@ -818,41 +817,41 @@ void QItemSelectionModelPrivate::_q_layoutChanged() } /*! - \class QItemSelectionModel + \class QItemSelectionModel - \brief The QItemSelectionModel class keeps track of a view's selected items. + \brief The QItemSelectionModel class keeps track of a view's selected items. - \ingroup model-view + \ingroup model-view - A QItemSelectionModel keeps track of the selected items in a view, or - in several views onto the same model. It also keeps track of the - currently selected item in a view. + A QItemSelectionModel keeps track of the selected items in a view, or + in several views onto the same model. It also keeps track of the + currently selected item in a view. - The QItemSelectionModel class is one of the \l{Model/View Classes} - and is part of Qt's \l{Model/View Programming}{model/view framework}. + The QItemSelectionModel class is one of the \l{Model/View Classes} + and is part of Qt's \l{Model/View Programming}{model/view framework}. - The selected items are stored using ranges. Whenever you want to - modify the selected items use select() and provide either a - QItemSelection, or a QModelIndex and a QItemSelectionModel::SelectionFlag. + The selected items are stored using ranges. Whenever you want to + modify the selected items use select() and provide either a + QItemSelection, or a QModelIndex and a QItemSelectionModel::SelectionFlag. - The QItemSelectionModel takes a two layer approach to selection - management, dealing with both selected items that have been committed - and items that are part of the current selection. The current - selected items are part of the current interactive selection (for - example with rubber-band selection or keyboard-shift selections). + The QItemSelectionModel takes a two layer approach to selection + management, dealing with both selected items that have been committed + and items that are part of the current selection. The current + selected items are part of the current interactive selection (for + example with rubber-band selection or keyboard-shift selections). - To update the currently selected items, use the bitwise OR of - QItemSelectionModel::Current and any of the other SelectionFlags. - If you omit the QItemSelectionModel::Current command, a new current - selection will be created, and the previous one added to the whole - selection. All functions operate on both layers; for example, - selectedItems() will return items from both layers. + To update the currently selected items, use the bitwise OR of + QItemSelectionModel::Current and any of the other SelectionFlags. + If you omit the QItemSelectionModel::Current command, a new current + selection will be created, and the previous one added to the whole + selection. All functions operate on both layers; for example, + selectedItems() will return items from both layers. - \sa {Model/View Programming}, QAbstractItemModel, {Chart Example} + \sa {Model/View Programming}, QAbstractItemModel, {Chart Example} */ /*! - Constructs a selection model that operates on the specified item \a model. + Constructs a selection model that operates on the specified item \a model. */ QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model) : QObject(*new QItemSelectionModelPrivate, model) @@ -875,7 +874,7 @@ QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model) } /*! - Constructs a selection model that operates on the specified item \a model with \a parent. + Constructs a selection model that operates on the specified item \a model with \a parent. */ QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model, QObject *parent) : QObject(*new QItemSelectionModelPrivate, parent) @@ -898,7 +897,7 @@ QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model, QObject *par } /*! - \internal + \internal */ QItemSelectionModel::QItemSelectionModel(QItemSelectionModelPrivate &dd, QAbstractItemModel *model) : QObject(dd, model) @@ -921,7 +920,7 @@ QItemSelectionModel::QItemSelectionModel(QItemSelectionModelPrivate &dd, QAbstra } /*! - Destroys the selection model. + Destroys the selection model. */ QItemSelectionModel::~QItemSelectionModel() { @@ -943,10 +942,10 @@ QItemSelectionModel::~QItemSelectionModel() } /*! - Selects the model item \a index using the specified \a command, and emits - selectionChanged(). + Selects the model item \a index using the specified \a command, and emits + selectionChanged(). - \sa QItemSelectionModel::SelectionFlags + \sa QItemSelectionModel::SelectionFlags */ void QItemSelectionModel::select(const QModelIndex &index, QItemSelectionModel::SelectionFlags command) { @@ -955,37 +954,37 @@ void QItemSelectionModel::select(const QModelIndex &index, QItemSelectionModel:: } /*! - \fn void QItemSelectionModel::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) + \fn void QItemSelectionModel::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) - This signal is emitted whenever the current item changes. The \a previous - model item index is replaced by the \a current index as the selection's - current item. + This signal is emitted whenever the current item changes. The \a previous + model item index is replaced by the \a current index as the selection's + current item. - Note that this signal will not be emitted when the item model is reset. + Note that this signal will not be emitted when the item model is reset. - \sa currentIndex() setCurrentIndex() selectionChanged() + \sa currentIndex() setCurrentIndex() selectionChanged() */ /*! - \fn void QItemSelectionModel::currentColumnChanged(const QModelIndex ¤t, const QModelIndex &previous) + \fn void QItemSelectionModel::currentColumnChanged(const QModelIndex ¤t, const QModelIndex &previous) - This signal is emitted if the \a current item changes and its column is - different to the column of the \a previous current item. + This signal is emitted if the \a current item changes and its column is + different to the column of the \a previous current item. - Note that this signal will not be emitted when the item model is reset. + Note that this signal will not be emitted when the item model is reset. - \sa currentChanged() currentRowChanged() currentIndex() setCurrentIndex() + \sa currentChanged() currentRowChanged() currentIndex() setCurrentIndex() */ /*! - \fn void QItemSelectionModel::currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous) + \fn void QItemSelectionModel::currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous) - This signal is emitted if the \a current item changes and its row is - different to the row of the \a previous current item. + This signal is emitted if the \a current item changes and its row is + different to the row of the \a previous current item. - Note that this signal will not be emitted when the item model is reset. + Note that this signal will not be emitted when the item model is reset. - \sa currentChanged() currentColumnChanged() currentIndex() setCurrentIndex() + \sa currentChanged() currentColumnChanged() currentIndex() setCurrentIndex() */ /*! @@ -1002,32 +1001,32 @@ void QItemSelectionModel::select(const QModelIndex &index, QItemSelectionModel:: */ /*! - \enum QItemSelectionModel::SelectionFlag + \enum QItemSelectionModel::SelectionFlag - This enum describes the way the selection model will be updated. + This enum describes the way the selection model will be updated. - \value NoUpdate No selection will be made. - \value Clear The complete selection will be cleared. - \value Select All specified indexes will be selected. - \value Deselect All specified indexes will be deselected. - \value Toggle All specified indexes will be selected or - deselected depending on their current state. - \value Current The current selection will be updated. - \value Rows All indexes will be expanded to span rows. - \value Columns All indexes will be expanded to span columns. - \value SelectCurrent A combination of Select and Current, provided for - convenience. - \value ToggleCurrent A combination of Toggle and Current, provided for - convenience. - \value ClearAndSelect A combination of Clear and Select, provided for - convenience. + \value NoUpdate No selection will be made. + \value Clear The complete selection will be cleared. + \value Select All specified indexes will be selected. + \value Deselect All specified indexes will be deselected. + \value Toggle All specified indexes will be selected or + deselected depending on their current state. + \value Current The current selection will be updated. + \value Rows All indexes will be expanded to span rows. + \value Columns All indexes will be expanded to span columns. + \value SelectCurrent A combination of Select and Current, provided for + convenience. + \value ToggleCurrent A combination of Toggle and Current, provided for + convenience. + \value ClearAndSelect A combination of Clear and Select, provided for + convenience. */ /*! - Selects the item \a selection using the specified \a command, and emits - selectionChanged(). + Selects the item \a selection using the specified \a command, and emits + selectionChanged(). - \sa QItemSelectionModel::SelectionFlag + \sa QItemSelectionModel::SelectionFlag */ void QItemSelectionModel::select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command) { @@ -1067,7 +1066,7 @@ void QItemSelectionModel::select(const QItemSelection &selection, QItemSelection } /*! - Clears the selection model. Emits selectionChanged() and currentChanged(). + Clears the selection model. Emits selectionChanged() and currentChanged(). */ void QItemSelectionModel::clear() { @@ -1083,7 +1082,7 @@ void QItemSelectionModel::clear() } /*! - Clears the selection model. Does not emit any signals. + Clears the selection model. Does not emit any signals. */ void QItemSelectionModel::reset() { @@ -1093,8 +1092,8 @@ void QItemSelectionModel::reset() } /*! - \since 4.2 - Clears the selection in the selection model. Emits selectionChanged(). + \since 4.2 + Clears the selection in the selection model. Emits selectionChanged(). */ void QItemSelectionModel::clearSelection() { @@ -1110,14 +1109,14 @@ void QItemSelectionModel::clearSelection() /*! - Sets the model item \a index to be the current item, and emits - currentChanged(). The current item is used for keyboard navigation and - focus indication; it is independent of any selected items, although a - selected item can also be the current item. + Sets the model item \a index to be the current item, and emits + currentChanged(). The current item is used for keyboard navigation and + focus indication; it is independent of any selected items, although a + selected item can also be the current item. - Depending on the specified \a command, the \a index can also become part - of the current selection. - \sa select() + Depending on the specified \a command, the \a index can also become part + of the current selection. + \sa select() */ void QItemSelectionModel::setCurrentIndex(const QModelIndex &index, QItemSelectionModel::SelectionFlags command) { @@ -1141,8 +1140,8 @@ void QItemSelectionModel::setCurrentIndex(const QModelIndex &index, QItemSelecti } /*! - Returns the model item index for the current item, or an invalid index - if there is no current item. + Returns the model item index for the current item, or an invalid index + if there is no current item. */ QModelIndex QItemSelectionModel::currentIndex() const { @@ -1150,7 +1149,7 @@ QModelIndex QItemSelectionModel::currentIndex() const } /*! - Returns true if the given model item \a index is selected. + Returns true if the given model item \a index is selected. */ bool QItemSelectionModel::isSelected(const QModelIndex &index) const { @@ -1187,12 +1186,12 @@ bool QItemSelectionModel::isSelected(const QModelIndex &index) const } /*! - Returns true if all items are selected in the \a row with the given - \a parent. + Returns true if all items are selected in the \a row with the given + \a parent. - Note that this function is usually faster than calling isSelected() - on all items in the same row and that unselectable items are - ignored. + Note that this function is usually faster than calling isSelected() + on all items in the same row and that unselectable items are + ignored. */ bool QItemSelectionModel::isRowSelected(int row, const QModelIndex &parent) const { @@ -1247,12 +1246,12 @@ bool QItemSelectionModel::isRowSelected(int row, const QModelIndex &parent) cons } /*! - Returns true if all items are selected in the \a column with the given - \a parent. + Returns true if all items are selected in the \a column with the given + \a parent. - Note that this function is usually faster than calling isSelected() - on all items in the same column and that unselectable items are - ignored. + Note that this function is usually faster than calling isSelected() + on all items in the same column and that unselectable items are + ignored. */ bool QItemSelectionModel::isColumnSelected(int column, const QModelIndex &parent) const { @@ -1307,8 +1306,8 @@ bool QItemSelectionModel::isColumnSelected(int column, const QModelIndex &parent } /*! - Returns true if there are any items selected in the \a row with the given - \a parent. + Returns true if there are any items selected in the \a row with the given + \a parent. */ bool QItemSelectionModel::rowIntersectsSelection(int row, const QModelIndex &parent) const { @@ -1336,8 +1335,8 @@ bool QItemSelectionModel::rowIntersectsSelection(int row, const QModelIndex &par } /*! - Returns true if there are any items selected in the \a column with the given - \a parent. + Returns true if there are any items selected in the \a column with the given + \a parent. */ bool QItemSelectionModel::columnIntersectsSelection(int column, const QModelIndex &parent) const { @@ -1377,15 +1376,14 @@ bool QItemSelectionModel::hasSelection() const QItemSelection sel = d->ranges; sel.merge(d->currentSelection, d->currentCommand); return !sel.isEmpty(); - } - else { + } else { return !(d->ranges.isEmpty() && d->currentSelection.isEmpty()); } } /*! - Returns a list of all selected model item indexes. The list contains no - duplicates, and is not sorted. + Returns a list of all selected model item indexes. The list contains no + duplicates, and is not sorted. */ QModelIndexList QItemSelectionModel::selectedIndexes() const { @@ -1396,10 +1394,10 @@ QModelIndexList QItemSelectionModel::selectedIndexes() const } /*! - \since 4.2 - Returns the indexes in the given \a column for the rows where all columns are selected. + \since 4.2 + Returns the indexes in the given \a column for the rows where all columns are selected. - \sa selectedIndexes(), selectedColumns() + \sa selectedIndexes(), selectedColumns() */ QModelIndexList QItemSelectionModel::selectedRows(int column) const @@ -1460,7 +1458,7 @@ QModelIndexList QItemSelectionModel::selectedColumns(int row) const } /*! - Returns the selection ranges stored in the selection model. + Returns the selection ranges stored in the selection model. */ const QItemSelection QItemSelectionModel::selection() const { @@ -1480,7 +1478,7 @@ const QItemSelection QItemSelectionModel::selection() const } /*! - Returns the item model operated on by the selection model. + Returns the item model operated on by the selection model. */ const QAbstractItemModel *QItemSelectionModel::model() const { @@ -1488,8 +1486,8 @@ const QAbstractItemModel *QItemSelectionModel::model() const } /*! - Compares the two selections \a newSelection and \a oldSelection - and emits selectionChanged() with the deselected and selected items. + Compares the two selections \a newSelection and \a oldSelection + and emits selectionChanged() with the deselected and selected items. */ void QItemSelectionModel::emitSelectionChanged(const QItemSelection &newSelection, const QItemSelection &oldSelection) diff --git a/src/gui/itemviews/qlistwidget.cpp b/src/gui/itemviews/qlistwidget.cpp index 7113217..2565657 100644 --- a/src/gui/itemviews/qlistwidget.cpp +++ b/src/gui/itemviews/qlistwidget.cpp @@ -561,6 +561,13 @@ Qt::DropActions QListModel::supportedDropActions() const given \a parent. If the parent is not specified, the item will need to be inserted into a list widget with QListWidget::insertItem(). + + \note that this constructor inserts this same object into the model of + the parent that is passed to the constructor. If the model is sorted then + the behavior of the insert is undetermined since the model will call + the '<' operator method on this object which has still not yet been + constructed. In this case it would be better not to specify the parent + and use the QListWidget::insertItem method to insert the item instead. \sa type() */ @@ -582,6 +589,13 @@ QListWidgetItem::QListWidgetItem(QListWidget *view, int type) given \a text and \a parent. If the parent is not specified, the item will need to be inserted into a list widget with QListWidget::insertItem(). + + \note that this constructor inserts this same object into the model of + the parent that is passed to the constructor. If the model is sorted then + the behavior of the insert is undetermined since the model will call + the '<' operator method on this object which has still not yet been + constructed. In this case it would be better not to specify the parent + and use the QListWidget::insertItem method to insert the item instead. \sa type() */ @@ -605,7 +619,14 @@ QListWidgetItem::QListWidgetItem(const QString &text, QListWidget *view, int typ given \a icon, \a text and \a parent. If the parent is not specified, the item will need to be inserted into a list widget with QListWidget::insertItem(). - + + \note that this constructor inserts this same object into the model of + the parent that is passed to the constructor. If the model is sorted then + the behavior of the insert is undetermined since the model will call + the '<' operator method on this object which has still not yet been + constructed. In this case it would be better not to specify the parent + and use the QListWidget::insertItem method to insert the item instead. + \sa type() */ QListWidgetItem::QListWidgetItem(const QIcon &icon,const QString &text, @@ -1268,7 +1289,7 @@ void QListWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, This signal is emitted whenever the selection changes. - \sa selectedItems() isItemSelected() currentItemChanged() + \sa selectedItems() QListWidgetItem::isSelected() currentItemChanged() */ /*! diff --git a/src/gui/itemviews/qstandarditemmodel.cpp b/src/gui/itemviews/qstandarditemmodel.cpp index e71d8f9..6f99fb5 100644 --- a/src/gui/itemviews/qstandarditemmodel.cpp +++ b/src/gui/itemviews/qstandarditemmodel.cpp @@ -1745,15 +1745,17 @@ QList<QStandardItem*> QStandardItem::takeRow(int row) if (d->model) d->model->d_func()->rowsAboutToBeRemoved(this, row, row); QList<QStandardItem*> items; - int index = d->childIndex(row, 0); - int col_count = d->columnCount(); - for (int column = 0; column < col_count; ++column) { - QStandardItem *ch = d->children.at(index + column); - if (ch) - ch->d_func()->setParentAndModel(0, 0); - items.append(ch); + int index = d->childIndex(row, 0); // Will return -1 if there are no columns + if (index != -1) { + int col_count = d->columnCount(); + for (int column = 0; column < col_count; ++column) { + QStandardItem *ch = d->children.at(index + column); + if (ch) + ch->d_func()->setParentAndModel(0, 0); + items.append(ch); + } + d->children.remove(index, col_count); } - d->children.remove(index, col_count); d->rows--; if (d->model) d->model->d_func()->rowsRemoved(this, row, 1); diff --git a/src/gui/itemviews/qstyleditemdelegate.cpp b/src/gui/itemviews/qstyleditemdelegate.cpp index bd8fdac..34667ee 100644 --- a/src/gui/itemviews/qstyleditemdelegate.cpp +++ b/src/gui/itemviews/qstyleditemdelegate.cpp @@ -674,22 +674,19 @@ bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event) } else if (event->type() == QEvent::FocusOut || (event->type() == QEvent::Hide && editor->isWindow())) { //the Hide event will take care of he editors that are in fact complete dialogs if (!editor->isActiveWindow() || (QApplication::focusWidget() != editor)) { - if (editor->isAncestorOf(QApplication::focusWidget())) - return false; // don't worry about focus changes internally in the editor - + QWidget *w = QApplication::focusWidget(); + while (w) { // don't worry about focus changes internally in the editor + if (w == editor) + return false; + w = w->parentWidget(); + } #ifndef QT_NO_DRAGANDDROP // The window may lose focus during an drag operation. // i.e when dragging involves the taskbar on Windows. if (QDragManager::self() && QDragManager::self()->object != 0) return false; #endif - // Opening a modal dialog will start a new eventloop - // that will process the deleteLater event. - QWidget *activeModalWidget = QApplication::activeModalWidget(); - if (activeModalWidget - && !activeModalWidget->isAncestorOf(editor) - && qobject_cast<QDialog*>(activeModalWidget)) - return false; + emit commitData(editor); emit closeEditor(editor, NoHint); } @@ -749,8 +746,13 @@ bool QStyledItemDelegate::editorEvent(QEvent *event, return false; } - Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked + Qt::CheckState state; + if ( flags & Qt::ItemIsTristate ) { + state = static_cast<Qt::CheckState>( (value.toInt() + 1) % 3 ); + } else { + state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked ? Qt::Unchecked : Qt::Checked); + } return model->setData(index, state, Qt::CheckStateRole); } diff --git a/src/gui/itemviews/qtablewidget.cpp b/src/gui/itemviews/qtablewidget.cpp index d975d58..5756f35 100644 --- a/src/gui/itemviews/qtablewidget.cpp +++ b/src/gui/itemviews/qtablewidget.cpp @@ -1719,7 +1719,7 @@ void QTableWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, This signal is emitted whenever the selection changes. - \sa selectedItems() isItemSelected() + \sa selectedItems() QTableWidgetItem::isSelected() */ diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index ccfa568..e724a7d 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -2437,7 +2437,7 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, \note This signal will not be emitted if an item changes its state when expandAll() is invoked. - \sa isItemExpanded(), itemCollapsed(), expandItem() + \sa QTreeWidgetItem::isExpanded(), itemCollapsed(), expandItem() */ /*! @@ -2449,7 +2449,7 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, \note This signal will not be emitted if an item changes its state when collapseAll() is invoked. - \sa isItemExpanded(), itemExpanded(), collapseItem() + \sa QTreeWidgetItem::isExpanded(), itemExpanded(), collapseItem() */ /*! @@ -3109,9 +3109,9 @@ bool QTreeWidget::isItemExpanded(const QTreeWidgetItem *item) const \sa expandItem(), collapseItem(), itemExpanded() - \obsolete + \obsolete - This function is deprecated. Use \l{QTreeWidgetItem::setExpanded()} instead. + This function is deprecated. Use \l{QTreeWidgetItem::setExpanded()} instead. */ void QTreeWidget::setItemExpanded(const QTreeWidgetItem *item, bool expand) { diff --git a/src/gui/kernel/qaction.h b/src/gui/kernel/qaction.h index 133fab4..cb681c4 100644 --- a/src/gui/kernel/qaction.h +++ b/src/gui/kernel/qaction.h @@ -68,24 +68,24 @@ class Q_GUI_EXPORT QAction : public QObject Q_ENUMS(MenuRole) Q_ENUMS(Priority) - Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable) + Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable NOTIFY changed) Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled) - Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) - Q_PROPERTY(QIcon icon READ icon WRITE setIcon) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QString iconText READ iconText WRITE setIconText) - Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip) - Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip) - Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis) - Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY changed) + Q_PROPERTY(QIcon icon READ icon WRITE setIcon NOTIFY changed) + Q_PROPERTY(QString text READ text WRITE setText NOTIFY changed) + Q_PROPERTY(QString iconText READ iconText WRITE setIconText NOTIFY changed) + Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip NOTIFY changed) + Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip NOTIFY changed) + Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis NOTIFY changed) + Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY changed) #ifndef QT_NO_SHORTCUT - Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut) - Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext) - Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat) + Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut NOTIFY changed) + Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext NOTIFY changed) + Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat NOTIFY changed) #endif - Q_PROPERTY(bool visible READ isVisible WRITE setVisible) - Q_PROPERTY(MenuRole menuRole READ menuRole WRITE setMenuRole) - Q_PROPERTY(bool iconVisibleInMenu READ isIconVisibleInMenu WRITE setIconVisibleInMenu) + Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY changed) + Q_PROPERTY(MenuRole menuRole READ menuRole WRITE setMenuRole NOTIFY changed) + Q_PROPERTY(bool iconVisibleInMenu READ isIconVisibleInMenu WRITE setIconVisibleInMenu NOTIFY changed) Q_PROPERTY(Priority priority READ priority WRITE setPriority) public: diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index 3453408..c24ff49 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -39,6 +39,7 @@ ** ****************************************************************************/ +#include "qplatformdefs.h" #include "qabstracteventdispatcher.h" #include "qaccessible.h" #include "qapplication.h" @@ -178,11 +179,11 @@ QApplicationPrivate::~QApplicationPrivate() QApplication contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the - application's initialization and finalization, and provides session - management. In addition, it handles most system-wide and application-wide - settings. + application's initialization, finalization, and provides session + management. In addition, QApplication handles most of the system-wide and + application-wide settings. - For any GUI application using Qt, there is precisely one QApplication + For any GUI application using Qt, there is precisely \bold one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time. For non-GUI Qt applications, use QCoreApplication instead, as it does not depend on the \l QtGui library. @@ -238,9 +239,9 @@ QApplicationPrivate::~QApplicationPrivate() saveState() for details. \endlist - The QApplication object does so much initialization. Hence, it \e{must} be + Since the QApplication object does so much initialization, it \e{must} be created before any other objects related to the user interface are created. - Since QApplication also deals with common command line arguments, it is + QApplication also deals with common command line arguments. Hence, it is usually a good idea to create it \e before any interpretation or modification of \c argv is done in the application itself. @@ -672,9 +673,9 @@ QApplication::QApplication(int &argc, char **argv, int _internal) On X11, the window system is initialized if \a GUIenabled is true. If \a GUIenabled is false, the application does not connect to the X server. - On Windows and Macintosh, currently the window system is always - initialized, regardless of the value of GUIenabled. This may change in - future versions of Qt. + On Windows and Mac OS, currently the window system is always initialized, + regardless of the value of GUIenabled. This may change in future versions + of Qt. The following example shows how to create an application that uses a graphical interface when available. @@ -1193,21 +1194,22 @@ bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventLis \since 4.4 \brief defines a threshold for auto maximizing widgets - The auto maximize threshold is only available as part of Qt for Windows CE. + \bold{The auto maximize threshold is only available as part of Qt for + Windows CE.} This property defines a threshold for the size of a window as a percentage of the screen size. If the minimum size hint of a window exceeds the - threshold, calling show() will then cause the window to be maximized + threshold, calling show() will cause the window to be maximized automatically. - Setting the threshold to be 100 or greater means that it will cause it to - always be maximized. Setting it to be 50 means that the widget is maximized - if the vertical minimum size hint is at least 50% of the vertical screen - size. + Setting the threshold to 100 or greater means that the widget will always + be maximized. Alternatively, setting the threshold to 50 means that the + widget will be maximized only if the vertical minimum size hint is at least + 50% of the vertical screen size. - If -1 is specified then this will disable the feature. + Setting the threshold to -1 disables the feature. - On Windows CE the default is -1 (i.e. it is disabled). + On Windows CE the default is -1 (i.e., it is disabled). On Windows Mobile the default is 40. */ @@ -1216,9 +1218,9 @@ bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventLis \since 4.5 \brief toggles automatic SIP (software input panel) visibility - The auto SIP property is only available as part of Qt for Windows CE. + \bold{The auto SIP property is only available as part of Qt for Windows CE.} - Set this property to true to automatically display the SIP when entering + Set this property to \c true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set. */ @@ -1516,7 +1518,7 @@ int QApplication::colorSpec() strategy. Use this option if your application uses buttons, menus, texts and pixmaps with few colors. With this option, the application uses system global colors. This works fine for most - applications under X11, but on Windows machines it may cause + applications under X11, but on the Windows platform, it may cause dithering of non-standard colors. \o QApplication::CustomColor. Use this option if your application needs a small number of custom colors. On X11, this option is the @@ -3512,12 +3514,12 @@ void QApplication::changeOverrideCursor(const QCursor &cursor) We recommend that you connect clean-up code to the \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your - application's \c{main()} function because on some platforms the - QApplication::exec() call may not return. For example, on Windows when the - user logs off, the system terminates the process after Qt closes all - top-level windows. Hence, there is no guarantee that the application will - have time to exit its event loop and execute code at the end of the - \c{main()} function after the QApplication::exec() call. + application's \c{main()} function. This is because, on some platforms the + QApplication::exec() call may not return. For example, on the Windows + platform, when the user logs off, the system terminates the process after Qt + closes all top-level windows. Hence, there is \e{no guarantee} that the + application will have time to exit its event loop and execute code at the + end of the \c{main()} function, after the QApplication::exec() call. \sa quitOnLastWindowClosed, quit(), exit(), processEvents(), QCoreApplication::exec() @@ -4050,7 +4052,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e) touchEvent->setAccepted(eventAccepted); break; } - case QEvent::WinGesture: + case QEvent::NativeGesture: { // only propagate the first gesture event (after the GID_BEGIN) QWidget *w = static_cast<QWidget *>(receiver); @@ -4761,7 +4763,7 @@ bool QApplication::keypadNavigationEnabled() On Mac OS X, this works more at the application level and will cause the application icon to bounce in the dock. - On Windows this causes the window's taskbar entry to flash for a time. If + On Windows, this causes the window's taskbar entry to flash for a time. If \a msec is zero, the flashing will stop and the taskbar entry will turn a different color (currently orange). @@ -4778,24 +4780,22 @@ bool QApplication::keypadNavigationEnabled() caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary. - The default value on X11 is 1000 milliseconds. On Windows, the control - panel value is used. Widgets should not cache this value since it may be - changed at any time by the user changing the global desktop settings. + The default value on X11 is 1000 milliseconds. On Windows, the + \gui{Control Panel} value is used and setting this property sets the cursor + flash time for all applications. - \note On Microsoft Windows, setting this property sets the cursor flash - time for all applications. + We recommend that widgets do not cache this value as it may change at any + time if the user changes the global desktop settings. */ /*! \property QApplication::doubleClickInterval - \brief the time limit in milliseconds that distinguishes a double click from two - consecutive mouse clicks - - The default value on X11 is 400 milliseconds. On Windows and Mac OS X, the - operating system's value is used. + \brief the time limit in milliseconds that distinguishes a double click + from two consecutive mouse clicks - On Microsoft Windows, calling this function sets the double click interval - for all applications. + The default value on X11 is 400 milliseconds. On Windows and Mac OS, the + operating system's value is used. However, on Windows, calling this + function sets the double click interval for all applications. */ /*! @@ -4804,7 +4804,7 @@ bool QApplication::keypadNavigationEnabled() from two consecutive key presses \since 4.2 - The default value on X11 is 400 milliseconds. On Windows and Mac OS X, the + The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system's value is used. */ @@ -4869,7 +4869,7 @@ bool QApplication::keypadNavigationEnabled() You need not have a main widget; connecting lastWindowClosed() to quit() is an alternative. - For X11, this function also resizes and moves the main widget according + On X11, this function also resizes and moves the main widget according to the \e -geometry command-line option, so you should set the default geometry (using \l QWidget::setGeometry()) before calling setMainWidget(). @@ -4898,9 +4898,10 @@ bool QApplication::keypadNavigationEnabled() Application cursors are stored on an internal stack. setOverrideCursor() pushes the cursor onto the stack, and restoreOverrideCursor() pops the active cursor off the stack. changeOverrideCursor() changes the curently - active application override cursor. Every setOverrideCursor() must - eventually be followed by a corresponding restoreOverrideCursor(), - otherwise the stack will never be emptied. + active application override cursor. + + Every setOverrideCursor() must eventually be followed by a corresponding + restoreOverrideCursor(), otherwise the stack will never be emptied. Example: \snippet doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp 0 @@ -5081,19 +5082,19 @@ bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy) */ /*! \fn QDecoration* QApplication::qwsSetDecoration(const QString &decoration) - \overload + \overload - Requests a QDecoration object for \a decoration from the QDecorationFactory. + Requests a QDecoration object for \a decoration from the + QDecorationFactory. - The string must be one of the QDecorationFactory::keys(). Keys are - case insensitive. + The string must be one of the QDecorationFactory::keys(). Keys are case + insensitive. - A later call to the QApplication constructor will override the - requested style when a "-style" option is passed in as a commandline - parameter. + A later call to the QApplication constructor will override the requested + style when a "-style" option is passed in as a commandline parameter. - Returns 0 if an unknown \a decoration is passed, otherwise the QStyle object - returned is set as the application's GUI style. + Returns 0 if an unknown \a decoration is passed, otherwise the QStyle object + returned is set as the application's GUI style. */ /*! diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm index beccfb0..ac132aa 100644 --- a/src/gui/kernel/qapplication_mac.mm +++ b/src/gui/kernel/qapplication_mac.mm @@ -1480,6 +1480,7 @@ QWidget *QApplicationPrivate::tryModalHelper_sys(QWidget *top) return top; } +#ifndef QT_MAC_USE_COCOA static bool qt_try_modal(QWidget *widget, EventRef event) { QWidget * top = 0; @@ -1513,6 +1514,7 @@ static bool qt_try_modal(QWidget *widget, EventRef event) #endif return !block_event; } +#endif OSStatus QApplicationPrivate::tabletProximityCallback(EventHandlerCallRef, EventRef carbonEvent, void *) @@ -2890,52 +2892,25 @@ bool QApplicationPrivate::canQuit() #endif } -void onApplicationWindowChangedActivation( QWidget*widget, bool activated ) +void onApplicationWindowChangedActivation(QWidget *widget, bool activated) { #if QT_MAC_USE_COCOA - QApplication *app = qApp; + if (!widget) + return; - if ( activated ) - { - if (QApplicationPrivate::app_style) - { + if (activated) { + if (QApplicationPrivate::app_style) { QEvent ev(QEvent::Style); qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev); } - - if (widget && app_do_modal && !qt_try_modal(widget, NULL)) - return; - - if (widget && widget->window()->isVisible()) - { - QWidget *tlw = widget->window(); - - if (tlw->isWindow() && !(tlw->windowType() == Qt::Popup) - && !qt_mac_is_macdrawer(tlw) - && (!tlw->parentWidget() || tlw->isModal() || !(tlw->windowType() == Qt::Tool))) { - bool just_send_event = false; -#if 0 - WindowActivationScope scope; - if ( GetWindowActivationScope((OSWindowRef)wid, &scope) == noErr && - scope == kWindowActivationScopeIndependent) - { - if ( GetFrontWindowOfClass(kAllWindowClasses, true) != wid ) - just_send_event = true; - } -#endif - if (just_send_event) { - QEvent e(QEvent::WindowActivate); - qt_sendSpontaneousEvent(widget, &e); - } else { - app->setActiveWindow(tlw); - } - } - } + qApp->setActiveWindow(widget); } else { // deactivated - if (widget && QApplicationPrivate::active_window == widget) - app->setActiveWindow(0); + if (QApplicationPrivate::active_window == widget) + qApp->setActiveWindow(0); } + QMenuBar::macUpdateMenuBar(); + #else Q_UNUSED(widget); Q_UNUSED(activated); diff --git a/src/gui/kernel/qapplication_p.h b/src/gui/kernel/qapplication_p.h index 595f220..700d1ab 100644 --- a/src/gui/kernel/qapplication_p.h +++ b/src/gui/kernel/qapplication_p.h @@ -234,6 +234,8 @@ typedef struct tagGESTUREINFO # define GC_PAN_WITH_SINGLE_FINGER_VERTICALLY 0x00000002 # define GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY 0x00000004 +# define GC_ZOOM 0x00000001 + typedef struct tagGESTURECONFIG { DWORD dwID; @@ -247,11 +249,12 @@ typedef struct tagGESTURECONFIG class QPanGesture; class QPinchGesture; -struct StandardGestures +struct QStandardGestures { QPanGesture *pan; QPinchGesture *pinch; - StandardGestures() : pan(0), pinch(0) { } + + QStandardGestures() : pan(0), pinch(0) { } }; @@ -513,6 +516,9 @@ public: QTouchEvent::DeviceType deviceType, const QList<QTouchEvent::TouchPoint> &touchPoints); + typedef QMap<QWidget*, QStandardGestures> WidgetStandardGesturesMap; + WidgetStandardGesturesMap widgetGestures; + #if defined(Q_WS_WIN) static PtrRegisterTouchWindow RegisterTouchWindow; static PtrGetTouchInputInfo GetTouchInputInfo; @@ -522,10 +528,6 @@ public: QList<QTouchEvent::TouchPoint> appAllTouchPoints; bool translateTouchEvent(const MSG &msg); - typedef QMap<QWidget*, StandardGestures> WidgetStandardGesturesMap; - WidgetStandardGesturesMap widgetGestures; - ulong lastGestureId; - PtrGetGestureInfo GetGestureInfo; PtrGetGestureExtraArgs GetGestureExtraArgs; PtrCloseGestureInfoHandle CloseGestureInfoHandle; diff --git a/src/gui/kernel/qapplication_qws.cpp b/src/gui/kernel/qapplication_qws.cpp index 347afc8..00695fa 100644 --- a/src/gui/kernel/qapplication_qws.cpp +++ b/src/gui/kernel/qapplication_qws.cpp @@ -101,7 +101,11 @@ #include <locale.h> #include <errno.h> #include <fcntl.h> -#include <sys/time.h> +#ifdef Q_OS_VXWORKS +# include <sys/times.h> +#else +# include <sys/time.h> +#endif #include <sys/stat.h> #include <sys/types.h> @@ -194,7 +198,14 @@ QString qws_dataDir() static QString result; if (!result.isEmpty()) return result; - QByteArray dataDir = QString::fromLatin1("/tmp/qtembedded-%1").arg(qws_display_id).toLocal8Bit(); + QByteArray dataDir; +#ifdef QT_QWS_TEMP_DIR + dataDir = QT_QWS_TEMP_DIR; +#else + dataDir = "/tmp"; +#endif + dataDir += "/qtembedded-"; + dataDir += QByteArray::number(qws_display_id); if (QT_MKDIR(dataDir, 0700)) { if (errno != EEXIST) { qFatal("Cannot create Qt for Embedded Linux data directory: %s", dataDir.constData()); @@ -208,7 +219,7 @@ QString qws_dataDir() if (!S_ISDIR(buf.st_mode)) qFatal("%s is not a directory", dataDir.constData()); -#ifndef Q_OS_INTEGRITY +#if !defined(Q_OS_INTEGRITY) && !defined(Q_OS_VXWORKS) if (buf.st_uid != getuid()) qFatal("Qt for Embedded Linux data directory is not owned by user %d", getuid()); diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index d5c820c..bdee6ec 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -815,8 +815,6 @@ void qt_init(QApplicationPrivate *priv, int) ptrSetProcessDPIAware(); #endif - priv->lastGestureId = 0; - priv->GetGestureInfo = (PtrGetGestureInfo)QLibrary::resolve(QLatin1String("user32"), "GetGestureInfo"); @@ -3718,13 +3716,8 @@ bool QETWidget::translateCloseEvent(const MSG &) bool QETWidget::translateGestureEvent(const MSG &msg) { GESTUREINFO gi; + memset(&gi, 0, sizeof(GESTUREINFO)); gi.cbSize = sizeof(GESTUREINFO); - gi.dwFlags = 0; - gi.ptsLocation.x = 0; - gi.ptsLocation.y = 0; - gi.dwID = 0; - gi.dwInstanceID = 0; - gi.dwSequenceID = 0; QApplicationPrivate *qAppPriv = getQApplicationPrivateInternal(); BOOL bResult = qAppPriv->GetGestureInfo((HANDLE)msg.lParam, &gi); @@ -3735,22 +3728,22 @@ bool QETWidget::translateGestureEvent(const MSG &msg) alienWidget = 0; QWidget *widget = alienWidget ? alienWidget : this; - QWinGestureEvent event; + QNativeGestureEvent event; event.sequenceId = gi.dwSequenceID; event.position = QPoint(gi.ptsLocation.x, gi.ptsLocation.y); if (bResult) { switch (gi.dwID) { case GID_BEGIN: - // we are not interested in this type of event. + event.gestureType = QNativeGestureEvent::GestureBegin; break; case GID_END: - event.gestureType = QWinGestureEvent::GestureEnd; + event.gestureType = QNativeGestureEvent::GestureEnd; break; case GID_ZOOM: - event.gestureType = QWinGestureEvent::Pinch; + event.gestureType = QNativeGestureEvent::Zoom; break; case GID_PAN: - event.gestureType = QWinGestureEvent::Pan; + event.gestureType = QNativeGestureEvent::Pan; break; case GID_ROTATE: case GID_TWOFINGERTAP: @@ -3758,14 +3751,14 @@ bool QETWidget::translateGestureEvent(const MSG &msg) default: break; } - if (event.gestureType != QWinGestureEvent::None) + qAppPriv->CloseGestureInfoHandle((HANDLE)msg.lParam); + if (event.gestureType != QNativeGestureEvent::None) qt_sendSpontaneousEvent(widget, &event); } else { DWORD dwErr = GetLastError(); if (dwErr > 0) qWarning() << "translateGestureEvent: error = " << dwErr; } - qAppPriv->CloseGestureInfoHandle((HANDLE)msg.lParam); return true; } diff --git a/src/gui/kernel/qboxlayout.cpp b/src/gui/kernel/qboxlayout.cpp index 770f5bb..23d20ff 100644 --- a/src/gui/kernel/qboxlayout.cpp +++ b/src/gui/kernel/qboxlayout.cpp @@ -527,7 +527,7 @@ void QBoxLayoutPrivate::calcHfw(int w) You will almost always want to use QVBoxLayout and QHBoxLayout rather than QBoxLayout because of their convenient constructors. - \sa QGridLayout, QStackedLayout, {Layout Classes} + \sa QGridLayout, QStackedLayout, {Layout Management} */ /*! @@ -1295,7 +1295,7 @@ QBoxLayout::Direction QBoxLayout::direction() const \image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets - \sa QVBoxLayout, QGridLayout, QStackedLayout, {Layout Classes}, {Basic Layouts Example} + \sa QVBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example} */ @@ -1413,7 +1413,7 @@ QHBoxLayout::~QHBoxLayout() \image qvboxlayout-with-5-children.png Horizontal box layout with five child widgets - \sa QHBoxLayout, QGridLayout, QStackedLayout, {Layout Classes}, {Basic Layouts Example} + \sa QHBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example} */ /*! diff --git a/src/gui/kernel/qcocoaview_mac.mm b/src/gui/kernel/qcocoaview_mac.mm index 3e5bfb6..8c6f394 100644 --- a/src/gui/kernel/qcocoaview_mac.mm +++ b/src/gui/kernel/qcocoaview_mac.mm @@ -50,6 +50,7 @@ #include <private/qdnd_p.h> #include <private/qmacinputcontext_p.h> #include <private/qmultitouch_mac_p.h> +#include <private/qevent_p.h> #include <qscrollarea.h> #include <qhash.h> @@ -200,6 +201,7 @@ extern "C" { composingText = new QString(); composing = false; sendKeyEvents = true; + inKeyDown = false; currentCustomTypes = 0; [self setHidden:YES]; return self; @@ -326,7 +328,7 @@ extern "C" { return NSDragOperationNone; } else { // save the mouse position, used by draggingExited handler. - DnDParams *dndParams = [QCocoaView currentMouseEvent]; + DnDParams *dndParams = [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent]; dndParams->activeDragEnterPos = windowPoint; // send a drag move event immediately after a drag enter event (as per documentation). QDragMoveEvent qDMEvent(posDrag, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers); @@ -405,7 +407,7 @@ extern "C" { dragEnterSequence = -1; if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) { // try sending the leave event to the last view which accepted drag enter. - DnDParams *dndParams = [QCocoaView currentMouseEvent]; + DnDParams *dndParams = [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent]; NSView *candidateView = [[[self window] contentView] hitTest:dndParams->activeDragEnterPos]; if (candidateView && candidateView != self) return [candidateView draggingExited:sender]; @@ -867,32 +869,65 @@ extern "C" { - (void)magnifyWithEvent:(NSEvent *)event; { - Q_UNUSED(event); -// qDebug() << "magnifyWithEvent"; + if (!QApplicationPrivate::tryModalHelper(qwidget, 0)) + return; + + QNativeGestureEvent qNGEvent; + qNGEvent.gestureType = QNativeGestureEvent::Zoom; + NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]]; + qNGEvent.position = flipPoint(p).toPoint(); + qNGEvent.percentage = [event magnification]; + qApp->sendEvent(qwidget, &qNGEvent); } - (void)rotateWithEvent:(NSEvent *)event; { - Q_UNUSED(event); -// qDebug() << "rotateWithEvent"; + if (!QApplicationPrivate::tryModalHelper(qwidget, 0)) + return; + + QNativeGestureEvent qNGEvent; + qNGEvent.gestureType = QNativeGestureEvent::Rotate; + NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]]; + qNGEvent.position = flipPoint(p).toPoint(); + qNGEvent.percentage = [event rotation]; + qApp->sendEvent(qwidget, &qNGEvent); } - (void)swipeWithEvent:(NSEvent *)event; { - Q_UNUSED(event); -// qDebug() << "swipeWithEvent"; + if (!QApplicationPrivate::tryModalHelper(qwidget, 0)) + return; + + QNativeGestureEvent qNGEvent; + qNGEvent.gestureType = QNativeGestureEvent::Swipe; + NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]]; + qNGEvent.position = flipPoint(p).toPoint(); + qNGEvent.direction = QSize(-[event deltaX], -[event deltaY]); + qApp->sendEvent(qwidget, &qNGEvent); } - (void)beginGestureWithEvent:(NSEvent *)event; { - Q_UNUSED(event); -// qDebug() << "beginGestureWithEvent"; + if (!QApplicationPrivate::tryModalHelper(qwidget, 0)) + return; + + QNativeGestureEvent qNGEvent; + qNGEvent.gestureType = QNativeGestureEvent::GestureBegin; + NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]]; + qNGEvent.position = flipPoint(p).toPoint(); + qApp->sendEvent(qwidget, &qNGEvent); } - (void)endGestureWithEvent:(NSEvent *)event; { - Q_UNUSED(event); -// qDebug() << "endGestureWithEvent"; + if (!QApplicationPrivate::tryModalHelper(qwidget, 0)) + return; + + QNativeGestureEvent qNGEvent; + qNGEvent.gestureType = QNativeGestureEvent::GestureEnd; + NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]]; + qNGEvent.position = flipPoint(p).toPoint(); + qApp->sendEvent(qwidget, &qNGEvent); } #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 @@ -983,6 +1018,7 @@ extern "C" { - (void)keyDown:(NSEvent *)theEvent { + inKeyDown = true; sendKeyEvents = true; QWidget *widgetToGetKey = qwidget; @@ -1002,6 +1038,7 @@ extern "C" { if (!keyOK && !sendToPopup) [super keyDown:theEvent]; } + inKeyDown = false; } @@ -1039,20 +1076,36 @@ extern "C" { - (void) insertText:(id)aString { + QString commitText; if ([aString length]) { - // Send the commit string to the widget. - QString commitText; if ([aString isKindOfClass:[NSAttributedString class]]) { - commitText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string])); + commitText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string])); } else { commitText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString)); }; + } + + if ([aString length] && !inKeyDown) { + // Handle the case where insertText is called from somewhere else than the keyDown + // implementation, for example when inserting text from the character palette. + QInputMethodEvent e; + e.setCommitString(commitText); + qt_sendSpontaneousEvent(qwidget, &e); + } else if ([aString length] && composing) { + // Send the commit string to the widget. composing = false; sendKeyEvents = false; QInputMethodEvent e; e.setCommitString(commitText); qt_sendSpontaneousEvent(qwidget, &e); + } else { + // The key sequence "`q" on a French Keyboard will generate two calls to insertText before + // it returns from interpretKeyEvents. The first call will turn off 'composing' and accept + // the "`" key. The last keyDown event needs to be processed by the widget to get the + // character "q". The string parameter is ignored for the second call. + sendKeyEvents = true; } + composingText->clear(); } diff --git a/src/gui/kernel/qcocoaview_mac_p.h b/src/gui/kernel/qcocoaview_mac_p.h index 4762b17..932c6ca 100644 --- a/src/gui/kernel/qcocoaview_mac_p.h +++ b/src/gui/kernel/qcocoaview_mac_p.h @@ -85,6 +85,7 @@ Q_GUI_EXPORT bool composing; int composingLength; bool sendKeyEvents; + bool inKeyDown; QString *composingText; QStringList *currentCustomTypes; NSInteger dragEnterSequence; diff --git a/src/gui/kernel/qcursor.cpp b/src/gui/kernel/qcursor.cpp index 9cca0d6..0b47b6f 100644 --- a/src/gui/kernel/qcursor.cpp +++ b/src/gui/kernel/qcursor.cpp @@ -127,11 +127,11 @@ QT_BEGIN_NAMESPACE \o Qt::SizeAllCursor \o \c size_all \row \o \inlineimage cursor-busy.png \o Qt::BusyCursor \o \c left_ptr_watch - \o \inlineimage cursor-hsplit.png + \o \inlineimage cursor-vsplit.png \o Qt::SplitVCursor \o \c split_v \row \o \inlineimage cursor-forbidden.png \o Qt::ForbiddenCursor \o \c forbidden - \o \inlineimage cursor-vsplit.png + \o \inlineimage cursor-hsplit.png \o Qt::SplitHCursor \o \c split_h \row \o \inlineimage cursor-hand.png \o Qt::PointingHandCursor \o \c pointing_hand diff --git a/src/gui/kernel/qdesktopwidget_x11.cpp b/src/gui/kernel/qdesktopwidget_x11.cpp index 1555fc0..8b0c215 100644 --- a/src/gui/kernel/qdesktopwidget_x11.cpp +++ b/src/gui/kernel/qdesktopwidget_x11.cpp @@ -285,26 +285,36 @@ const QRect QDesktopWidget::availableGeometry(int screen) const if (d->workareas[screen].isValid()) return d->workareas[screen]; - if ((d->screenCount == 1 || !isVirtualDesktop()) - && X11->isSupportedByWM(ATOM(_NET_WORKAREA))) { + if (X11->isSupportedByWM(ATOM(_NET_WORKAREA))) { + int x11Screen = isVirtualDesktop() ? DefaultScreen(X11->display) : screen; + Atom ret; int format, e; unsigned char *data = 0; unsigned long nitems, after; e = XGetWindowProperty(X11->display, - QX11Info::appRootWindow(screen), - ATOM(_NET_WORKAREA), 0, 4, False, XA_CARDINAL, - &ret, &format, &nitems, &after, &data); + QX11Info::appRootWindow(x11Screen), + ATOM(_NET_WORKAREA), 0, 4, False, XA_CARDINAL, + &ret, &format, &nitems, &after, &data); + QRect workArea; if (e == Success && ret == XA_CARDINAL && format == 32 && nitems == 4) { long *workarea = (long *) data; - d->workareas[screen].setRect(workarea[0], workarea[1], - workarea[2], workarea[3]); + workArea = QRect(workarea[0], workarea[1], workarea[2], workarea[3]); } else { - d->workareas[screen] = screenGeometry(screen); + workArea = screenGeometry(screen); + } + + if (isVirtualDesktop()) { + // intersect the workarea (which spawns all Xinerama screens) with the rect for the + // requested screen + workArea &= screenGeometry(screen); } + + d->workareas[screen] = workArea; + if (data) XFree(data); } else { diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp index 328ba3d..0fc36e7 100644 --- a/src/gui/kernel/qevent.cpp +++ b/src/gui/kernel/qevent.cpp @@ -49,7 +49,6 @@ #include "qmime.h" #include "qdnd_p.h" #include "qevent_p.h" -#include "qgesture.h" QT_BEGIN_NAMESPACE @@ -675,8 +674,9 @@ QWheelEvent::QWheelEvent(const QPoint &pos, const QPoint& globalPos, int delta, The QWidget::setEnable() function can be used to enable or disable mouse and keyboard events for a widget. - The event handlers QWidget::keyPressEvent() and - QWidget::keyReleaseEvent() receive key events. + The event handlers QWidget::keyPressEvent(), QWidget::keyReleaseEvent(), + QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent() + receive key events. \sa QFocusEvent, QWidget::grabKeyboard() */ @@ -992,8 +992,9 @@ bool QKeyEvent::matches(QKeySequence::StandardKey matchKey) const The reason for a particular focus event is returned by reason() in the appropriate event handler. - The event handlers QWidget::focusInEvent() and - QWidget::focusOutEvent() receive focus events. + The event handlers QWidget::focusInEvent(), + QWidget::focusOutEvent(), QGraphicsItem::focusInEvent and + QGraphicsItem::focusOutEvent() receive focus events. \sa QWidget::setFocus(), QWidget::setFocusPolicy(), {Keyboard Focus} */ @@ -1611,12 +1612,14 @@ Qt::ButtonState QContextMenuEvent::state() const string is controlled by the widget only). The AttributeType enum describes the different attributes that can be set. - A class implementing QWidget::inputMethodEvent() should at least - understand and honor the \l TextFormat and \l Cursor attributes. + A class implementing QWidget::inputMethodEvent() or + QGraphicsItem::inputMethodEvent() should at least understand and + honor the \l TextFormat and \l Cursor attributes. Since input methods need to be able to query certain properties - from the widget, the widget must also implement - QWidget::inputMethodQuery(). + from the widget or graphics item, subclasses must also implement + QWidget::inputMethodQuery() and QGraphicsItem::inputMethodQuery(), + respectively. When receiving an input method event, the text widget has to performs the following steps: diff --git a/src/gui/kernel/qevent_p.h b/src/gui/kernel/qevent_p.h index 67441ea..b21b35c 100644 --- a/src/gui/kernel/qevent_p.h +++ b/src/gui/kernel/qevent_p.h @@ -119,20 +119,34 @@ public: qreal pressure; }; -class QWinGestureEvent : public QEvent +class QNativeGestureEvent : public QEvent { public: enum Type { None, + GestureBegin, GestureEnd, Pan, - Pinch + Zoom, + Rotate, + Swipe }; - QWinGestureEvent() : QEvent(QEvent::WinGesture), gestureType(None), sequenceId(0) { } + QNativeGestureEvent() + : QEvent(QEvent::NativeGesture), gestureType(None), percentage(0), direction(0, 0) +#ifdef Q_WS_WIN + , sequenceId(0) +#endif + { + } + Type gestureType; + float percentage; QPoint position; + QSize direction; +#ifdef Q_WS_WIN ulong sequenceId; +#endif }; QT_END_NAMESPACE diff --git a/src/gui/kernel/qeventdispatcher_mac.mm b/src/gui/kernel/qeventdispatcher_mac.mm index cde0c47..af36d9f 100644 --- a/src/gui/kernel/qeventdispatcher_mac.mm +++ b/src/gui/kernel/qeventdispatcher_mac.mm @@ -506,16 +506,6 @@ bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags) wakeUp(); emit awake(); -#ifndef QT_MAC_NO_QUICKDRAW - if(!qt_mac_safe_pdev) { //create an empty widget and this can be used for a port anytime - QWidget *tlw = new QWidget; - tlw->setAttribute(Qt::WA_DeleteOnClose); - tlw->setObjectName(QLatin1String("empty_widget")); - tlw->hide(); - qt_mac_safe_pdev = tlw; - } -#endif - bool retVal = false; forever { if (d->interrupt) diff --git a/src/gui/kernel/qformlayout.cpp b/src/gui/kernel/qformlayout.cpp index 0b7656f..de33f93 100644 --- a/src/gui/kernel/qformlayout.cpp +++ b/src/gui/kernel/qformlayout.cpp @@ -689,16 +689,12 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width) // are split. maxLabelWidth = 0; if (!wrapAllRows) { - int maxFieldMinWidth = 0; //the maximum minimum size of the field for (int i = 0; i < rr; ++i) { const QFormLayoutItem *label = m_matrix(i, 0); const QFormLayoutItem *field = m_matrix(i, 1); - if (label && field && label->sideBySide) + if (label && (label->sizeHint.width() + (field ? field->minSize.width() : 0) <= width)) maxLabelWidth = qMax(maxLabelWidth, label->sizeHint.width()); - if (field) - maxFieldMinWidth = qMax(maxFieldMinWidth, field->minSize.width() + field->sbsHSpace); } - maxLabelWidth = qMin(maxLabelWidth, width - maxFieldMinWidth); } else { maxLabelWidth = width; } diff --git a/src/gui/kernel/qgesture.cpp b/src/gui/kernel/qgesture.cpp index d53b419..38e8851 100644 --- a/src/gui/kernel/qgesture.cpp +++ b/src/gui/kernel/qgesture.cpp @@ -97,7 +97,7 @@ private: This is a base class, to create a custom gesture type, you should subclass it and implement its pure virtual functions. - \sa QPanGesture, QTapAndHoldGesture + \sa QPanGesture */ /*! \fn bool QGesture::filterEvent(QEvent *event) @@ -153,7 +153,7 @@ QGesture::QGesture(QObject *parent) : QObject(*new QGesturePrivate, parent) { if (parent) - installEventFilter(parent); + parent->installEventFilter(this); } /*! \internal @@ -162,7 +162,7 @@ QGesture::QGesture(QGesturePrivate &dd, QObject *parent) : QObject(dd, parent) { if (parent) - installEventFilter(parent); + parent->installEventFilter(this); } /*! @@ -197,56 +197,44 @@ Qt::GestureState QGesture::state() const } /*! - Sets this gesture's recognition state to \a state. - */ -void QGesture::setState(Qt::GestureState state) -{ - d_func()->state = state; -} - -/*! - \property QGesture::startPos - - \brief The start position of the gesture (if relevant). -*/ -QPoint QGesture::startPos() const -{ - return d_func()->startPos; -} - -void QGesture::setStartPos(const QPoint &point) -{ - d_func()->startPos = point; -} - -/*! - \property QGesture::lastPos - - \brief The last recorded position of the gesture (if relevant). -*/ -QPoint QGesture::lastPos() const -{ - return d_func()->lastPos; -} - -void QGesture::setLastPos(const QPoint &point) -{ - d_func()->lastPos = point; -} + Sets this gesture's recognition state to \a state and emits appropriate + signals. -/*! - \property QGesture::pos + This functions emits the signals according to the old state and the new + \a state, and it should be called after all the internal properties have been + initialized. - \brief The current position of the gesture (if relevant). -*/ -QPoint QGesture::pos() const + \sa started, triggered, finished, cancelled + */ +void QGesture::updateState(Qt::GestureState state) { - return d_func()->pos; -} + Q_D(QGesture); + if (d->state == state) { + if (state == Qt::GestureUpdated) + emit triggered(); + return; + } + const Qt::GestureState oldState = d->state; + d->state = state; + if (state != Qt::NoGesture && oldState > state) { + // comparing the state as ints: state should only be changed from + // started to (optionally) updated and to finished. + qWarning("QGesture::updateState: incorrect new state"); + return; + } + if (oldState == Qt::NoGesture) + emit started(); + if (state == Qt::GestureUpdated) + emit triggered(); + else if (state == Qt::GestureFinished) + emit finished(); + else if (state == Qt::NoGesture) + emit cancelled(); -void QGesture::setPos(const QPoint &point) -{ - d_func()->pos = point; + if (state == Qt::GestureFinished) { + // gesture is finished, so we reset the internal state. + d->state = Qt::NoGesture; + } } /*! @@ -283,14 +271,13 @@ QGraphicsItem* QGesture::graphicsItem() const Resets the internal state of the gesture. This function might be called by the filterEvent() implementation in a derived class, or by the user to - cancel a gesture. The base class implementation emits the cancelled() - signal if the state() of the gesture wasn't empty. + cancel a gesture. The base class implementation calls + updateState(Qt::NoGesture) which emits the cancelled() + signal if the state() of the gesture indicated it was active. */ void QGesture::reset() { - if (state() != Qt::NoGesture) - emit cancelled(); - setState(Qt::NoGesture); + updateState(Qt::NoGesture); } QT_END_NAMESPACE diff --git a/src/gui/kernel/qgesture.h b/src/gui/kernel/qgesture.h index 1cd9cae..7da37c4 100644 --- a/src/gui/kernel/qgesture.h +++ b/src/gui/kernel/qgesture.h @@ -64,10 +64,6 @@ class Q_GUI_EXPORT QGesture : public QObject Q_PROPERTY(Qt::GestureState state READ state) - Q_PROPERTY(QPoint startPos READ startPos WRITE setStartPos) - Q_PROPERTY(QPoint lastPos READ lastPos WRITE setLastPos) - Q_PROPERTY(QPoint pos READ pos WRITE setPos) - public: explicit QGesture(QObject *parent = 0); ~QGesture(); @@ -80,19 +76,13 @@ public: virtual void reset(); Qt::GestureState state() const; - void setState(Qt::GestureState state); - - QPoint startPos() const; - void setStartPos(const QPoint &point); - QPoint lastPos() const; - void setLastPos(const QPoint &point); - QPoint pos() const; - void setPos(const QPoint &point); protected: QGesture(QGesturePrivate &dd, QObject *parent); bool eventFilter(QObject*, QEvent*); + void updateState(Qt::GestureState state); + Q_SIGNALS: void started(); void triggered(); diff --git a/src/gui/kernel/qgesture_p.h b/src/gui/kernel/qgesture_p.h index 99f572f..56eaee7 100644 --- a/src/gui/kernel/qgesture_p.h +++ b/src/gui/kernel/qgesture_p.h @@ -73,22 +73,11 @@ public: { } - void init(const QPoint &startPos, const QPoint &lastPos, - const QPoint &pos) - { - this->startPos = startPos; - this->lastPos = lastPos; - this->pos = pos; - } QGraphicsItem *graphicsItem; QGraphicsItem *eventFilterProxyGraphicsItem; Qt::GestureState state; - - QPoint startPos; - QPoint lastPos; - QPoint pos; }; QT_END_NAMESPACE diff --git a/src/gui/kernel/qgridlayout.cpp b/src/gui/kernel/qgridlayout.cpp index 8dbc3cb..558f570 100644 --- a/src/gui/kernel/qgridlayout.cpp +++ b/src/gui/kernel/qgridlayout.cpp @@ -1034,18 +1034,19 @@ QRect QGridLayoutPrivate::cellRect(int row, int col) const other layouts into the cells of your grid layout using addWidget(), addItem(), and addLayout(). - QGridLayout also includes two margin widths: the margin() and the - spacing(). The margin is the width of the reserved space along - each of the QGridLayout's four sides. The spacing is the width of - the automatically allocated spacing between neighboring boxes. - - The default margin() and spacing() values are provided by the - style. The default margin Qt styles specify is 9 for child - widgets and 11 for windows. The spacing defaults to the same as + QGridLayout also includes two margin widths: + the \l{getContentsMargins()}{contents margin} and the spacing(). + The contents margin is the width of the reserved space along each + of the QGridLayout's four sides. The spacing() is the width of the + automatically allocated spacing between neighboring boxes. + + The default contents margin values are provided by the + \l{QStyle::pixelMetric()}{style}. The default value Qt styles specify + is 9 for child widgets and 11 for windows. The spacing defaults to the same as the margin width for a top-level layout, or to the same as the parent layout. - \sa QBoxLayout, QStackedLayout, {Layout Classes}, {Basic Layouts Example} + \sa QBoxLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example} */ @@ -1078,7 +1079,7 @@ QGridLayout::QGridLayout() #ifdef QT3_SUPPORT /*! - \obsolete + \obsolete Constructs a new QGridLayout with \a nRows rows, \a nCols columns and parent widget, \a parent. \a parent may not be 0. The grid layout is called \a name. diff --git a/src/gui/kernel/qkeymapper_mac.cpp b/src/gui/kernel/qkeymapper_mac.cpp index 017c13c..8eee665 100644 --- a/src/gui/kernel/qkeymapper_mac.cpp +++ b/src/gui/kernel/qkeymapper_mac.cpp @@ -729,8 +729,10 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, EventHandlerCallRef e QString text(ourChar); /* This is actually wrong - but unfortunatly it is the best that can be done for now because of the Control/Meta mapping problems */ - if (modifiers & (Qt::ControlModifier | Qt::MetaModifier)) + if (modifiers & (Qt::ControlModifier | Qt::MetaModifier) + && !qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) { text = QString(); + } if (widget) { diff --git a/src/gui/kernel/qlayout.cpp b/src/gui/kernel/qlayout.cpp index e750088..941db8f 100644 --- a/src/gui/kernel/qlayout.cpp +++ b/src/gui/kernel/qlayout.cpp @@ -83,7 +83,7 @@ static int menuBarHeightForWidth(QWidget *menubar, int w) For users of QLayout subclasses or of QMainWindow there is seldom any need to use the basic functions provided by QLayout, such as - setSizeConstraint() or setMenuBar(). See \l{Layout Classes} + setSizeConstraint() or setMenuBar(). See \l{Layout Management} for more information. To make your own layout manager, implement the functions @@ -98,7 +98,7 @@ static int menuBarHeightForWidth(QWidget *menubar, int w) Geometry management stops when the layout manager is deleted. - \sa QLayoutItem, {Layout Classes}, {Basic Layouts Example}, + \sa QLayoutItem, {Layout Management}, {Basic Layouts Example}, {Border Layout Example}, {Flow Layout Example} */ diff --git a/src/gui/kernel/qstandardgestures.cpp b/src/gui/kernel/qstandardgestures.cpp index c8b11c5..7078dbf 100644 --- a/src/gui/kernel/qstandardgestures.cpp +++ b/src/gui/kernel/qstandardgestures.cpp @@ -45,9 +45,15 @@ #include <qabstractscrollarea.h> #include <qscrollbar.h> #include <private/qapplication_p.h> +#include <private/qevent_p.h> +#include <private/qwidget_p.h> QT_BEGIN_NAMESPACE +#ifdef Q_WS_WIN +QWidgetPrivate *qt_widget_private(QWidget *widget); +#endif + /*! \class QPanGesture \since 4.6 @@ -66,36 +72,103 @@ QT_BEGIN_NAMESPACE QPanGesture::QPanGesture(QWidget *parent) : QGesture(*new QPanGesturePrivate, parent) { -#ifdef Q_WS_WIN if (parent) { - QApplicationPrivate* getQApplicationPrivateInternal(); - QApplicationPrivate *qAppPriv = getQApplicationPrivateInternal(); + QApplicationPrivate *qAppPriv = QApplicationPrivate::instance(); qAppPriv->widgetGestures[parent].pan = this; - } +#ifdef Q_WS_WIN + qt_widget_private(parent)->winSetupGestures(); #endif + } } /*! \internal */ bool QPanGesture::event(QEvent *event) { -#ifdef Q_WS_WIN - QApplicationPrivate* getQApplicationPrivateInternal(); switch (event->type()) { case QEvent::ParentAboutToChange: - if (QWidget *w = qobject_cast<QWidget*>(parent())) - getQApplicationPrivateInternal()->widgetGestures[w].pan = 0; + if (QWidget *w = qobject_cast<QWidget*>(parent())) { + QApplicationPrivate::instance()->widgetGestures[w].pan = 0; +#ifdef Q_WS_WIN + qt_widget_private(w)->winSetupGestures(); +#endif + } break; case QEvent::ParentChange: - if (QWidget *w = qobject_cast<QWidget*>(parent())) - getQApplicationPrivateInternal()->widgetGestures[w].pan = this; + if (QWidget *w = qobject_cast<QWidget*>(parent())) { + QApplicationPrivate::instance()->widgetGestures[w].pan = this; +#ifdef Q_WS_WIN + qt_widget_private(w)->winSetupGestures(); +#endif + } break; default: break; } + +#if defined(Q_OS_MAC) && !defined(QT_MAC_USE_COCOA) + Q_D(QPanGesture); + if (event->type() == QEvent::Timer) { + const QTimerEvent *te = static_cast<QTimerEvent *>(event); + if (te->timerId() == d->panFinishedTimer) { + killTimer(d->panFinishedTimer); + d->panFinishedTimer = 0; + d->lastOffset = QSize(0, 0); + updateState(Qt::GestureFinished); + } + } #endif + return QObject::event(event); } +bool QPanGesture::eventFilter(QObject *receiver, QEvent *event) +{ +#ifdef Q_WS_WIN + Q_D(QPanGesture); + if (receiver->isWidgetType() && event->type() == QEvent::NativeGesture) { + QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event); + QApplicationPrivate *qAppPriv = QApplicationPrivate::instance(); + QApplicationPrivate::WidgetStandardGesturesMap::iterator it; + it = qAppPriv->widgetGestures.find(static_cast<QWidget*>(receiver)); + if (it == qAppPriv->widgetGestures.end()) + return false; + QPanGesture *gesture = it.value().pan; + if (this != gesture) + return false; + Qt::GestureState nextState = Qt::NoGesture; + switch(ev->gestureType) { + case QNativeGestureEvent::GestureBegin: + // next we might receive the first gesture update event, so we + // prepare for it. + d->state = Qt::NoGesture; + return false; + case QNativeGestureEvent::Pan: + nextState = Qt::GestureUpdated; + event->accept(); + break; + case QNativeGestureEvent::GestureEnd: + if (state() == Qt::NoGesture) + return false; // some other gesture has ended + nextState = Qt::GestureFinished; + break; + default: + return false; + } + if (state() == Qt::NoGesture) { + d->lastOffset = d->totalOffset = QSize(); + } else { + d->lastOffset = QSize(ev->position.x() - d->lastPosition.x(), + ev->position.y() - d->lastPosition.y()); + d->totalOffset += d->lastOffset; + } + d->lastPosition = ev->position; + gesture->updateState(nextState); + return true; + } +#endif + return QGesture::eventFilter(receiver, event); +} + /*! \internal */ bool QPanGesture::filterEvent(QEvent *event) { @@ -104,35 +177,62 @@ bool QPanGesture::filterEvent(QEvent *event) return false; const QTouchEvent *ev = static_cast<const QTouchEvent*>(event); if (event->type() == QEvent::TouchBegin) { - d->touchPoints = ev->touchPoints(); - const QPoint p = ev->touchPoints().at(0).pos().toPoint(); - setStartPos(p); - setLastPos(p); - setPos(p); - return false; + QTouchEvent::TouchPoint p = ev->touchPoints().at(0); + d->lastPosition = p.pos().toPoint(); + d->lastOffset = d->totalOffset = QSize(); } else if (event->type() == QEvent::TouchEnd) { if (state() != Qt::NoGesture) { - setState(Qt::GestureFinished); - setLastPos(pos()); - setPos(ev->touchPoints().at(0).pos().toPoint()); - emit triggered(); - emit finished(); + if (!ev->touchPoints().isEmpty()) { + QTouchEvent::TouchPoint p = ev->touchPoints().at(0); + const QPoint pos = p.pos().toPoint(); + const QPoint lastPos = p.lastPos().toPoint(); + const QPoint startPos = p.startPos().toPoint(); + d->lastOffset = QSize(pos.x() - lastPos.x(), pos.y() - lastPos.y()); + d->totalOffset = QSize(pos.x() - startPos.x(), pos.y() - startPos.y()); + } + updateState(Qt::GestureFinished); } - setState(Qt::NoGesture); reset(); } else if (event->type() == QEvent::TouchUpdate) { - d->touchPoints = ev->touchPoints(); - QPointF pt = d->touchPoints.at(0).pos() - d->touchPoints.at(0).startPos(); - setLastPos(pos()); - setPos(ev->touchPoints().at(0).pos().toPoint()); - if (pt.x() > 10 || pt.y() > 10 || pt.x() < -10 || pt.y() < -10) { - if (state() == Qt::NoGesture) - setState(Qt::GestureStarted); - else - setState(Qt::GestureUpdated); - emit triggered(); + QTouchEvent::TouchPoint p = ev->touchPoints().at(0); + const QPoint pos = p.pos().toPoint(); + const QPoint lastPos = p.lastPos().toPoint(); + const QPoint startPos = p.startPos().toPoint(); + d->lastOffset = QSize(pos.x() - lastPos.x(), pos.y() - lastPos.y()); + d->totalOffset = QSize(pos.x() - startPos.x(), pos.y() - startPos.y()); + if (d->totalOffset.width() > 10 || d->totalOffset.height() > 10 || + d->totalOffset.width() < -10 || d->totalOffset.height() < -10) { + updateState(Qt::GestureUpdated); } } +#ifdef Q_OS_MAC + else if (event->type() == QEvent::Wheel) { + // On Mac, there is really no native panning gesture. Instead, a two + // finger pan is delivered as mouse wheel events. Otoh, on Windows, you + // either get mouse wheel events or pan events. We have decided to make this + // the Qt behaviour as well, meaning that on Mac, wheel + // events will be masked away when listening for pan events. +#ifndef QT_MAC_USE_COCOA + // In Carbon we receive neither touch-, nor pan gesture events. + // So we create pan gestures by converting wheel events. After all, this + // is how things are supposed to work on mac in the first place. + const QWheelEvent *wev = static_cast<const QWheelEvent*>(event); + int offset = wev->delta() / -120; + d->lastOffset = wev->orientation() == Qt::Horizontal ? QSize(offset, 0) : QSize(0, offset); + + if (state() == Qt::NoGesture) { + d->totalOffset = d->lastOffset; + } else { + d->totalOffset += d->lastOffset; + } + + killTimer(d->panFinishedTimer); + d->panFinishedTimer = startTimer(200); + updateState(Qt::GestureUpdated); +#endif + return true; + } +#endif return false; } @@ -140,7 +240,14 @@ bool QPanGesture::filterEvent(QEvent *event) void QPanGesture::reset() { Q_D(QPanGesture); - d->touchPoints.clear(); + d->lastOffset = d->totalOffset = QSize(); + d->lastPosition = QPoint(); +#if defined(Q_OS_MAC) && !defined(QT_MAC_USE_COCOA) + if (d->panFinishedTimer) { + killTimer(d->panFinishedTimer); + d->panFinishedTimer = 0; + } +#endif } /*! @@ -150,8 +257,8 @@ void QPanGesture::reset() */ QSize QPanGesture::totalOffset() const { - QPoint pt = pos() - startPos(); - return QSize(pt.x(), pt.y()); + Q_D(const QPanGesture); + return d->totalOffset; } /*! @@ -162,93 +269,11 @@ QSize QPanGesture::totalOffset() const */ QSize QPanGesture::lastOffset() const { - QPoint pt = pos() - lastPos(); - return QSize(pt.x(), pt.y()); + Q_D(const QPanGesture); + return d->lastOffset; } -/*! - \class QTapAndHoldGesture - \since 4.6 - - \brief The QTapAndHoldGesture class represents a Tap-and-Hold gesture, - providing additional information. -*/ - -const int QTapAndHoldGesturePrivate::iterationCount = 40; -const int QTapAndHoldGesturePrivate::iterationTimeout = 50; - -/*! - Creates a new Tap and Hold gesture handler object and marks it as a child - of \a parent. - - On some platforms like Windows there is a system-wide tap and hold gesture - that cannot be overriden, hence the gesture might never trigger and default - context menu will be shown instead. -*/ -QTapAndHoldGesture::QTapAndHoldGesture(QWidget *parent) - : QGesture(*new QTapAndHoldGesturePrivate, parent) -{ -} - -/*! \internal */ -bool QTapAndHoldGesture::filterEvent(QEvent *event) -{ - Q_D(QTapAndHoldGesture); - if (!event->spontaneous()) - return false; - const QTouchEvent *ev = static_cast<const QTouchEvent*>(event); - switch (event->type()) { - case QEvent::TouchBegin: { - if (d->timer.isActive()) - d->timer.stop(); - d->timer.start(QTapAndHoldGesturePrivate::iterationTimeout, this); - const QPoint p = ev->touchPoints().at(0).pos().toPoint(); - setStartPos(p); - setLastPos(p); - setPos(p); - break; - } - case QEvent::TouchUpdate: - if (ev->touchPoints().size() != 1) - reset(); - else if ((startPos() - ev->touchPoints().at(0).pos().toPoint()).manhattanLength() > 15) - reset(); - break; - case QEvent::TouchEnd: - reset(); - break; - default: - break; - } - return false; -} - -/*! \internal */ -void QTapAndHoldGesture::timerEvent(QTimerEvent *event) -{ - Q_D(QTapAndHoldGesture); - if (event->timerId() != d->timer.timerId()) - return; - if (d->iteration == QTapAndHoldGesturePrivate::iterationCount) { - d->timer.stop(); - setState(Qt::GestureFinished); - emit triggered(); - } else { - setState(Qt::GestureStarted); - emit triggered(); - } - ++d->iteration; -} +QT_END_NAMESPACE -/*! \internal */ -void QTapAndHoldGesture::reset() -{ - Q_D(QTapAndHoldGesture); - if (state() != Qt::NoGesture) - emit cancelled(); - setState(Qt::NoGesture); - d->timer.stop(); - d->iteration = 0; -} +#include "moc_qstandardgestures.cpp" -QT_END_NAMESPACE diff --git a/src/gui/kernel/qstandardgestures.h b/src/gui/kernel/qstandardgestures.h index 2234702..c734fba 100644 --- a/src/gui/kernel/qstandardgestures.h +++ b/src/gui/kernel/qstandardgestures.h @@ -71,29 +71,13 @@ public: QSize totalOffset() const; QSize lastOffset() const; -protected: +private: bool event(QEvent *event); + bool eventFilter(QObject *receiver, QEvent *event); -private: friend class QWidget; }; -class QTapAndHoldGesturePrivate; -class Q_GUI_EXPORT QTapAndHoldGesture : public QGesture -{ - Q_OBJECT - Q_DECLARE_PRIVATE(QTapAndHoldGesture) - -public: - QTapAndHoldGesture(QWidget *parent); - - bool filterEvent(QEvent *event); - void reset(); - -protected: - void timerEvent(QTimerEvent *event); -}; - QT_END_NAMESPACE QT_END_HEADER diff --git a/src/gui/kernel/qstandardgestures_p.h b/src/gui/kernel/qstandardgestures_p.h index bb11c9f..0fe24ee 100644 --- a/src/gui/kernel/qstandardgestures_p.h +++ b/src/gui/kernel/qstandardgestures_p.h @@ -60,6 +60,8 @@ #include "qgesture.h" #include "qgesture_p.h" +#include "qstandardgestures.h" + QT_BEGIN_NAMESPACE class QPanGesturePrivate : public QGesturePrivate @@ -67,23 +69,20 @@ class QPanGesturePrivate : public QGesturePrivate Q_DECLARE_PUBLIC(QPanGesture) public: - QPanGesturePrivate() { } - - QList<QTouchEvent::TouchPoint> touchPoints; -}; + QPanGesturePrivate() + { +#if defined(Q_OS_MAC) && !defined(QT_MAC_USE_COCOA) + panFinishedTimer = 0; +#endif + } -class QTapAndHoldGesturePrivate : public QGesturePrivate -{ - Q_DECLARE_PUBLIC(QTapAndHoldGesture) - -public: - QTapAndHoldGesturePrivate() - : iteration(0) { } + QSize totalOffset; + QSize lastOffset; + QPoint lastPosition; - QBasicTimer timer; - int iteration; - static const int iterationCount; - static const int iterationTimeout; +#if defined(Q_OS_MAC) && !defined(QT_MAC_USE_COCOA) + int panFinishedTimer; +#endif }; QT_END_NAMESPACE diff --git a/src/gui/kernel/qt_cocoa_helpers_mac.mm b/src/gui/kernel/qt_cocoa_helpers_mac.mm index 223e36b..3104083 100644 --- a/src/gui/kernel/qt_cocoa_helpers_mac.mm +++ b/src/gui/kernel/qt_cocoa_helpers_mac.mm @@ -74,6 +74,7 @@ ****************************************************************************/ #include <private/qcore_mac_p.h> +#include <qaction.h> #include <qwidget.h> #include <qdesktopwidget.h> #include <qevent.h> @@ -1068,6 +1069,17 @@ void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::H #endif } +void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show) +{ +#if QT_MAC_USE_COCOA + QMacCocoaAutoReleasePool pool; + OSWindowRef theWindow = static_cast<OSWindowRef>(window); + NSToolbar *macToolbar = [theWindow toolbar]; + if (macToolbar) + [macToolbar setShowsBaselineSeparator: show]; +#endif +} + QStringList qt_mac_NSArrayToQStringList(void *nsarray) { QStringList result; @@ -1193,4 +1205,37 @@ void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayI } } +void qt_mac_menu_collapseSeparators(void */*NSMenu **/ theMenu, bool collapse) +{ + OSMenuRef menu = static_cast<OSMenuRef>(theMenu); + if (collapse) { + bool previousIsSeparator = true; // setting to true kills all the separators placed at the top. + NSMenuItem *previousItem = nil; + + NSArray *itemArray = [menu itemArray]; + for (unsigned int i = 0; i < [itemArray count]; ++i) { + NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]); + if ([item isSeparatorItem]) { + [item setHidden:previousIsSeparator]; + } + + if (![item isHidden]) { + previousItem = item; + previousIsSeparator = ([previousItem isSeparatorItem]); + } + } + + // We now need to check the final item since we don't want any separators at the end of the list. + if (previousItem && previousIsSeparator) + [previousItem setHidden:YES]; + } else { + NSArray *itemArray = [menu itemArray]; + for (unsigned int i = 0; i < [itemArray count]; ++i) { + NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]); + if (QAction *action = reinterpret_cast<QAction *>([item tag])) + [item setHidden:!action->isVisible()]; + } + } +} + QT_END_NAMESPACE diff --git a/src/gui/kernel/qt_cocoa_helpers_mac_p.h b/src/gui/kernel/qt_cocoa_helpers_mac_p.h index af3b4cb..741edd6 100644 --- a/src/gui/kernel/qt_cocoa_helpers_mac_p.h +++ b/src/gui/kernel/qt_cocoa_helpers_mac_p.h @@ -125,6 +125,7 @@ void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow ); void macWindowFlush(void * /*OSWindowRef*/ window); void macSendToolbarChangeEvent(QWidget *widget); void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics); +void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show); void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm); void qt_mac_update_mouseTracking(QWidget *widget); OSStatus qt_mac_drawCGImage(CGContextRef cg, const CGRect *inbounds, CGImageRef); @@ -133,6 +134,7 @@ void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent); #ifdef QT_MAC_USE_COCOA bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent); #endif +void qt_mac_menu_collapseSeparators(void * /*NSMenu */ menu, bool collapse); bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent); void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent); void qt_mac_dispatchNCMouseMessage(void */* NSWindow* */eventWindow, void */* NSEvent* */mouseEvent, diff --git a/src/gui/kernel/qt_x11_p.h b/src/gui/kernel/qt_x11_p.h index 1c8394b..1ac51e0 100644 --- a/src/gui/kernel/qt_x11_p.h +++ b/src/gui/kernel/qt_x11_p.h @@ -74,11 +74,19 @@ #include <X11/Xutil.h> #include <X11/Xos.h> #ifdef index -# undef index +# undef index #endif #ifdef rindex -# undef rindex +# undef rindex #endif +#ifdef Q_OS_VXWORS +# ifdef open +# undef open +# endif +# ifdef getpid +# undef getpid +# endif +#endif // Q_OS_VXWORKS #include <X11/Xatom.h> //#define QT_NO_SHAPE diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 7026525..f705761 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -505,7 +505,7 @@ void QWidget::setAutoFillBackground(bool enabled) been outlined to indicate their full sizes. If you want to use a QWidget to hold child widgets you will usually want to - add a layout to the parent QWidget. See \l{Layout Classes} for more + add a layout to the parent QWidget. See \l{Layout Management} for more information. @@ -1375,6 +1375,11 @@ QWidget::~QWidget() // set all QPointers for this object to zero QObjectPrivate::clearGuards(this); + if (d->declarativeData) { + d->declarativeData->destroyed(this); + d->declarativeData = 0; // don't activate again in ~QObject + } + if (!d->children.isEmpty()) d->deleteChildren(); @@ -3475,27 +3480,32 @@ bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh) } } #endif + int mw = minw, mh = minh; + if (mw == QWIDGETSIZE_MAX) + mw = 0; + if (mh == QWIDGETSIZE_MAX) + mh = 0; if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) { qWarning("QWidget::setMinimumSize: (%s/%s) " "The largest allowed size is (%d,%d)", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); - minw = qMin<int>(minw, QWIDGETSIZE_MAX); - minh = qMin<int>(minh, QWIDGETSIZE_MAX); + minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX); + minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX); } if (minw < 0 || minh < 0) { qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) " "are not possible", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh); - minw = qMax(minw, 0); - minh = qMax(minh, 0); + minw = mw = qMax(minw, 0); + minh = mh = qMax(minh, 0); } createExtra(); - if (extra->minw == minw && extra->minh == minh) + if (extra->minw == mw && extra->minh == mh) return false; - extra->minw = minw; - extra->minh = minh; - extra->explicitMinSize = (minw ? Qt::Horizontal : 0) | (minh ? Qt::Vertical : 0); + extra->minw = mw; + extra->minh = mh; + extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0); return true; } @@ -3555,7 +3565,8 @@ bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh) return false; extra->maxw = maxw; extra->maxh = maxh; - extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) | (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0); + extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) | + (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0); return true; } @@ -3634,6 +3645,8 @@ void QWidget::setBaseSize(int basew, int baseh) This will override the default size constraints set by QLayout. + To remove constraints, set the size to QWIDGETSIZE_MAX. + Alternatively, if you want the widget to have a fixed size based on its contents, you can call QLayout::setSizeConstraint(QLayout::SetFixedSize); @@ -3675,7 +3688,8 @@ void QWidget::setFixedSize(int w, int h) else d->updateGeometry_helper(true); - resize(w, h); + if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX) + resize(w, h); } void QWidget::setMinimumWidth(int w) @@ -7925,59 +7939,6 @@ bool QWidget::event(QEvent *event) (void) QApplication::sendEvent(this, &mouseEvent); break; } -#ifdef Q_WS_WIN - case QEvent::WinGesture: { - QWinGestureEvent *ev = static_cast<QWinGestureEvent*>(event); - QApplicationPrivate *qAppPriv = qApp->d_func(); - QApplicationPrivate::WidgetStandardGesturesMap::iterator it; - it = qAppPriv->widgetGestures.find(this); - if (it != qAppPriv->widgetGestures.end()) { - Qt::GestureState state = Qt::GestureUpdated; - if (qAppPriv->lastGestureId == 0) - state = Qt::GestureStarted; - QWinGestureEvent::Type type = ev->gestureType; - if (ev->gestureType == QWinGestureEvent::GestureEnd) { - type = (QWinGestureEvent::Type)qAppPriv->lastGestureId; - state = Qt::GestureFinished; - } - - QGesture *gesture = 0; - switch (type) { - case QWinGestureEvent::Pan: { - QPanGesture *pan = it.value().pan; - gesture = pan; - if (state == Qt::GestureStarted) { - gesture->setStartPos(ev->position); - gesture->setLastPos(ev->position); - } else { - gesture->setLastPos(gesture->pos()); - } - gesture->setPos(ev->position); - break; - } - case QWinGestureEvent::Pinch: - break; - default: - break; - } - if (gesture) { - gesture->setState(state); - if (state == Qt::GestureStarted) - emit gesture->started(); - emit gesture->triggered(); - if (state == Qt::GestureFinished) - emit gesture->finished(); - event->accept(); - } - if (ev->gestureType == QWinGestureEvent::GestureEnd) { - qAppPriv->lastGestureId = 0; - } else { - qAppPriv->lastGestureId = type; - } - } - break; - } -#endif #ifndef QT_NO_PROPERTIES case QEvent::DynamicPropertyChange: { const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName(); @@ -8029,10 +7990,12 @@ void QWidget::changeEvent(QEvent * event) case QEvent::FontChange: case QEvent::StyleChange: { + Q_D(QWidget); update(); updateGeometry(); + if (d->layout) + d->layout->invalidate(); #ifdef Q_WS_QWS - Q_D(QWidget); if (isWindow()) d->data.fstrut_dirty = true; #endif @@ -8854,7 +8817,7 @@ QRegion QWidget::mask() const The layout manager sets the geometry of the widget's children that have been added to the layout. - \sa setLayout(), sizePolicy(), {Layout Classes} + \sa setLayout(), sizePolicy(), {Layout Management} */ QLayout *QWidget::layout() const { @@ -8884,7 +8847,7 @@ QLayout *QWidget::layout() const The QWidget will take ownership of \a layout. - \sa layout(), {Layout Classes} + \sa layout(), {Layout Management} */ void QWidget::setLayout(QLayout *l) @@ -9850,6 +9813,10 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on) data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader)) ? Qt::WindowModal : Qt::ApplicationModal; + // Some window managers does not allow us to enter modal after the + // window is showing. Therefore, to be consistent, we cannot call + // QApplicationPrivate::enterModal(this) here. The window must be + // hidden before changing modality. } if (testAttribute(Qt::WA_WState_Created)) { // don't call setModal_sys() before create_sys() @@ -11149,8 +11116,6 @@ Q_GUI_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget) } - - #ifndef QT_NO_GRAPHICSVIEW /*! \since 4.5 diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index 1717fbd..6851e25 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -1116,23 +1116,9 @@ OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, //update handles GrafPtr qd = 0; CGContextRef cg = 0; -#ifndef QT_MAC_NO_QUICKDRAW - { - if(GetEventParameter(event, kEventParamGrafPort, typeGrafPtr, 0, sizeof(qd), 0, &qd) != noErr) { - GDHandle dev = 0; - GetGWorld(&qd, &dev); //just use the global port.. - } - } - bool end_cg_context = false; - if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr && qd) { - end_cg_context = true; - QDBeginCGContext(qd, &cg); - } -#else if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr) { Q_ASSERT(false); } -#endif widget->d_func()->hd = cg; widget->d_func()->qd_hd = qd; CGContextSaveGState(cg); @@ -1252,10 +1238,6 @@ OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, widget->d_func()->hd = 0; widget->d_func()->qd_hd = 0; CGContextRestoreGState(cg); -#ifndef QT_MAC_NO_QUICKDRAW - if(end_cg_context) - QDEndCGContext(qd, &cg); -#endif } else if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) { CallNextEventHandler(er, event); } @@ -3118,7 +3100,12 @@ void QWidgetPrivate::update_sys(const QRegion &rgn) return; dirtyOnWidget += rgn; #ifndef QT_MAC_USE_COCOA - HIViewSetNeedsDisplayInRegion(qt_mac_nativeview_for(q), QMacSmartQuickDrawRegion(rgn.toQDRgn()), true); + RgnHandle rgnHandle = rgn.toQDRgnForUpdate_sys(); + if (rgnHandle) + HIViewSetNeedsDisplayInRegion(qt_mac_nativeview_for(q), QMacSmartQuickDrawRegion(rgnHandle), true); + else { + HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true); // do a complete repaint on overflow. + } #else // Cocoa doesn't do regions, it seems more efficient to just update the bounding rect instead of a potential number of message passes for each rect. const QRect &boundingRect = rgn.boundingRect(); @@ -3189,6 +3176,12 @@ void QWidgetPrivate::show_sys() #ifndef QT_MAC_USE_COCOA SizeWindow(window, q->width(), q->height(), true); #endif + +#ifdef QT_MAC_USE_COCOA + // Make sure that we end up sending a repaint event to + // the widget if the window has been visible one before: + [qt_mac_get_contentview_for(window) setNeedsDisplay:YES]; +#endif if(qt_mac_is_macsheet(q)) { qt_event_request_showsheet(q); } else if(qt_mac_is_macdrawer(q)) { @@ -4602,6 +4595,7 @@ void QWidgetPrivate::setModal_sys() OSWindowRef windowRef = qt_mac_window_for(q); #ifdef QT_MAC_USE_COCOA + QMacCocoaAutoReleasePool pool; bool alreadySheet = [windowRef styleMask] & NSDocModalWindowMask; if (windowParent && q->windowModality() == Qt::WindowModal){ @@ -4678,31 +4672,40 @@ void QWidgetPrivate::setModal_sys() || (primaryWindow && primaryWindow->windowModality() == Qt::WindowModal)){ // Window should be window-modal (which implies a sheet). if (old_wclass != kSheetWindowClass){ - // We cannot convert a created window to a sheet. So we recreate the window: + // We cannot convert a created window to a sheet. + // So we recreate the window: recreateMacWindow(); return; } - } else if (!(q->data->window_flags & Qt::CustomizeWindowHint)) { - if (old_wclass == kDocumentWindowClass || old_wclass == kFloatingWindowClass || old_wclass == kUtilityWindowClass){ - // Only change the class to kMovableModalWindowClass if the no explicit jewels - // are set (kMovableModalWindowClass can't contain them), and the current window class - // can be converted to modal (according to carbon doc). Mind the order of - // HIWindowChangeClass and ChangeWindowAttributes. - WindowGroupRef group = GetWindowGroup(windowRef); - HIWindowChangeClass(windowRef, kMovableModalWindowClass); - quint32 tmpWattr = kWindowCloseBoxAttribute | kWindowHorizontalZoomAttribute; - ChangeWindowAttributes(windowRef, tmpWattr, kWindowNoAttributes); - ChangeWindowAttributes(windowRef, kWindowNoAttributes, tmpWattr); - // If the window belongs to a qt-created group, set that group once more: - if (data.window_flags & Qt::WindowStaysOnTopHint - || q->windowType() == Qt::Popup - || q->windowType() == Qt::ToolTip) - SetWindowGroup(windowRef, group); + } else { + // Window should be application-modal (which implies NOT using a sheet). + if (old_wclass == kSheetWindowClass){ + // We cannot convert a sheet to a window. + // So we recreate the window: + recreateMacWindow(); + return; + } else if (!(q->data->window_flags & Qt::CustomizeWindowHint)) { + if (old_wclass == kDocumentWindowClass || old_wclass == kFloatingWindowClass || old_wclass == kUtilityWindowClass){ + // Only change the class to kMovableModalWindowClass if the no explicit jewels + // are set (kMovableModalWindowClass can't contain them), and the current window class + // can be converted to modal (according to carbon doc). Mind the order of + // HIWindowChangeClass and ChangeWindowAttributes. + WindowGroupRef group = GetWindowGroup(windowRef); + HIWindowChangeClass(windowRef, kMovableModalWindowClass); + quint32 tmpWattr = kWindowCloseBoxAttribute | kWindowHorizontalZoomAttribute; + ChangeWindowAttributes(windowRef, tmpWattr, kWindowNoAttributes); + ChangeWindowAttributes(windowRef, kWindowNoAttributes, tmpWattr); + // If the window belongs to a qt-created group, set that group once more: + if (data.window_flags & Qt::WindowStaysOnTopHint + || q->windowType() == Qt::Popup + || q->windowType() == Qt::ToolTip) + SetWindowGroup(windowRef, group); + } + // Popups are usually handled "special" and are never modal. + Qt::WindowType winType = q->windowType(); + if (winType != Qt::Popup && winType != Qt::ToolTip) + SetWindowModality(windowRef, kWindowModalityAppModal, 0); } - // Popups are usually handled "special" and are never modal. - Qt::WindowType winType = q->windowType(); - if (winType != Qt::Popup && winType != Qt::ToolTip) - SetWindowModality(windowRef, kWindowModalityAppModal, 0); } } else if (windowRef) { if (old_wclass == kSheetWindowClass){ diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h index 998181e..ac145b7 100644 --- a/src/gui/kernel/qwidget_p.h +++ b/src/gui/kernel/qwidget_p.h @@ -558,6 +558,7 @@ public: #endif void grabMouseWhileInWindow(); void registerTouchWindow(); + void winSetupGestures(); #elif defined(Q_WS_MAC) // <--------------------------------------------------------- MAC // This is new stuff uint needWindowChange : 1; diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp index 46fa3be..7cfa111 100644 --- a/src/gui/kernel/qwidget_win.cpp +++ b/src/gui/kernel/qwidget_win.cpp @@ -56,6 +56,10 @@ #include "private/qbackingstore_p.h" #include "private/qwindowsurface_raster_p.h" +#include "qscrollbar.h" +#include "qabstractscrollarea.h" +#include <private/qabstractscrollarea_p.h> + #include <qdebug.h> #include <private/qapplication_p.h> @@ -467,6 +471,17 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO } } + if (topLevel) { + if (data.window_flags & Qt::CustomizeWindowHint + && data.window_flags & Qt::WindowTitleHint) { + HMENU systemMenu = GetSystemMenu((HWND)q->internalWinId(), FALSE); + if (data.window_flags & Qt::WindowCloseButtonHint) + EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED); + else + EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED); + } + } + q->setAttribute(Qt::WA_WState_Created); // accept move/resize events hd = 0; // no display context @@ -638,16 +653,6 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) || (!q->isWindow() && q->parentWidget() && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))) q->setAttribute(Qt::WA_DropSiteRegistered, true); - - if (data.window_flags & Qt::CustomizeWindowHint - && data.window_flags & Qt::WindowTitleHint) { - HMENU systemMenu = GetSystemMenu((HWND)q->internalWinId(), FALSE); - if (data.window_flags & Qt::WindowCloseButtonHint) - EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED); - else - EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED); - } - #ifdef Q_WS_WINCE // Show borderless toplevel windows in tasklist & NavBar if (!parent) { @@ -1431,10 +1436,7 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) qt_wince_maximize(q); } else { #endif - if (!isTranslucentWindow) - MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true); - else if (isMove && !isResize) - SetWindowPos(q->internalWinId(), 0, fs.x(), fs.y(), 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); + MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true); } if (!q->isVisible()) InvalidateRect(q->internalWinId(), 0, FALSE); @@ -1524,6 +1526,11 @@ bool QWidgetPrivate::shouldShowMaximizeButton() { if (data.window_flags & Qt::MSWindowsFixedSizeDialogHint) return false; + // if the user explicitely asked for the maximize button, we try to add + // it even if the window has fixed size. + if (data.window_flags & Qt::CustomizeWindowHint && + data.window_flags & Qt::WindowMaximizeButtonHint) + return true; if (extra) { if ((extra->maxw && extra->maxw != QWIDGETSIZE_MAX && extra->maxw != QLAYOUTSIZE_MAX) || (extra->maxh && extra->maxh != QWIDGETSIZE_MAX && extra->maxh != QLAYOUTSIZE_MAX)) @@ -2046,6 +2053,58 @@ void QWidgetPrivate::registerTouchWindow() QApplicationPrivate::RegisterTouchWindow(q->effectiveWinId(), 0); } +void QWidgetPrivate::winSetupGestures() +{ + Q_Q(QWidget); + if (!q) + return; + extern QApplicationPrivate* getQApplicationPrivateInternal(); + QApplicationPrivate *qAppPriv = getQApplicationPrivateInternal(); + bool needh = false; + bool needv = false; + bool singleFingerPanEnabled = false; + QStandardGestures gestures = qAppPriv->widgetGestures[q]; + WId winid = 0; + + if (QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea*>(q)) { + winid = asa->viewport()->winId(); + QScrollBar *hbar = asa->horizontalScrollBar(); + QScrollBar *vbar = asa->verticalScrollBar(); + Qt::ScrollBarPolicy hbarpolicy = asa->horizontalScrollBarPolicy(); + Qt::ScrollBarPolicy vbarpolicy = asa->verticalScrollBarPolicy(); + needh = (hbarpolicy == Qt::ScrollBarAlwaysOn + || (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum())); + needv = (vbarpolicy == Qt::ScrollBarAlwaysOn + || (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum())); + singleFingerPanEnabled = asa->d_func()->singleFingerPanEnabled; + } else { + winid = q->winId(); + } + if (qAppPriv->SetGestureConfig) { + GESTURECONFIG gc[2]; + gc[0].dwID = GID_PAN; + if (gestures.pan || needh || needv) { + gc[0].dwWant = GC_PAN; + gc[0].dwBlock = 0; + if (needv && singleFingerPanEnabled) + gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY; + if (needh && singleFingerPanEnabled) + gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY; + } else { + gc[0].dwWant = 0; + gc[0].dwBlock = GC_PAN; + } + + gc[1].dwID = GID_ZOOM; + if (gestures.pinch) { + gc[1].dwWant = GC_ZOOM; + gc[1].dwBlock = 0; + } + Q_ASSERT(winid); + qAppPriv->SetGestureConfig(winid, 0, sizeof(gc)/sizeof(gc[0]), gc, sizeof(gc[0])); + } +} + QT_END_NAMESPACE #ifdef Q_WS_WINCE diff --git a/src/gui/kernel/qx11embed_x11.cpp b/src/gui/kernel/qx11embed_x11.cpp index 659331f..359434e 100644 --- a/src/gui/kernel/qx11embed_x11.cpp +++ b/src/gui/kernel/qx11embed_x11.cpp @@ -39,6 +39,7 @@ ** ****************************************************************************/ +#include "qplatformdefs.h" #include "qx11embed_x11.h" #include <qapplication.h> #include <qevent.h> diff --git a/src/gui/math3d/qquaternion.h b/src/gui/math3d/qquaternion.h index 55c871d..9a1b590 100644 --- a/src/gui/math3d/qquaternion.h +++ b/src/gui/math3d/qquaternion.h @@ -198,24 +198,17 @@ inline QQuaternion &QQuaternion::operator*=(qreal factor) inline const QQuaternion operator*(const QQuaternion &q1, const QQuaternion& q2) { - // Algorithm from: - // http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q53 - float x = q1.wp * q2.xp + - q1.xp * q2.wp + - q1.yp * q2.zp - - q1.zp * q2.yp; - float y = q1.wp * q2.yp + - q1.yp * q2.wp + - q1.zp * q2.xp - - q1.xp * q2.zp; - float z = q1.wp * q2.zp + - q1.zp * q2.wp + - q1.xp * q2.yp - - q1.yp * q2.xp; - float w = q1.wp * q2.wp - - q1.xp * q2.xp - - q1.yp * q2.yp - - q1.zp * q2.zp; + float ww = (q1.zp + q1.xp) * (q2.xp + q2.yp); + float yy = (q1.wp - q1.yp) * (q2.wp + q2.zp); + float zz = (q1.wp + q1.yp) * (q2.wp - q2.zp); + float xx = ww + yy + zz; + float qq = 0.5 * (xx + (q1.zp - q1.xp) * (q2.xp - q2.yp)); + + float w = qq - ww + (q1.zp - q1.yp) * (q2.yp - q2.zp); + float x = qq - xx + (q1.xp + q1.wp) * (q2.xp + q2.wp); + float y = qq - yy + (q1.wp - q1.xp) * (q2.yp + q2.zp); + float z = qq - zz + (q1.zp + q1.yp) * (q2.wp - q2.xp); + return QQuaternion(w, x, y, z, 1); } diff --git a/src/gui/math3d/qvector3d.cpp b/src/gui/math3d/qvector3d.cpp index 881f47c..c1f5a3e 100644 --- a/src/gui/math3d/qvector3d.cpp +++ b/src/gui/math3d/qvector3d.cpp @@ -513,7 +513,8 @@ QVector4D QVector3D::toVector4D() const /*! \fn QPoint QVector3D::toPoint() const - Returns the QPoint form of this 3D vector. + Returns the QPoint form of this 3D vector. The z coordinate + is dropped. \sa toPointF(), toVector2D() */ @@ -521,7 +522,8 @@ QVector4D QVector3D::toVector4D() const /*! \fn QPointF QVector3D::toPointF() const - Returns the QPointF form of this 3D vector. + Returns the QPointF form of this 3D vector. The z coordinate + is dropped. \sa toPoint(), toVector2D() */ diff --git a/src/gui/math3d/qvector4d.cpp b/src/gui/math3d/qvector4d.cpp index 1a84db6..ae03bc7 100644 --- a/src/gui/math3d/qvector4d.cpp +++ b/src/gui/math3d/qvector4d.cpp @@ -484,7 +484,8 @@ QVector3D QVector4D::toVector3DAffine() const /*! \fn QPoint QVector4D::toPoint() const - Returns the QPoint form of this 4D vector. + Returns the QPoint form of this 4D vector. The z and w coordinates + are dropped. \sa toPointF(), toVector2D() */ @@ -492,7 +493,8 @@ QVector3D QVector4D::toVector3DAffine() const /*! \fn QPointF QVector4D::toPointF() const - Returns the QPointF form of this 4D vector. + Returns the QPointF form of this 4D vector. The z and w coordinates + are dropped. \sa toPoint(), toVector2D() */ diff --git a/src/gui/painting/painting.pri b/src/gui/painting/painting.pri index 34d1779..d226be2 100644 --- a/src/gui/painting/painting.pri +++ b/src/gui/painting/painting.pri @@ -100,8 +100,8 @@ win32 { painting/qcolormap_win.cpp \ painting/qpaintdevice_win.cpp \ painting/qprintengine_win.cpp \ - painting/qprinterinfo_win.cpp \ - painting/qregion_win.cpp + painting/qprinterinfo_win.cpp + !win32-borland:!wince*:LIBS += -lmsimg32 } @@ -126,10 +126,6 @@ embedded { painting/qwindowsurface_raster.cpp \ } -wince* { - SOURCES -= painting/qregion_win.cpp -} - unix:x11 { HEADERS += \ painting/qpaintengine_x11_p.h diff --git a/src/gui/painting/qbackingstore.cpp b/src/gui/painting/qbackingstore.cpp index 34bc578..01c6159 100644 --- a/src/gui/painting/qbackingstore.cpp +++ b/src/gui/painting/qbackingstore.cpp @@ -39,6 +39,9 @@ ** ****************************************************************************/ + +#include "qplatformdefs.h" + #include "qbackingstore_p.h" #include <QtCore/qglobal.h> diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp index 831d389..fc2eb60 100644 --- a/src/gui/painting/qblendfunctions.cpp +++ b/src/gui/painting/qblendfunctions.cpp @@ -223,8 +223,8 @@ void qt_scale_image_16bit(uchar *destPixels, int dbpl, int h = ty2 - ty1; int w = tx2 - tx1; - const int dstx = int((tx1 + 0.5 - qMin(targetRect.left(), targetRect.right())) * ix); - const int dsty = int((ty1 + 0.5 - qMin(targetRect.top(), targetRect.bottom())) * iy); + const int dstx = qCeil((tx1 + 0.5 - qMin(targetRect.left(), targetRect.right())) * ix) - 1; + const int dsty = qCeil((ty1 + 0.5 - qMin(targetRect.top(), targetRect.bottom())) * iy) - 1; quint32 basex = quint32((sx < 0 ? srcRect.right() : srcRect.left()) * 65536) + dstx; quint32 srcy = quint32((sy < 0 ? srcRect.bottom() : srcRect.top()) * 65536) + dsty; @@ -723,8 +723,8 @@ template <typename T> void qt_scale_image_32bit(uchar *destPixels, int dbpl, int h = ty2 - ty1; int w = tx2 - tx1; - const int dstx = int((tx1 + 0.5 - qMin(targetRect.left(), targetRect.right())) * ix); - const int dsty = int((ty1 + 0.5 - qMin(targetRect.top(), targetRect.bottom())) * iy); + const int dstx = qCeil((tx1 + 0.5 - qMin(targetRect.left(), targetRect.right())) * ix) - 1; + const int dsty = qCeil((ty1 + 0.5 - qMin(targetRect.top(), targetRect.bottom())) * iy) - 1; quint32 basex = quint32((sx < 0 ? srcRect.right() : srcRect.left()) * 65536) + dstx; quint32 srcy = quint32((sy < 0 ? srcRect.bottom() : srcRect.top()) * 65536) + dsty; diff --git a/src/gui/painting/qbrush.h b/src/gui/painting/qbrush.h index 6dbb94b..13b5eba 100644 --- a/src/gui/painting/qbrush.h +++ b/src/gui/painting/qbrush.h @@ -51,6 +51,15 @@ #include <QtGui/qimage.h> #include <QtGui/qpixmap.h> +#if defined(Q_OS_VXWORKS) +# if defined(m_data) +# undef m_data +# endif +# if defined(m_type) +# undef m_type +# endif +#endif + QT_BEGIN_HEADER QT_BEGIN_NAMESPACE diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index 979390a..b6603e4 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -4794,30 +4794,60 @@ Q_STATIC_TEMPLATE_FUNCTION void blendTiled(int count, const QSpan *spans, void * if (sy < 0) sy += image_height; - while (length) { - int l = qMin(image_width - sx, length); - if (buffer_size < l) - l = buffer_size; - - DST *dest = ((DST*)data->rasterBuffer->scanLine(spans->y)) + x; - const SRC *src = (SRC*)data->texture.scanLine(sy) + sx; - if (modeSource && coverage == 255) { + if (modeSource && coverage == 255) { + // Copy the first texture block + length = image_width; + while (length) { + int l = qMin(image_width - sx, length); + if (buffer_size < l) + l = buffer_size; + DST *dest = ((DST*)data->rasterBuffer->scanLine(spans->y)) + x; + const SRC *src = (SRC*)data->texture.scanLine(sy) + sx; qt_memconvert<DST, SRC>(dest, src, l); - } else if (sizeof(DST) == 3 && sizeof(SRC) == 3 && l >= 4 && - (quintptr(dest) & 3) == (quintptr(src) & 3)) - { - blendUntransformed_dest24(dest, src, coverage, l); - } else if (sizeof(DST) == 2 && sizeof(SRC) == 2 && l >= 2 && - (quintptr(dest) & 3) == (quintptr(src) & 3)) - { - blendUntransformed_dest16(dest, src, coverage, l); - } else { - blendUntransformed_unaligned(dest, src, coverage, l); + length -= l; + sx = 0; } - x += l; - length -= l; - sx = 0; + // Now use the rasterBuffer as the source of the texture, + // We can now progressively copy larger blocks + // - Less cpu time in code figuring out what to copy + // We are dealing with one block of data + // - More likely to fit in the cache + // - can use memcpy + int copy_image_width = image_width; + length = spans->len - image_width; + DST *src = ((DST*)data->rasterBuffer->scanLine(spans->y)) + x; + DST *dest = src + copy_image_width; + while (copy_image_width < length) { + qt_memconvert(dest, src, copy_image_width); + dest += copy_image_width; + length -= copy_image_width; + copy_image_width *= 2; + } + qt_memconvert(dest, src, length); + } else { + while (length) { + int l = qMin(image_width - sx, length); + if (buffer_size < l) + l = buffer_size; + DST *dest = ((DST*)data->rasterBuffer->scanLine(spans->y)) + x; + const SRC *src = (SRC*)data->texture.scanLine(sy) + sx; + if (sizeof(DST) == 3 && sizeof(SRC) == 3 && l >= 4 && + (quintptr(dest) & 3) == (quintptr(src) & 3)) + { + blendUntransformed_dest24(dest, src, coverage, l); + } else if (sizeof(DST) == 2 && sizeof(SRC) == 2 && l >= 2 && + (quintptr(dest) & 3) == (quintptr(src) & 3)) + { + blendUntransformed_dest16(dest, src, coverage, l); + } else { + blendUntransformed_unaligned(dest, src, coverage, l); + } + + x += l; + length -= l; + sx = 0; + } } ++spans; } diff --git a/src/gui/painting/qgrayraster.c b/src/gui/painting/qgrayraster.c index 7a9eda3..c41b040 100644 --- a/src/gui/painting/qgrayraster.c +++ b/src/gui/painting/qgrayraster.c @@ -134,7 +134,9 @@ #define ErrRaster_MemoryOverflow -4 - +#if defined(VXWORKS) +# include <vxWorksCommon.h> /* needed for setjmp.h */ +#endif #include <string.h> /* for qt_ft_memcpy() */ #include <setjmp.h> #include <limits.h> diff --git a/src/gui/painting/qmatrix.cpp b/src/gui/painting/qmatrix.cpp index 221267f..39f4d95 100644 --- a/src/gui/painting/qmatrix.cpp +++ b/src/gui/painting/qmatrix.cpp @@ -55,11 +55,15 @@ QT_BEGIN_NAMESPACE \class QMatrix \brief The QMatrix class specifies 2D transformations of a coordinate system. + \obsolete \ingroup multimedia A matrix specifies how to translate, scale, shear or rotate the coordinate system, and is typically used when rendering graphics. + QMatrix, in contrast to QTransform, does not allow perspective + transformations. QTransform is the recommended transformation + class in Qt. A QMatrix object can be built using the setMatrix(), scale(), rotate(), translate() and shear() functions. Alternatively, it @@ -172,8 +176,8 @@ QT_BEGIN_NAMESPACE \snippet doc/src/snippets/matrix/matrix.cpp 2 \endtable - \sa QPainter, {The Coordinate System}, {demos/affine}{Affine - Transformations Demo}, {Transformations Example} + \sa QPainter, QTransform, {The Coordinate System}, + {demos/affine}{Affine Transformations Demo}, {Transformations Example} */ diff --git a/src/gui/painting/qoutlinemapper.cpp b/src/gui/painting/qoutlinemapper.cpp index 401fad9..1287672 100644 --- a/src/gui/painting/qoutlinemapper.cpp +++ b/src/gui/painting/qoutlinemapper.cpp @@ -198,33 +198,11 @@ void QOutlineMapper::endOutline() m_m22 * e.y() + m_m12 * e.x() + m_dy); } } else { - // ## TODO: this case needs to be plain code polygonal paths - QPainterPath path; - if (m_element_types.isEmpty()) { - if (!m_elements.isEmpty()) - path.moveTo(m_elements.at(0)); - for (int i=1; i<m_elements.size(); ++i) - path.lineTo(m_elements.at(i)); - } else { - for (int i=0; i<m_elements.size(); ++i) { - switch (m_element_types.at(i)) { - case QPainterPath::MoveToElement: - path.moveTo(m_elements.at(i)); - break; - case QPainterPath::LineToElement: - path.lineTo(m_elements.at(i)); - break; - case QPainterPath::CurveToElement: - path.cubicTo(m_elements.at(i), m_elements.at(i+1), m_elements.at(i+2)); - i += 2; - break; - default: - Q_ASSERT(false); - break; - } - } - } + const QVectorPath vp((qreal *)m_elements.data(), m_elements.size(), m_element_types.data()); + QPainterPath path = vp.convertToPainterPath(); path = QTransform(m_m11, m_m12, m_m13, m_m21, m_m22, m_m23, m_dx, m_dy, m_m33).map(path); + if (!(m_outline.flags & QT_FT_OUTLINE_EVEN_ODD_FILL)) + path.setFillRule(Qt::WindingFill); uint old_txop = m_txop; m_txop = QTransform::TxNone; if (path.isEmpty()) diff --git a/src/gui/painting/qpaintengine_mac_p.h b/src/gui/painting/qpaintengine_mac_p.h index 755b7b1..20a4a08 100644 --- a/src/gui/painting/qpaintengine_mac_p.h +++ b/src/gui/painting/qpaintengine_mac_p.h @@ -58,9 +58,6 @@ #include "private/qpaintengine_p.h" #include "private/qpolygonclipper_p.h" #include "QtCore/qhash.h" -#ifndef QT_MAC_NO_QUICKDRAW -#include <private/qwidget_p.h> -#endif typedef struct CGColorSpace *CGColorSpaceRef; QT_BEGIN_NAMESPACE @@ -69,108 +66,6 @@ extern int qt_defaultDpi(); extern int qt_defaultDpiX(); extern int qt_defaultDpiY(); -#ifndef QT_MAC_NO_QUICKDRAW -class QMacSavedPortInfo -{ - RgnHandle clip; - GWorldPtr world; - GDHandle handle; - PenState pen; //go pennstate - RGBColor back, fore; - bool valid_gworld; - void init(); - -public: - inline QMacSavedPortInfo() { init(); } - inline QMacSavedPortInfo(QPaintDevice *pd) { init(); setPaintDevice(pd); } - inline QMacSavedPortInfo(QPaintDevice *pd, const QRect &r) - { init(); setPaintDevice(pd); setClipRegion(r); } - inline QMacSavedPortInfo(QPaintDevice *pd, const QRegion &r) - { init(); setPaintDevice(pd); setClipRegion(r); } - ~QMacSavedPortInfo(); - static inline bool setClipRegion(const QRect &r); - static inline bool setClipRegion(const QRegion &r); - static inline bool setPaintDevice(QPaintDevice *); -}; - -inline bool -QMacSavedPortInfo::setClipRegion(const QRect &rect) -{ - Rect r; - SetRect(&r, rect.x(), rect.y(), rect.right()+1, rect.bottom()+1); - ClipRect(&r); - return true; -} - -inline bool -QMacSavedPortInfo::setClipRegion(const QRegion &r) -{ - if(r.isEmpty()) - return setClipRegion(QRect()); - QMacSmartQuickDrawRegion rgn(r.toQDRgn()); - SetClip(rgn); - return true; -} - -inline bool -QMacSavedPortInfo::setPaintDevice(QPaintDevice *pd) -{ - if(!pd) - return false; - bool ret = true; - extern GrafPtr qt_mac_qd_context(const QPaintDevice *); // qpaintdevice_mac.cpp - if(pd->devType() == QInternal::Widget) - SetPortWindowPort(qt_mac_window_for(static_cast<QWidget*>(pd))); - else if(pd->devType() == QInternal::Pixmap || pd->devType() == QInternal::Printer) - SetGWorld((GrafPtr)qt_mac_qd_context(pd), 0); //set the gworld - return ret; -} - -inline void -QMacSavedPortInfo::init() -{ - GetBackColor(&back); - GetForeColor(&fore); - GetGWorld(&world, &handle); - valid_gworld = true; - clip = NewRgn(); - GetClip(clip); - GetPenState(&pen); -} - -inline QMacSavedPortInfo::~QMacSavedPortInfo() -{ - bool set_state = false; - if(valid_gworld) { - set_state = IsValidPort(world); - if(set_state) - SetGWorld(world,handle); //always do this one first - } else { - setPaintDevice(qt_mac_safe_pdev); - } - if(set_state) { - SetClip(clip); - SetPenState(&pen); - RGBForeColor(&fore); - RGBBackColor(&back); - } - DisposeRgn(clip); -} -#else -class QMacSavedPortInfo -{ -public: - inline QMacSavedPortInfo() { } - inline QMacSavedPortInfo(QPaintDevice *) { } - inline QMacSavedPortInfo(QPaintDevice *, const QRect &) { } - inline QMacSavedPortInfo(QPaintDevice *, const QRegion &) { } - ~QMacSavedPortInfo() { } - static inline bool setClipRegion(const QRect &) { return false; } - static inline bool setClipRegion(const QRegion &) { return false; } - static inline bool setPaintDevice(QPaintDevice *) { return false; } -}; -#endif - class QCoreGraphicsPaintEnginePrivate; class QCoreGraphicsPaintEngine : public QPaintEngine { diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index e9ff752..74456dd 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1101,6 +1101,9 @@ void QRasterPaintEnginePrivate::systemStateChanged() #ifdef QT_DEBUG_DRAW qDebug() << "systemStateChanged" << this << "deviceRect" << deviceRect << clipRect << systemClip; #endif + + exDeviceRect = deviceRect; + Q_Q(QRasterPaintEngine); q->state()->strokeFlags |= QPaintEngine::DirtyClipRegion; q->state()->fillFlags |= QPaintEngine::DirtyClipRegion; @@ -1669,34 +1672,6 @@ void QRasterPaintEngine::drawRects(const QRectF *rects, int rectCount) QPaintEngineEx::drawRects(rects, rectCount); } -void QRasterPaintEnginePrivate::strokeProjective(const QPainterPath &path) -{ - Q_Q(QRasterPaintEngine); - QRasterPaintEngineState *s = q->state(); - - const QPen &pen = s->lastPen; - QPainterPathStroker pathStroker; - pathStroker.setWidth(pen.width() == 0 ? qreal(1) : pen.width()); - pathStroker.setCapStyle(pen.capStyle()); - pathStroker.setJoinStyle(pen.joinStyle()); - pathStroker.setMiterLimit(pen.miterLimit()); - pathStroker.setDashOffset(pen.dashOffset()); - - if (qpen_style(pen) == Qt::CustomDashLine) - pathStroker.setDashPattern(pen.dashPattern()); - else - pathStroker.setDashPattern(qpen_style(pen)); - - outlineMapper->setMatrix(QTransform()); - const QPainterPath stroke = pen.isCosmetic() - ? pathStroker.createStroke(s->matrix.map(path)) - : s->matrix.map(pathStroker.createStroke(path)); - - rasterize(outlineMapper->convertPath(stroke), s->penData.blend, &s->penData, rasterBuffer); - outlinemapper_xform_dirty = true; -} - - /*! \internal @@ -1708,11 +1683,30 @@ void QRasterPaintEngine::stroke(const QVectorPath &path, const QPen &pen) if (!s->penData.blend) return; - if (s->flags.fast_pen && path.shape() <= QVectorPath::NonCurvedShapeHint && s->lastPen.brush().isOpaque()) { - strokePolygonCosmetic((QPointF *) path.points(), path.elementCount(), - path.hasImplicitClose() - ? WindingMode - : PolylineMode); + if (s->flags.fast_pen && path.shape() <= QVectorPath::NonCurvedShapeHint + && s->lastPen.brush().isOpaque()) { + int count = path.elementCount(); + QPointF *points = (QPointF *) path.points(); + const QPainterPath::ElementType *types = path.elements(); + if (types) { + int first = 0; + int last; + while (first < count) { + while (first < count && types[first] != QPainterPath::MoveToElement) ++first; + last = first + 1; + while (last < count && types[last] == QPainterPath::LineToElement) ++last; + strokePolygonCosmetic(points + first, last - first, + path.hasImplicitClose() && last == count // only close last one.. + ? WindingMode + : PolylineMode); + first = last; + } + } else { + strokePolygonCosmetic(points, count, + path.hasImplicitClose() + ? WindingMode + : PolylineMode); + } } else if (s->flags.non_complex_pen && path.shape() == QVectorPath::LinesHint) { qreal width = s->lastPen.isCosmetic() @@ -1742,6 +1736,8 @@ void QRasterPaintEngine::stroke(const QVectorPath &path, const QPen &pen) const QLineF *lines = reinterpret_cast<const QLineF *>(path.points()); for (int i = 0; i < lineCount; ++i) { + if (path.shape() == QVectorPath::LinesHint) + dashOffset = s->lastPen.dashOffset(); if (lines[i].p1() == lines[i].p2()) { if (s->lastPen.capStyle() != Qt::FlatCap) { QPointF p = lines[i].p1(); @@ -1947,67 +1943,6 @@ void QRasterPaintEngine::fillRect(const QRectF &r, const QColor &color) fillRect(r, &d->solid_color_filler); } -/*! - \reimp -*/ -void QRasterPaintEngine::drawPath(const QPainterPath &path) -{ -#ifdef QT_DEBUG_DRAW - QRectF bounds = path.boundingRect(); - qDebug(" - QRasterPaintEngine::drawPath(), [%.2f, %.2f, %.2f, %.2f]", - bounds.x(), bounds.y(), bounds.width(), bounds.height()); -#endif - - if (path.isEmpty()) - return; - - // Filling.., - Q_D(QRasterPaintEngine); - QRasterPaintEngineState *s = state(); - - ensureBrush(); - if (s->brushData.blend) { - ensureOutlineMapper(); - fillPath(path, &s->brushData); - } - - // Stroking... - ensurePen(); - if (!s->penData.blend) - return; - { - if (s->matrix.type() >= QTransform::TxProject) { - d->strokeProjective(path); - } else { - Q_ASSERT(s->stroker); - d->outlineMapper->beginOutline(Qt::WindingFill); - qreal txscale = 1; - if (s->pen.isCosmetic() || (qt_scaleForTransform(s->matrix, &txscale) && txscale != 1)) { - const qreal strokeWidth = d->basicStroker.strokeWidth(); - const QRectF clipRect = d->dashStroker ? d->dashStroker->clipRect() : QRectF(); - if (d->dashStroker) - d->dashStroker->setClipRect(d->deviceRect); - d->basicStroker.setStrokeWidth(strokeWidth * txscale); - d->outlineMapper->setMatrix(QTransform()); - s->stroker->strokePath(path, d->outlineMapper, s->matrix); - d->outlinemapper_xform_dirty = true; - d->basicStroker.setStrokeWidth(strokeWidth); - if (d->dashStroker) - d->dashStroker->setClipRect(clipRect); - } else { - ensureOutlineMapper(); - s->stroker->strokePath(path, d->outlineMapper, QTransform()); - } - d->outlineMapper->endOutline(); - - ProcessSpans blend = d->getPenFunc(d->outlineMapper->controlPointRect, - &s->penData); - d->rasterize(d->outlineMapper->outline(), blend, &s->penData, d->rasterBuffer); - } - } - -} - static inline bool isAbove(const QPointF *a, const QPointF *b) { return a->y() < b->y(); @@ -3521,8 +3456,8 @@ void QRasterPaintEngine::drawLines(const QLine *lines, int lineCount) int m22 = int(s->matrix.m22()); int dx = qFloor(s->matrix.dx() + aliasedCoordinateDelta); int dy = qFloor(s->matrix.dy() + aliasedCoordinateDelta); - int dashOffset = int(s->lastPen.dashOffset()); for (int i=0; i<lineCount; ++i) { + int dashOffset = int(s->lastPen.dashOffset()); if (s->flags.int_xform) { const QLine &l = lines[i]; int x1 = l.x1() * m11 + dx; @@ -3621,8 +3556,8 @@ void QRasterPaintEngine::drawLines(const QLineF *lines, int lineCount) ? LineDrawNormal : LineDrawIncludeLastPixel; - int dashOffset = int(s->lastPen.dashOffset()); for (int i=0; i<lineCount; ++i) { + int dashOffset = int(s->lastPen.dashOffset()); QLineF line = (lines[i] * s->matrix).translated(aliasedCoordinateDelta, aliasedCoordinateDelta); const QRectF brect(QPointF(line.x1(), line.y1()), QPointF(line.x2(), line.y2())); diff --git a/src/gui/painting/qpaintengine_raster_p.h b/src/gui/painting/qpaintengine_raster_p.h index 283c442..3dab491 100644 --- a/src/gui/painting/qpaintengine_raster_p.h +++ b/src/gui/painting/qpaintengine_raster_p.h @@ -165,7 +165,6 @@ public: void updateMatrix(const QTransform &matrix); - void drawPath(const QPainterPath &path); void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode); void drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode); void fillPath(const QPainterPath &path, QSpanData *fillData); @@ -327,7 +326,6 @@ public: inline const QClipData *clip() const; - void strokeProjective(const QPainterPath &path); void initializeRasterizer(QSpanData *data); void recalculateFastImages(); diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index a4db284..ed9b858 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -42,6 +42,7 @@ #include "qpaintengineex_p.h" #include "qpainter_p.h" #include "qstroker_p.h" +#include "qbezier_p.h" #include <private/qpainterpath_p.h> #include <qvarlengtharray.h> @@ -91,6 +92,40 @@ QRectF QVectorPath::controlPointRect() const return QRectF(QPointF(m_cp_rect.x1, m_cp_rect.y1), QPointF(m_cp_rect.x2, m_cp_rect.y2)); } +QPainterPath QVectorPath::convertToPainterPath() const +{ + QPainterPath path; + + if (m_count == 0) + return path; + + const QPointF *points = (const QPointF *) m_points; + + if (m_elements) { + for (int i=0; i<m_count; ++i) { + switch (m_elements[i]) { + case QPainterPath::MoveToElement: + path.moveTo(points[i]); + break; + case QPainterPath::LineToElement: + path.lineTo(points[i]); + break; + case QPainterPath::CurveToElement: + path.cubicTo(points[i], points[i+1], points[i+2]); + break; + default: + break; + } + } + } else { + path.moveTo(points[0]); + for (int i=1; i<m_count; ++i) + path.lineTo(points[i]); + } + + return path; +} + const QVectorPath &qtVectorPathForPath(const QPainterPath &path) { Q_ASSERT(path.d_func()); @@ -364,12 +399,12 @@ void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) d->activeStroker = 0; } else { // ### re-enable... -// if (pen.isCosmetic()) { -// d->dashStroker->setClipRect(d->deviceRect); -// } else { -// QRectF clipRect = s->matrix.inverted().mapRect(QRectF(d->deviceRect)); -// d->dashStroker->setClipRect(clipRect); -// } + if (pen.isCosmetic()) { + d->dasher.setClipRect(d->exDeviceRect); + } else { + QRectF clipRect = state()->matrix.inverted().mapRect(QRectF(d->exDeviceRect)); + d->dasher.setClipRect(clipRect); + } d->dasher.setDashPattern(pen.dashPattern()); d->dasher.setDashOffset(pen.dashOffset()); d->activeStroker = &d->dasher; @@ -386,7 +421,6 @@ void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) const qreal *lastPoint = points + (pointCount<<1); - d->activeStroker->begin(d->strokeHandler); d->strokeHandler->types.reset(); d->strokeHandler->pts.reset(); @@ -395,13 +429,13 @@ void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) if (d->stroker.capStyle() == Qt::RoundCap || d->stroker.joinStyle() == Qt::RoundJoin) flags |= QVectorPath::CurvedShapeHint; - // ### Perspective Xforms are currently not supported... qreal txscale = 1; if (!(pen.isCosmetic() || (qt_scaleForTransform(state()->matrix, &txscale) && txscale != 1))) { // We include cosmetic pens in this case to avoid having to // change the current transform. Normal transformed, // non-cosmetic pens will be transformed as part of fill // later, so they are also covered here.. + d->activeStroker->begin(d->strokeHandler); if (types) { while (points < lastPoint) { switch (*types) { @@ -450,69 +484,75 @@ void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) QVectorPath strokePath(d->strokeHandler->pts.data(), d->strokeHandler->types.size(), d->strokeHandler->types.data(), - QVectorPath::WindingFill); + flags); fill(strokePath, pen.brush()); } else { const qreal strokeWidth = d->stroker.strokeWidth(); d->stroker.setStrokeWidth(strokeWidth * txscale); // For cosmetic pens we need a bit of trickery... We to process xform the input points - if (types) { - while (points < lastPoint) { - switch (*types) { - case QPainterPath::MoveToElement: { - QPointF pt = (*(QPointF *) points) * state()->matrix; - d->activeStroker->moveTo(pt.x(), pt.y()); - points += 2; - ++types; - break; + if (state()->matrix.type() >= QTransform::TxProject) { + QPainterPath painterPath = state()->matrix.map(path.convertToPainterPath()); + d->activeStroker->strokePath(painterPath, d->strokeHandler, QTransform()); + } else { + d->activeStroker->begin(d->strokeHandler); + if (types) { + while (points < lastPoint) { + switch (*types) { + case QPainterPath::MoveToElement: { + QPointF pt = (*(QPointF *) points) * state()->matrix; + d->activeStroker->moveTo(pt.x(), pt.y()); + points += 2; + ++types; + break; + } + case QPainterPath::LineToElement: { + QPointF pt = (*(QPointF *) points) * state()->matrix; + d->activeStroker->lineTo(pt.x(), pt.y()); + points += 2; + ++types; + break; + } + case QPainterPath::CurveToElement: { + QPointF c1 = ((QPointF *) points)[0] * state()->matrix; + QPointF c2 = ((QPointF *) points)[1] * state()->matrix; + QPointF e = ((QPointF *) points)[2] * state()->matrix; + d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y()); + points += 6; + types += 3; + flags |= QVectorPath::CurvedShapeHint; + break; + } + default: + break; + } } - case QPainterPath::LineToElement: { - QPointF pt = (*(QPointF *) points) * state()->matrix; + if (path.hasImplicitClose()) { + QPointF pt = * ((QPointF *) path.points()) * state()->matrix; d->activeStroker->lineTo(pt.x(), pt.y()); - points += 2; - ++types; - break; - } - case QPainterPath::CurveToElement: { - QPointF c1 = ((QPointF *) points)[0] * state()->matrix; - QPointF c2 = ((QPointF *) points)[1] * state()->matrix; - QPointF e = ((QPointF *) points)[2] * state()->matrix; - d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y()); - points += 6; - types += 3; - flags |= QVectorPath::CurvedShapeHint; - break; } - default: - break; - } - } - if (path.hasImplicitClose()) { - QPointF pt = * ((QPointF *) path.points()) * state()->matrix; - d->activeStroker->lineTo(pt.x(), pt.y()); - } - } else { - QPointF p = ((QPointF *)points)[0] * state()->matrix; - d->activeStroker->moveTo(p.x(), p.y()); - points += 2; - ++types; - while (points < lastPoint) { + } else { QPointF p = ((QPointF *)points)[0] * state()->matrix; - d->activeStroker->lineTo(p.x(), p.y()); + d->activeStroker->moveTo(p.x(), p.y()); points += 2; ++types; + while (points < lastPoint) { + QPointF p = ((QPointF *)points)[0] * state()->matrix; + d->activeStroker->lineTo(p.x(), p.y()); + points += 2; + ++types; + } + if (path.hasImplicitClose()) + d->activeStroker->lineTo(p.x(), p.y()); } - if (path.hasImplicitClose()) - d->activeStroker->lineTo(p.x(), p.y()); + d->activeStroker->end(); } - d->activeStroker->end(); d->stroker.setStrokeWidth(strokeWidth); QVectorPath strokePath(d->strokeHandler->pts.data(), d->strokeHandler->types.size(), d->strokeHandler->types.data(), - QVectorPath::WindingFill); + flags); QTransform xform = state()->matrix; state()->matrix = QTransform(); diff --git a/src/gui/painting/qpaintengineex_p.h b/src/gui/painting/qpaintengineex_p.h index d4e4862..7705cc1 100644 --- a/src/gui/painting/qpaintengineex_p.h +++ b/src/gui/painting/qpaintengineex_p.h @@ -225,6 +225,8 @@ public: StrokeHandler *strokeHandler; QStrokerOps *activeStroker; QPen strokerPen; + + QRect exDeviceRect; }; inline uint QVectorPath::polygonFlags(QPaintEngine::PolygonDrawMode mode) { diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 34305c2..8192fb7 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -184,7 +184,7 @@ void QPainterPrivate::checkEmulation() extended = emulationEngine; extended->setState(state); } - } else if (emulationEngine && emulationEngine != extended) { + } else if (emulationEngine == extended) { extended = emulationEngine->real_engine; } } @@ -1005,7 +1005,7 @@ void QPainterPrivate::updateState(QPainterState *newState) \o brushOrigin() defines the origin of the tiled brushes, normally the origin of widget's background. - \o viewport(), window(), worldMatrix() make up the painter's coordinate + \o viewport(), window(), worldTransform() make up the painter's coordinate transformation system. For more information, see the \l {Coordinate Transformations} section and the \l {The Coordinate System} documentation. @@ -1016,7 +1016,7 @@ void QPainterPrivate::updateState(QPainterState *newState) \o layoutDirection() defines the layout direction used by the painter when drawing text. - \o matrixEnabled() tells whether world transformation is enabled. + \o worldMatrixEnabled() tells whether world transformation is enabled. \o viewTransformEnabled() tells whether view transformation is enabled. @@ -1212,15 +1212,15 @@ void QPainterPrivate::updateState(QPainterState *newState) \endtable All the tranformation operations operate on the transformation - worldMatrix(). A matrix transforms a point in the plane to another + worldTransform(). A matrix transforms a point in the plane to another point. For more information about the transformation matrix, see - the \l {The Coordinate System} and QMatrix documentation. + the \l {The Coordinate System} and QTransform documentation. - The setWorldMatrix() function can replace or add to the currently - set worldMatrix(). The resetMatrix() function resets any + The setWorldTransform() function can replace or add to the currently + set worldTransform(). The resetTransform() function resets any transformations that were made using translate(), scale(), - shear(), rotate(), setWorldMatrix(), setViewport() and setWindow() - functions. The deviceMatrix() returns the matrix that transforms + shear(), rotate(), setWorldTransform(), setViewport() and setWindow() + functions. The deviceTransform() returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device. The latter function is only needed when using platform painting commands on the platform dependent handle, @@ -1229,11 +1229,11 @@ void QPainterPrivate::updateState(QPainterState *newState) When drawing with QPainter, we specify points using logical coordinates which then are converted into the physical coordinates of the paint device. The mapping of the logical coordinates to the - physical coordinates are handled by QPainter's combinedMatrix(), a - combination of viewport() and window() and worldMatrix(). The + physical coordinates are handled by QPainter's combinedTransform(), a + combination of viewport() and window() and worldTransform(). The viewport() represents the physical coordinates specifying an arbitrary rectangle, the window() describes the same rectangle in - logical coordinates, and the worldMatrix() is identical with the + logical coordinates, and the worldTransform() is identical with the transformation matrix. See also \l {The Coordinate System} documentation. @@ -1672,7 +1672,7 @@ bool QPainter::begin(QPaintDevice *pd) if (!d->engine) { qWarning("QPainter::begin: Paint device returned engine == 0, type: %d", pd->devType()); - return true; + return false; } // Slip a painter state into the engine before we do any other operations @@ -2677,6 +2677,7 @@ void QPainter::setClipRegion(const QRegion &r, Qt::ClipOperation op) /*! \since 4.2 + \obsolete Sets the transformation matrix to \a matrix and enables transformations. @@ -2715,7 +2716,7 @@ void QPainter::setClipRegion(const QRegion &r, Qt::ClipOperation op) and window-viewport conversion, see \l {The Coordinate System} documentation. - \sa worldMatrixEnabled(), QMatrix + \sa setWorldTransform(), QTransform */ void QPainter::setWorldMatrix(const QMatrix &matrix, bool combine) @@ -2725,6 +2726,7 @@ void QPainter::setWorldMatrix(const QMatrix &matrix, bool combine) /*! \since 4.2 + \obsolete Returns the world transformation matrix. @@ -2774,6 +2776,7 @@ const QMatrix &QPainter::matrix() const /*! \since 4.2 + \obsolete Returns the transformation matrix combining the current window/viewport and world transformation. @@ -2781,7 +2784,7 @@ const QMatrix &QPainter::matrix() const It is advisable to use combinedTransform() instead of this function to preserve the properties of perspective transformations. - \sa setWorldMatrix(), setWindow(), setViewport() + \sa setWorldTransform(), setWindow(), setViewport() */ QMatrix QPainter::combinedMatrix() const { @@ -2790,6 +2793,8 @@ QMatrix QPainter::combinedMatrix() const /*! + \obsolete + Returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device. @@ -2817,6 +2822,8 @@ const QMatrix &QPainter::deviceMatrix() const } /*! + \obsolete + Resets any transformations that were made using translate(), scale(), shear(), rotate(), setWorldMatrix(), setViewport() and setWindow(). @@ -2841,7 +2848,7 @@ void QPainter::resetMatrix() transformations if \a enable is false. The world transformation matrix is not changed. - \sa worldMatrixEnabled(), worldMatrix(), {QPainter#Coordinate + \sa worldMatrixEnabled(), worldTransform(), {QPainter#Coordinate Transformations}{Coordinate Transformations} */ @@ -2870,7 +2877,7 @@ void QPainter::setWorldMatrixEnabled(bool enable) Returns true if world transformation is enabled; otherwise returns false. - \sa setWorldMatrixEnabled(), worldMatrix(), {The Coordinate System} + \sa setWorldMatrixEnabled(), worldTransform(), {The Coordinate System} */ bool QPainter::worldMatrixEnabled() const @@ -2912,7 +2919,7 @@ bool QPainter::matrixEnabled() const /*! Scales the coordinate system by (\a{sx}, \a{sy}). - \sa setWorldMatrix() {QPainter#Coordinate Transformations}{Coordinate + \sa setWorldTransform() {QPainter#Coordinate Transformations}{Coordinate Transformations} */ @@ -2936,7 +2943,7 @@ void QPainter::scale(qreal sx, qreal sy) /*! Shears the coordinate system by (\a{sh}, \a{sv}). - \sa setWorldMatrix(), {QPainter#Coordinate Transformations}{Coordinate + \sa setWorldTransform(), {QPainter#Coordinate Transformations}{Coordinate Transformations} */ @@ -2962,7 +2969,7 @@ void QPainter::shear(qreal sh, qreal sv) Rotates the coordinate system the given \a angle clockwise. - \sa setWorldMatrix(), {QPainter#Coordinate Transformations}{Coordinate + \sa setWorldTransform(), {QPainter#Coordinate Transformations}{Coordinate Transformations} */ @@ -2987,7 +2994,7 @@ void QPainter::rotate(qreal a) Translates the coordinate system by the given \a offset; i.e. the given \a offset is added to points. - \sa setWorldMatrix(), {QPainter#Coordinate Transformations}{Coordinate + \sa setWorldTransform(), {QPainter#Coordinate Transformations}{Coordinate Transformations} */ void QPainter::translate(const QPointF &offset) @@ -6769,7 +6776,7 @@ QPainter::RenderHints QPainter::renderHints() const Returns true if view transformation is enabled; otherwise returns false. - \sa setViewTransformEnabled(), worldMatrix() + \sa setViewTransformEnabled(), worldTransform() */ bool QPainter::viewTransformEnabled() const @@ -6925,7 +6932,7 @@ QRect QPainter::viewport() const /*! \fn void QPainter::resetXForm() \compat - Use resetMatrix() instead. + Use resetTransform() instead. */ /*! \fn void QPainter::setViewXForm(bool enabled) @@ -6971,14 +6978,16 @@ void QPainter::setViewTransformEnabled(bool enable) #ifdef QT3_SUPPORT /*! - Use the worldMatrix() combined with QMatrix::dx() instead. + \obsolete + + Use the worldTransform() combined with QTransform::dx() instead. \oldcode QPainter painter(this); qreal x = painter.translationX(); \newcode QPainter painter(this); - qreal x = painter.worldMatrix().dx(); + qreal x = painter.worldTransform().dx(); \endcode */ qreal QPainter::translationX() const @@ -6992,14 +7001,16 @@ qreal QPainter::translationX() const } /*! - Use the worldMatrix() combined with QMatrix::dy() instead. + \obsolete + + Use the worldTransform() combined with QTransform::dy() instead. \oldcode QPainter painter(this); qreal y = painter.translationY(); \newcode QPainter painter(this); - qreal y = painter.worldMatrix().dy(); + qreal y = painter.worldTransform().dy(); \endcode */ qreal QPainter::translationY() const @@ -7097,7 +7108,7 @@ QPolygon QPainter::xForm(const QPolygon &a) const QPolygon transformed = painter.xForm(polygon, index, count) \newcode QPainter painter(this); - QPolygon transformed = polygon.mid(index, count) * painter.combinedMatrix(); + QPolygon transformed = polygon.mid(index, count) * painter.combinedTransform(); \endcode */ @@ -7112,15 +7123,16 @@ QPolygon QPainter::xForm(const QPolygon &av, int index, int npoints) const /*! \fn QPoint QPainter::xFormDev(const QPoint &point) const \overload + \obsolete - Use combinedTransform() combined with QMatrix::inverted() instead. + Use combinedTransform() combined with QTransform::inverted() instead. \oldcode QPainter painter(this); QPoint transformed = painter.xFormDev(point); \newcode QPainter painter(this); - QPoint transformed = point * painter.combinedMatrix().inverted(); + QPoint transformed = point * painter.combinedTransform().inverted(); \endcode */ @@ -7139,15 +7151,16 @@ QPoint QPainter::xFormDev(const QPoint &p) const /*! \fn QRect QPainter::xFormDev(const QRect &rectangle) const \overload + \obsolete - Use mapRect() combined with QMatrix::inverted() instead. + Use combinedTransform() combined with QTransform::inverted() instead. \oldcode QPainter painter(this); QRect transformed = painter.xFormDev(rectangle); \newcode QPainter painter(this); - QRect transformed = painter.combinedMatrix().inverted(rectangle); + QRect transformed = painter.combinedTransform().inverted(rectangle); \endcode */ @@ -7167,16 +7180,16 @@ QRect QPainter::xFormDev(const QRect &r) const \overload \fn QPoint QPainter::xFormDev(const QPolygon &polygon) const - \overload + \obsolete - Use combinedMatrix() combined with QMatrix::inverted() instead. + Use combinedTransform() combined with QTransform::inverted() instead. \oldcode QPainter painter(this); QPolygon transformed = painter.xFormDev(rectangle); \newcode QPainter painter(this); - QPolygon transformed = polygon * painter.combinedMatrix().inverted(); + QPolygon transformed = polygon * painter.combinedTransform().inverted(); \endcode */ @@ -7195,15 +7208,16 @@ QPolygon QPainter::xFormDev(const QPolygon &a) const /*! \fn QPolygon QPainter::xFormDev(const QPolygon &polygon, int index, int count) const \overload + \obsolete - Use combinedMatrix() combined with QPolygon::mid() and QMatrix::inverted() instead. + Use combinedTransform() combined with QPolygon::mid() and QTransform::inverted() instead. \oldcode QPainter painter(this); QPolygon transformed = painter.xFormDev(polygon, index, count); \newcode QPainter painter(this); - QPolygon transformed = polygon.mid(index, count) * painter.combinedMatrix().inverted(); + QPolygon transformed = polygon.mid(index, count) * painter.combinedTransform().inverted(); \endcode */ @@ -8107,7 +8121,7 @@ void bitBlt(QPaintDevice *dst, int dx, int dy, \row \o QPaintEngine::DirtyClipRegion \o clipRegion() \row \o QPaintEngine::DirtyCompositionMode \o compositionMode() \row \o QPaintEngine::DirtyFont \o font() - \row \o QPaintEngine::DirtyTransform \o matrix() + \row \o QPaintEngine::DirtyTransform \o transform() \row \o QPaintEngine::DirtyClipEnabled \o isClipEnabled() \row \o QPaintEngine::DirtyPen \o pen() \row \o QPaintEngine::DirtyHints \o renderHints() @@ -8226,10 +8240,14 @@ QFont QPaintEngineState::font() const /*! \since 4.2 + \obsolete Returns the matrix in the current paint engine state. + \note It is advisable to use transform() instead of this function to + preserve the properties of perspective transformations. + This variable should only be used when the state() returns a combination which includes the QPaintEngine::DirtyTransform flag. @@ -8410,11 +8428,7 @@ qreal QPaintEngineState::opacity() const If \a combine is true, the specified \a transform is combined with the current matrix; otherwise it replaces the current matrix. - This function has been added for compatibility with setMatrix(), - but as with setMatrix() the preferred method of setting a - transformation on the painter is through setWorldTransform(). - - \sa transform() + \sa transform() setWorldTransform() */ void QPainter::setTransform(const QTransform &transform, bool combine ) @@ -8424,6 +8438,8 @@ void QPainter::setTransform(const QTransform &transform, bool combine ) /*! Returns the world transformation matrix. + + \sa worldTransform() */ const QTransform & QPainter::transform() const @@ -8534,7 +8550,7 @@ const QTransform & QPainter::worldTransform() const Returns the transformation matrix combining the current window/viewport and world transformation. - \sa setWorldMatrix(), setWindow(), setViewport() + \sa setWorldTransform(), setWindow(), setViewport() */ QTransform QPainter::combinedTransform() const diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp index 027d5c8..09972b0 100644 --- a/src/gui/painting/qpainterpath.cpp +++ b/src/gui/painting/qpainterpath.cpp @@ -3156,7 +3156,7 @@ void QPainterPath::addRoundRect(const QRectF &r, int xRnd, int yRnd) Set operations on paths will treat the paths as areas. Non-closed paths will be treated as implicitly closed. - \sa intersected(), subtracted(), subtractedInverted() + \sa intersected(), subtracted() */ QPainterPath QPainterPath::united(const QPainterPath &p) const { @@ -3271,6 +3271,8 @@ void QPainterPath::setDirty(bool dirty) { d_func()->dirtyBounds = dirty; d_func()->dirtyControlBounds = dirty; + delete d_func()->pathConverter; + d_func()->pathConverter = 0; } void QPainterPath::computeBoundingRect() const diff --git a/src/gui/painting/qprinter.cpp b/src/gui/painting/qprinter.cpp index 411b74d..02a5a02 100644 --- a/src/gui/painting/qprinter.cpp +++ b/src/gui/painting/qprinter.cpp @@ -2162,8 +2162,8 @@ bool QPrinter::collateCopiesEnabled() const } /*! - Use QPrintDialog::addEnabledOption(QPrintDialog::PrintCollateCopies) - or QPrintDialog::setEnabledOptions(QPrintDialog::enabledOptions() + Use QPrintDialog::setOption(QPrintDialog::PrintCollateCopies) + or QPrintDialog::setOptions(QPrintDialog::options() & ~QPrintDialog::PrintCollateCopies) instead, depending on \a enable. */ diff --git a/src/gui/painting/qregion.cpp b/src/gui/painting/qregion.cpp index 762e9e0..d59f3ff 100644 --- a/src/gui/painting/qregion.cpp +++ b/src/gui/painting/qregion.cpp @@ -49,7 +49,7 @@ #include <qdebug.h> -#if defined(Q_OS_UNIX) || defined(Q_OS_WINCE) +#if defined(Q_OS_UNIX) || defined(Q_WS_WIN) #include "qimage.h" #include "qbitmap.h" #include <stdlib.h> @@ -545,7 +545,7 @@ QRegion& QRegion::operator|=(const QRegion &r) \sa intersected() */ -#if !defined (Q_OS_UNIX) && !defined (Q_OS_WINCE) +#if !defined (Q_OS_UNIX) && !defined (Q_WS_WIN) QRegion& QRegion::operator+=(const QRect &r) { return operator+=(QRegion(r)); @@ -561,16 +561,14 @@ QRegion& QRegion::operator+=(const QRect &r) \sa intersected() */ -#if !defined(Q_WS_WIN) || defined(Q_OS_WINCE) QRegion& QRegion::operator&=(const QRegion &r) { return *this = *this & r; } -#endif /*! \overload \since 4.4 */ -#if defined (Q_OS_UNIX) || defined (Q_OS_WINCE) +#if defined (Q_OS_UNIX) || defined (Q_WS_WIN) QRegion& QRegion::operator&=(const QRect &r) { return *this = *this & r; @@ -591,10 +589,8 @@ QRegion& QRegion::operator&=(const QRect &r) \sa subtracted() */ -#if !defined(Q_WS_WIN) || defined(Q_OS_WINCE) QRegion& QRegion::operator-=(const QRegion &r) { return *this = *this - r; } -#endif /*! Applies the xored() function to this region and \a r and @@ -731,7 +727,7 @@ bool QRegion::intersects(const QRect &rect) const return false; } -#if !defined (Q_OS_UNIX) && !defined (Q_OS_WINCE) +#if !defined (Q_OS_UNIX) && !defined (Q_WS_WIN) /*! \overload \since 4.4 @@ -1086,7 +1082,7 @@ Q_AUTOTEST_EXPORT QPainterPath qt_regionToPath(const QRegion ®ion) return result; } -#if defined(Q_OS_UNIX) || defined(Q_OS_WINCE) +#if defined(Q_OS_UNIX) || defined(Q_WS_WIN) //#define QT_REGION_DEBUG /* @@ -1627,9 +1623,9 @@ QT_END_INCLUDE_NAMESPACE QT_BEGIN_INCLUDE_NAMESPACE # include "qregion_mac.cpp" QT_END_INCLUDE_NAMESPACE -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) QT_BEGIN_INCLUDE_NAMESPACE -# include "qregion_wince.cpp" +# include "qregion_win.cpp" QT_END_INCLUDE_NAMESPACE #elif defined(Q_WS_QWS) static QRegionPrivate qrp; @@ -3829,7 +3825,7 @@ QRegion::QRegion(const QRect &r, RegionType t) #if defined(Q_WS_X11) d->rgn = 0; d->xrectangles = 0; -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) d->rgn = 0; #endif if (t == Rectangle) { @@ -3851,7 +3847,7 @@ QRegion::QRegion(const QPolygon &a, Qt::FillRule fillRule) #if defined(Q_WS_X11) d->rgn = 0; d->xrectangles = 0; -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) d->rgn = 0; #endif d->qt_rgn = PolygonRegion(a.constData(), a.size(), @@ -3881,7 +3877,7 @@ QRegion::QRegion(const QBitmap &bm) #if defined(Q_WS_X11) d->rgn = 0; d->xrectangles = 0; -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) d->rgn = 0; #endif d->qt_rgn = qt_bitmapToRegion(bm); @@ -3896,7 +3892,7 @@ void QRegion::cleanUp(QRegion::QRegionData *x) XDestroyRegion(x->rgn); if (x->xrectangles) free(x->xrectangles); -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) if (x->rgn) qt_win_dispose_rgn(x->rgn); #endif @@ -3932,7 +3928,7 @@ QRegion QRegion::copy() const #if defined(Q_WS_X11) x->rgn = 0; x->xrectangles = 0; -#elif defined(Q_OS_WINCE) +#elif defined(Q_WS_WIN) x->rgn = 0; #endif if (d->qt_rgn) diff --git a/src/gui/painting/qregion.h b/src/gui/painting/qregion.h index bfedcb1..84024ce 100644 --- a/src/gui/painting/qregion.h +++ b/src/gui/painting/qregion.h @@ -59,7 +59,7 @@ QT_MODULE(Gui) template <class T> class QVector; class QVariant; -#if defined(Q_WS_QWS) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_WINCE) +#if defined(Q_WS_QWS) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_WIN) struct QRegionPrivate; #endif @@ -148,6 +148,7 @@ public: #elif defined(Q_WS_MAC) #if defined Q_WS_MAC32 RgnHandle toQDRgn() const; + RgnHandle toQDRgnForUpdate_sys() const; static QRegion fromQDRgn(RgnHandle shape); #endif #ifdef QT_MAC_USE_COCOA @@ -199,7 +200,7 @@ private: #elif defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA) mutable RgnHandle unused; // Here for binary compatability reasons. ### Qt 5 remove. #endif -#if defined(Q_WS_QWS) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_WINCE) +#if defined(Q_WS_QWS) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_WIN) QRegionPrivate *qt_rgn; #endif }; diff --git a/src/gui/painting/qregion_mac.cpp b/src/gui/painting/qregion_mac.cpp index b57f234..6fe7805 100644 --- a/src/gui/painting/qregion_mac.cpp +++ b/src/gui/painting/qregion_mac.cpp @@ -155,6 +155,43 @@ RgnHandle QRegion::toQDRgn() const } return rgnHandle; } + +/*! + \internal + Create's a RegionHandle, it's the caller's responsibility to release. + Returns 0 if the QRegion overflows. +*/ +RgnHandle QRegion::toQDRgnForUpdate_sys() const +{ + RgnHandle rgnHandle = qt_mac_get_rgn(); + if(d->qt_rgn && d->qt_rgn->numRects) { + RgnHandle tmp_rgn = qt_mac_get_rgn(); + int n = d->qt_rgn->numRects; + const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData(); + while (n--) { + + // detect overflow. Tested for use with HIViewSetNeedsDisplayInRegion + // in QWidgetPrivate::update_sys(). + enum { HIViewSetNeedsDisplayInRegionOverflow = 10000 }; // empirically determined conservative value + if (qt_r->right() > HIViewSetNeedsDisplayInRegionOverflow || qt_r->bottom() > HIViewSetNeedsDisplayInRegionOverflow) { + qt_mac_dispose_rgn(tmp_rgn); + qt_mac_dispose_rgn(rgnHandle); + return 0; + } + + SetRectRgn(tmp_rgn, + qMax(SHRT_MIN, qt_r->x()), + qMax(SHRT_MIN, qt_r->y()), + qMin(SHRT_MAX, qt_r->right() + 1), + qMin(SHRT_MAX, qt_r->bottom() + 1)); + UnionRgn(rgnHandle, tmp_rgn, rgnHandle); + ++qt_r; + } + qt_mac_dispose_rgn(tmp_rgn); + } + return rgnHandle; +} + #endif #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) diff --git a/src/gui/painting/qregion_win.cpp b/src/gui/painting/qregion_win.cpp index 249b1a6..8708461 100644 --- a/src/gui/painting/qregion_win.cpp +++ b/src/gui/painting/qregion_win.cpp @@ -39,22 +39,20 @@ ** ****************************************************************************/ +#include "qatomic.h" #include "qbitmap.h" #include "qbuffer.h" #include "qimage.h" #include "qpolygon.h" #include "qregion.h" #include "qt_windows.h" +#include "qpainterpath.h" +#include "qguifunctions_wince.h" QT_BEGIN_NAMESPACE +QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 }; -/* - In Windows versions before Windows Vista CreateRectRgn - when called in a multi-threaded - environment - might return an invalid handle. This function works around this limitation - by verifying the handle with a quick GetRegionData() call and re-creates the region - if necessary. -*/ HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom) { const int tries = 10; @@ -80,497 +78,73 @@ HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, return 0; } -#ifndef Q_OS_WINCE -HRGN qt_tryCreatePolygonRegion(const QPolygon &a, Qt::FillRule fillRule) -{ - const int tries = 10; - for (int i = 0; i < tries; ++i) { - HRGN region = CreatePolygonRgn(reinterpret_cast<const POINT*>(a.data()), a.size(), - fillRule == Qt::OddEvenFill ? ALTERNATE : WINDING); - if (region) { - if (GetRegionData(region, 0, 0)) - return region; - else - DeleteObject(region); - } - } - return 0; -} -#endif - -QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0 }; - -QRegion::QRegion() - : d(&shared_empty) -{ - d->ref.ref(); -} - -#ifndef Q_OS_WINCE //implementation for WindowsCE in qregion_wce.cpp -QRegion::QRegion(const QRect &r, RegionType t) -{ - if (r.isEmpty()) { - d = &shared_empty; - d->ref.ref(); - } else { - d = new QRegionData; - d->ref = 1; - if (t == Rectangle) - d->rgn = qt_tryCreateRegion(t, r.left(), r.top(), r.x() + r.width(), r.y() + r.height()); - else if (t == Ellipse) { - // need to add 1 to width/height for the ellipse to have correct boundingrect. - d->rgn = qt_tryCreateRegion(t, r.x(), r.y(), r.x() + r.width() + 1, r.y() + r.height() + 1); - } - } -} -#endif - -#ifndef Q_OS_WINCE //implementation for WindowsCE in qregion_wce.cpp -QRegion::QRegion(const QPolygon &a, Qt::FillRule fillRule) -{ - if (a.size() < 3) { - d = &shared_empty; - d->ref.ref(); - } else { - d = new QRegionData; - d->ref = 1; - d->rgn = qt_tryCreatePolygonRegion(a, fillRule); - } -} -#endif - -QRegion::QRegion(const QRegion &r) -{ - d = r.d; - d->ref.ref(); -} - -HRGN qt_win_bitmapToRegion(const QBitmap& bitmap) -{ - HRGN region=0; - QImage image = bitmap.toImage(); - const int MAXRECT = 256; - struct RData { - RGNDATAHEADER header; - RECT rect[MAXRECT]; - }; - RData data; - -#define FlushSpans \ - { \ - data.header.dwSize = sizeof(RGNDATAHEADER); \ - data.header.iType = RDH_RECTANGLES; \ - data.header.nCount = n; \ - data.header.nRgnSize = 0; \ - data.header.rcBound.bottom = y; \ - HRGN r = ExtCreateRegion(0, \ - sizeof(RGNDATAHEADER)+n*sizeof(RECT),(RGNDATA*)&data); \ - if (region) { \ - CombineRgn(region, region, r, RGN_OR); \ - DeleteObject(r); \ - } else { \ - region = r; \ - } \ - data.header.rcBound.top = y; \ - } - -#define AddSpan \ - { \ - data.rect[n].left=prev1; \ - data.rect[n].top=y; \ - data.rect[n].right=x-1+1; \ - data.rect[n].bottom=y+1; \ - n++; \ - if (n == MAXRECT) { \ - FlushSpans \ - n=0; \ - } \ - } - - data.header.rcBound.top = 0; - data.header.rcBound.left = 0; - data.header.rcBound.right = image.width()-1; - int n = 0; - - int zero = 0x00; - - int x, y; - for (y = 0; y < image.height(); ++y) { - uchar *line = image.scanLine(y); - int w = image.width(); - uchar all=zero; - int prev1 = -1; - for (x = 0; x < w;) { - uchar byte = line[x/8]; - if (x > w - 8 || byte != all) { - for (int b = 8; b > 0 && x < w; --b) { - if (!(byte & 0x01) == !all) { - // More of the same - } else { - // A change. - if (all != zero) { - AddSpan; - all = zero; - } else { - prev1 = x; - all = ~zero; - } - } - byte >>= 1; - ++x; - } - } else { - x += 8; - } - } - if (all != zero) { - AddSpan; - } - } - if (n) { - FlushSpans; - } - - if (!region) { - // Surely there is some better way. - region = qt_tryCreateRegion(QRegion::Rectangle, 0,0,1,1); - CombineRgn(region, region, region, RGN_XOR); - } - return region; -} - -#ifndef Q_OS_WINCE //implementation for WindowsCE in qregion_wce.cpp -QRegion::QRegion(const QBitmap &bm) -{ - if (bm.isNull()) { - d = &shared_empty; - d->ref.ref(); - } else { - d = new QRegionData; - d->ref = 1; - d->rgn = qt_win_bitmapToRegion(bm); - } -} -#endif - -void QRegion::cleanUp(QRegion::QRegionData *x) -{ - if (x->rgn) - DeleteObject(x->rgn); - delete x; -} - -QRegion::~QRegion() -{ - if (!d->ref.deref()) - cleanUp(d); -} - -QRegion &QRegion::operator=(const QRegion &r) -{ - r.d->ref.ref(); - if (!d->ref.deref()) - cleanUp(d); - d = r.d; - return *this; -} - - -QRegion QRegion::copy() const -{ - QRegion r; - QRegionData *x = new QRegionData; - x->ref = 1; - if (d->rgn) { - x->rgn = qt_tryCreateRegion(QRegion::Rectangle, 0, 0, 2, 2); - CombineRgn(x->rgn, d->rgn, 0, RGN_COPY); - } else { - x->rgn = 0; - } - if (!r.d->ref.deref()) - cleanUp(r.d); - r.d = x; - return r; -} - -bool QRegion::isEmpty() const -{ - return (d == &shared_empty || boundingRect().isEmpty()); -} - - -bool QRegion::contains(const QPoint &p) const -{ - return d->rgn ? PtInRegion(d->rgn, p.x(), p.y()) : false; -} - -bool QRegion::contains(const QRect &r) const -{ - if (!d->rgn) - return false; - RECT rect; - SetRect(&rect, r.left(), r.top(), r.right(), r.bottom()); - return RectInRegion(d->rgn, &rect); -} - - -void QRegion::translate(int dx, int dy) -{ - if (!d->rgn || (dx == 0 && dy == 0)) - return; - detach(); - OffsetRgn(d->rgn, dx, dy); -} - - -#define RGN_NOP -1 - -// Duplicates of those in qregion.cpp -#define QRGN_OR 6 -#define QRGN_AND 7 -#define QRGN_SUB 8 -#define QRGN_XOR 9 - -/* - Performs the actual OR, AND, SUB and XOR operation between regions. - Sets the resulting region handle to 0 to indicate an empty region. -*/ - -QRegion QRegion::winCombine(const QRegion &r, int op) const +QRegion qt_region_from_HRGN(HRGN rgn) { - int both=RGN_NOP, - left=RGN_NOP, - right=RGN_NOP; - switch (op) { - case QRGN_OR: - both = RGN_OR; - left = right = RGN_COPY; - break; - case QRGN_AND: - both = RGN_AND; - break; - case QRGN_SUB: - both = RGN_DIFF; - left = RGN_COPY; - break; - case QRGN_XOR: - both = RGN_XOR; - left = right = RGN_COPY; - break; - default: - qWarning("QRegion: Internal error in winCombine"); - } - - int allCombineRgnResults = NULLREGION; - QRegion result; - result.detach(); - result.d->rgn = qt_tryCreateRegion(QRegion::Rectangle, 0, 0, 0, 0); - if (d->rgn && r.d->rgn) - allCombineRgnResults = CombineRgn(result.d->rgn, d->rgn, r.d->rgn, both); - else if (d->rgn && left != RGN_NOP) - allCombineRgnResults = CombineRgn(result.d->rgn, d->rgn, d->rgn, left); - else if (r.d->rgn && right != RGN_NOP) - allCombineRgnResults = CombineRgn(result.d->rgn, r.d->rgn, r.d->rgn, right); - - if (allCombineRgnResults == NULLREGION || allCombineRgnResults == ERROR) - result = QRegion(); - - //##### do not delete this. A null pointer is different from an empty region in SelectClipRgn in qpainter_win! (M) -// if (allCombineRgnResults == NULLREGION) { -// if (result.data->rgn) -// DeleteObject(result.data->rgn); -// result.data->rgn = 0; // empty region -// } - return result; -} - -QRegion QRegion::unite(const QRegion &r) const -{ - if (!d->rgn) - return r; - if (!r.d->rgn) - return *this; - return winCombine(r, QRGN_OR); -} - -QRegion QRegion::unite(const QRect &r) const -{ - return unite(QRegion(r)); -} - -QRegion QRegion::intersect(const QRegion &r) const -{ - if (!r.d->rgn || !d->rgn) - return QRegion(); - return winCombine(r, QRGN_AND); -} - -QRegion QRegion::subtract(const QRegion &r) const -{ - if (!r.d->rgn || !d->rgn) - return *this; - return winCombine(r, QRGN_SUB); -} - -QRegion QRegion::eor(const QRegion &r) const -{ - if (!d->rgn) - return r; - if (!r.d->rgn) - return *this; - return winCombine(r, QRGN_XOR); -} - - -QRect QRegion::boundingRect() const -{ - if (!d->rgn) - return QRect(); - RECT r; - if (GetRgnBox(d->rgn, &r) == NULLREGION) - return QRect(); - else - return QRect(r.left, r.top, r.right - r.left, r.bottom - r.top); -} - -QVector<QRect> QRegion::rects() const -{ - if (d->rgn == 0) - return QVector<QRect>(); - - int numBytes = GetRegionData(d->rgn, 0, 0); + int numBytes = GetRegionData(rgn, 0, 0); if (numBytes == 0) - return QVector<QRect>(); + return QRegion(); char *buf = new char[numBytes]; if (buf == 0) - return QVector<QRect>(); + return QRegion(); RGNDATA *rd = reinterpret_cast<RGNDATA*>(buf); - if (GetRegionData(d->rgn, numBytes, rd) == 0) { + if (GetRegionData(rgn, numBytes, rd) == 0) { delete [] buf; - return QVector<QRect>(); + return QRegion(); } - QVector<QRect> a(rd->rdh.nCount); + QRegion region; RECT *r = reinterpret_cast<RECT*>(rd->Buffer); - for (int i = 0; i < a.size(); ++i) { - a[i].setCoords(r->left, r->top, r->right - 1, r->bottom - 1); + for (uint i = 0; i < rd->rdh.nCount; ++i) { + QRect rect; + rect.setCoords(r->left, r->top, r->right - 1, r->bottom - 1); ++r; + region |= rect; } delete [] buf; - return a; -} - -void QRegion::setRects(const QRect *rects, int num) -{ - *this = QRegion(); - if (!rects || num == 0 || (num == 1 && rects->isEmpty())) - return; - for (int i = 0; i < num; ++i) - *this |= rects[i]; -} - -int QRegion::numRects() const -{ - if (d->rgn == 0) - return 0; - - const int numBytes = GetRegionData(d->rgn, 0, 0); - if (numBytes == 0) - return 0; - - char *buf = new char[numBytes]; - if (buf == 0) - return 0; - - RGNDATA *rd = reinterpret_cast<RGNDATA*>(buf); - if (GetRegionData(d->rgn, numBytes, rd) == 0) { - delete[] buf; - return 0; - } - - const int n = rd->rdh.nCount; - delete[] buf; - return n; + return region; } -bool QRegion::operator==(const QRegion &r) const +void qt_win_dispose_rgn(HRGN r) { - if (d == r.d) - return true; - if ((d->rgn == 0) ^ (r.d->rgn == 0)) // one is empty, not both - return false; - return d->rgn == 0 ? true // both empty - : EqualRgn(d->rgn, r.d->rgn); // both non-empty + if (r) + DeleteObject(r); } -QRegion& QRegion::operator+=(const QRegion &r) +static void qt_add_rect(HRGN &winRegion, QRect r) { - if (!r.d->rgn) - return *this; - - if (!d->rgn) { - *this = r; - return *this; + HRGN rgn = CreateRectRgn(r.left(), r.top(), r.x() + r.width(), r.y() + r.height()); + if (rgn) { + HRGN dest = CreateRectRgn(0,0,0,0); + int result = CombineRgn(dest, winRegion, rgn, RGN_OR); + if (result) { + DeleteObject(winRegion); + winRegion = dest; + } + DeleteObject(rgn); } - - detach(); - - int result; - result = CombineRgn(d->rgn, d->rgn, r.d->rgn, RGN_OR); - if (result == NULLREGION || result == ERROR) - *this = QRegion(); - - return *this; -} - -QRegion& QRegion::operator-=(const QRegion &r) -{ - if (!r.d->rgn || !d->rgn) - return *this; - - detach(); - - int result; - result = CombineRgn(d->rgn, d->rgn, r.d->rgn, RGN_DIFF); - if (result == NULLREGION || result == ERROR) - *this = QRegion(); - - return *this; } -QRegion& QRegion::operator&=(const QRegion &r) +void QRegion::ensureHandle() const { - if (!d->rgn) - return *this; - - if (!r.d->rgn) { - *this = QRegion(); - return *this; + if (d->rgn) + DeleteObject(d->rgn); + d->rgn = CreateRectRgn(0,0,0,0); + if (d->qt_rgn) { + if (d->qt_rgn->numRects == 1) { + QRect r = d->qt_rgn->extents; + qt_add_rect(d->rgn, r); + return; + } + for (int i = 0;i < d->qt_rgn->numRects;i++) { + QRect r = d->qt_rgn->rects.at(i); + qt_add_rect(d->rgn, r); + } } - - detach(); - - int result; - result = CombineRgn(d->rgn, d->rgn, r.d->rgn, RGN_AND); - if (result == NULLREGION || result == ERROR) - *this = QRegion(); - - return *this; -} - -bool qt_region_strictContains(const QRegion ®ion, const QRect &rect) -{ - Q_UNUSED(region); - Q_UNUSED(rect); - return false; } -void QRegion::ensureHandle() const -{ -} QT_END_NAMESPACE diff --git a/src/gui/painting/qstroker.cpp b/src/gui/painting/qstroker.cpp index 0649589..b24bf86 100644 --- a/src/gui/painting/qstroker.cpp +++ b/src/gui/painting/qstroker.cpp @@ -1012,10 +1012,13 @@ void QDashStroker::processCurrentSubpath() int dashCount = qMin(m_dashPattern.size(), 32); qfixed dashes[32]; + qreal longestLength = 0; qreal sumLength = 0; for (int i=0; i<dashCount; ++i) { dashes[i] = qMax(m_dashPattern.at(i), qreal(0)) * m_stroker->strokeWidth(); sumLength += dashes[i]; + if (dashes[i] > longestLength) + longestLength = dashes[i]; } if (qFuzzyIsNull(sumLength)) @@ -1053,7 +1056,7 @@ void QDashStroker::processCurrentSubpath() qfixed2d line_to_pos; // Pad to avoid clipping the borders of thick pens. - qfixed padding = qMax(m_stroker->strokeWidth(), m_stroker->miterLimit()); + qfixed padding = qt_real_to_fixed(qMax(m_stroker->strokeWidth(), m_stroker->miterLimit()) * longestLength); qfixed2d clip_tl = { qt_real_to_fixed(m_clip_rect.left()) - padding, qt_real_to_fixed(m_clip_rect.top()) - padding }; qfixed2d clip_br = { qt_real_to_fixed(m_clip_rect.right()) + padding , diff --git a/src/gui/painting/qtextureglyphcache_p.h b/src/gui/painting/qtextureglyphcache_p.h index 6968f4e..a34c354 100644 --- a/src/gui/painting/qtextureglyphcache_p.h +++ b/src/gui/painting/qtextureglyphcache_p.h @@ -60,6 +60,10 @@ #include <private/qfontengineglyphcache_p.h> +#if defined(Q_OS_VXWORKS) && defined(m_type) +# undef m_type +#endif + struct glyph_metrics_t; typedef unsigned int glyph_t; diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index f0b2351..a13b494 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -48,11 +48,15 @@ #include "qvariant.h" #include <qmath.h> +#include <private/qbezier_p.h> + QT_BEGIN_NAMESPACE #define Q_NEAR_CLIP 0.000001 - +#ifdef MAP +# undef MAP +#endif #define MAP(x, y, nx, ny) \ do { \ qreal FX_ = x; \ @@ -99,7 +103,7 @@ QT_BEGIN_NAMESPACE allowing perspective transformations. QTransform's toAffine() method allows casting QTransform to QMatrix. If a perspective transformation has been specified on the matrix, then the - conversion to an affine QMatrix will cause loss of data. + conversion will cause loss of data. QTransform is the recommended transformation class in Qt. @@ -123,11 +127,13 @@ QT_BEGIN_NAMESPACE which returns true if the matrix is non-singular (i.e. AB = BA = I). The inverted() function returns an inverted copy of \e this matrix if it is invertible (otherwise it returns the identity - matrix). In addition, QTransform provides the det() function - returning the matrix's determinant. + matrix), and adjoint() returns the matrix's classical adjoint. + In addition, QTransform provides the determinant() function which + returns the matrix's determinant. - Finally, the QTransform class supports matrix multiplication, and - objects of the class can be streamed as well as compared. + Finally, the QTransform class supports matrix multiplication, addition + and subtraction, and objects of the class can be streamed as well + as compared. \tableofcontents @@ -189,7 +195,7 @@ QT_BEGIN_NAMESPACE The various matrix elements can be set when constructing the matrix, or by using the setMatrix() function later on. They can also be manipulated using the translate(), rotate(), scale() and - shear() convenience functions, The currently set values can be + shear() convenience functions. The currently set values can be retrieved using the m11(), m12(), m13(), m21(), m22(), m23(), m31(), m32(), m33(), dx() and dy() functions. @@ -202,9 +208,9 @@ QT_BEGIN_NAMESPACE to 0) mapping a point to itself. Shearing is controlled by \c m12 and \c m21. Setting these elements to values different from zero will twist the coordinate system. Rotation is achieved by - carefully setting both the shearing factors and the scaling - factors. Perspective transformation is achieved by carefully setting - both the projection factors and the scaling factors. + setting both the shearing factors and the scaling factors. Perspective + transformation is achieved by setting both the projection factors and + the scaling factors. Here's the combined transformations example using basic matrix operations: @@ -956,8 +962,8 @@ QTransform & QTransform::operator=(const QTransform &matrix) /*! Resets the matrix to an identity matrix, i.e. all elements are set - to zero, except \c m11 and \c m22 (specifying the scale) which are - set to 1. + to zero, except \c m11 and \c m22 (specifying the scale) and \c m33 + which are set to 1. \sa QTransform(), isIdentity(), {QTransform#Basic Matrix Operations}{Basic Matrix Operations} @@ -1488,27 +1494,12 @@ static inline bool lineTo_clipped(QPainterPath &path, const QTransform &transfor static inline bool cubicTo_clipped(QPainterPath &path, const QTransform &transform, const QPointF &a, const QPointF &b, const QPointF &c, const QPointF &d, bool needsMoveTo) { - const QHomogeneousCoordinate ha = mapHomogeneous(transform, a); - const QHomogeneousCoordinate hb = mapHomogeneous(transform, b); - const QHomogeneousCoordinate hc = mapHomogeneous(transform, c); - const QHomogeneousCoordinate hd = mapHomogeneous(transform, d); - - if (ha.w < Q_NEAR_CLIP && hb.w < Q_NEAR_CLIP && hc.w < Q_NEAR_CLIP && hd.w < Q_NEAR_CLIP) - return false; - - if (ha.w >= Q_NEAR_CLIP && hb.w >= Q_NEAR_CLIP && hc.w >= Q_NEAR_CLIP && hd.w >= Q_NEAR_CLIP) { - if (needsMoveTo) - path.moveTo(ha.toPoint()); + // Convert projective xformed curves to line + // segments so they can be transformed more accurately + QPolygonF segment = QBezier::fromPoints(a, b, c, d).toPolygon(); - path.cubicTo(hb.toPoint(), hc.toPoint(), hd.toPoint()); - return true; - } - - if (lineTo_clipped(path, transform, a, b, needsMoveTo)) - needsMoveTo = false; - if (lineTo_clipped(path, transform, b, c, needsMoveTo)) - needsMoveTo = false; - if (lineTo_clipped(path, transform, c, d, needsMoveTo)) + for (int i = 0; i < segment.size() - 1; ++i) + if (lineTo_clipped(path, transform, segment.at(i), segment.at(i+1), needsMoveTo)) needsMoveTo = false; return !needsMoveTo; @@ -1550,6 +1541,7 @@ static QPainterPath mapProjective(const QTransform &transform, const QPainterPat if (path.elementCount() > 0 && lastMoveTo != last) lineTo_clipped(result, transform, last, lastMoveTo, needsMoveTo, false); + result.setFillRule(path.fillRule()); return result; } @@ -1771,7 +1763,7 @@ bool QTransform::quadToQuad(const QPolygonF &one, Sets the matrix elements to the specified values, \a m11, \a m12, \a m13 \a m21, \a m22, \a m23 \a m31, \a m32 and \a m33. Note that this function replaces the previous values. - QMatrix provides the translate(), rotate(), scale() and shear() + QTransform provides the translate(), rotate(), scale() and shear() convenience functions to manipulate the various matrix elements based on the currently defined coordinate system. @@ -1789,6 +1781,14 @@ void QTransform::setMatrix(qreal m11, qreal m12, qreal m13, m_dirty = TxProject; } +static inline bool needsPerspectiveClipping(const QRectF &rect, const QTransform &transform) +{ + const qreal wx = qMin(transform.m13() * rect.left(), transform.m13() * rect.right()); + const qreal wy = qMin(transform.m23() * rect.top(), transform.m23() * rect.bottom()); + + return wx + wy + transform.m33() < Q_NEAR_CLIP; +} + QRect QTransform::mapRect(const QRect &rect) const { TransformationType t = inline_type(); @@ -1809,7 +1809,7 @@ QRect QTransform::mapRect(const QRect &rect) const y -= h; } return QRect(x, y, w, h); - } else { + } else if (t < TxProject || !needsPerspectiveClipping(rect, *this)) { // see mapToPolygon for explanations of the algorithm. qreal x = 0, y = 0; MAP(rect.left(), rect.top(), x, y); @@ -1833,6 +1833,10 @@ QRect QTransform::mapRect(const QRect &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRect(qRound(xmin), qRound(ymin), qRound(xmax)-qRound(xmin), qRound(ymax)-qRound(ymin)); + } else { + QPainterPath path; + path.addRect(rect); + return map(path).boundingRect().toRect(); } } @@ -1875,7 +1879,7 @@ QRectF QTransform::mapRect(const QRectF &rect) const y -= h; } return QRectF(x, y, w, h); - } else { + } else if (t < TxProject || !needsPerspectiveClipping(rect, *this)) { qreal x = 0, y = 0; MAP(rect.x(), rect.y(), x, y); qreal xmin = x; @@ -1898,6 +1902,10 @@ QRectF QTransform::mapRect(const QRectF &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRectF(xmin, ymin, xmax-xmin, ymax - ymin); + } else { + QPainterPath path; + path.addRect(rect); + return map(path).boundingRect(); } } @@ -1949,8 +1957,11 @@ void QTransform::map(int x, int y, int *tx, int *ty) const } /*! - Returns the QTransform cast to a QMatrix. - */ + Returns the QTransform as an affine matrix. + + \warning If a perspective transformation has been specified, + then the conversion will cause loss of data. +*/ const QMatrix &QTransform::toAffine() const { return affine; @@ -2028,8 +2039,9 @@ QTransform::operator QVariant() const /*! \fn qreal QTransform::det() const + \obsolete - Returns the matrix's determinant. + Returns the matrix's determinant. Use determinant() instead. */ diff --git a/src/gui/painting/qtransform.h b/src/gui/painting/qtransform.h index 291d35c..69d4de2 100644 --- a/src/gui/painting/qtransform.h +++ b/src/gui/painting/qtransform.h @@ -50,6 +50,10 @@ #include <QtCore/qpoint.h> #include <QtCore/qrect.h> +#if defined(Q_OS_VXWORKS) && defined(m_type) +# undef m_type +#endif + QT_BEGIN_HEADER QT_BEGIN_NAMESPACE diff --git a/src/gui/painting/qvectorpath_p.h b/src/gui/painting/qvectorpath_p.h index b6b85fa..9264c9c 100644 --- a/src/gui/painting/qvectorpath_p.h +++ b/src/gui/painting/qvectorpath_p.h @@ -130,6 +130,8 @@ public: static inline uint polygonFlags(QPaintEngine::PolygonDrawMode mode); + QPainterPath convertToPainterPath() const; + private: Q_DISABLE_COPY(QVectorPath) diff --git a/src/gui/painting/qwindowsurface_raster.cpp b/src/gui/painting/qwindowsurface_raster.cpp index 22433dd..eddbfd2 100644 --- a/src/gui/painting/qwindowsurface_raster.cpp +++ b/src/gui/painting/qwindowsurface_raster.cpp @@ -118,7 +118,7 @@ QPaintDevice *QRasterWindowSurface::paintDevice() void QRasterWindowSurface::beginPaint(const QRegion &rgn) { #if (defined(Q_WS_X11) && !defined(QT_NO_XRENDER)) || (defined(Q_WS_WIN) && !defined(Q_WS_WINCE)) - if (!qt_widget_private(window())->isOpaque) { + if (!qt_widget_private(window())->isOpaque && window()->testAttribute(Qt::WA_TranslucentBackground)) { #if defined(Q_WS_WIN) && !defined(Q_WS_WINCE) if (d_ptr->image->image.format() != QImage::Format_ARGB32_Premultiplied) prepareBuffer(QImage::Format_ARGB32_Premultiplied, window()); @@ -149,7 +149,7 @@ void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoi QRect br = rgn.boundingRect(); #ifndef Q_WS_WINCE - if (!qt_widget_private(window())->isOpaque) { + if (!qt_widget_private(window())->isOpaque && window()->testAttribute(Qt::WA_TranslucentBackground)) { QRect r = window()->frameGeometry(); QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft(); QRect dirtyRect = br.translated(offset + frameOffset); diff --git a/src/gui/painting/qwindowsurface_x11.cpp b/src/gui/painting/qwindowsurface_x11.cpp index d8b0d9e..95f6ce3 100644 --- a/src/gui/painting/qwindowsurface_x11.cpp +++ b/src/gui/painting/qwindowsurface_x11.cpp @@ -154,7 +154,7 @@ void QX11WindowSurface::setGeometry(const QRect &rect) QX11PixmapData *oldData = static_cast<QX11PixmapData *>(d_ptr->device.pixmapData()); Q_ASSERT(oldData); - if (!oldData->uninit && hasStaticContents()) { + if (!(oldData->flags & QX11PixmapData::Uninitialized) && hasStaticContents()) { // Copy the content of the old pixmap into the new one. QX11PixmapData *newData = new QX11PixmapData(QPixmapData::PixmapType); newData->resize(size.width(), size.height()); @@ -175,7 +175,7 @@ void QX11WindowSurface::setGeometry(const QRect &rect) dx, dy, qMin(boundingRect.width(), size.width()), qMin(boundingRect.height(), size.height()), dx, dy); XFreeGC(X11->display, tmpGc); - newData->uninit = false; + newData->flags &= ~QX11PixmapData::Uninitialized; d_ptr->device = QPixmap(newData); } else { diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp index 51b3ccc..21a0736 100644 --- a/src/gui/statemachine/qkeyeventtransition.cpp +++ b/src/gui/statemachine/qkeyeventtransition.cpp @@ -106,19 +106,6 @@ QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, } /*! - Constructs a new key event transition for events of the given \a type for - the given \a object, with the given \a key, \a targets and \a sourceState. -*/ -QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, - int key, const QList<QAbstractState*> &targets, - QState *sourceState) - : QEventTransition(*new QKeyEventTransitionPrivate, object, type, targets, sourceState) -{ - Q_D(QKeyEventTransition); - d->transition = new QBasicKeyEventTransition(type, key); -} - -/*! Destroys this key event transition. */ QKeyEventTransition::~QKeyEventTransition() diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h index f5e8de3..45ae684 100644 --- a/src/gui/statemachine/qkeyeventtransition.h +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -62,9 +62,6 @@ public: QKeyEventTransition(QState *sourceState = 0); QKeyEventTransition(QObject *object, QEvent::Type type, int key, QState *sourceState = 0); - QKeyEventTransition(QObject *object, QEvent::Type type, int key, - const QList<QAbstractState*> &targets, - QState *sourceState = 0); ~QKeyEventTransition(); int key() const; diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp index 0cd096a..dbe50b3 100644 --- a/src/gui/statemachine/qmouseeventtransition.cpp +++ b/src/gui/statemachine/qmouseeventtransition.cpp @@ -112,21 +112,6 @@ QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, } /*! - Constructs a new mouse event transition for events of the given \a type for - the given \a object, with the given \a button, \a targets and \a - sourceState. -*/ -QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, - const QList<QAbstractState*> &targets, - QState *sourceState) - : QEventTransition(*new QMouseEventTransitionPrivate, object, type, targets, sourceState) -{ - Q_D(QMouseEventTransition); - d->transition = new QBasicMouseEventTransition(type, button); -} - -/*! Destroys this mouse event transition. */ QMouseEventTransition::~QMouseEventTransition() diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h index 73ae6c9..a56a554 100644 --- a/src/gui/statemachine/qmouseeventtransition.h +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -63,10 +63,6 @@ public: QMouseEventTransition(QState *sourceState = 0); QMouseEventTransition(QObject *object, QEvent::Type type, Qt::MouseButton button, QState *sourceState = 0); - QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, - const QList<QAbstractState*> &targets, - QState *sourceState = 0); ~QMouseEventTransition(); Qt::MouseButton button() const; diff --git a/src/gui/styles/gtksymbols.cpp b/src/gui/styles/gtksymbols.cpp index c2c7876..f947ac1 100644 --- a/src/gui/styles/gtksymbols.cpp +++ b/src/gui/styles/gtksymbols.cpp @@ -752,7 +752,24 @@ static void setupGtkFileChooser(GtkWidget* gtkFileChooser, QWidget *parent, QGtk::gtk_file_filter_set_name(gtkFilter, qPrintable(name.isEmpty() ? extensions.join(QLS(", ")) : name)); foreach (const QString &fileExtension, extensions) { - QGtk::gtk_file_filter_add_pattern (gtkFilter, qPrintable(fileExtension)); + // Note Gtk file dialogs are by default case sensitive + // and only supports basic glob syntax so we + // rewrite .xyz to .[xX][yY][zZ] + QString caseInsensitive; + for (int i = 0 ; i < fileExtension.length() ; ++i) { + QChar ch = fileExtension.at(i); + if (ch.isLetter()) { + caseInsensitive.append( + QLatin1Char('[') + + ch.toLower() + + ch.toUpper() + + QLatin1Char(']')); + } else { + caseInsensitive.append(ch); + } + } + QGtk::gtk_file_filter_add_pattern (gtkFilter, qPrintable(caseInsensitive)); + } if (filterMap) filterMap->insert(gtkFilter, rawfilter); diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index 308a0b8..ba28e75 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -2960,6 +2960,9 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt, horizontalShift *= -1; verticalShift *= -1; } + if (tab->shape == QTabBar::RoundedWest || tab->shape == QTabBar::TriangularWest) + horizontalShift = -horizontalShift; + tr.adjust(0, 0, horizontalShift, verticalShift); if (selected) { diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm index 2f93034..235cba6 100644 --- a/src/gui/styles/qmacstyle_mac.mm +++ b/src/gui/styles/qmacstyle_mac.mm @@ -5510,9 +5510,15 @@ QRect QMacStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *op break; } case SC_SpinBoxEditField: - ret.setRect(fw, fw, - spin->rect.width() - spinner_w - fw * 2 - spinBoxSep, - spin->rect.height() - fw * 2); + if (spin->buttonSymbols == QAbstractSpinBox::NoButtons) { + ret.setRect(fw, fw, + spin->rect.width() - fw * 2, + spin->rect.height() - fw * 2); + } else { + ret.setRect(fw, fw, + spin->rect.width() - fw * 2 - spinBoxSep - spinner_w, + spin->rect.height() - fw * 2); + } ret = visualRect(spin->direction, spin->rect, ret); break; default: diff --git a/src/gui/styles/qstyle.cpp b/src/gui/styles/qstyle.cpp index a5ab80e..598fe6b 100644 --- a/src/gui/styles/qstyle.cpp +++ b/src/gui/styles/qstyle.cpp @@ -564,7 +564,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, /*! \enum QStyle::PrimitiveElement - This enum describes that various primitive elements. A + This enum describes the various primitive elements. A primitive element is a common GUI element, such as a checkbox indicator or button bevel. @@ -1108,7 +1108,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, \value CC_ScrollBar A scroll bar, like QScrollBar. \value CC_Slider A slider, like QSlider. \value CC_ToolButton A tool button, like QToolButton. - \value CC_TitleBar A Title bar, like those used in QWorkspace. + \value CC_TitleBar A Title bar, like those used in QMdiSubWindow. \value CC_Q3ListView Used for drawing the Q3ListView class. \value CC_GroupBox A group box, like QGroupBox. \value CC_Dial A dial, like QDial. @@ -1894,7 +1894,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, can follow some existing GUI style or guideline. \value SP_TitleBarMinButton Minimize button on title bars (e.g., - in QWorkspace). + in QMdiSubWindow). \value SP_TitleBarMenuButton Menu button on a title bar. \value SP_TitleBarMaxButton Maximize button on title bars. \value SP_TitleBarCloseButton Close button on title bars. @@ -1966,22 +1966,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, \value SP_CustomBase Base value for custom standard pixmaps; custom values must be greater than this value. - \sa standardPixmap() standardIcon() -*/ - -/*### - \enum QStyle::IconMode - - This enum represents the effects performed on a pixmap to achieve a - GUI style's perferred way of representing the image in different - states. - - \value IM_Disabled A disabled pixmap (drawn on disabled widgets) - \value IM_Active An active pixmap (drawn on active tool buttons and menu items) - \value IM_CustomBase Base value for custom PixmapTypes; custom - values must be greater than this value - - \sa generatedIconPixmap() + \sa standardIcon() */ /*! @@ -2264,7 +2249,7 @@ QPalette QStyle::standardPalette() const slot in your subclass instead. The standardIcon() function will dynamically detect the slot and call it. - \sa standardIconImplementation(), standardPixmap() + \sa standardIconImplementation() */ QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const @@ -2289,8 +2274,7 @@ QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *opti subclass; because of binary compatibility constraints, the standardIcon() function (introduced in Qt 4.1) is not virtual. Instead, standardIcon() will dynamically detect and call - \e this slot. The default implementation simply calls the - standardPixmap() function with the given parameters. + \e this slot. The \a standardIcon is a standard pixmap which can follow some existing GUI style or guideline. The \a option argument can be diff --git a/src/gui/styles/qstyleoption.cpp b/src/gui/styles/qstyleoption.cpp index e174370..0ff7995 100644 --- a/src/gui/styles/qstyleoption.cpp +++ b/src/gui/styles/qstyleoption.cpp @@ -657,7 +657,7 @@ QStyleOptionFrameV2 &QStyleOptionFrameV2::operator=(const QStyleOptionFrame &oth /*! \enum QStyleOptionFrameV2::FrameFeature - This enum describles the different types of features a frame can have. + This enum describes the different types of features a frame can have. \value None Indicates a normal frame. \value Flat Indicates a flat frame. @@ -899,7 +899,7 @@ QStyleOptionViewItemV2 &QStyleOptionViewItemV2::operator=(const QStyleOptionView /*! \enum QStyleOptionViewItemV2::ViewItemFeature - This enum describles the different types of features an item can have. + This enum describes the different types of features an item can have. \value None Indicates a normal item. \value WrapText Indicates an item with wrapped text. @@ -4258,8 +4258,7 @@ QStyleOptionRubberBand::QStyleOptionRubberBand(int version) parameters for drawing a title bar. QStyleOptionTitleBar contains all the information that QStyle - functions need to draw the title bars of QWorkspace's MDI - children. + functions need to draw the title bar of a QMdiSubWindow. For performance reasons, the access to the member variables is direct (i.e., using the \c . or \c -> operator). This low-level feel @@ -4269,7 +4268,7 @@ QStyleOptionRubberBand::QStyleOptionRubberBand(int version) For an example demonstrating how style options can be used, see the \l {widgets/styles}{Styles} example. - \sa QStyleOption, QStyleOptionComplex, QWorkspace + \sa QStyleOption, QStyleOptionComplex, QMdiSubWindow */ /*! @@ -4983,8 +4982,7 @@ QStyleOptionSizeGrip::QStyleOptionSizeGrip(int version) */ /*! - Constructs a QStyleOptionGraphicsItem. The levelOfDetail parameter is - initialized to 1. + Constructs a QStyleOptionGraphicsItem. */ QStyleOptionGraphicsItem::QStyleOptionGraphicsItem() : QStyleOption(Version, Type), levelOfDetail(1) @@ -5009,11 +5007,6 @@ QStyleOptionGraphicsItem::QStyleOptionGraphicsItem(int version) of the painter used to draw the item. By default, if no transformations are applied, its value is 1. If zoomed out 1:2, the level of detail will be 0.5, and if zoomed in 2:1, its value is 2. - - For more advanced level-of-detail metrics, use - QStyleOptionGraphicsItem::matrix directly. - - \sa QStyleOptionGraphicsItem::matrix */ qreal QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &worldTransform) { @@ -5040,28 +5033,40 @@ qreal QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &wor Make use of this rectangle to speed up item drawing when only parts of the item are exposed. If the whole item is exposed, this rectangle will be the same as QGraphicsItem::boundingRect(). + + This member is only initialized for items that have the + QGraphicsItem::ItemUsesExtendedStyleOption flag set. */ /*! \variable QStyleOptionGraphicsItem::matrix \brief the complete transformation matrix for the item + \obsolete - This matrix is the sum of the item's scene matrix and the matrix of the - painter used for drawing the item. It is provided for convenience, + The QMatrix provided through this member does include information about + any perspective transformations applied to the view or item. To get the + correct transformation matrix, use QPainter::transform() on the painter + passed into the QGraphicsItem::paint() implementation. + + This matrix is the combination of the item's scene matrix and the matrix + of the painter used for drawing the item. It is provided for convenience, allowing anvanced level-of-detail metrics that can be used to speed up item drawing. - To find the dimentions of an item in screen coordinates (i.e., pixels), + To find the dimensions of an item in screen coordinates (i.e., pixels), you can use the mapping functions of QMatrix, such as QMatrix::map(). - \sa QStyleOptionGraphicsItem::levelOfDetail + This member is only initialized for items that have the + QGraphicsItem::ItemUsesExtendedStyleOption flag set. + + \sa QStyleOptionGraphicsItem::levelOfDetailFromTransform() */ /*! \variable QStyleOptionGraphicsItem::levelOfDetail \obsolete - Use QStyleOptionGraphicsItem::levelOfDetailFromTransform + Use QStyleOptionGraphicsItem::levelOfDetailFromTransform() together with QPainter::worldTransform() instead. */ diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index 2efa4a7..5f6d4ab 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -2891,8 +2891,8 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC bool customUp = true, customDown = true; QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton); QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton); - bool upRuleMatch = upRule.hasGeometry(); - bool downRuleMatch = downRule.hasGeometry(); + bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition(); + bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition(); if (rule.hasNativeBorder() && !upRuleMatch && !downRuleMatch) { rule.drawBackgroundImage(p, spinOpt.rect); customUp = (opt->subControls & QStyle::SC_SpinBoxUp) @@ -5167,8 +5167,8 @@ QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComp QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton); QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton); bool ruleMatch = rule.hasBox() || !rule.hasNativeBorder(); - bool upRuleMatch = upRule.hasGeometry(); - bool downRuleMatch = downRule.hasGeometry(); + bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition(); + bool downRuleMatch = downRule.hasGeometry() || upRule.hasPosition(); if (ruleMatch || upRuleMatch || downRuleMatch) { switch (sc) { case SC_SpinBoxFrame: diff --git a/src/gui/styles/qwindowsvistastyle.cpp b/src/gui/styles/qwindowsvistastyle.cpp index f3d0f04..6f3017a 100644 --- a/src/gui/styles/qwindowsvistastyle.cpp +++ b/src/gui/styles/qwindowsvistastyle.cpp @@ -364,7 +364,8 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt w->setProperty("_q_stylestate", (int)option->state); w->setProperty("_q_stylerect", w->rect()); - bool doTransition = ((state & State_Sunken) != (oldState & State_Sunken) || + bool doTransition = oldState && + ((state & State_Sunken) != (oldState & State_Sunken) || (state & State_On) != (oldState & State_On) || (state & State_MouseOver) != (oldState & State_MouseOver)); @@ -2229,7 +2230,7 @@ QRect QWindowsVistaStyle::subControlRect(ComplexControl control, const QStyleOpt rect = cb->rect; break; case SC_ComboBoxArrow: - rect.setRect(cb->editable ? xpos : 0, y , wi - xpos, he); + rect.setRect(xpos, y , wi - xpos, he); break; case SC_ComboBoxEditField: rect.setRect(x + margin, y + margin, wi - 2 * margin - 16, he - 2 * margin); diff --git a/src/gui/styles/qwindowsxpstyle.cpp b/src/gui/styles/qwindowsxpstyle.cpp index 9560c4b..ad87354 100644 --- a/src/gui/styles/qwindowsxpstyle.cpp +++ b/src/gui/styles/qwindowsxpstyle.cpp @@ -134,6 +134,7 @@ static const int windowsRightBorder = 12; // right border on windows // External function calls extern Q_GUI_EXPORT HDC qt_win_display_dc(); +extern QRegion qt_region_from_HRGN(HRGN rgn); @@ -445,6 +446,7 @@ bool QWindowsXPStylePrivate::isTransparent(XPThemeData &themeData) themeData.stateId); } + /*! \internal Returns a QRegion of the region of the part */ @@ -456,12 +458,18 @@ QRegion QWindowsXPStylePrivate::region(XPThemeData &themeData) themeData.stateId, &rect, &hRgn))) return QRegion(); - QRegion rgn = QRegion(0,0,1,1); - const bool success = CombineRgn(rgn.handle(), hRgn, 0, RGN_COPY) != ERROR; - DeleteObject(hRgn); + HRGN dest = CreateRectRgn(0, 0, 0, 0); + const bool success = CombineRgn(dest, hRgn, 0, RGN_COPY) != ERROR; + + QRegion region; + if (success) - return rgn; - return QRegion(); + region = qt_region_from_HRGN(dest); + + DeleteObject(hRgn); + DeleteObject(dest); + + return region; } /*! \internal diff --git a/src/gui/text/qcssparser_p.h b/src/gui/text/qcssparser_p.h index b07acd5..9f046ff 100644 --- a/src/gui/text/qcssparser_p.h +++ b/src/gui/text/qcssparser_p.h @@ -67,6 +67,11 @@ #ifndef QT_NO_CSSPARSER +// VxWorks defines NONE as (-1) "for times when NULL won't do" +#if defined(Q_OS_VXWORKS) && defined(NONE) +# undef NONE +#endif + QT_BEGIN_NAMESPACE namespace QCss diff --git a/src/gui/text/qfontdatabase_qws.cpp b/src/gui/text/qfontdatabase_qws.cpp index d348e1b..34239ff 100644 --- a/src/gui/text/qfontdatabase_qws.cpp +++ b/src/gui/text/qfontdatabase_qws.cpp @@ -360,7 +360,7 @@ static QString qwsFontPath() return fontpath; } -#ifdef QFONTDATABASE_DEBUG +#if defined(QFONTDATABASE_DEBUG) && defined(QT_FONTS_ARE_RESOURCES) class FriendlyResource : public QResource { public: @@ -694,8 +694,12 @@ QFontEngine *loadSingleEngine(int script, const QFontPrivate *fp, QFontDef def = request; def.pixelSize = pixelSize; +#ifdef QT_NO_QWS_SHARE_FONTS + bool shareFonts = false; +#else static bool dontShareFonts = !qgetenv("QWS_NO_SHARE_FONTS").isEmpty(); bool shareFonts = !dontShareFonts; +#endif QFontEngine *engine = 0; diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp index a0b6f0c..d210cb4 100644 --- a/src/gui/text/qfontengine_ft.cpp +++ b/src/gui/text/qfontengine_ft.cpp @@ -1378,8 +1378,8 @@ bool QFontEngineFT::loadGlyphs(QGlyphSet *gs, glyph_t *glyphs, int num_glyphs, G FT_Face face = 0; for (int i = 0; i < num_glyphs; ++i) { - if (!gs->glyph_data.contains(glyphs[i]) - || gs->glyph_data.value(glyphs[i])->format != format) { + Glyph *glyph = gs->glyph_data.value(glyphs[i]); + if (glyph == 0 || glyph->format != format) { if (!face) { face = lockFace(); FT_Matrix m = matrix; diff --git a/src/gui/text/qfontengine_mac.mm b/src/gui/text/qfontengine_mac.mm index 76132df..dbf3015 100644 --- a/src/gui/text/qfontengine_mac.mm +++ b/src/gui/text/qfontengine_mac.mm @@ -156,7 +156,7 @@ QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(const ATSFontFamilyRef &, con if (!kerning) { float zero = 0.0; QCFType<CFNumberRef> noKern = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero); - CFDictionaryAddValue(attributeDict, kCTKernAttributeName, &noKern); + CFDictionaryAddValue(attributeDict, kCTKernAttributeName, noKern); } QCoreTextFontEngine *fe = new QCoreTextFontEngine(ctfont, fontDef, this); @@ -1588,6 +1588,7 @@ QFontEngine::FaceId QFontEngineMac::faceId() const { FaceId ret; #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) +if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) { // CTFontGetPlatformFont FSRef ref; if (ATSFontGetFileReference(FMGetATSFontRefFromFont(fontID), &ref) != noErr) @@ -1595,7 +1596,9 @@ QFontEngine::FaceId QFontEngineMac::faceId() const ret.filename = QByteArray(128, 0); ret.index = fontID; FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size()); -#else +}else +#endif +{ FSSpec spec; if (ATSFontGetFileSpecification(FMGetATSFontRefFromFont(fontID), &spec) != noErr) return ret; @@ -1605,7 +1608,7 @@ QFontEngine::FaceId QFontEngineMac::faceId() const ret.filename = QByteArray(128, 0); ret.index = fontID; FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size()); -#endif +} return ret; } diff --git a/src/gui/text/qfontengine_qpf.cpp b/src/gui/text/qfontengine_qpf.cpp index b255694..ed8abb8 100644 --- a/src/gui/text/qfontengine_qpf.cpp +++ b/src/gui/text/qfontengine_qpf.cpp @@ -331,16 +331,37 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng #if defined(DEBUG_FONTENGINE) qDebug() << "found existing qpf:" << fileName; #endif - if (::access(encodedName, W_OK | R_OK) == 0) - fd = QT_OPEN(encodedName, O_RDWR, 0); - else if (::access(encodedName, R_OK) == 0) - fd = QT_OPEN(encodedName, O_RDONLY, 0); + if (::access(encodedName, W_OK | R_OK) == 0) { + fd = QT_OPEN(encodedName, O_RDWR); + } + // read-write access failed - try read-only access + if (fd == -1 && ::access(encodedName, R_OK) == 0) { + fd = QT_OPEN(encodedName, O_RDONLY); + if (fd == -1) { +#if defined(DEBUG_FONTENGINE) + qErrnoWarning("QFontEngineQPF: unable to open %s", encodedName.constData()); +#endif + return; + } + } + if (fd == -1) { +#if defined(DEBUG_FONTENGINE) + qWarning("QFontEngineQPF: insufficient access rights to %s", encodedName.constData()); +#endif + return; + } } else { #if defined(DEBUG_FONTENGINE) qDebug() << "creating qpf on the fly:" << fileName; #endif if (::access(QFile::encodeName(qws_fontCacheDir()), W_OK) == 0) { fd = QT_OPEN(encodedName, O_RDWR | O_EXCL | O_CREAT, 0644); + if (fd == -1) { +#if defined(DEBUG_FONTENGINE) + qErrnoWarning(errno, "QFontEngineQPF: open() failed for %s", encodedName.constData()); +#endif + return; + } QBuffer buffer; buffer.open(QIODevice::ReadWrite); @@ -348,7 +369,17 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng generator.generate(); buffer.close(); const QByteArray &data = buffer.data(); - QT_WRITE(fd, data.constData(), data.size()); + if (QT_WRITE(fd, data.constData(), data.size()) == -1) { +#if defined(DEBUG_FONTENGINE) + qErrnoWarning(errno, "QFontEngineQPF: write() failed for %s", encodedName.constData()); +#endif + return; + } + } else { +#if defined(DEBUG_FONTENGINE) + qErrnoWarning(errno, "QFontEngineQPF: access() failed for %s", qPrintable(qws_fontCacheDir())); +#endif + return; } } } @@ -356,7 +387,7 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng QT_STATBUF st; if (QT_FSTAT(fd, &st)) { #if defined(DEBUG_FONTENGINE) - qDebug() << "stat failed!"; + qErrnoWarning(errno, "QFontEngineQPF: fstat failed!"); #endif return; } @@ -486,8 +517,13 @@ QFontEngineQPF::~QFontEngineQPF() qt_fbdpy->sendFontCommand(QWSFontCommand::StoppedUsingFont, QFile::encodeName(fileName)); #endif delete renderingFontEngine; - if (fontData) - munmap((void *)fontData, dataSize); + if (fontData) { + if (munmap((void *)fontData, dataSize) == -1) { +#if defined(DEBUG_FONTENGINE) + qErrnoWarning(errno, "~QFontEngineQPF: Unable to munmap"); +#endif + } + } if (fd != -1) ::close(fd); #if !defined(QT_NO_FREETYPE) diff --git a/src/gui/text/qfontengine_qws.cpp b/src/gui/text/qfontengine_qws.cpp index 70ce8f9..10bee2c 100644 --- a/src/gui/text/qfontengine_qws.cpp +++ b/src/gui/text/qfontengine_qws.cpp @@ -396,7 +396,7 @@ QFontEngineQPF1::QFontEngineQPF1(const QFontDef&, const QString &fn) uchar* data = (uchar*)mmap( 0, // any address st.st_size, // whole file PROT_READ, // read-only memory -#if !defined(Q_OS_SOLARIS) && !defined(Q_OS_QNX4) && !defined(Q_OS_INTEGRITY) +#if !defined(Q_OS_SOLARIS) && !defined(Q_OS_QNX4) && !defined(Q_OS_INTEGRITY) && !defined(Q_OS_VXWORKS) MAP_FILE | MAP_PRIVATE, // swap-backed map from file #else MAP_PRIVATE, diff --git a/src/gui/text/qfontmetrics.cpp b/src/gui/text/qfontmetrics.cpp index abab91c..012c0f6 100644 --- a/src/gui/text/qfontmetrics.cpp +++ b/src/gui/text/qfontmetrics.cpp @@ -557,11 +557,10 @@ int QFontMetrics::width(const QString &text, int len) const \warning This function will produce incorrect results for Arabic characters or non-spacing marks in the middle of a string, as the glyph shaping and positioning of marks that happens when - processing strings cannot be taken into account. Use charWidth() - instead if you aren't looking for the width of isolated - characters. + processing strings cannot be taken into account. When implementing + an interactive text control, use QTextLayout instead. - \sa boundingRect(), charWidth() + \sa boundingRect() */ int QFontMetrics::width(QChar ch) const { @@ -1386,9 +1385,8 @@ qreal QFontMetricsF::width(const QString &text) const \warning This function will produce incorrect results for Arabic characters or non-spacing marks in the middle of a string, as the glyph shaping and positioning of marks that happens when - processing strings cannot be taken into account. Use charWidth() - instead if you aren't looking for the width of isolated - characters. + processing strings cannot be taken into account. When implementing + an interactive text control, use QTextLayout instead. \sa boundingRect() */ diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index 2a590fd..b2ad686 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -1245,8 +1245,7 @@ void QTextControlPrivate::keyPressEvent(QKeyEvent *e) process: { QString text = e->text(); - if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t')) && - ((e->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) == Qt::NoModifier)) { + if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t'))) { if (overwriteMode // no need to call deleteChar() if we have a selection, insertText // does it already diff --git a/src/gui/text/qtextcontrol_p.h b/src/gui/text/qtextcontrol_p.h index 872bcd5..eb0d749 100644 --- a/src/gui/text/qtextcontrol_p.h +++ b/src/gui/text/qtextcontrol_p.h @@ -83,7 +83,7 @@ class QAbstractScrollArea; class QEvent; class QTimerEvent; -class Q_AUTOTEST_EXPORT QTextControl : public QObject +class Q_GUI_EXPORT QTextControl : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QTextControl) diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp index ea37e04..e66b07c 100644 --- a/src/gui/text/qtextdocument_p.cpp +++ b/src/gui/text/qtextdocument_p.cpp @@ -60,6 +60,15 @@ QT_BEGIN_NAMESPACE #define PMDEBUG if(0) qDebug +// The VxWorks DIAB compiler crashes when initializing the anonymouse union with { a7 } +#if !defined(Q_CC_DIAB) +# define QT_INIT_TEXTUNDOCOMMAND(c, a1, a2, a3, a4, a5, a6, a7, a8) \ + QTextUndoCommand c = { a1, a2, a3, a4, a5, a6, { a7 }, a8 } +#else +# define QT_INIT_TEXTUNDOCOMMAND(c, a1, a2, a3, a4, a5, a6, a7, a8) \ + QTextUndoCommand c = { a1, a2, a3, a4, a5, a6 }; c.blockFormat = a7; c.revision = a8 +#endif + /* Structure of a document: @@ -406,9 +415,9 @@ int QTextDocumentPrivate::insertBlock(const QChar &blockSeparator, int b = blocks.findNode(pos); QTextBlockData *B = blocks.fragment(b); - QTextUndoCommand c = { QTextUndoCommand::BlockInserted, editBlock != 0, - op, charFormat, strPos, pos, { blockFormat }, - B->revision }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::BlockInserted, editBlock != 0, + op, charFormat, strPos, pos, blockFormat, + B->revision); appendUndoItem(c); Q_ASSERT(undoState == undoStack.size()); @@ -447,9 +456,9 @@ void QTextDocumentPrivate::insert(int pos, int strPos, int strLength, int format int b = blocks.findNode(pos); QTextBlockData *B = blocks.fragment(b); - QTextUndoCommand c = { QTextUndoCommand::Inserted, editBlock != 0, - QTextUndoCommand::MoveCursor, format, strPos, pos, { strLength }, - B->revision }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::Inserted, editBlock != 0, + QTextUndoCommand::MoveCursor, format, strPos, pos, strLength, + B->revision); appendUndoItem(c); B->revision = undoState; Q_ASSERT(undoState == undoStack.size()); @@ -606,12 +615,12 @@ void QTextDocumentPrivate::move(int pos, int to, int length, QTextUndoCommand::O int blockRevision = B->revision; QTextFragmentData *X = fragments.fragment(x); - QTextUndoCommand c = { QTextUndoCommand::Removed, editBlock != 0, - op, X->format, X->stringPosition, key, { X->size_array[0] }, - blockRevision }; - QTextUndoCommand cInsert = { QTextUndoCommand::Inserted, editBlock != 0, - op, X->format, X->stringPosition, dstKey, { X->size_array[0] }, - blockRevision }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::Removed, editBlock != 0, + op, X->format, X->stringPosition, key, X->size_array[0], + blockRevision); + QT_INIT_TEXTUNDOCOMMAND(cInsert, QTextUndoCommand::Inserted, editBlock != 0, + op, X->format, X->stringPosition, dstKey, X->size_array[0], + blockRevision); if (key+1 != blocks.position(b)) { // qDebug("remove_string from %d length %d", key, X->size_array[0]); @@ -723,8 +732,8 @@ void QTextDocumentPrivate::setCharFormat(int pos, int length, const QTextCharFor fragment->format = newFormatIdx; } - QTextUndoCommand c = { QTextUndoCommand::CharFormatChanged, true, QTextUndoCommand::MoveCursor, oldFormat, - 0, pos, { length }, 0 }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::CharFormatChanged, true, QTextUndoCommand::MoveCursor, oldFormat, + 0, pos, length, 0); appendUndoItem(c); pos += length; @@ -783,8 +792,8 @@ void QTextDocumentPrivate::setBlockFormat(const QTextBlock &from, const QTextBlo block(it)->invalidate(); - QTextUndoCommand c = { QTextUndoCommand::BlockFormatChanged, true, QTextUndoCommand::MoveCursor, oldFormat, - 0, it.position(), { 1 }, 0 }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::BlockFormatChanged, true, QTextUndoCommand::MoveCursor, oldFormat, + 0, it.position(), 1, 0); appendUndoItem(c); if (group != oldGroup) { @@ -1298,8 +1307,8 @@ void QTextDocumentPrivate::changeObjectFormat(QTextObject *obj, int format) if (f) documentChange(f->firstPosition(), f->lastPosition() - f->firstPosition()); - QTextUndoCommand c = { QTextUndoCommand::GroupFormatChange, editBlock != 0, QTextUndoCommand::MoveCursor, oldFormatIndex, - 0, 0, { obj->d_func()->objectIndex }, 0 }; + QT_INIT_TEXTUNDOCOMMAND(c, QTextUndoCommand::GroupFormatChange, editBlock != 0, QTextUndoCommand::MoveCursor, oldFormatIndex, + 0, 0, obj->d_func()->objectIndex, 0); appendUndoItem(c); endEditBlock(); diff --git a/src/gui/text/qtextdocumentfragment.cpp b/src/gui/text/qtextdocumentfragment.cpp index a940aa4..cb09452 100644 --- a/src/gui/text/qtextdocumentfragment.cpp +++ b/src/gui/text/qtextdocumentfragment.cpp @@ -54,7 +54,11 @@ QT_BEGIN_NAMESPACE QTextCopyHelper::QTextCopyHelper(const QTextCursor &_source, const QTextCursor &_destination, bool forceCharFormat, const QTextCharFormat &fmt) +#if defined(Q_CC_DIAB) // compiler bug + : formatCollection(*_destination.d->priv->formatCollection()), originalText((const QString)_source.d->priv->buffer()) +#else : formatCollection(*_destination.d->priv->formatCollection()), originalText(_source.d->priv->buffer()) +#endif { src = _source.d->priv; dst = _destination.d->priv; diff --git a/src/gui/text/qtextformat.cpp b/src/gui/text/qtextformat.cpp index 4e43418..a3dd83e 100644 --- a/src/gui/text/qtextformat.cpp +++ b/src/gui/text/qtextformat.cpp @@ -89,7 +89,7 @@ QT_BEGIN_NAMESPACE /*! \fn Type QTextLength::type() const - Returns the type of length. + Returns the type of this length object. \sa QTextLength::Type */ @@ -129,9 +129,15 @@ QT_BEGIN_NAMESPACE /*! \enum QTextLength::Type - \value VariableLength - \value FixedLength - \value PercentageLength + This enum describes the different types a length object can + have. + + \value VariableLength The width of the object is variable + \value FixedLength The width of the object is fixed + \value PercentageLength The width of the object is in + percentage of the maximum width + + \sa type() */ /*! @@ -417,7 +423,7 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) more useful, and describe the formatting that is applied to specific parts of the document. - A format has a \c FormatType which specifies the kinds of thing it + A format has a \c FormatType which specifies the kinds of text item it can format; e.g. a block of text, a list, a table, etc. A format also has various properties (some specific to particular format types), as described by the Property enum. Every property has a @@ -447,24 +453,32 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) /*! \enum QTextFormat::FormatType - \value InvalidFormat - \value BlockFormat - \value CharFormat - \value ListFormat - \value TableFormat - \value FrameFormat + This enum describes the text item a QTextFormat object is formatting. + + \value InvalidFormat An invalid format as created by the default + constructor + \value BlockFormat The object formats a text block + \value CharFormat The object formats a single character + \value ListFormat The object formats a list + \value TableFormat The object formats a table + \value FrameFormat The object formats a frame \value UserFormat + + \sa QTextCharFormat, QTextBlockFormat, QTextListFormat, + QTextTableFormat, type() */ /*! \enum QTextFormat::Property - \value ObjectIndex + This enum describes the different properties a format can have. + + \value ObjectIndex The index of the formatted object. See objectIndex(). Paragraph and character properties - \value CssFloat + \value CssFloat How a frame is located relative to the surrounding text \value LayoutDirection The layout direction of the text in the document (Qt::LayoutDirection). @@ -482,25 +496,25 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) \value BlockRightMargin \value TextIndent \value TabPositions Specifies the tab positions. The tab positions are structs of QTextOption::Tab which are stored in - a QList (internally, in a QList<QVariant>). + a QList (internally, in a QList<QVariant>). \value BlockIndent \value BlockNonBreakableLines - \value BlockTrailingHorizontalRulerWidth + \value BlockTrailingHorizontalRulerWidth The width of a horizontal ruler element. Character properties \value FontFamily \value FontPointSize + \value FontPixelSize \value FontSizeAdjustment Specifies the change in size given to the fontsize already set using FontPointSize or FontPixelSize. + \value FontFixedPitch \omitvalue FontSizeIncrement \value FontWeight \value FontItalic \value FontUnderline \e{This property has been deprecated.} Use QTextFormat::TextUnderlineStyle instead. \value FontOverline \value FontStrikeOut - \value FontFixedPitch - \value FontPixelSize \value FontCapitalization Specifies the capitalization type that is to be applied to the text. \value FontLetterSpacing Changes the default spacing between individual letters in the font. The value is specified in percentage, with 100 as the default value. @@ -512,7 +526,7 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) \omitvalue FirstFontProperty \omitvalue LastFontProperty - + \value TextUnderlineColor \value TextVerticalAlignment \value TextOutline @@ -533,7 +547,7 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) \value FrameBorder \value FrameBorderBrush - \value FrameBorderStyle + \value FrameBorderStyle See the \l{QTextFrameFormat::BorderStyle}{BorderStyle} enum. \value FrameBottomMargin \value FrameHeight \value FrameLeftMargin @@ -565,33 +579,46 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) Selection properties - \value FullWidthSelection When set on the characterFormat of a selection, the whole width of the text will be shown selected + \value FullWidthSelection When set on the characterFormat of a selection, + the whole width of the text will be shown selected. Page break properties - \value PageBreakPolicy + \value PageBreakPolicy Specifies how pages are broken. See the PageBreakFlag enum. \value UserProperty + + \sa property(), setProperty() */ /*! \enum QTextFormat::ObjectTypes + This enum describes what kind of QTextObject this format is associated with. + \value NoObject \value ImageObject \value TableObject \value TableCellObject \value UserObject The first object that can be used for application-specific purposes. + + \sa QTextObject, QTextTable, QTextObject::format() */ /*! \enum QTextFormat::PageBreakFlag \since 4.2 + This enum describes how page breaking is performed when printing. It maps to the + corresponding css properties. + \value PageBreak_Auto The page break is determined automatically depending on the available space on the current page \value PageBreak_AlwaysBefore The page is always broken before the paragraph/table \value PageBreak_AlwaysAfter A new page is always started after the paragraph/table + + \sa QTextBlockFormat::pageBreakPolicy(), QTextFrameFormat::pageBreakPolicy(), + PageBreakPolicy */ /*! @@ -971,6 +998,8 @@ QVector<QTextLength> QTextFormat::lengthVectorProperty(int propertyId) const /*! Returns the property specified by the given \a propertyId. + + \sa Property */ QVariant QTextFormat::property(int propertyId) const { @@ -979,6 +1008,8 @@ QVariant QTextFormat::property(int propertyId) const /*! Sets the property specified by the \a propertyId to the given \a value. + + \sa Property */ void QTextFormat::setProperty(int propertyId, const QVariant &value) { @@ -1006,8 +1037,10 @@ void QTextFormat::setProperty(int propertyId, const QVector<QTextLength> &value) } /*! - Clears the value of the property given by \a propertyId - */ + Clears the value of the property given by \a propertyId + + \sa Property +*/ void QTextFormat::clearProperty(int propertyId) { if (!d) @@ -1019,14 +1052,18 @@ void QTextFormat::clearProperty(int propertyId) /*! \fn void QTextFormat::setObjectType(int type) - Sets the text format's object \a type. See \c{ObjectTypes}. + Sets the text format's object type to \a type. + + \sa ObjectTypes, objectType() */ /*! \fn int QTextFormat::objectType() const - Returns the text format's object type. See \c{ObjectTypes}. + Returns the text format's object type. + + \sa ObjectTypes, setObjectType() */ @@ -2116,17 +2153,17 @@ QTextListFormat::QTextListFormat(const QTextFormat &fmt) /*! \fn void QTextListFormat::setStyle(Style style) - Sets the list format's \a style. See \c{Style} for the available styles. + Sets the list format's \a style. - \sa style() + \sa style() Style */ /*! \fn Style QTextListFormat::style() const - Returns the list format's style. See \c{Style}. + Returns the list format's style. - \sa setStyle() + \sa setStyle() Style */ @@ -2188,16 +2225,21 @@ QTextListFormat::QTextListFormat(const QTextFormat &fmt) /*! \enum QTextFrameFormat::Position + This enum describes how a frame is located relative to the surrounding text. + \value InFlow \value FloatLeft \value FloatRight + \sa position() CssFloat */ /*! \enum QTextFrameFormat::BorderStyle \since 4.3 + This enum describes different border styles for the text frame. + \value BorderStyle_None \value BorderStyle_Dotted \value BorderStyle_Dashed @@ -2210,6 +2252,7 @@ QTextListFormat::QTextListFormat(const QTextFormat &fmt) \value BorderStyle_Inset \value BorderStyle_Outset + \sa borderStyle() FrameBorderStyle */ /*! diff --git a/src/gui/text/qtextlist.cpp b/src/gui/text/qtextlist.cpp index 02b1c63..5e9898a 100644 --- a/src/gui/text/qtextlist.cpp +++ b/src/gui/text/qtextlist.cpp @@ -129,8 +129,6 @@ QTextList::~QTextList() /*! Returns the number of items in the list. - - \sa isEmpty() */ int QTextList::count() const { diff --git a/src/gui/util/qcompleter.cpp b/src/gui/util/qcompleter.cpp index bf1fa6a..f4dd87c 100644 --- a/src/gui/util/qcompleter.cpp +++ b/src/gui/util/qcompleter.cpp @@ -772,7 +772,7 @@ QMatchData QUnsortedModelEngine::filter(const QString& part, const QModelIndex& /////////////////////////////////////////////////////////////////////////////// QCompleterPrivate::QCompleterPrivate() : widget(0), proxy(0), popup(0), cs(Qt::CaseSensitive), role(Qt::EditRole), column(0), - sorting(QCompleter::UnsortedModel), wrap(true), maxVisibleItems(7), eatFocusOut(true) + maxVisibleItems(7), sorting(QCompleter::UnsortedModel), wrap(true), eatFocusOut(true) { } @@ -824,6 +824,9 @@ void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted) Q_Q(QCompleter); QString completion; + if (!(index.flags() & Qt::ItemIsEnabled)) + return; + if (!index.isValid() || (!proxy->showAll && (index.row() >= proxy->engine->matchCount()))) { completion = prefix; } else { @@ -1102,7 +1105,8 @@ void QCompleter::setPopup(QAbstractItemView *popup) QObject::connect(popup, SIGNAL(clicked(QModelIndex)), this, SLOT(_q_complete(QModelIndex))); - QObject::connect(popup, SIGNAL(clicked(QModelIndex)), popup, SLOT(hide())); + QObject::connect(this, SIGNAL(activated(QModelIndex)), + popup, SLOT(hide())); QObject::connect(popup->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(_q_completionSelected(QItemSelection))); diff --git a/src/gui/util/qdesktopservices_x11.cpp b/src/gui/util/qdesktopservices_x11.cpp index f0202d4..0a3c2d0 100644 --- a/src/gui/util/qdesktopservices_x11.cpp +++ b/src/gui/util/qdesktopservices_x11.cpp @@ -56,7 +56,11 @@ QT_BEGIN_NAMESPACE inline static bool launch(const QUrl &url, const QString &client) { +#if !defined(QT_NO_PROCESS) return (QProcess::startDetached(client + QLatin1Char(' ') + QString::fromLatin1(url.toEncoded().constData()))); +#else + return (::system((client + QLatin1Char(' ') + QString::fromLatin1(url.toEncoded().constData())).toLocal8Bit().constData()) != -1); +#endif } static bool openDocument(const QUrl &url) diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp index 85eae26..a0648a1 100644 --- a/src/gui/util/qsystemtrayicon_win.cpp +++ b/src/gui/util/qsystemtrayicon_win.cpp @@ -106,6 +106,7 @@ public: private: uint notifyIconSize; int maxTipLength; + bool ignoreNextMouseRelease; }; bool QSystemTrayIconSys::allowsMessages() @@ -128,7 +129,8 @@ bool QSystemTrayIconSys::supportsMessages() } QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object) - : hIcon(0), q(object) + : hIcon(0), q(object), ignoreNextMouseRelease(false) + { #ifndef Q_OS_WINCE notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, guidItem); // NOTIFYICONDATAW_V2_SIZE; @@ -311,10 +313,15 @@ bool QSystemTrayIconSys::winEvent( MSG *m, long *result ) switch (m->lParam) { case WM_LBUTTONUP: - emit q->activated(QSystemTrayIcon::Trigger); + if (ignoreNextMouseRelease) + ignoreNextMouseRelease = false; + else + emit q->activated(QSystemTrayIcon::Trigger); break; case WM_LBUTTONDBLCLK: + ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse + // release we must ignore it emit q->activated(QSystemTrayIcon::DoubleClick); break; diff --git a/src/gui/widgets/qabstractscrollarea.cpp b/src/gui/widgets/qabstractscrollarea.cpp index dd92e17..f6c1892 100644 --- a/src/gui/widgets/qabstractscrollarea.cpp +++ b/src/gui/widgets/qabstractscrollarea.cpp @@ -159,7 +159,7 @@ QT_BEGIN_NAMESPACE QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate() :hbar(0), vbar(0), vbarpolicy(Qt::ScrollBarAsNeeded), hbarpolicy(Qt::ScrollBarAsNeeded), viewport(0), cornerWidget(0), left(0), top(0), right(0), bottom(0), - xoffset(0), yoffset(0), viewportFilter(0) + xoffset(0), yoffset(0), viewportFilter(0), panGesture(0) #ifdef Q_WS_WIN , singleFingerPanEnabled(false) #endif @@ -294,33 +294,18 @@ void QAbstractScrollAreaPrivate::init() q->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); layoutChildren(); + + panGesture = new QPanGesture(q); + QObject::connect(panGesture, SIGNAL(triggered()), q, SLOT(_q_gestureTriggered())); } -void QAbstractScrollAreaPrivate::setupGestures() +#ifdef Q_WS_WIN +void QAbstractScrollAreaPrivate::setSingleFingerPanEnabled(bool on) { -#ifdef Q_OS_WIN - if (!viewport) - return; - QApplicationPrivate* getQApplicationPrivateInternal(); - QApplicationPrivate *qAppPriv = getQApplicationPrivateInternal(); - bool needh = (hbarpolicy == Qt::ScrollBarAlwaysOn - || (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum())); - - bool needv = (vbarpolicy == Qt::ScrollBarAlwaysOn - || (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum())); - if (qAppPriv->SetGestureConfig && (needh || needv)) { - GESTURECONFIG gc[1]; - gc[0].dwID = GID_PAN; - gc[0].dwWant = GC_PAN; - gc[0].dwBlock = 0; - if (needv && singleFingerPanEnabled) - gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY; - if (needh && singleFingerPanEnabled) - gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY; - qAppPriv->SetGestureConfig(viewport->winId(), 0, 1, gc, sizeof(gc)); - } -#endif // Q_OS_WIN + singleFingerPanEnabled = on; + winSetupGestures(); } +#endif // Q_WS_WIN void QAbstractScrollAreaPrivate::layoutChildren() { @@ -1267,7 +1252,11 @@ void QAbstractScrollAreaPrivate::_q_vslide(int y) void QAbstractScrollAreaPrivate::_q_showOrHideScrollBars() { layoutChildren(); - setupGestures(); +#ifdef Q_OS_WIN + // Need to re-subscribe to gestures as the content changes to make sure we + // enable/disable panning when needed. + winSetupGestures(); +#endif // Q_OS_WIN } QPoint QAbstractScrollAreaPrivate::contentsOffset() const @@ -1332,6 +1321,25 @@ void QAbstractScrollArea::setupViewport(QWidget *viewport) Q_UNUSED(viewport); } +void QAbstractScrollAreaPrivate::_q_gestureTriggered() +{ + Q_Q(QAbstractScrollArea); + QPanGesture *g = qobject_cast<QPanGesture*>(q->sender()); + if (!g) + return; + QScrollBar *hBar = q->horizontalScrollBar(); + QScrollBar *vBar = q->verticalScrollBar(); + QSize delta = g->lastOffset(); + if (!delta.isNull()) { + if (QApplication::isRightToLeft()) + delta.rwidth() *= -1; + int newX = hBar->value() - delta.width(); + int newY = vBar->value() - delta.height(); + hbar->setValue(newX); + vbar->setValue(newY); + } +} + QT_END_NAMESPACE #include "moc_qabstractscrollarea.cpp" diff --git a/src/gui/widgets/qabstractscrollarea.h b/src/gui/widgets/qabstractscrollarea.h index 3ec41d1..9178629 100644 --- a/src/gui/widgets/qabstractscrollarea.h +++ b/src/gui/widgets/qabstractscrollarea.h @@ -128,8 +128,10 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_hslide(int)) Q_PRIVATE_SLOT(d_func(), void _q_vslide(int)) Q_PRIVATE_SLOT(d_func(), void _q_showOrHideScrollBars()) + Q_PRIVATE_SLOT(d_func(), void _q_gestureTriggered()) friend class QStyleSheetStyle; + friend class QWidgetPrivate; }; #endif // QT_NO_SCROLLAREA diff --git a/src/gui/widgets/qabstractscrollarea_p.h b/src/gui/widgets/qabstractscrollarea_p.h index aef8ac5..8011ed5 100644 --- a/src/gui/widgets/qabstractscrollarea_p.h +++ b/src/gui/widgets/qabstractscrollarea_p.h @@ -60,6 +60,7 @@ QT_BEGIN_NAMESPACE #ifndef QT_NO_SCROLLAREA +class QPanGesture; class QScrollBar; class QAbstractScrollAreaScrollBarContainer; class Q_AUTOTEST_EXPORT QAbstractScrollAreaPrivate: public QFramePrivate @@ -100,10 +101,12 @@ public: { return q_func()->viewportEvent(event); } QObject *viewportFilter; + virtual void _q_gestureTriggered(); + QPanGesture *panGesture; #ifdef Q_WS_WIN bool singleFingerPanEnabled; + void setSingleFingerPanEnabled(bool on = true); #endif - void setupGestures(); }; class QAbstractScrollAreaFilter : public QObject diff --git a/src/gui/widgets/qabstractspinbox.cpp b/src/gui/widgets/qabstractspinbox.cpp index 433406c..7fa26ae 100644 --- a/src/gui/widgets/qabstractspinbox.cpp +++ b/src/gui/widgets/qabstractspinbox.cpp @@ -976,7 +976,7 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event) #endif case Qt::Key_Enter: case Qt::Key_Return: - d->edit->d_func()->modifiedState = d->edit->d_func()->undoState = 0; + d->edit->d_func()->control->clearUndo(); d->interpret(d->keyboardTracking ? AlwaysEmit : EmitIfChanged); selectAll(); event->ignore(); diff --git a/src/gui/widgets/qcocoamenu_mac.mm b/src/gui/widgets/qcocoamenu_mac.mm index 3338fd8..f3bb73e 100644 --- a/src/gui/widgets/qcocoamenu_mac.mm +++ b/src/gui/widgets/qcocoamenu_mac.mm @@ -98,7 +98,9 @@ QT_USE_NAMESPACE while (QWidget *popup = QApplication::activePopupWidget()) popup->close(); - qt_mac_emit_menuSignals(((QT_MANGLE_NAMESPACE(QCocoaMenu) *)menu)->qmenu, true); + QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu; + qt_mac_emit_menuSignals(qtmenu, true); + qt_mac_menu_collapseSeparators(menu, qtmenu->separatorsCollapsible()); } - (void)menuWillClose:(NSMenu*)menu; diff --git a/src/gui/widgets/qdatetimeedit.cpp b/src/gui/widgets/qdatetimeedit.cpp index 5ddf7f7..cb76876 100644 --- a/src/gui/widgets/qdatetimeedit.cpp +++ b/src/gui/widgets/qdatetimeedit.cpp @@ -1086,10 +1086,6 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event) //hide cursor d->edit->d_func()->setCursorVisible(false); - if (d->edit->d_func()->cursorTimer > 0) - killTimer(d->edit->d_func()->cursorTimer); - d->edit->d_func()->cursorTimer = 0; - d->setSelected(0); } } diff --git a/src/gui/widgets/qlinecontrol.cpp b/src/gui/widgets/qlinecontrol.cpp new file mode 100644 index 0000000..f4a2348 --- /dev/null +++ b/src/gui/widgets/qlinecontrol.cpp @@ -0,0 +1,1750 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qlinecontrol_p.h" + +#ifndef QT_NO_LINEEDIT + +#include "qabstractitemview.h" +#include "qclipboard.h" +#ifndef QT_NO_ACCESSIBILITY +#include "qaccessible.h" +#endif +#ifndef QT_NO_IM +#include "qinputcontext.h" +#include "qlist.h" +#endif +#include "qapplication.h" +#ifndef QT_NO_GRAPHICSVIEW +#include "qgraphicssceneevent.h" +#endif + +QT_BEGIN_NAMESPACE + +/*! + \internal + + Updates the display text based of the current edit text + If the text has changed will emit displayTextChanged() +*/ +void QLineControl::updateDisplayText() +{ + QString orig = m_textLayout.text(); + QString str; + if (m_echoMode == QLineEdit::NoEcho) + str = QString::fromLatin1(""); + else + str = m_text; + + if (m_echoMode == QLineEdit::Password || (m_echoMode == QLineEdit::PasswordEchoOnEdit + && !m_passwordEchoEditing)) + str.fill(m_passwordCharacter); + + // replace certain non-printable characters with spaces (to avoid + // drawing boxes when using fonts that don't have glyphs for such + // characters) + QChar* uc = str.data(); + for (int i = 0; i < (int)str.length(); ++i) { + if ((uc[i] < 0x20 && uc[i] != 0x09) + || uc[i] == QChar::LineSeparator + || uc[i] == QChar::ParagraphSeparator + || uc[i] == QChar::ObjectReplacementCharacter) + uc[i] = QChar(0x0020); + } + + m_textLayout.setText(str); + + QTextOption option; + option.setTextDirection(m_layoutDirection); + option.setFlags(QTextOption::IncludeTrailingSpaces); + m_textLayout.setTextOption(option); + + m_textLayout.beginLayout(); + QTextLine l = m_textLayout.createLine(); + m_textLayout.endLayout(); + m_ascent = qRound(l.ascent()); + + if (str != orig) + emit displayTextChanged(str); +} + +#ifndef QT_NO_CLIPBOARD +/*! + \internal + + Copies the currently selected text into the clipboard using the given + \a mode. + + \note If the echo mode is set to a mode other than Normal then copy + will not work. This is to prevent using copy as a method of bypassing + password features of the line control. +*/ +void QLineControl::copy(QClipboard::Mode mode) const +{ + QString t = selectedText(); + if (!t.isEmpty() && m_echoMode == QLineEdit::Normal) { + disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), this, 0); + QApplication::clipboard()->setText(t, mode); + connect(QApplication::clipboard(), SIGNAL(selectionChanged()), + this, SLOT(_q_clipboardChanged())); + } +} + +/*! + \internal + + Inserts the text stored in the application clipboard into the line + control. + + \sa insert() +*/ +void QLineControl::paste() +{ + insert(QApplication::clipboard()->text(QClipboard::Clipboard)); +} + +#endif // !QT_NO_CLIPBOARD + +/*! + \internal + + Handles the behavior for the backspace key or function. + Removes the current selection if there is a selection, otherwise + removes the character prior to the cursor position. + + \sa del() +*/ +void QLineControl::backspace() +{ + int priorState = m_undoState; + if (hasSelectedText()) { + removeSelectedText(); + } else if (m_cursor) { + --m_cursor; + if (m_maskData) + m_cursor = prevMaskBlank(m_cursor); + QChar uc = m_text.at(m_cursor); + if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { + // second half of a surrogate, check if we have the first half as well, + // if yes delete both at once + uc = m_text.at(m_cursor - 1); + if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) { + internalDelete(true); + --m_cursor; + } + } + internalDelete(true); + } + finishChange(priorState); +} + +/*! + \internal + + Handles the behavior for the delete key or function. + Removes the current selection if there is a selection, otherwise + removes the character after the cursor position. + + \sa del() +*/ +void QLineControl::del() +{ + int priorState = m_undoState; + if (hasSelectedText()) { + removeSelectedText(); + } else { + int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor; + while (n--) + internalDelete(); + } + finishChange(priorState); +} + +/*! + \internal + + Inserts the given \a newText at the current cursor position. + If there is any selected text it is removed prior to insertion of + the new text. +*/ +void QLineControl::insert(const QString &newText) +{ + int priorState = m_undoState; + removeSelectedText(); + internalInsert(newText); + finishChange(priorState); +} + +/*! + \internal + + Clears the line control text. +*/ +void QLineControl::clear() +{ + int priorState = m_undoState; + m_selstart = 0; + m_selend = m_text.length(); + removeSelectedText(); + separate(); + finishChange(priorState, /*update*/false, /*edited*/false); +} + +/*! + \internal + + Sets \a length characters from the given \a start position as selected. + The given \a start position must be within the current text for + the line control. If \a length characters cannot be selected, then + the selection will extend to the end of the current text. +*/ +void QLineControl::setSelection(int start, int length) +{ + if(start < 0 || start > (int)m_text.length()){ + qWarning("QLineControl::setSelection: Invalid start position"); + return; + } + + if (length > 0) { + if (start == m_selstart && start + length == m_selend) + return; + m_selstart = start; + m_selend = qMin(start + length, (int)m_text.length()); + m_cursor = m_selend; + } else { + if (start == m_selend && start + length == m_selstart) + return; + m_selstart = qMax(start + length, 0); + m_selend = start; + m_cursor = m_selstart; + } + emit selectionChanged(); + emitCursorPositionChanged(); +} + +void QLineControl::_q_clipboardChanged() +{ +} + +void QLineControl::_q_deleteSelected() +{ + if (!hasSelectedText()) + return; + + int priorState = m_undoState; + emit resetInputContext(); + removeSelectedText(); + separate(); + finishChange(priorState); +} + +/*! + \internal + + Initializes the line control with a starting text value of \a txt. +*/ +void QLineControl::init(const QString &txt) +{ + m_text = txt; + updateDisplayText(); + m_cursor = m_text.length(); +} + +/*! + \internal + + Sets the password echo editing to \a editing. If password echo editing + is true, then the text of the password is displayed even if the echo + mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing + does not affect other echo modes. +*/ +void QLineControl::updatePasswordEchoEditing(bool editing) +{ + m_passwordEchoEditing = editing; + updateDisplayText(); +} + +/*! + \internal + + Returns the cursor position of the given \a x pixel value in relation + to the displayed text. The given \a betweenOrOn specified what kind + of cursor position is requested. +*/ +int QLineControl::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const +{ + return m_textLayout.lineAt(0).xToCursor(x, betweenOrOn); +} + +/*! + \internal + + Returns the bounds of the current cursor, as defined as a + between characters cursor. +*/ +QRect QLineControl::cursorRect() const +{ + QTextLine l = m_textLayout.lineAt(0); + int c = m_cursor; + if (m_preeditCursor != -1) + c += m_preeditCursor; + int cix = qRound(l.cursorToX(c)); + int w = m_cursorWidth; + int ch = l.height() + 1; + + return QRect(cix-5, 0, w+9, ch); +} + +/*! + \internal + + Fixes the current text so that it is valid given any set validators. + + Returns true if the text was changed. Otherwise returns false. +*/ +bool QLineControl::fixup() // this function assumes that validate currently returns != Acceptable +{ +#ifndef QT_NO_VALIDATOR + if (m_validator) { + QString textCopy = m_text; + int cursorCopy = m_cursor; + m_validator->fixup(textCopy); + if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) { + if (textCopy != m_text || cursorCopy != m_cursor) + internalSetText(textCopy, cursorCopy); + return true; + } + } +#endif + return false; +} + +/*! + \internal + + Moves the cursor to the given position \a pos. If \a mark is true will + adjust the currently selected text. +*/ +void QLineControl::moveCursor(int pos, bool mark) +{ + if (pos != m_cursor) { + separate(); + if (m_maskData) + pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos); + } + if (mark) { + int anchor; + if (m_selend > m_selstart && m_cursor == m_selstart) + anchor = m_selend; + else if (m_selend > m_selstart && m_cursor == m_selend) + anchor = m_selstart; + else + anchor = m_cursor; + m_selstart = qMin(anchor, pos); + m_selend = qMax(anchor, pos); + updateDisplayText(); + } else { + internalDeselect(); + } + m_cursor = pos; + if (mark || m_selDirty) { + m_selDirty = false; + emit selectionChanged(); + } + emitCursorPositionChanged(); +} + +/*! + \internal + + Applies the given input method event \a event to the text of the line + control +*/ +void QLineControl::processInputMethodEvent(QInputMethodEvent *event) +{ + int priorState = m_undoState; + removeSelectedText(); + + int c = m_cursor; // cursor position after insertion of commit string + if (event->replacementStart() <= 0) + c += event->commitString().length() + qMin(-event->replacementStart(), event->replacementLength()); + + m_cursor += event->replacementStart(); + + // insert commit string + if (event->replacementLength()) { + m_selstart = m_cursor; + m_selend = m_selstart + event->replacementLength(); + removeSelectedText(); + } + if (!event->commitString().isEmpty()) + insert(event->commitString()); + + m_cursor = qMin(c, m_text.length()); + + setPreeditArea(m_cursor, event->preeditString()); + m_preeditCursor = event->preeditString().length(); + m_hideCursor = false; + QList<QTextLayout::FormatRange> formats; + for (int i = 0; i < event->attributes().size(); ++i) { + const QInputMethodEvent::Attribute &a = event->attributes().at(i); + if (a.type == QInputMethodEvent::Cursor) { + m_preeditCursor = a.start; + m_hideCursor = !a.length; + } else if (a.type == QInputMethodEvent::TextFormat) { + QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat(); + if (f.isValid()) { + QTextLayout::FormatRange o; + o.start = a.start + m_cursor; + o.length = a.length; + o.format = f; + formats.append(o); + } + } + } + m_textLayout.setAdditionalFormats(formats); + updateDisplayText(); + if (!event->commitString().isEmpty()) + emitCursorPositionChanged(); + finishChange(priorState); +} + +/*! + \internal + + Draws the display text for the line control using the given + \a painter, \a clip, and \a offset. Which aspects of the display text + are drawn is specified by the given \a flags. + + If the flags contain DrawSelections, then the selection or input mask + backgrounds and foregrounds will be applied before drawing the text. + + If the flags contain DrawCursor a cursor of the current cursorWidth() + will be drawn after drawing the text. + + The display text will only be drawn if the flags contain DrawText +*/ +void QLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &clip, int flags) +{ + QVector<QTextLayout::FormatRange> selections; + if (flags & DrawSelections) { + QTextLayout::FormatRange o; + if (m_selstart < m_selend) { + o.start = m_selstart; + o.length = m_selend - m_selstart; + o.format.setBackground(m_palette.brush(QPalette::Highlight)); + o.format.setForeground(m_palette.brush(QPalette::HighlightedText)); + } else { + // mask selection + o.start = m_cursor; + o.length = 1; + o.format.setBackground(m_palette.brush(QPalette::Text)); + o.format.setForeground(m_palette.brush(QPalette::Window)); + } + selections.append(o); + } + + if (flags & DrawText) + m_textLayout.draw(painter, offset, selections, clip); + + if (flags & DrawCursor){ + if(!m_blinkPeriod || m_blinkStatus) + m_textLayout.drawCursor(painter, offset, m_cursor, m_cursorWidth); + } +} + +/*! + \internal + + Sets the selection to cover the word at the given cursor position. + The word boundries is defined by the behavior of QTextLayout::SkipWords + cursor mode. +*/ +void QLineControl::selectWordAtPos(int cursor) +{ + int c = m_textLayout.previousCursorPosition(cursor, QTextLayout::SkipWords); + moveCursor(c, false); + // ## text layout should support end of words. + int end = m_textLayout.nextCursorPosition(cursor, QTextLayout::SkipWords); + while (end > cursor && m_text[end-1].isSpace()) + --end; + moveCursor(end, true); +} + +/*! + \internal + + Completes a change to the line control text. If the change is not valid + will undo the line control state back to the given \a validateFromState. + + If \a edited is true and the change is valid, will emit textEdited() in + addition to textChanged(). Otherwise only emits textChanged() on a valid + change. + + The \a update value is currently unused. +*/ +bool QLineControl::finishChange(int validateFromState, bool update, bool edited) +{ + Q_UNUSED(update) + bool lineDirty = m_selDirty; + if (m_textDirty) { + // do validation + bool wasValidInput = m_validInput; + m_validInput = true; +#ifndef QT_NO_VALIDATOR + if (m_validator) { + m_validInput = false; + QString textCopy = m_text; + int cursorCopy = m_cursor; + m_validInput = (m_validator->validate(textCopy, cursorCopy) != QValidator::Invalid); + if (m_validInput) { + if (m_text != textCopy) { + internalSetText(textCopy, cursorCopy); + return true; + } + m_cursor = cursorCopy; + } + } +#endif + if (validateFromState >= 0 && wasValidInput && !m_validInput) { + if (m_transactions.count()) + return false; + internalUndo(validateFromState); + m_history.resize(m_undoState); + if (m_modifiedState > m_undoState) + m_modifiedState = -1; + m_validInput = true; + m_textDirty = false; + } + updateDisplayText(); + lineDirty |= m_textDirty; + if (m_textDirty) { + m_textDirty = false; + QString actualText = text(); + if (edited) + emit textEdited(actualText); + emit textChanged(actualText); + } + } + if (m_selDirty) { + m_selDirty = false; + emit selectionChanged(); + } + emitCursorPositionChanged(); + return true; +} + +/*! + \internal + + An internal function for setting the text of the line control. +*/ +void QLineControl::internalSetText(const QString &txt, int pos, bool edited) +{ + internalDeselect(); + emit resetInputContext(); + QString oldText = m_text; + if (m_maskData) { + m_text = maskString(0, txt, true); + m_text += clearString(m_text.length(), m_maxLength - m_text.length()); + } else { + m_text = txt.isEmpty() ? txt : txt.left(m_maxLength); + } + m_history.clear(); + m_modifiedState = m_undoState = 0; + m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos; + m_textDirty = (oldText != m_text); + finishChange(-1, true, edited); +} + + +/*! + \internal + + Adds the given \a command to the undo history + of the line control. Does not apply the command. +*/ +void QLineControl::addCommand(const Command &cmd) +{ + if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) { + m_history.resize(m_undoState + 2); + m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend); + } else { + m_history.resize(m_undoState + 1); + } + m_separator = false; + m_history[m_undoState++] = cmd; +} + +/*! + \internal + + Inserts the given string \a s into the line + control. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::internalInsert(const QString &s) +{ + if (hasSelectedText()) + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + if (m_maskData) { + QString ms = maskString(m_cursor, s); + for (int i = 0; i < (int) ms.length(); ++i) { + addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1)); + addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1)); + } + m_text.replace(m_cursor, ms.length(), ms); + m_cursor += ms.length(); + m_cursor = nextMaskBlank(m_cursor); + m_textDirty = true; + } else { + int remaining = m_maxLength - m_text.length(); + if (remaining != 0) { + m_text.insert(m_cursor, s.left(remaining)); + for (int i = 0; i < (int) s.left(remaining).length(); ++i) + addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1)); + m_textDirty = true; + } + } +} + +/*! + \internal + + deletes a single character from the current text. If \a wasBackspace, + the character prior to the cursor is removed. Otherwise the character + after the cursor is removed. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::internalDelete(bool wasBackspace) +{ + if (m_cursor < (int) m_text.length()) { + if (hasSelectedText()) + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)), + m_cursor, m_text.at(m_cursor), -1, -1)); + if (m_maskData) { + m_text.replace(m_cursor, 1, clearString(m_cursor, 1)); + addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1)); + } else { + m_text.remove(m_cursor, 1); + } + m_textDirty = true; + } +} + +/*! + \internal + + removes the currently selected text from the line control. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::removeSelectedText() +{ + if (m_selstart < m_selend && m_selend <= (int) m_text.length()) { + separate(); + int i ; + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + if (m_selstart <= m_cursor && m_cursor < m_selend) { + // cursor is within the selection. Split up the commands + // to be able to restore the correct cursor position + for (i = m_cursor; i >= m_selstart; --i) + addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1)); + for (i = m_selend - 1; i > m_cursor; --i) + addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1)); + } else { + for (i = m_selend-1; i >= m_selstart; --i) + addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1)); + } + if (m_maskData) { + m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart)); + for (int i = 0; i < m_selend - m_selstart; ++i) + addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1)); + } else { + m_text.remove(m_selstart, m_selend - m_selstart); + } + if (m_cursor > m_selstart) + m_cursor -= qMin(m_cursor, m_selend) - m_selstart; + internalDeselect(); + m_textDirty = true; + } +} + +/*! + \internal + + Parses the input mask specified by \a maskFields to generate + the mask data used to handle input masks. +*/ +void QLineControl::parseInputMask(const QString &maskFields) +{ + int delimiter = maskFields.indexOf(QLatin1Char(';')); + if (maskFields.isEmpty() || delimiter == 0) { + if (m_maskData) { + delete [] m_maskData; + m_maskData = 0; + m_maxLength = 32767; + internalSetText(QString()); + } + return; + } + + if (delimiter == -1) { + m_blank = QLatin1Char(' '); + m_inputMask = maskFields; + } else { + m_inputMask = maskFields.left(delimiter); + m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' '); + } + + // calculate m_maxLength / m_maskData length + m_maxLength = 0; + QChar c = 0; + for (int i=0; i<m_inputMask.length(); i++) { + c = m_inputMask.at(i); + if (i > 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) { + m_maxLength++; + continue; + } + if (c != QLatin1Char('\\') && c != QLatin1Char('!') && + c != QLatin1Char('<') && c != QLatin1Char('>') && + c != QLatin1Char('{') && c != QLatin1Char('}') && + c != QLatin1Char('[') && c != QLatin1Char(']')) + m_maxLength++; + } + + delete [] m_maskData; + m_maskData = new MaskInputData[m_maxLength]; + + MaskInputData::Casemode m = MaskInputData::NoCaseMode; + c = 0; + bool s; + bool escape = false; + int index = 0; + for (int i = 0; i < m_inputMask.length(); i++) { + c = m_inputMask.at(i); + if (escape) { + s = true; + m_maskData[index].maskChar = c; + m_maskData[index].separator = s; + m_maskData[index].caseMode = m; + index++; + escape = false; + } else if (c == QLatin1Char('<')) { + m = MaskInputData::Lower; + } else if (c == QLatin1Char('>')) { + m = MaskInputData::Upper; + } else if (c == QLatin1Char('!')) { + m = MaskInputData::NoCaseMode; + } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) { + switch (c.unicode()) { + case 'A': + case 'a': + case 'N': + case 'n': + case 'X': + case 'x': + case '9': + case '0': + case 'D': + case 'd': + case '#': + case 'H': + case 'h': + case 'B': + case 'b': + s = false; + break; + case '\\': + escape = true; + default: + s = true; + break; + } + + if (!escape) { + m_maskData[index].maskChar = c; + m_maskData[index].separator = s; + m_maskData[index].caseMode = m; + index++; + } + } + } + internalSetText(m_text); +} + + +/*! + \internal + + checks if the key is valid compared to the inputMask +*/ +bool QLineControl::isValidInput(QChar key, QChar mask) const +{ + switch (mask.unicode()) { + case 'A': + if (key.isLetter()) + return true; + break; + case 'a': + if (key.isLetter() || key == m_blank) + return true; + break; + case 'N': + if (key.isLetterOrNumber()) + return true; + break; + case 'n': + if (key.isLetterOrNumber() || key == m_blank) + return true; + break; + case 'X': + if (key.isPrint()) + return true; + break; + case 'x': + if (key.isPrint() || key == m_blank) + return true; + break; + case '9': + if (key.isNumber()) + return true; + break; + case '0': + if (key.isNumber() || key == m_blank) + return true; + break; + case 'D': + if (key.isNumber() && key.digitValue() > 0) + return true; + break; + case 'd': + if ((key.isNumber() && key.digitValue() > 0) || key == m_blank) + return true; + break; + case '#': + if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank) + return true; + break; + case 'B': + if (key == QLatin1Char('0') || key == QLatin1Char('1')) + return true; + break; + case 'b': + if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank) + return true; + break; + case 'H': + if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F'))) + return true; + break; + case 'h': + if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank) + return true; + break; + default: + break; + } + return false; +} + +/*! + \internal + + Returns true if the given text \a str is valid for any + validator or input mask set for the line control. + + Otherwise returns false +*/ +bool QLineControl::hasAcceptableInput(const QString &str) const +{ +#ifndef QT_NO_VALIDATOR + QString textCopy = str; + int cursorCopy = m_cursor; + if (m_validator && m_validator->validate(textCopy, cursorCopy) + != QValidator::Acceptable) + return false; +#endif + + if (!m_maskData) + return true; + + if (str.length() != m_maxLength) + return false; + + for (int i=0; i < m_maxLength; ++i) { + if (m_maskData[i].separator) { + if (str.at(i) != m_maskData[i].maskChar) + return false; + } else { + if (!isValidInput(str.at(i), m_maskData[i].maskChar)) + return false; + } + } + return true; +} + +/*! + \internal + + Applies the inputMask on \a str starting from position \a pos in the mask. \a clear + specifies from where characters should be gotten when a separator is met in \a str - true means + that blanks will be used, false that previous input is used. + Calling this when no inputMask is set is undefined. +*/ +QString QLineControl::maskString(uint pos, const QString &str, bool clear) const +{ + if (pos >= (uint)m_maxLength) + return QString::fromLatin1(""); + + QString fill; + fill = clear ? clearString(0, m_maxLength) : m_text; + + int strIndex = 0; + QString s = QString::fromLatin1(""); + int i = pos; + while (i < m_maxLength) { + if (strIndex < str.length()) { + if (m_maskData[i].separator) { + s += m_maskData[i].maskChar; + if (str[(int)strIndex] == m_maskData[i].maskChar) + strIndex++; + ++i; + } else { + if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) { + switch (m_maskData[i].caseMode) { + case MaskInputData::Upper: + s += str[(int)strIndex].toUpper(); + break; + case MaskInputData::Lower: + s += str[(int)strIndex].toLower(); + break; + default: + s += str[(int)strIndex]; + } + ++i; + } else { + // search for separator first + int n = findInMask(i, true, true, str[(int)strIndex]); + if (n != -1) { + if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) { + s += fill.mid(i, n-i+1); + i = n + 1; // update i to find + 1 + } + } else { + // search for valid m_blank if not + n = findInMask(i, true, false, str[(int)strIndex]); + if (n != -1) { + s += fill.mid(i, n-i); + switch (m_maskData[n].caseMode) { + case MaskInputData::Upper: + s += str[(int)strIndex].toUpper(); + break; + case MaskInputData::Lower: + s += str[(int)strIndex].toLower(); + break; + default: + s += str[(int)strIndex]; + } + i = n + 1; // updates i to find + 1 + } + } + } + ++strIndex; + } + } else + break; + } + + return s; +} + + + +/*! + \internal + + Returns a "cleared" string with only separators and blank chars. + Calling this when no inputMask is set is undefined. +*/ +QString QLineControl::clearString(uint pos, uint len) const +{ + if (pos >= (uint)m_maxLength) + return QString(); + + QString s; + int end = qMin((uint)m_maxLength, pos + len); + for (int i = pos; i < end; ++i) + if (m_maskData[i].separator) + s += m_maskData[i].maskChar; + else + s += m_blank; + + return s; +} + +/*! + \internal + + Strips blank parts of the input in a QLineControl when an inputMask is set, + separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1". +*/ +QString QLineControl::stripString(const QString &str) const +{ + if (!m_maskData) + return str; + + QString s; + int end = qMin(m_maxLength, (int)str.length()); + for (int i = 0; i < end; ++i) + if (m_maskData[i].separator) + s += m_maskData[i].maskChar; + else + if (str[i] != m_blank) + s += str[i]; + + return s; +} + +/*! + \internal + searches forward/backward in m_maskData for either a separator or a m_blank +*/ +int QLineControl::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const +{ + if (pos >= m_maxLength || pos < 0) + return -1; + + int end = forward ? m_maxLength : -1; + int step = forward ? 1 : -1; + int i = pos; + + while (i != end) { + if (findSeparator) { + if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar) + return i; + } else { + if (!m_maskData[i].separator) { + if (searchChar.isNull()) + return i; + else if (isValidInput(searchChar, m_maskData[i].maskChar)) + return i; + } + } + i += step; + } + return -1; +} + +void QLineControl::internalUndo(int until) +{ + if (!isUndoAvailable()) + return; + internalDeselect(); + while (m_undoState && m_undoState > until) { + Command& cmd = m_history[--m_undoState]; + switch (cmd.type) { + case Insert: + m_text.remove(cmd.pos, 1); + m_cursor = cmd.pos; + break; + case SetSelection: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Remove: + case RemoveSelection: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos + 1; + break; + case Delete: + case DeleteSelection: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos; + break; + case Separator: + continue; + } + if (until < 0 && m_undoState) { + Command& next = m_history[m_undoState-1]; + if (next.type != cmd.type && next.type < RemoveSelection + && (cmd.type < RemoveSelection || next.type == Separator)) + break; + } + } + m_textDirty = true; + emitCursorPositionChanged(); +} + +void QLineControl::internalRedo() +{ + if (!isRedoAvailable()) + return; + internalDeselect(); + while (m_undoState < (int)m_history.size()) { + Command& cmd = m_history[m_undoState++]; + switch (cmd.type) { + case Insert: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos + 1; + break; + case SetSelection: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Remove: + case Delete: + case RemoveSelection: + case DeleteSelection: + m_text.remove(cmd.pos, 1); + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Separator: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + } + if (m_undoState < (int)m_history.size()) { + Command& next = m_history[m_undoState]; + if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator + && (next.type < RemoveSelection || cmd.type == Separator)) + break; + } + } + m_textDirty = true; + emitCursorPositionChanged(); +} + +/*! + \internal + + If the current cursor position differs from the last emited cursor + position, emits cursorPositionChanged(). +*/ +void QLineControl::emitCursorPositionChanged() +{ + if (m_cursor != m_lastCursorPos) { + const int oldLast = m_lastCursorPos; + m_lastCursorPos = m_cursor; + cursorPositionChanged(oldLast, m_cursor); + } +} + +#ifndef QT_NO_COMPLETER +// iterating forward(dir=1)/backward(dir=-1) from the +// current row based. dir=0 indicates a new completion prefix was set. +bool QLineControl::advanceToEnabledItem(int dir) +{ + int start = m_completer->currentRow(); + if (start == -1) + return false; + int i = start + dir; + if (dir == 0) dir = 1; + do { + if (!m_completer->setCurrentRow(i)) { + if (!m_completer->wrapAround()) + break; + i = i > 0 ? 0 : m_completer->completionCount() - 1; + } else { + QModelIndex currentIndex = m_completer->currentIndex(); + if (m_completer->completionModel()->flags(currentIndex) & Qt::ItemIsEnabled) + return true; + i += dir; + } + } while (i != start); + + m_completer->setCurrentRow(start); // restore + return false; +} + +void QLineControl::complete(int key) +{ + if (!m_completer || isReadOnly() || echoMode() != QLineEdit::Normal) + return; + + QString text = this->text(); + if (m_completer->completionMode() == QCompleter::InlineCompletion) { + if (key == Qt::Key_Backspace) + return; + int n = 0; + if (key == Qt::Key_Up || key == Qt::Key_Down) { + if (textAfterSelection().length()) + return; + QString prefix = hasSelectedText() ? textBeforeSelection() + : text; + if (text.compare(m_completer->currentCompletion(), m_completer->caseSensitivity()) != 0 + || prefix.compare(m_completer->completionPrefix(), m_completer->caseSensitivity()) != 0) { + m_completer->setCompletionPrefix(prefix); + } else { + n = (key == Qt::Key_Up) ? -1 : +1; + } + } else { + m_completer->setCompletionPrefix(text); + } + if (!advanceToEnabledItem(n)) + return; + } else { +#ifndef QT_KEYPAD_NAVIGATION + if (text.isEmpty()) { + m_completer->popup()->hide(); + return; + } +#endif + m_completer->setCompletionPrefix(text); + } + + m_completer->complete(); +} +#endif + +void QLineControl::setCursorBlinkPeriod(int msec) +{ + if (msec == m_blinkPeriod) + return; + if (m_blinkTimer) { + killTimer(m_blinkTimer); + } + if (msec) { + m_blinkTimer = startTimer(msec / 2); + m_blinkStatus = 1; + } else { + m_blinkTimer = 0; + if (m_blinkStatus == 0) + emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); + } + m_blinkPeriod = msec; +} + +void QLineControl::timerEvent(QTimerEvent *event) +{ + if (event->timerId() == m_blinkTimer) { + m_blinkStatus = !m_blinkStatus; + emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); + } else if (event->timerId() == m_deleteAllTimer) { + killTimer(m_deleteAllTimer); + m_deleteAllTimer = 0; + clear(); + } else if (event->timerId() == m_tripleClickTimer) { + killTimer(m_tripleClickTimer); + m_tripleClickTimer = 0; + } +} + +bool QLineControl::processEvent(QEvent* ev) +{ +#ifdef QT_KEYPAD_NAVIGATION + if (QApplication::keypadNavigationEnabled()) { + if ((ev->type() == QEvent::KeyPress) || (ev->type() == QEvent::KeyRelease)) { + QKeyEvent *ke = (QKeyEvent *)ev; + if (ke->key() == Qt::Key_Back) { + if (ke->isAutoRepeat()) { + // Swallow it. We don't want back keys running amok. + ke->accept(); + return true; + } + if ((ev->type() == QEvent::KeyRelease) + && !isReadOnly() + && m_deleteAllTimer) { + killTimer(m_deleteAllTimer); + m_deleteAllTimer = 0; + backspace(); + ke->accept(); + return true; + } + } + } + } +#endif + switch(ev->type()){ +#ifndef QT_NO_GRAPHICSVIEW + case QEvent::GraphicsSceneMouseMove: + case QEvent::GraphicsSceneMouseRelease: + case QEvent::GraphicsSceneMousePress:{ + QGraphicsSceneMouseEvent *gvEv = static_cast<QGraphicsSceneMouseEvent*>(ev); + QMouseEvent* mouse = new QMouseEvent(ev->type(), + gvEv->pos().toPoint(), gvEv->button(), gvEv->buttons(), gvEv->modifiers()); + processMouseEvent(mouse); break; + } +#endif + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::MouseMove: + processMouseEvent(static_cast<QMouseEvent*>(ev)); break; + case QEvent::KeyPress: + case QEvent::KeyRelease: + processKeyEvent(static_cast<QKeyEvent*>(ev)); break; + case QEvent::InputMethod: + processInputMethodEvent(static_cast<QInputMethodEvent*>(ev)); break; +#ifndef QT_NO_SHORTCUT + case QEvent::ShortcutOverride:{ + QKeyEvent* ke = static_cast<QKeyEvent*>(ev); + if (ke == QKeySequence::Copy + || ke == QKeySequence::Paste + || ke == QKeySequence::Cut + || ke == QKeySequence::Redo + || ke == QKeySequence::Undo + || ke == QKeySequence::MoveToNextWord + || ke == QKeySequence::MoveToPreviousWord + || ke == QKeySequence::MoveToStartOfDocument + || ke == QKeySequence::MoveToEndOfDocument + || ke == QKeySequence::SelectNextWord + || ke == QKeySequence::SelectPreviousWord + || ke == QKeySequence::SelectStartOfLine + || ke == QKeySequence::SelectEndOfLine + || ke == QKeySequence::SelectStartOfBlock + || ke == QKeySequence::SelectEndOfBlock + || ke == QKeySequence::SelectStartOfDocument + || ke == QKeySequence::SelectAll + || ke == QKeySequence::SelectEndOfDocument) { + ke->accept(); + } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier + || ke->modifiers() == Qt::KeypadModifier) { + if (ke->key() < Qt::Key_Escape) { + ke->accept(); + } else { + switch (ke->key()) { + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + ke->accept(); + default: + break; + } + } + } + } +#endif + default: + return false; + } + return true; +} + +void QLineControl::processMouseEvent(QMouseEvent* ev) +{ + + switch (ev->type()) { + case QEvent::GraphicsSceneMousePress: + case QEvent::MouseButtonPress:{ + if (m_tripleClickTimer + && (ev->pos() - m_tripleClick).manhattanLength() + < QApplication::startDragDistance()) { + selectAll(); + return; + } + if (ev->button() == Qt::RightButton) + return; + + bool mark = ev->modifiers() & Qt::ShiftModifier; + int cursor = xToPos(ev->pos().x()); + moveCursor(cursor, mark); + break; + } + case QEvent::MouseButtonDblClick: + if (ev->button() == Qt::LeftButton) { + selectWordAtPos(xToPos(ev->pos().x())); + if (m_tripleClickTimer) + killTimer(m_tripleClickTimer); + m_tripleClickTimer = startTimer(QApplication::doubleClickInterval()); + m_tripleClick = ev->pos(); + } + break; + case QEvent::GraphicsSceneMouseRelease: + case QEvent::MouseButtonRelease: +#ifndef QT_NO_CLIPBOARD + if (QApplication::clipboard()->supportsSelection()) { + if (ev->button() == Qt::LeftButton) { + copy(QClipboard::Selection); + } else if (!isReadOnly() && ev->button() == Qt::MidButton) { + deselect(); + insert(QApplication::clipboard()->text(QClipboard::Selection)); + } + } +#endif + break; + case QEvent::GraphicsSceneMouseMove: + case QEvent::MouseMove: + if (ev->buttons() & Qt::LeftButton) { + moveCursor(xToPos(ev->pos().x()), true); + } + break; + default: + break; + } +} + +void QLineControl::processKeyEvent(QKeyEvent* event) +{ + bool inlineCompletionAccepted = false; + +#ifndef QT_NO_COMPLETER + if (m_completer) { + QCompleter::CompletionMode completionMode = m_completer->completionMode(); + if ((completionMode == QCompleter::PopupCompletion + || completionMode == QCompleter::UnfilteredPopupCompletion) + && m_completer->popup() + && m_completer->popup()->isVisible()) { + // The following keys are forwarded by the completer to the widget + // Ignoring the events lets the completer provide suitable default behavior + switch (event->key()) { + case Qt::Key_Escape: + event->ignore(); + return; + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_F4: +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Select: + if (!QApplication::keypadNavigationEnabled()) + break; +#endif + m_completer->popup()->hide(); // just hide. will end up propagating to parent + default: + break; // normal key processing + } + } else if (completionMode == QCompleter::InlineCompletion) { + switch (event->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_F4: +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Select: + if (!QApplication::keypadNavigationEnabled()) + break; +#endif + if (!m_completer->currentCompletion().isEmpty() && hasSelectedText() + && textAfterSelection().isEmpty()) { + setText(m_completer->currentCompletion()); + inlineCompletionAccepted = true; + } + default: + break; // normal key processing + } + } + } +#endif // QT_NO_COMPLETER + + if (echoMode() == QLineEdit::PasswordEchoOnEdit + && !passwordEchoEditing() + && !isReadOnly() + && !event->text().isEmpty() +#ifdef QT_KEYPAD_NAVIGATION + && event->key() != Qt::Key_Select + && event->key() != Qt::Key_Up + && event->key() != Qt::Key_Down + && event->key() != Qt::Key_Back +#endif + && !(event->modifiers() & Qt::ControlModifier)) { + // Clear the edit and reset to normal echo mode while editing; the + // echo mode switches back when the edit loses focus + // ### resets current content. dubious code; you can + // navigate with keys up, down, back, and select(?), but if you press + // "left" or "right" it clears? + updatePasswordEchoEditing(true); + clear(); + } + + if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { + if (hasAcceptableInput() || fixup()) { + emit accepted(); + emit editingFinished(); + } + if (inlineCompletionAccepted) + event->accept(); + else + event->ignore(); + return; + } + bool unknown = false; + + if (false) { + } +#ifndef QT_NO_SHORTCUT + else if (event == QKeySequence::Undo) { + if (!isReadOnly()) + undo(); + } + else if (event == QKeySequence::Redo) { + if (!isReadOnly()) + redo(); + } + else if (event == QKeySequence::SelectAll) { + selectAll(); + } +#ifndef QT_NO_CLIPBOARD + else if (event == QKeySequence::Copy) { + copy(); + } + else if (event == QKeySequence::Paste) { + if (!isReadOnly()) + paste(); + } + else if (event == QKeySequence::Cut) { + if (!isReadOnly()) { + copy(); + del(); + } + } + else if (event == QKeySequence::DeleteEndOfLine) { + if (!isReadOnly()) { + setSelection(cursor(), end()); + copy(); + del(); + } + } +#endif //QT_NO_CLIPBOARD + else if (event == QKeySequence::MoveToStartOfLine) { + home(0); + } + else if (event == QKeySequence::MoveToEndOfLine) { + end(0); + } + else if (event == QKeySequence::SelectStartOfLine) { + home(1); + } + else if (event == QKeySequence::SelectEndOfLine) { + end(1); + } + else if (event == QKeySequence::MoveToNextChar) { +#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) + if (hasSelectedText()) { +#else + if (hasSelectedText() && m_completer + && m_completer->completionMode() == QCompleter::InlineCompletion) { +#endif + moveCursor(selectionEnd(), false); + } else { + cursorForward(0, layoutDirection() == Qt::LeftToRight ? 1 : -1); + } + } + else if (event == QKeySequence::SelectNextChar) { + cursorForward(1, layoutDirection() == Qt::LeftToRight ? 1 : -1); + } + else if (event == QKeySequence::MoveToPreviousChar) { +#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) + if (hasSelectedText()) { +#else + if (hasSelectedText() && m_completer + && m_completer->completionMode() == QCompleter::InlineCompletion) { +#endif + moveCursor(selectionStart(), false); + } else { + cursorForward(0, layoutDirection() == Qt::LeftToRight ? -1 : 1); + } + } + else if (event == QKeySequence::SelectPreviousChar) { + cursorForward(1, layoutDirection() == Qt::LeftToRight ? -1 : 1); + } + else if (event == QKeySequence::MoveToNextWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0); + else + layoutDirection() == Qt::LeftToRight ? end(0) : home(0); + } + else if (event == QKeySequence::MoveToPreviousWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0); + else if (!isReadOnly()) { + layoutDirection() == Qt::LeftToRight ? home(0) : end(0); + } + } + else if (event == QKeySequence::SelectNextWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1); + else + layoutDirection() == Qt::LeftToRight ? end(1) : home(1); + } + else if (event == QKeySequence::SelectPreviousWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1); + else + layoutDirection() == Qt::LeftToRight ? home(1) : end(1); + } + else if (event == QKeySequence::Delete) { + if (!isReadOnly()) + del(); + } + else if (event == QKeySequence::DeleteEndOfWord) { + if (!isReadOnly()) { + cursorWordForward(true); + del(); + } + } + else if (event == QKeySequence::DeleteStartOfWord) { + if (!isReadOnly()) { + cursorWordBackward(true); + del(); + } + } +#endif // QT_NO_SHORTCUT + else { +#ifdef Q_WS_MAC + if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { + Qt::KeyboardModifiers myModifiers = (event->modifiers() & ~Qt::KeypadModifier); + if (myModifiers & Qt::ShiftModifier) { + if (myModifiers == (Qt::ControlModifier|Qt::ShiftModifier) + || myModifiers == (Qt::AltModifier|Qt::ShiftModifier) + || myModifiers == Qt::ShiftModifier) { + + event->key() == Qt::Key_Up ? home(1) : end(1); + } + } else { + if ((myModifiers == Qt::ControlModifier + || myModifiers == Qt::AltModifier + || myModifiers == Qt::NoModifier)) { + event->key() == Qt::Key_Up ? home(0) : end(0); + } + } + } +#endif + if (event->modifiers() & Qt::ControlModifier) { + switch (event->key()) { + case Qt::Key_Backspace: + if (!isReadOnly()) { + cursorWordBackward(true); + del(); + } + break; +#ifndef QT_NO_COMPLETER + case Qt::Key_Up: + case Qt::Key_Down: + complete(event->key()); + break; +#endif +#if defined(Q_WS_X11) + case Qt::Key_E: + end(0); + break; + + case Qt::Key_U: + if (!isReadOnly()) { + setSelection(0, text().size()); +#ifndef QT_NO_CLIPBOARD + copy(); +#endif + del(); + } + break; +#endif + default: + unknown = true; + } + } else { // ### check for *no* modifier + switch (event->key()) { + case Qt::Key_Backspace: + if (!isReadOnly()) { + backspace(); +#ifndef QT_NO_COMPLETER + complete(Qt::Key_Backspace); +#endif + } + break; +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Back: + if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat() + && !isReadOnly()) { + if (text().length() == 0) { + setText(m_cancelText); + + if (passwordEchoEditing()) + updatePasswordEchoEditing(false); + + emit editFocusChange(false); + } else if (!m_deleteAllTimer) { + m_deleteAllTimer = startTimer(750); + } + } else { + unknown = true; + } + break; +#endif + + default: + unknown = true; + } + } + } + + if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) { + setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft); + unknown = false; + } + + if (unknown && !isReadOnly()) { + QString t = event->text(); + if (!t.isEmpty() && t.at(0).isPrint()) { + insert(t); +#ifndef QT_NO_COMPLETER + complete(event->key()); +#endif + event->accept(); + return; + } + } + + if (unknown) + event->ignore(); + else + event->accept(); +} + + +QT_END_NAMESPACE + +#endif diff --git a/src/gui/widgets/qlinecontrol_p.h b/src/gui/widgets/qlinecontrol_p.h new file mode 100644 index 0000000..ad4e4e4 --- /dev/null +++ b/src/gui/widgets/qlinecontrol_p.h @@ -0,0 +1,744 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QLINECONTROL_P_H +#define QLINECONTROL_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "QtCore/qglobal.h" + +#ifndef QT_NO_LINEEDIT +#include "private/qwidget_p.h" +#include "QtGui/qlineedit.h" +#include "QtGui/qtextlayout.h" +#include "QtGui/qstyleoption.h" +#include "QtCore/qpointer.h" +#include "QtGui/qlineedit.h" +#include "QtGui/qclipboard.h" +#include "QtCore/qpoint.h" +#include "QtGui/qcompleter.h" + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class Q_GUI_EXPORT QLineControl : public QObject +{ + Q_OBJECT + +public: + QLineControl(const QString &txt = QString()) + : m_cursor(0), m_preeditCursor(0), m_layoutDirection(Qt::LeftToRight), + m_hideCursor(false), m_separator(0), m_readOnly(0), + m_dragEnabled(0), m_echoMode(0), m_textDirty(0), m_selDirty(0), + m_validInput(1), m_blinkPeriod(0), m_blinkTimer(0), m_deleteAllTimer(0), + m_ascent(0), m_maxLength(32767), m_lastCursorPos(-1), + m_tripleClickTimer(0), m_maskData(0), m_modifiedState(0), m_undoState(0), + m_selstart(0), m_selend(0), m_passwordEchoEditing(false) + { + init(txt); + } + + ~QLineControl() + { + delete [] m_maskData; + } + + int nextMaskBlank(int pos); + int prevMaskBlank(int pos); + + bool isUndoAvailable() const; + bool isRedoAvailable() const; + void clearUndo(); + bool isModified() const; + void setModified(bool modified); + + bool allSelected() const; + bool hasSelectedText() const; + + int width() const; + int height() const; + int ascent() const; + + void setSelection(int start, int length); + + QString selectedText() const; + QString textBeforeSelection() const; + QString textAfterSelection() const; + + int selectionStart() const; + int selectionEnd() const; + bool inSelection(int x) const; + + void removeSelection(); + + int start() const; + int end() const; + +#ifndef QT_NO_CLIPBOARD + void copy(QClipboard::Mode mode = QClipboard::Clipboard) const; + void paste(); +#endif + + int cursor() const; + int preeditCursor() const; + + int cursorWidth() const; + void setCursorWidth(int value); + + void moveCursor(int pos, bool mark = false); + void cursorForward(bool mark, int steps); + void cursorWordForward(bool mark); + void cursorWordBackward(bool mark); + void home(bool mark); + void end(bool mark); + + int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; + QRect cursorRect() const; + + qreal cursorToX(int cursor) const; + qreal cursorToX() const; + + bool isReadOnly() const; + void setReadOnly(bool enable); + + QString text() const; + void setText(const QString &txt); + + QString displayText() const; + + void backspace(); + void del(); + void deselect(); + void selectAll(); + void insert(const QString &); + void clear(); + void undo(); + void redo(); + void selectWordAtPos(int); + + uint echoMode() const; + void setEchoMode(uint mode); + + void setMaxLength(int maxLength); + int maxLength() const; + + const QValidator *validator() const; + void setValidator(const QValidator *); + +#ifndef QT_NO_COMPLETER + QCompleter *completer() const; + void setCompleter(const QCompleter*); + void complete(int key); +#endif + + void setCursorPosition(int pos); + int cursorPosition() const; + + bool hasAcceptableInput() const; + bool fixup(); + + QString inputMask() const; + void setInputMask(const QString &mask); + + // input methods +#ifndef QT_NO_IM + bool composeMode() const; + void setPreeditArea(int cursor, const QString &text); +#endif + + QString preeditAreaText() const; + + void updatePasswordEchoEditing(bool editing); + bool passwordEchoEditing() const; + + QChar passwordCharacter() const; + void setPasswordCharacter(const QChar &character); + + Qt::LayoutDirection layoutDirection() const; + void setLayoutDirection(Qt::LayoutDirection direction); + void setFont(const QFont &font); + + void processInputMethodEvent(QInputMethodEvent *event); + void processMouseEvent(QMouseEvent* ev); + void processKeyEvent(QKeyEvent* ev); + + int cursorBlinkPeriod() const; + void setCursorBlinkPeriod(int msec); + + QString cancelText() const; + void setCancelText(const QString &text); + + enum DrawFlags { + DrawText = 0x01, + DrawSelections = 0x02, + DrawCursor = 0x04, + DrawAll = DrawText | DrawSelections | DrawCursor + }; + void draw(QPainter *, const QPoint &, const QRect &, int flags = DrawAll); + + bool processEvent(QEvent *ev); + +private: + void init(const QString &txt); + void removeSelectedText(); + void internalSetText(const QString &txt, int pos = -1, bool edited = true); + void updateDisplayText(); + + void internalInsert(const QString &s); + void internalDelete(bool wasBackspace = false); + void internalRemove(int pos); + + inline void internalDeselect() + { + m_selDirty |= (m_selend > m_selstart); + m_selstart = m_selend = 0; + } + + void internalUndo(int until = -1); + void internalRedo(); + + QString m_text; + QPalette m_palette; + int m_cursor; + int m_preeditCursor; + int m_cursorWidth; + Qt::LayoutDirection m_layoutDirection; + uint m_hideCursor : 1; // used to hide the m_cursor inside preedit areas + uint m_separator : 1; + uint m_readOnly : 1; + uint m_dragEnabled : 1; + uint m_echoMode : 2; + uint m_textDirty : 1; + uint m_selDirty : 1; + uint m_validInput : 1; + int m_blinkPeriod; // 0 for non-blinking cursor + int m_blinkTimer; + int m_deleteAllTimer; + int m_blinkStatus; + int m_ascent; + int m_maxLength; + int m_lastCursorPos; + QList<int> m_transactions; + QPoint m_tripleClick; + int m_tripleClickTimer; + QString m_cancelText; + + void emitCursorPositionChanged(); + + bool finishChange(int validateFromState = -1, bool update = false, bool edited = true); + + QPointer<QValidator> m_validator; + QPointer<QCompleter> m_completer; +#ifndef QT_NO_COMPLETER + bool advanceToEnabledItem(int dir); +#endif + + struct MaskInputData { + enum Casemode { NoCaseMode, Upper, Lower }; + QChar maskChar; // either the separator char or the inputmask + bool separator; + Casemode caseMode; + }; + QString m_inputMask; + QChar m_blank; + MaskInputData *m_maskData; + + // undo/redo handling + enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection }; + struct Command { + inline Command() {} + inline Command(CommandType t, int p, QChar c, int ss, int se) : type(t),uc(c),pos(p),selStart(ss),selEnd(se) {} + uint type : 4; + QChar uc; + int pos, selStart, selEnd; + }; + int m_modifiedState; + int m_undoState; + QVector<Command> m_history; + void addCommand(const Command& cmd); + + inline void separate() { m_separator = true; } + + // selection + int m_selstart; + int m_selend; + + // masking + void parseInputMask(const QString &maskFields); + bool isValidInput(QChar key, QChar mask) const; + bool hasAcceptableInput(const QString &text) const; + QString maskString(uint pos, const QString &str, bool clear = false) const; + QString clearString(uint pos, uint len) const; + QString stripString(const QString &str) const; + int findInMask(int pos, bool forward, bool findSeparator, QChar searchChar = QChar()) const; + + // complex text layout + QTextLayout m_textLayout; + + bool m_passwordEchoEditing; + QChar m_passwordCharacter; + +Q_SIGNALS: + void cursorPositionChanged(int, int); + void selectionChanged(); + + void displayTextChanged(const QString &); + void textChanged(const QString &); + void textEdited(const QString &); + + void resetInputContext(); + + void accepted(); + void editingFinished(); + void updateNeeded(const QRect &); + +#ifdef QT_KEYPAD_NAVIGATION + void editFocusChange(bool); +#endif +protected: + virtual void timerEvent(QTimerEvent *event); + +private slots: + void _q_clipboardChanged(); + void _q_deleteSelected(); + +}; + +inline int QLineControl::nextMaskBlank(int pos) +{ + int c = findInMask(pos, true, false); + m_separator |= (c != pos); + return (c != -1 ? c : m_maxLength); +} + +inline int QLineControl::prevMaskBlank(int pos) +{ + int c = findInMask(pos, false, false); + m_separator |= (c != pos); + return (c != -1 ? c : 0); +} + +inline bool QLineControl::isUndoAvailable() const +{ + return !m_readOnly && m_undoState; +} + +inline bool QLineControl::isRedoAvailable() const +{ + return !m_readOnly && m_undoState < (int)m_history.size(); +} + +inline void QLineControl::clearUndo() +{ + m_history.clear(); + m_modifiedState = m_undoState = 0; +} + +inline bool QLineControl::isModified() const +{ + return m_modifiedState != m_undoState; +} + +inline void QLineControl::setModified(bool modified) +{ + m_modifiedState = modified ? -1 : m_undoState; +} + +inline bool QLineControl::allSelected() const +{ + return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); +} + +inline bool QLineControl::hasSelectedText() const +{ + return !m_text.isEmpty() && m_selend > m_selstart; +} + +inline int QLineControl::width() const +{ + return qRound(m_textLayout.lineAt(0).width()) + 1; +} + +inline int QLineControl::height() const +{ + return qRound(m_textLayout.lineAt(0).height()) + 1; +} + +inline int QLineControl::ascent() const +{ + return m_ascent; +} + +inline QString QLineControl::selectedText() const +{ + if (hasSelectedText()) + return m_text.mid(m_selstart, m_selend - m_selstart); + return QString(); +} + +inline QString QLineControl::textBeforeSelection() const +{ + if (hasSelectedText()) + return m_text.left(m_selstart); + return QString(); +} + +inline QString QLineControl::textAfterSelection() const +{ + if (hasSelectedText()) + return m_text.mid(m_selend); + return QString(); +} + +inline int QLineControl::selectionStart() const +{ + return hasSelectedText() ? m_selstart : -1; +} + +inline int QLineControl::selectionEnd() const +{ + return hasSelectedText() ? m_selend : -1; +} + +inline int QLineControl::start() const +{ + return 0; +} + +inline int QLineControl::end() const +{ + return m_text.length(); +} + +inline void QLineControl::removeSelection() +{ + int priorState = m_undoState; + removeSelectedText(); + finishChange(priorState); +} + +inline bool QLineControl::inSelection(int x) const +{ + if (m_selstart >= m_selend) + return false; + int pos = xToPos(x, QTextLine::CursorOnCharacter); + return pos >= m_selstart && pos < m_selend; +} + +inline int QLineControl::cursor() const +{ + return m_cursor; +} + +inline int QLineControl::preeditCursor() const +{ + return m_preeditCursor; +} + +inline int QLineControl::cursorWidth() const +{ + return m_cursorWidth; +} + +inline void QLineControl::setCursorWidth(int value) +{ + m_cursorWidth = value; +} + +inline void QLineControl::cursorForward(bool mark, int steps) +{ + int c = m_cursor; + if (steps > 0) { + while (steps--) + c = m_textLayout.nextCursorPosition(c); + } else if (steps < 0) { + while (steps++) + c = m_textLayout.previousCursorPosition(c); + } + moveCursor(c, mark); +} + +inline void QLineControl::cursorWordForward(bool mark) +{ + moveCursor(m_textLayout.nextCursorPosition(m_cursor, QTextLayout::SkipWords), mark); +} + +inline void QLineControl::home(bool mark) +{ + moveCursor(0, mark); +} + +inline void QLineControl::end(bool mark) +{ + moveCursor(text().length(), mark); +} + +inline void QLineControl::cursorWordBackward(bool mark) +{ + moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); +} + +inline qreal QLineControl::cursorToX(int cursor) const +{ + return m_textLayout.lineAt(0).cursorToX(cursor); +} + +inline qreal QLineControl::cursorToX() const +{ + return cursorToX(m_cursor); +} + +inline bool QLineControl::isReadOnly() const +{ + return m_readOnly; +} + +inline void QLineControl::setReadOnly(bool enable) +{ + m_readOnly = enable; +} + +inline QString QLineControl::text() const +{ + QString res = m_maskData ? stripString(m_text) : m_text; + return (res.isNull() ? QString::fromLatin1("") : res); +} + +inline void QLineControl::setText(const QString &txt) +{ + internalSetText(txt, -1, false); +} + +inline QString QLineControl::displayText() const +{ + return m_textLayout.text(); +} + +inline void QLineControl::deselect() +{ + internalDeselect(); + finishChange(); +} + +inline void QLineControl::selectAll() +{ + m_selstart = m_selend = m_cursor = 0; + moveCursor(m_text.length(), true); +} + +inline void QLineControl::undo() +{ + internalUndo(); + finishChange(-1, true); +} + +inline void QLineControl::redo() +{ + internalRedo(); + finishChange(); +} + +inline uint QLineControl::echoMode() const +{ + return m_echoMode; +} + +inline void QLineControl::setEchoMode(uint mode) +{ + m_echoMode = mode; + m_passwordEchoEditing = false; + updateDisplayText(); +} + +inline void QLineControl::setMaxLength(int maxLength) +{ + if (m_maskData) + return; + m_maxLength = maxLength; + setText(m_text); +} + +inline int QLineControl::maxLength() const +{ + return m_maxLength; +} + +inline const QValidator *QLineControl::validator() const +{ + return m_validator; +} + +inline void QLineControl::setValidator(const QValidator *v) +{ + m_validator = const_cast<QValidator*>(v); +} + +#ifndef QT_NO_COMPLETER +inline QCompleter *QLineControl::completer() const +{ + return m_completer; +} + +/* Note that you must set the widget for the completer seperately */ +inline void QLineControl::setCompleter(const QCompleter* c) +{ + m_completer = const_cast<QCompleter*>(c); +} +#endif + +inline void QLineControl::setCursorPosition(int pos) +{ + if (pos < 0) + pos = 0; + if (pos <= m_text.length()) + moveCursor(pos); +} + +inline int QLineControl::cursorPosition() const +{ + return m_cursor; +} + +inline bool QLineControl::hasAcceptableInput() const +{ + return hasAcceptableInput(m_text); +} + +inline QString QLineControl::inputMask() const +{ + return m_maskData ? m_inputMask + QLatin1Char(';') + m_blank : QString(); +} + +inline void QLineControl::setInputMask(const QString &mask) +{ + parseInputMask(mask); + if (m_maskData) + moveCursor(nextMaskBlank(0)); +} + +// input methods +#ifndef QT_NO_IM +inline bool QLineControl::composeMode() const +{ + return !m_textLayout.preeditAreaText().isEmpty(); +} + +inline void QLineControl::setPreeditArea(int cursor, const QString &text) +{ + m_textLayout.setPreeditArea(cursor, text); +} +#endif + +inline QString QLineControl::preeditAreaText() const +{ + return m_textLayout.preeditAreaText(); +} + +inline bool QLineControl::passwordEchoEditing() const +{ + return m_passwordEchoEditing; +} + +inline QChar QLineControl::passwordCharacter() const +{ + return m_passwordCharacter; +} + +inline void QLineControl::setPasswordCharacter(const QChar &character) +{ + m_passwordCharacter = character; + updateDisplayText(); +} + +inline Qt::LayoutDirection QLineControl::layoutDirection() const +{ + return m_layoutDirection; +} + +inline void QLineControl::setLayoutDirection(Qt::LayoutDirection direction) +{ + if (direction != m_layoutDirection) { + m_layoutDirection = direction; + updateDisplayText(); + } +} + +inline void QLineControl::setFont(const QFont &font) +{ + m_textLayout.setFont(font); + updateDisplayText(); +} + +inline int QLineControl::cursorBlinkPeriod() const +{ + return m_blinkPeriod; +} + +inline QString QLineControl::cancelText() const +{ + return m_cancelText; +} + +inline void QLineControl::setCancelText(const QString &text) +{ + m_cancelText = text; +} + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QT_NO_LINEEDIT + +#endif // QLINECONTROL_P_H diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp index d1067a8..9f315fd 100644 --- a/src/gui/widgets/qlineedit.cpp +++ b/src/gui/widgets/qlineedit.cpp @@ -86,21 +86,12 @@ #include <limits.h> -#define verticalMargin 1 -#define horizontalMargin 2 - QT_BEGIN_NAMESPACE #ifdef Q_WS_MAC extern void qt_mac_secure_keyboard(bool); //qapplication_mac.cpp #endif -static inline bool shouldEnableInputMethod(QLineEdit *lineedit) -{ - const QLineEdit::EchoMode mode = lineedit->echoMode(); - return !lineedit->isReadOnly() && (mode == QLineEdit::Normal || mode == QLineEdit::PasswordEchoOnEdit); -} - /*! Initialize \a option with the values from this QLineEdit. This method is useful for subclasses when they need a QStyleOptionFrame or QStyleOptionFrameV2, but don't want @@ -122,7 +113,7 @@ void QLineEdit::initStyleOption(QStyleOptionFrame *option) const : 0; option->midLineWidth = 0; option->state |= QStyle::State_Sunken; - if (d->readOnly) + if (d->control->isReadOnly()) option->state |= QStyle::State_ReadOnly; #ifdef QT_KEYPAD_NAVIGATION if (hasEditFocus()) @@ -350,14 +341,9 @@ QLineEdit::QLineEdit(const QString& contents, const QString &inputMask, QWidget* { Q_D(QLineEdit); setObjectName(QString::fromAscii(name)); - d->parseInputMask(inputMask); - if (d->maskData) { - QString ms = d->maskString(0, contents); - d->init(ms + d->clearString(ms.length(), d->maxLength - ms.length())); - d->cursor = d->nextMaskBlank(ms.length()); - } else { - d->init(contents); - } + d->init(contents); + d->control->setInputMask(inputMask); + d->control->moveCursor(d->control->nextMaskBlank(contents.length())); } #endif @@ -388,19 +374,13 @@ QLineEdit::~QLineEdit() QString QLineEdit::text() const { Q_D(const QLineEdit); - QString res = d->text; - if (d->maskData) - res = d->stripString(d->text); - return (res.isNull() ? QString::fromLatin1("") : res); + return d->control->text(); } void QLineEdit::setText(const QString& text) { Q_D(QLineEdit); - d->setText(text, -1, false); -#ifdef QT_KEYPAD_NAVIGATION - d->origText = d->text; -#endif + d->control->setText(text); } @@ -421,17 +401,7 @@ void QLineEdit::setText(const QString& text) QString QLineEdit::displayText() const { Q_D(const QLineEdit); - if (d->echoMode == NoEcho) - return QString::fromLatin1(""); - QString res = d->text; - - if (d->echoMode == Password || (d->echoMode == PasswordEchoOnEdit - && !d->passwordEchoEditing)) { - QStyleOptionFrameV2 opt; - initStyleOption(&opt); - res.fill(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this)); - } - return (res.isNull() ? QString::fromLatin1("") : res); + return d->control->displayText(); } @@ -456,20 +426,15 @@ QString QLineEdit::displayText() const int QLineEdit::maxLength() const { Q_D(const QLineEdit); - return d->maxLength; + return d->control->maxLength(); } void QLineEdit::setMaxLength(int maxLength) { Q_D(QLineEdit); - if (d->maskData) - return; - d->maxLength = maxLength; - setText(d->text); + d->control->setMaxLength(maxLength); } - - /*! \property QLineEdit::frame \brief whether the line edit draws itself with a frame @@ -536,22 +501,20 @@ void QLineEdit::setFrame(bool enable) QLineEdit::EchoMode QLineEdit::echoMode() const { Q_D(const QLineEdit); - return (EchoMode) d->echoMode; + return (EchoMode) d->control->echoMode(); } void QLineEdit::setEchoMode(EchoMode mode) { Q_D(QLineEdit); - if (mode == (EchoMode)d->echoMode) + if (mode == (EchoMode)d->control->echoMode()) return; - setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this)); - d->echoMode = mode; - d->passwordEchoEditing = false; - d->updateTextLayout(); + setAttribute(Qt::WA_InputMethodEnabled, d->shouldEnableInputMethod()); + d->control->setEchoMode(mode); update(); #ifdef Q_WS_MAC if (hasFocus()) - qt_mac_secure_keyboard(d->echoMode == Password || d->echoMode == NoEcho); + qt_mac_secure_keyboard(mode == Password || mode == NoEcho); #endif } @@ -567,7 +530,7 @@ void QLineEdit::setEchoMode(EchoMode mode) const QValidator * QLineEdit::validator() const { Q_D(const QLineEdit); - return d->validator; + return d->control->validator(); } /*! @@ -585,7 +548,7 @@ const QValidator * QLineEdit::validator() const void QLineEdit::setValidator(const QValidator *v) { Q_D(QLineEdit); - d->validator = const_cast<QValidator*>(v); + d->control->setValidator(v); } #endif // QT_NO_VALIDATOR @@ -609,23 +572,23 @@ void QLineEdit::setValidator(const QValidator *v) void QLineEdit::setCompleter(QCompleter *c) { Q_D(QLineEdit); - if (c == d->completer) + if (c == d->control->completer()) return; - if (d->completer) { - disconnect(d->completer, 0, this, 0); - d->completer->setWidget(0); - if (d->completer->parent() == this) - delete d->completer; + if (d->control->completer()) { + disconnect(d->control->completer(), 0, this, 0); + d->control->completer()->setWidget(0); + if (d->control->completer()->parent() == this) + delete d->control->completer(); } - d->completer = c; + d->control->setCompleter(c); if (!c) return; if (c->widget() == 0) c->setWidget(this); if (hasFocus()) { - QObject::connect(d->completer, SIGNAL(activated(QString)), + QObject::connect(d->control->completer(), SIGNAL(activated(QString)), this, SLOT(setText(QString))); - QObject::connect(d->completer, SIGNAL(highlighted(QString)), + QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)), this, SLOT(_q_completionHighlighted(QString))); } } @@ -638,83 +601,9 @@ void QLineEdit::setCompleter(QCompleter *c) QCompleter *QLineEdit::completer() const { Q_D(const QLineEdit); - return d->completer; -} - -// looks for an enabled item iterating forward(dir=1)/backward(dir=-1) from the -// current row based. dir=0 indicates a new completion prefix was set. -bool QLineEditPrivate::advanceToEnabledItem(int dir) -{ - int start = completer->currentRow(); - if (start == -1) - return false; - int i = start + dir; - if (dir == 0) dir = 1; - do { - if (!completer->setCurrentRow(i)) { - if (!completer->wrapAround()) - break; - i = i > 0 ? 0 : completer->completionCount() - 1; - } else { - QModelIndex currentIndex = completer->currentIndex(); - if (completer->completionModel()->flags(currentIndex) & Qt::ItemIsEnabled) - return true; - i += dir; - } - } while (i != start); - - completer->setCurrentRow(start); // restore - return false; -} - -void QLineEditPrivate::complete(int key) -{ - if (!completer || readOnly || echoMode != QLineEdit::Normal) - return; - - if (completer->completionMode() == QCompleter::InlineCompletion) { - if (key == Qt::Key_Backspace) - return; - int n = 0; - if (key == Qt::Key_Up || key == Qt::Key_Down) { - if (selend != 0 && selend != text.length()) - return; - QString prefix = hasSelectedText() ? text.left(selstart) : text; - if (text.compare(completer->currentCompletion(), completer->caseSensitivity()) != 0 - || prefix.compare(completer->completionPrefix(), completer->caseSensitivity()) != 0) { - completer->setCompletionPrefix(prefix); - } else { - n = (key == Qt::Key_Up) ? -1 : +1; - } - } else { - completer->setCompletionPrefix(text); - } - if (!advanceToEnabledItem(n)) - return; - } else { -#ifndef QT_KEYPAD_NAVIGATION - if (text.isEmpty()) { - completer->popup()->hide(); - return; - } -#endif - completer->setCompletionPrefix(text); - } - - completer->complete(); + return d->control->completer(); } -void QLineEditPrivate::_q_completionHighlighted(QString newText) -{ - Q_Q(QLineEdit); - if (completer->completionMode() != QCompleter::InlineCompletion) - q->setText(newText); - else { - int c = cursor; - q->setText(text.left(c) + newText.mid(c)); - q->setSelection(text.length(), c - newText.length()); - } -} #endif // QT_NO_COMPLETER /*! @@ -729,10 +618,10 @@ QSize QLineEdit::sizeHint() const Q_D(const QLineEdit); ensurePolished(); QFontMetrics fm(font()); - int h = qMax(fm.lineSpacing(), 14) + 2*verticalMargin + int h = qMax(fm.lineSpacing(), 14) + 2*d->verticalMargin + d->topTextMargin + d->bottomTextMargin + d->topmargin + d->bottommargin; - int w = fm.width(QLatin1Char('x')) * 17 + 2*horizontalMargin + int w = fm.width(QLatin1Char('x')) * 17 + 2*d->horizontalMargin + d->leftTextMargin + d->rightTextMargin + d->leftmargin + d->rightmargin; // "some" QStyleOptionFrameV2 opt; @@ -753,7 +642,7 @@ QSize QLineEdit::minimumSizeHint() const Q_D(const QLineEdit); ensurePolished(); QFontMetrics fm = fontMetrics(); - int h = fm.height() + qMax(2*verticalMargin, fm.leading()) + int h = fm.height() + qMax(2*d->verticalMargin, fm.leading()) + d->topmargin + d->bottommargin; int w = fm.maxWidth() + d->leftmargin + d->rightmargin; QStyleOptionFrameV2 opt; @@ -775,17 +664,13 @@ QSize QLineEdit::minimumSizeHint() const int QLineEdit::cursorPosition() const { Q_D(const QLineEdit); - return d->cursor; + return d->control->cursorPosition(); } void QLineEdit::setCursorPosition(int pos) { Q_D(QLineEdit); - if (pos < 0) - pos = 0; - - if (pos <= d->text.length()) - d->moveCursor(pos); + d->control->setCursorPosition(pos); } /*! @@ -807,22 +692,17 @@ int QLineEdit::cursorPositionAt(const QPoint &pos) bool QLineEdit::validateAndSet(const QString &newText, int newPos, int newMarkAnchor, int newMarkDrag) { - Q_D(QLineEdit); - int priorState = d->undoState; - d->selstart = 0; - d->selend = d->text.length(); - d->removeSelectedText(); - d->insert(newText); - d->finishChange(priorState); - if (d->undoState > priorState) { - d->cursor = newPos; - d->selstart = qMin(newMarkAnchor, newMarkDrag); - d->selend = qMax(newMarkAnchor, newMarkDrag); - update(); - d->emitCursorPositionChanged(); - return true; + // The suggested functions above in the docs don't seem to validate, + // below code tries to mimic previous behaviour. + QString oldText = text(); + setText(newText); + if(!hasAcceptableInput()){ + setText(oldText); + return false; } - return false; + setCursorPosition(newPos); + setSelection(qMin(newMarkAnchor, newMarkDrag), qAbs(newMarkAnchor - newMarkDrag)); + return true; } #endif //QT3_SUPPORT @@ -863,15 +743,7 @@ void QLineEdit::setAlignment(Qt::Alignment alignment) void QLineEdit::cursorForward(bool mark, int steps) { Q_D(QLineEdit); - int cursor = d->cursor; - if (steps > 0) { - while(steps--) - cursor = d->textLayout.nextCursorPosition(cursor); - } else if (steps < 0) { - while (steps++) - cursor = d->textLayout.previousCursorPosition(cursor); - } - d->moveCursor(cursor, mark); + d->control->cursorForward(mark, steps); } @@ -896,7 +768,7 @@ void QLineEdit::cursorBackward(bool mark, int steps) void QLineEdit::cursorWordForward(bool mark) { Q_D(QLineEdit); - d->moveCursor(d->textLayout.nextCursorPosition(d->cursor, QTextLayout::SkipWords), mark); + d->control->cursorWordForward(mark); } /*! @@ -909,7 +781,7 @@ void QLineEdit::cursorWordForward(bool mark) void QLineEdit::cursorWordBackward(bool mark) { Q_D(QLineEdit); - d->moveCursor(d->textLayout.previousCursorPosition(d->cursor, QTextLayout::SkipWords), mark); + d->control->cursorWordBackward(mark); } @@ -924,26 +796,7 @@ void QLineEdit::cursorWordBackward(bool mark) void QLineEdit::backspace() { Q_D(QLineEdit); - int priorState = d->undoState; - if (d->hasSelectedText()) { - d->removeSelectedText(); - } else if (d->cursor) { - --d->cursor; - if (d->maskData) - d->cursor = d->prevMaskBlank(d->cursor); - QChar uc = d->text.at(d->cursor); - if (d->cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { - // second half of a surrogate, check if we have the first half as well, - // if yes delete both at once - uc = d->text.at(d->cursor - 1); - if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) { - d->del(true); - --d->cursor; - } - } - d->del(true); - } - d->finishChange(priorState); + d->control->backspace(); } /*! @@ -957,15 +810,7 @@ void QLineEdit::backspace() void QLineEdit::del() { Q_D(QLineEdit); - int priorState = d->undoState; - if (d->hasSelectedText()) { - d->removeSelectedText(); - } else { - int n = d->textLayout.nextCursorPosition(d->cursor) - d->cursor; - while (n--) - d->del(); - } - d->finishChange(priorState); + d->control->del(); } /*! @@ -980,7 +825,7 @@ void QLineEdit::del() void QLineEdit::home(bool mark) { Q_D(QLineEdit); - d->moveCursor(0, mark); + d->control->home(mark); } /*! @@ -995,7 +840,7 @@ void QLineEdit::home(bool mark) void QLineEdit::end(bool mark) { Q_D(QLineEdit); - d->moveCursor(d->text.length(), mark); + d->control->end(mark); } @@ -1020,16 +865,13 @@ void QLineEdit::end(bool mark) bool QLineEdit::isModified() const { Q_D(const QLineEdit); - return d->modifiedState != d->undoState; + return d->control->isModified(); } void QLineEdit::setModified(bool modified) { Q_D(QLineEdit); - if (modified) - d->modifiedState = -1; - else - d->modifiedState = d->undoState; + d->control->setModified(modified); } @@ -1057,7 +899,7 @@ Use setModified(false) instead. bool QLineEdit::hasSelectedText() const { Q_D(const QLineEdit); - return d->hasSelectedText(); + return d->control->hasSelectedText(); } /*! @@ -1075,9 +917,7 @@ bool QLineEdit::hasSelectedText() const QString QLineEdit::selectedText() const { Q_D(const QLineEdit); - if (d->hasSelectedText()) - return d->text.mid(d->selstart, d->selend - d->selstart); - return QString(); + return d->control->selectedText(); } /*! @@ -1090,7 +930,7 @@ QString QLineEdit::selectedText() const int QLineEdit::selectionStart() const { Q_D(const QLineEdit); - return d->hasSelectedText() ? d->selstart : -1; + return d->control->selectionStart(); } @@ -1120,9 +960,10 @@ void QLineEdit::setEdited(bool on) { setModified(on); } int QLineEdit::characterAt(int xpos, QChar *chr) const { Q_D(const QLineEdit); - int pos = d->xToPos(xpos + contentsRect().x() - d->hscroll + horizontalMargin); - if (chr && pos < (int) d->text.length()) - *chr = d->text.at(pos); + int pos = d->xToPos(xpos + contentsRect().x() - d->hscroll + d->horizontalMargin); + QString txt = d->control->text(); + if (chr && pos < (int) txt.length()) + *chr = txt.at(pos); return pos; } @@ -1133,9 +974,9 @@ int QLineEdit::characterAt(int xpos, QChar *chr) const bool QLineEdit::getSelection(int *start, int *end) { Q_D(QLineEdit); - if (d->hasSelectedText() && start && end) { - *start = d->selstart; - *end = d->selend; + if (d->control->hasSelectedText() && start && end) { + *start = selectionStart(); + *end = *start + selectedText().length(); return true; } return false; @@ -1153,30 +994,19 @@ bool QLineEdit::getSelection(int *start, int *end) void QLineEdit::setSelection(int start, int length) { Q_D(QLineEdit); - if (start < 0 || start > (int)d->text.length()) { + if (start < 0 || start > (int)d->control->text().length()) { qWarning("QLineEdit::setSelection: Invalid start position (%d)", start); return; - } else { - if (length > 0) { - d->selstart = start; - d->selend = qMin(start + length, (int)d->text.length()); - d->cursor = d->selend; - } else { - d->selstart = qMax(start + length, 0); - d->selend = start; - d->cursor = d->selstart; - } } - if (d->hasSelectedText()){ + d->control->setSelection(start, length); + + if (d->control->hasSelectedText()){ QStyleOptionFrameV2 opt; initStyleOption(&opt); if (!style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this)) d->setCursorVisible(false); } - - update(); - d->emitCursorPositionChanged(); } @@ -1192,7 +1022,7 @@ void QLineEdit::setSelection(int start, int length) bool QLineEdit::isUndoAvailable() const { Q_D(const QLineEdit); - return d->isUndoAvailable(); + return d->control->isUndoAvailable(); } /*! @@ -1208,7 +1038,7 @@ bool QLineEdit::isUndoAvailable() const bool QLineEdit::isRedoAvailable() const { Q_D(const QLineEdit); - return d->isRedoAvailable(); + return d->control->isRedoAvailable(); } /*! @@ -1244,7 +1074,7 @@ void QLineEdit::setDragEnabled(bool b) bool QLineEdit::hasAcceptableInput() const { Q_D(const QLineEdit); - return d->hasAcceptableInput(d->text); + return d->control->hasAcceptableInput(); } /*! @@ -1350,15 +1180,13 @@ void QLineEdit::getTextMargins(int *left, int *top, int *right, int *bottom) con QString QLineEdit::inputMask() const { Q_D(const QLineEdit); - return (d->maskData ? d->inputMask + QLatin1Char(';') + d->blank : QString()); + return d->control->inputMask(); } void QLineEdit::setInputMask(const QString &inputMask) { Q_D(QLineEdit); - d->parseInputMask(inputMask); - if (d->maskData) - d->moveCursor(d->nextMaskBlank(0)); + d->control->setInputMask(inputMask); } /*! @@ -1373,8 +1201,7 @@ void QLineEdit::setInputMask(const QString &inputMask) void QLineEdit::selectAll() { Q_D(QLineEdit); - d->selstart = d->selend = d->cursor = 0; - d->moveCursor(d->text.length(), true); + d->control->selectAll(); } /*! @@ -1386,8 +1213,7 @@ void QLineEdit::selectAll() void QLineEdit::deselect() { Q_D(QLineEdit); - d->deselect(); - d->finishChange(); + d->control->deselect(); } @@ -1402,10 +1228,7 @@ void QLineEdit::insert(const QString &newText) { // q->resetInputContext(); //#### FIX ME IN QT Q_D(QLineEdit); - int priorState = d->undoState; - d->removeSelectedText(); - d->insert(newText); - d->finishChange(priorState); + d->control->insert(newText); } /*! @@ -1416,13 +1239,8 @@ void QLineEdit::insert(const QString &newText) void QLineEdit::clear() { Q_D(QLineEdit); - int priorState = d->undoState; resetInputContext(); - d->selstart = 0; - d->selend = d->text.length(); - d->removeSelectedText(); - d->separate(); - d->finishChange(priorState, /*update*/false, /*edited*/false); + d->control->clear(); } /*! @@ -1435,8 +1253,7 @@ void QLineEdit::undo() { Q_D(QLineEdit); resetInputContext(); - d->undo(); - d->finishChange(-1, true); + d->control->undo(); } /*! @@ -1447,8 +1264,7 @@ void QLineEdit::redo() { Q_D(QLineEdit); resetInputContext(); - d->redo(); - d->finishChange(); + d->control->redo(); } @@ -1470,16 +1286,16 @@ void QLineEdit::redo() bool QLineEdit::isReadOnly() const { Q_D(const QLineEdit); - return d->readOnly; + return d->control->isReadOnly(); } void QLineEdit::setReadOnly(bool enable) { Q_D(QLineEdit); - if (d->readOnly != enable) { - d->readOnly = enable; - setAttribute(Qt::WA_MacShowFocusRect, !d->readOnly); - setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this)); + if (d->control->isReadOnly() != enable) { + d->control->setReadOnly(enable); + setAttribute(Qt::WA_MacShowFocusRect, !enable); + setAttribute(Qt::WA_InputMethodEnabled, d->shouldEnableInputMethod()); #ifndef QT_NO_CURSOR setCursor(enable ? Qt::ArrowCursor : Qt::IBeamCursor); #endif @@ -1518,7 +1334,7 @@ void QLineEdit::cut() void QLineEdit::copy() const { Q_D(const QLineEdit); - d->copy(); + d->control->copy(); } /*! @@ -1535,23 +1351,7 @@ void QLineEdit::copy() const void QLineEdit::paste() { Q_D(QLineEdit); - if (echoMode() == PasswordEchoOnEdit && !d->passwordEchoEditing) { - // Clear the edit and reset to normal echo mode when pasting; the echo - // mode switches back when the edit loses focus. ### changes a public - // property, resets current content - d->updatePasswordEchoEditing(true); - clear(); - } - insert(QApplication::clipboard()->text(QClipboard::Clipboard)); -} - -void QLineEditPrivate::copy(bool clipboard) const -{ - Q_Q(const QLineEdit); - QString t = q->selectedText(); - if (!t.isEmpty() && echoMode == QLineEdit::Normal) { - QApplication::clipboard()->setText(t, clipboard ? QClipboard::Clipboard : QClipboard::Selection); - } + d->control->paste(); } #endif // !QT_NO_CLIPBOARD @@ -1561,57 +1361,10 @@ void QLineEditPrivate::copy(bool clipboard) const bool QLineEdit::event(QEvent * e) { Q_D(QLineEdit); -#ifndef QT_NO_SHORTCUT - if (e->type() == QEvent::ShortcutOverride && !d->readOnly) { - QKeyEvent* ke = (QKeyEvent*) e; - if (ke == QKeySequence::Copy - || ke == QKeySequence::Paste - || ke == QKeySequence::Cut - || ke == QKeySequence::Redo - || ke == QKeySequence::Undo - || ke == QKeySequence::MoveToNextWord - || ke == QKeySequence::MoveToPreviousWord - || ke == QKeySequence::MoveToStartOfDocument - || ke == QKeySequence::MoveToEndOfDocument - || ke == QKeySequence::SelectNextWord - || ke == QKeySequence::SelectPreviousWord - || ke == QKeySequence::SelectStartOfLine - || ke == QKeySequence::SelectEndOfLine - || ke == QKeySequence::SelectStartOfBlock - || ke == QKeySequence::SelectEndOfBlock - || ke == QKeySequence::SelectStartOfDocument - || ke == QKeySequence::SelectAll - || ke == QKeySequence::SelectEndOfDocument) { - ke->accept(); - } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier - || ke->modifiers() == Qt::KeypadModifier) { - if (ke->key() < Qt::Key_Escape) { - ke->accept(); - } else { - switch (ke->key()) { - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - ke->accept(); - default: - break; - } - } - } - } else -#endif - if (e->type() == QEvent::Timer) { + if (e->type() == QEvent::Timer) { // should be timerEvent, is here for binary compatibility int timerId = ((QTimerEvent*)e)->timerId(); - if (timerId == d->cursorTimer) { - QStyleOptionFrameV2 opt; - initStyleOption(&opt); - if(!hasSelectedText() - || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this)) - d->setCursorVisible(!d->cursorVisible); + if (false) { #ifndef QT_NO_DRAGANDDROP } else if (timerId == d->dndTimer.timerId()) { d->drag(); @@ -1619,60 +1372,31 @@ bool QLineEdit::event(QEvent * e) } else if (timerId == d->tripleClickTimer.timerId()) d->tripleClickTimer.stop(); -#ifdef QT_KEYPAD_NAVIGATION - else if (timerId == d->deleteAllTimer.timerId()) { - d->deleteAllTimer.stop(); - clear(); - } -#endif } else if (e->type() == QEvent::ContextMenu) { #ifndef QT_NO_IM - if (d->composeMode()) + if (d->control->composeMode()) return true; #endif - d->separate(); + //d->separate(); } else if (e->type() == QEvent::WindowActivate) { QTimer::singleShot(0, this, SLOT(_q_handleWindowActivate())); + }else if(e->type() == QEvent::ShortcutOverride){ + d->control->processEvent(e); } + #ifdef QT_KEYPAD_NAVIGATION if (QApplication::keypadNavigationEnabled()) { - if ((e->type() == QEvent::KeyPress) || (e->type() == QEvent::KeyRelease)) { - QKeyEvent *ke = (QKeyEvent *)e; - if (ke->key() == Qt::Key_Back) { - if (ke->isAutoRepeat()) { - // Swallow it. We don't want back keys running amok. - ke->accept(); - return true; - } - if ((e->type() == QEvent::KeyRelease) - && !isReadOnly() - && d->deleteAllTimer.isActive()) { - d->deleteAllTimer.stop(); - backspace(); - ke->accept(); - return true; - } - } - } else if (e->type() == QEvent::EnterEditFocus) { + if (e->type() == QEvent::EnterEditFocus) { end(false); - if (!d->cursorTimer) { - int cft = QApplication::cursorFlashTime(); - d->cursorTimer = cft ? startTimer(cft/2) : -1; - } + int cft = QApplication::cursorFlashTime(); + d->control->setCursorBlinkPeriod(cft/2); } else if (e->type() == QEvent::LeaveEditFocus) { d->setCursorVisible(false); - if (d->cursorTimer > 0) - killTimer(d->cursorTimer); - d->cursorTimer = 0; - - if (!d->emitingEditingFinished) { - if (hasAcceptableInput() || d->fixup()) { - d->emitingEditingFinished = true; - emit editingFinished(); - d->emitingEditingFinished = false; - } - } + d->control->setCursorBlinkPeriod(0); + if (d->control->hasAcceptableInput() || d->control->fixup()) + emit editingFinished(); } + return true; } #endif return QWidget::event(e); @@ -1684,15 +1408,15 @@ void QLineEdit::mousePressEvent(QMouseEvent* e) { Q_D(QLineEdit); if (d->sendMouseEventToInputContext(e)) - return; + return; if (e->button() == Qt::RightButton) return; #ifdef QT_KEYPAD_NAVIGATION if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) { setEditFocus(true); // Get the completion list to pop up. - if (d->completer) - d->completer->complete(); + if (d->control->completer()) + d->control->completer()->complete(); } #endif if (d->tripleClickTimer.isActive() && (e->pos() - d->tripleClick).manhattanLength() < @@ -1703,18 +1427,16 @@ void QLineEdit::mousePressEvent(QMouseEvent* e) bool mark = e->modifiers() & Qt::ShiftModifier; int cursor = d->xToPos(e->pos().x()); #ifndef QT_NO_DRAGANDDROP - if (!mark && d->dragEnabled && d->echoMode == Normal && - e->button() == Qt::LeftButton && d->inSelection(e->pos().x())) { - d->cursor = cursor; - update(); + if (!mark && d->dragEnabled && d->control->echoMode() == Normal && + e->button() == Qt::LeftButton && d->control->inSelection(e->pos().x())) { + d->control->moveCursor(cursor); d->dndPos = e->pos(); if (!d->dndTimer.isActive()) d->dndTimer.start(QApplication::startDragTime(), this); - d->emitCursorPositionChanged(); } else #endif { - d->moveCursor(cursor, mark); + d->control->moveCursor(cursor, mark); } } @@ -1724,7 +1446,7 @@ void QLineEdit::mouseMoveEvent(QMouseEvent * e) { Q_D(QLineEdit); if (d->sendMouseEventToInputContext(e)) - return; + return; if (e->buttons() & Qt::LeftButton) { #ifndef QT_NO_DRAGANDDROP @@ -1734,7 +1456,7 @@ void QLineEdit::mouseMoveEvent(QMouseEvent * e) } else #endif { - d->moveCursor(d->xToPos(e->pos().x()), true); + d->control->moveCursor(d->xToPos(e->pos().x()), true); } } } @@ -1745,7 +1467,7 @@ void QLineEdit::mouseReleaseEvent(QMouseEvent* e) { Q_D(QLineEdit); if (d->sendMouseEventToInputContext(e)) - return; + return; #ifndef QT_NO_DRAGANDDROP if (e->button() == Qt::LeftButton) { if (d->dndTimer.isActive()) { @@ -1758,9 +1480,9 @@ void QLineEdit::mouseReleaseEvent(QMouseEvent* e) #ifndef QT_NO_CLIPBOARD if (QApplication::clipboard()->supportsSelection()) { if (e->button() == Qt::LeftButton) { - d->copy(false); - } else if (!d->readOnly && e->button() == Qt::MidButton) { - d->deselect(); + d->control->copy(QClipboard::Selection); + } else if (!d->control->isReadOnly() && e->button() == Qt::MidButton) { + deselect(); insert(QApplication::clipboard()->text(QClipboard::Selection)); } } @@ -1773,16 +1495,9 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e) { Q_D(QLineEdit); if (d->sendMouseEventToInputContext(e)) - return; + return; if (e->button() == Qt::LeftButton) { - deselect(); - d->cursor = d->xToPos(e->pos().x()); - d->cursor = d->textLayout.previousCursorPosition(d->cursor, QTextLayout::SkipWords); - // ## text layout should support end of words. - int end = d->textLayout.nextCursorPosition(d->cursor, QTextLayout::SkipWords); - while (end > d->cursor && d->text[end-1].isSpace()) - --end; - d->moveCursor(end, true); + d->control->selectWordAtPos(d->xToPos(e->pos().x())); d->tripleClickTimer.start(QApplication::doubleClickInterval(), this); d->tripleClick = e->pos(); } @@ -1822,65 +1537,15 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e) void QLineEdit::keyPressEvent(QKeyEvent *event) { Q_D(QLineEdit); - - bool inlineCompletionAccepted = false; - -#ifndef QT_NO_COMPLETER - if (d->completer) { - QCompleter::CompletionMode completionMode = d->completer->completionMode(); - if ((completionMode == QCompleter::PopupCompletion - || completionMode == QCompleter::UnfilteredPopupCompletion) - &&d->completer->popup() - && d->completer->popup()->isVisible()) { - // The following keys are forwarded by the completer to the widget - // Ignoring the events lets the completer provide suitable default behavior - switch (event->key()) { - case Qt::Key_Escape: - event->ignore(); - return; - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_F4: -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Select: - if (!QApplication::keypadNavigationEnabled()) - break; -#endif - d->completer->popup()->hide(); // just hide. will end up propagating to parent - default: - break; // normal key processing - } - } else if (completionMode == QCompleter::InlineCompletion) { - switch (event->key()) { - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_F4: -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Select: - if (!QApplication::keypadNavigationEnabled()) - break; -#endif - if (!d->completer->currentCompletion().isEmpty() && d->selend > d->selstart - && d->selend == d->text.length()) { - setText(d->completer->currentCompletion()); - inlineCompletionAccepted = true; - } - default: - break; // normal key processing - } - } - } -#endif // QT_NO_COMPLETER - -#ifdef QT_KEYPAD_NAVIGATION + #ifdef QT_KEYPAD_NAVIGATION bool select = false; switch (event->key()) { case Qt::Key_Select: if (QApplication::keypadNavigationEnabled()) { if (hasEditFocus()) { setEditFocus(false); - if (d->completer && d->completer->popup()->isVisible()) - d->completer->popup()->hide(); + if (d->control->completer() && d->control->completer()->popup()->isVisible()) + d->control->completer()->popup()->hide(); select = true; } } @@ -1916,274 +1581,7 @@ void QLineEdit::keyPressEvent(QKeyEvent *event) return; // Just start. No action. } #endif - - if (echoMode() == PasswordEchoOnEdit - && !d->passwordEchoEditing - && !isReadOnly() - && !event->text().isEmpty() -#ifdef QT_KEYPAD_NAVIGATION - && event->key() != Qt::Key_Select - && event->key() != Qt::Key_Up - && event->key() != Qt::Key_Down - && event->key() != Qt::Key_Back -#endif - && !(event->modifiers() & Qt::ControlModifier)) { - // Clear the edit and reset to normal echo mode while editing; the - // echo mode switches back when the edit loses focus. ### changes a - // public property, resets current content. dubious code; you can - // navigate with keys up, down, back, and select(?), but if you press - // "left" or "right" it clears? - d->updatePasswordEchoEditing(true); - clear(); - } - - d->setCursorVisible(true); - if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { - if (hasAcceptableInput() || d->fixup()) { - emit returnPressed(); - d->emitingEditingFinished = true; - emit editingFinished(); - d->emitingEditingFinished = false; - } - if (inlineCompletionAccepted) - event->accept(); - else - event->ignore(); - return; - } - bool unknown = false; - - if (false) { - } -#ifndef QT_NO_SHORTCUT - else if (event == QKeySequence::Undo) { - if (!d->readOnly) - undo(); - } - else if (event == QKeySequence::Redo) { - if (!d->readOnly) - redo(); - } - else if (event == QKeySequence::SelectAll) { - selectAll(); - } -#ifndef QT_NO_CLIPBOARD - else if (event == QKeySequence::Copy) { - copy(); - } - else if (event == QKeySequence::Paste) { - if (!d->readOnly) - paste(); - } - else if (event == QKeySequence::Cut) { - if (!d->readOnly) { - cut(); - } - } - else if (event == QKeySequence::DeleteEndOfLine) { - if (!d->readOnly) { - setSelection(d->cursor, d->text.size()); - copy(); - del(); - } - } -#endif //QT_NO_CLIPBOARD - else if (event == QKeySequence::MoveToStartOfLine) { - home(0); - } - else if (event == QKeySequence::MoveToEndOfLine) { - end(0); - } - else if (event == QKeySequence::SelectStartOfLine) { - home(1); - } - else if (event == QKeySequence::SelectEndOfLine) { - end(1); - } - else if (event == QKeySequence::MoveToNextChar) { -#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) - if (d->hasSelectedText()) { -#else - if (d->hasSelectedText() && d->completer - && d->completer->completionMode() == QCompleter::InlineCompletion) { -#endif - d->moveCursor(d->selend, false); - } else { - cursorForward(0, layoutDirection() == Qt::LeftToRight ? 1 : -1); - } - } - else if (event == QKeySequence::SelectNextChar) { - cursorForward(1, layoutDirection() == Qt::LeftToRight ? 1 : -1); - } - else if (event == QKeySequence::MoveToPreviousChar) { -#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) - if (d->hasSelectedText()) { -#else - if (d->hasSelectedText() && d->completer - && d->completer->completionMode() == QCompleter::InlineCompletion) { -#endif - d->moveCursor(d->selstart, false); - } else { - cursorBackward(0, layoutDirection() == Qt::LeftToRight ? 1 : -1); - } - } - else if (event == QKeySequence::SelectPreviousChar) { - cursorBackward(1, layoutDirection() == Qt::LeftToRight ? 1 : -1); - } - else if (event == QKeySequence::MoveToNextWord) { - if (echoMode() == Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0); - else - layoutDirection() == Qt::LeftToRight ? end(0) : home(0); - } - else if (event == QKeySequence::MoveToPreviousWord) { - if (echoMode() == Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0); - else if (!d->readOnly) { - layoutDirection() == Qt::LeftToRight ? home(0) : end(0); - } - } - else if (event == QKeySequence::SelectNextWord) { - if (echoMode() == Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1); - else - layoutDirection() == Qt::LeftToRight ? end(1) : home(1); - } - else if (event == QKeySequence::SelectPreviousWord) { - if (echoMode() == Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1); - else - layoutDirection() == Qt::LeftToRight ? home(1) : end(1); - } - else if (event == QKeySequence::Delete) { - if (!d->readOnly) - del(); - } - else if (event == QKeySequence::DeleteEndOfWord) { - if (!d->readOnly) { - cursorWordForward(true); - del(); - } - } - else if (event == QKeySequence::DeleteStartOfWord) { - if (!d->readOnly) { - cursorWordBackward(true); - del(); - } - } -#endif // QT_NO_SHORTCUT - else { -#ifdef Q_WS_MAC - if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { - Qt::KeyboardModifiers myModifiers = (event->modifiers() & ~Qt::KeypadModifier); - if (myModifiers & Qt::ShiftModifier) { - if (myModifiers == (Qt::ControlModifier|Qt::ShiftModifier) - || myModifiers == (Qt::AltModifier|Qt::ShiftModifier) - || myModifiers == Qt::ShiftModifier) { - - event->key() == Qt::Key_Up ? home(1) : end(1); - } - } else { - if ((myModifiers == Qt::ControlModifier - || myModifiers == Qt::AltModifier - || myModifiers == Qt::NoModifier)) { - event->key() == Qt::Key_Up ? home(0) : end(0); - } - } - } -#endif - if (event->modifiers() & Qt::ControlModifier) { - switch (event->key()) { - case Qt::Key_Backspace: - if (!d->readOnly) { - cursorWordBackward(true); - del(); - } - break; -#ifndef QT_NO_COMPLETER - case Qt::Key_Up: - case Qt::Key_Down: - d->complete(event->key()); - break; -#endif -#if defined(Q_WS_X11) - case Qt::Key_E: - end(0); - break; - - case Qt::Key_U: - if (!d->readOnly) { - setSelection(0, d->text.size()); -#ifndef QT_NO_CLIPBOARD - copy(); -#endif - del(); - } - break; -#endif - default: - unknown = true; - } - } else { // ### check for *no* modifier - switch (event->key()) { - case Qt::Key_Backspace: - if (!d->readOnly) { - backspace(); -#ifndef QT_NO_COMPLETER - d->complete(Qt::Key_Backspace); -#endif - } - break; -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Back: - if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat() - && !isReadOnly()) { - if (text().length() == 0) { - setText(d->origText); - - if (d->passwordEchoEditing) - d->updatePasswordEchoEditing(false); - - setEditFocus(false); - } else if (!d->deleteAllTimer.isActive()) { - d->deleteAllTimer.start(750, this); - } - } else { - unknown = true; - } - break; -#endif - - default: - unknown = true; - } - } - } - - if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) { - setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft); - d->updateTextLayout(); - update(); - unknown = false; - } - - if (unknown && !d->readOnly) { - QString t = event->text(); - if (!t.isEmpty() && t.at(0).isPrint() && - ((event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) == Qt::NoModifier)) { - insert(t); -#ifndef QT_NO_COMPLETER - d->complete(event->key()); -#endif - event->accept(); - return; - } - } - - if (unknown) - event->ignore(); - else - event->accept(); + d->control->processKeyEvent(event); } /*! @@ -2197,50 +1595,17 @@ QRect QLineEdit::cursorRect() const return d->cursorRect(); } -/*! - This function is not intended as polymorphic usage. Just a shared code - fragment that calls QInputContext::mouseHandler for this - class. -*/ -bool QLineEditPrivate::sendMouseEventToInputContext( QMouseEvent *e ) -{ -#if !defined QT_NO_IM - Q_Q(QLineEdit); - if ( composeMode() ) { - int tmp_cursor = xToPos(e->pos().x()); - int mousePos = tmp_cursor - cursor; - if ( mousePos < 0 || mousePos > textLayout.preeditAreaText().length() ) { - mousePos = -1; - // don't send move events outside the preedit area - if ( e->type() == QEvent::MouseMove ) - return true; - } - - QInputContext *qic = q->inputContext(); - if ( qic ) - // may be causing reset() in some input methods - qic->mouseHandler(mousePos, e); - if (!textLayout.preeditAreaText().isEmpty()) - return true; - } -#else - Q_UNUSED(e); -#endif - - return false; -} - /*! \reimp */ void QLineEdit::inputMethodEvent(QInputMethodEvent *e) { Q_D(QLineEdit); - if (d->readOnly) { + if (d->control->isReadOnly()) { e->ignore(); return; } - if (echoMode() == PasswordEchoOnEdit && !d->passwordEchoEditing) { + if (echoMode() == PasswordEchoOnEdit && !d->control->passwordEchoEditing()) { // Clear the edit and reset to normal echo mode while entering input // method data; the echo mode switches back when the edit loses focus. // ### changes a public property, resets current content. @@ -2260,55 +1625,11 @@ void QLineEdit::inputMethodEvent(QInputMethodEvent *e) } #endif - int priorState = d->undoState; - d->removeSelectedText(); - - int c = d->cursor; // cursor position after insertion of commit string - if (e->replacementStart() <= 0) - c += e->commitString().length() + qMin(-e->replacementStart(), e->replacementLength()); - - d->cursor += e->replacementStart(); + d->control->processInputMethodEvent(e); - // insert commit string - if (e->replacementLength()) { - d->selstart = d->cursor; - d->selend = d->selstart + e->replacementLength(); - d->removeSelectedText(); - } - if (!e->commitString().isEmpty()) - d->insert(e->commitString()); - - d->cursor = qMin(c, d->text.length()); - - d->textLayout.setPreeditArea(d->cursor, e->preeditString()); - d->preeditCursor = e->preeditString().length(); - d->hideCursor = false; - QList<QTextLayout::FormatRange> formats; - for (int i = 0; i < e->attributes().size(); ++i) { - const QInputMethodEvent::Attribute &a = e->attributes().at(i); - if (a.type == QInputMethodEvent::Cursor) { - d->preeditCursor = a.start; - d->hideCursor = !a.length; - } else if (a.type == QInputMethodEvent::TextFormat) { - QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat(); - if (f.isValid()) { - QTextLayout::FormatRange o; - o.start = a.start + d->cursor; - o.length = a.length; - o.format = f; - formats.append(o); - } - } - } - d->textLayout.setAdditionalFormats(formats); - d->updateTextLayout(); - update(); - if (!e->commitString().isEmpty()) - d->emitCursorPositionChanged(); - d->finishChange(priorState); #ifndef QT_NO_COMPLETER if (!e->commitString().isEmpty()) - d->complete(Qt::Key_unknown); + d->control->complete(Qt::Key_unknown); #endif } @@ -2323,9 +1644,9 @@ QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property) const case Qt::ImFont: return font(); case Qt::ImCursorPosition: - return QVariant((d->selend - d->selstart == 0) ? d->cursor : d->selend); + return QVariant(d->control->hasSelectedText() ? d->control->selectionEnd() : d->control->cursor()); case Qt::ImSurroundingText: - return QVariant(d->text); + return QVariant(text()); case Qt::ImCurrentSelection: return QVariant(selectedText()); default: @@ -2342,36 +1663,35 @@ void QLineEdit::focusInEvent(QFocusEvent *e) if (e->reason() == Qt::TabFocusReason || e->reason() == Qt::BacktabFocusReason || e->reason() == Qt::ShortcutFocusReason) { - if (d->maskData) - d->moveCursor(d->nextMaskBlank(0)); - else if (!d->hasSelectedText()) + if (!d->control->inputMask().isEmpty()) + d->control->moveCursor(d->control->nextMaskBlank(0)); + else if (!d->control->hasSelectedText()) selectAll(); } #ifdef QT_KEYPAD_NAVIGATION - if (!QApplication::keypadNavigationEnabled() || (hasEditFocus() && e->reason() == Qt::PopupFocusReason)) + if (!QApplication::keypadNavigationEnabled() || (hasEditFocus() && e->reason() == Qt::PopupFocusReason)){ #endif - if (!d->cursorTimer) { - int cft = QApplication::cursorFlashTime(); - d->cursorTimer = cft ? startTimer(cft/2) : -1; - } + int cft = QApplication::cursorFlashTime(); + d->control->setCursorBlinkPeriod(cft/2); QStyleOptionFrameV2 opt; initStyleOption(&opt); - if((!hasSelectedText() && d->textLayout.preeditAreaText().isEmpty()) + if((!hasSelectedText() && d->control->preeditAreaText().isEmpty()) || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this)) d->setCursorVisible(true); #ifdef Q_WS_MAC - if (d->echoMode == Password || d->echoMode == NoEcho) + if (d->control->echoMode() == Password || d->control->echoMode() == NoEcho) qt_mac_secure_keyboard(true); #endif #ifdef QT_KEYPAD_NAVIGATION - d->origText = d->text; + d->control->setCancelText(d->control->text()); + } #endif #ifndef QT_NO_COMPLETER - if (d->completer) { - d->completer->setWidget(this); - QObject::connect(d->completer, SIGNAL(activated(QString)), + if (d->control->completer()) { + d->control->completer()->setWidget(this); + QObject::connect(d->control->completer(), SIGNAL(activated(QString)), this, SLOT(setText(QString))); - QObject::connect(d->completer, SIGNAL(highlighted(QString)), + QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)), this, SLOT(_q_completionHighlighted(QString))); } #endif @@ -2384,7 +1704,7 @@ void QLineEdit::focusInEvent(QFocusEvent *e) void QLineEdit::focusOutEvent(QFocusEvent *e) { Q_D(QLineEdit); - if (d->passwordEchoEditing) { + if (d->control->passwordEchoEditing()) { // Reset the echomode back to PasswordEchoOnEdit when the widget loses // focus. d->updatePasswordEchoEditing(false); @@ -2396,37 +1716,29 @@ void QLineEdit::focusOutEvent(QFocusEvent *e) deselect(); d->setCursorVisible(false); - if (d->cursorTimer > 0) - killTimer(d->cursorTimer); - d->cursorTimer = 0; - + d->control->setCursorBlinkPeriod(0); #ifdef QT_KEYPAD_NAVIGATION // editingFinished() is already emitted on LeaveEditFocus if (!QApplication::keypadNavigationEnabled()) #endif if (reason != Qt::PopupFocusReason || !(QApplication::activePopupWidget() && QApplication::activePopupWidget()->parentWidget() == this)) { - if (!d->emitingEditingFinished) { - if (hasAcceptableInput() || d->fixup()) { - d->emitingEditingFinished = true; + if (hasAcceptableInput() || d->control->fixup()) emit editingFinished(); - d->emitingEditingFinished = false; - } - } #ifdef QT3_SUPPORT emit lostFocus(); #endif } #ifdef Q_WS_MAC - if (d->echoMode == Password || d->echoMode == NoEcho) + if (d->control->echoMode() == Password || d->control->echoMode() == NoEcho) qt_mac_secure_keyboard(false); #endif #ifdef QT_KEYPAD_NAVIGATION - d->origText = QString(); + d->control->setCancelText(QString()); #endif #ifndef QT_NO_COMPLETER - if (d->completer) { - QObject::disconnect(d->completer, 0, this, 0); + if (d->control->completer()) { + QObject::disconnect(d->control->completer(), 0, this, 0); } #endif update(); @@ -2456,24 +1768,19 @@ void QLineEdit::paintEvent(QPaintEvent *) Qt::Alignment va = QStyle::visualAlignment(layoutDirection(), QFlag(d->alignment)); switch (va & Qt::AlignVertical_Mask) { case Qt::AlignBottom: - d->vscroll = r.y() + r.height() - fm.height() - verticalMargin; + d->vscroll = r.y() + r.height() - fm.height() - d->verticalMargin; break; case Qt::AlignTop: - d->vscroll = r.y() + verticalMargin; + d->vscroll = r.y() + d->verticalMargin; break; default: //center d->vscroll = r.y() + (r.height() - fm.height() + 1) / 2; break; } - QRect lineRect(r.x() + horizontalMargin, d->vscroll, r.width() - 2*horizontalMargin, fm.height()); - QTextLine line = d->textLayout.lineAt(0); + QRect lineRect(r.x() + d->horizontalMargin, d->vscroll, r.width() - 2*d->horizontalMargin, fm.height()); - int cursor = d->cursor; - if (d->preeditCursor != -1) - cursor += d->preeditCursor; - // locate cursor position - int cix = qRound(line.cursorToX(cursor)); + int cix = qRound(d->control->cursorToX()); // horizontal scrolling. d->hscroll is the left indent from the beginning // of the text line to the left edge of lineRect. we update this value @@ -2483,7 +1790,7 @@ void QLineEdit::paintEvent(QPaintEvent *) // (cix). int minLB = qMax(0, -fm.minLeftBearing()); int minRB = qMax(0, -fm.minRightBearing()); - int widthUsed = qRound(line.naturalTextWidth()) + 1 + minRB; + int widthUsed = d->control->width() + minRB; if ((minLB + widthUsed) <= lineRect.width()) { // text fits in lineRect; use hscroll for alignment switch (va & ~(Qt::AlignAbsolute|Qt::AlignVertical_Mask)) { @@ -2511,7 +1818,7 @@ void QLineEdit::paintEvent(QPaintEvent *) d->hscroll = widthUsed - lineRect.width() + 1; } // the y offset is there to keep the baseline constant in case we have script changes in the text. - QPoint topLeft = lineRect.topLeft() - QPoint(d->hscroll, d->ascent - fm.ascent()); + QPoint topLeft = lineRect.topLeft() - QPoint(d->hscroll, d->control->ascent() - fm.ascent()); // draw text, selections and cursors #ifndef QT_NO_STYLE_STYLESHEET @@ -2521,33 +1828,23 @@ void QLineEdit::paintEvent(QPaintEvent *) #endif p.setPen(pal.text().color()); - QVector<QTextLayout::FormatRange> selections; + int flags = QLineControl::DrawText; + #ifdef QT_KEYPAD_NAVIGATION if (!QApplication::keypadNavigationEnabled() || hasEditFocus()) #endif - if (d->selstart < d->selend || (d->cursorVisible && d->maskData && !d->readOnly)) { - QTextLayout::FormatRange o; - if (d->selstart < d->selend) { - o.start = d->selstart; - o.length = d->selend - d->selstart; - o.format.setBackground(pal.brush(QPalette::Highlight)); - o.format.setForeground(pal.brush(QPalette::HighlightedText)); - } else { - // mask selection - o.start = d->cursor; - o.length = 1; - o.format.setBackground(pal.brush(QPalette::Text)); - o.format.setForeground(pal.brush(QPalette::Window)); - } - selections.append(o); - } + if (d->control->hasSelectedText() || (d->cursorVisible && !d->control->inputMask().isEmpty() && !d->control->isReadOnly())) + flags |= QLineControl::DrawSelections; // Asian users see an IM selection text as cursor on candidate // selection phase of input method, so the ordinary cursor should be // invisible if we have a preedit string. - d->textLayout.draw(&p, topLeft, selections, r); - if (d->cursorVisible && !d->readOnly && !d->hideCursor) - d->textLayout.drawCursor(&p, topLeft, cursor, style()->pixelMetric(QStyle::PM_TextCursorWidth)); + if (d->cursorVisible && !d->control->isReadOnly()) + flags |= QLineControl::DrawCursor; + + d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth)); + d->control->draw(&p, topLeft, r, flags); + } @@ -2557,12 +1854,11 @@ void QLineEdit::paintEvent(QPaintEvent *) void QLineEdit::dragMoveEvent(QDragMoveEvent *e) { Q_D(QLineEdit); - if (!d->readOnly && e->mimeData()->hasFormat(QLatin1String("text/plain"))) { + if (!d->control->isReadOnly() && e->mimeData()->hasFormat(QLatin1String("text/plain"))) { e->acceptProposedAction(); - d->cursor = d->xToPos(e->pos().x()); + d->control->moveCursor(d->xToPos(e->pos().x()), false); d->cursorVisible = true; update(); - d->emitCursorPositionChanged(); } } @@ -2588,13 +1884,14 @@ void QLineEdit::dropEvent(QDropEvent* e) Q_D(QLineEdit); QString str = e->mimeData()->text(); - if (!str.isNull() && !d->readOnly) { + if (!str.isNull() && !d->control->isReadOnly()) { if (e->source() == this && e->dropAction() == Qt::CopyAction) deselect(); - d->cursor =d->xToPos(e->pos().x()); - int selStart = d->cursor; - int oldSelStart = d->selstart; - int oldSelEnd = d->selend; + int cursorPos = d->xToPos(e->pos().x()); + int selStart = cursorPos; + int oldSelStart = d->control->selectionStart(); + int oldSelEnd = d->control->selectionEnd(); + d->control->moveCursor(cursorPos, false); d->cursorVisible = false; e->acceptProposedAction(); insert(str); @@ -2616,22 +1913,6 @@ void QLineEdit::dropEvent(QDropEvent* e) } } -void QLineEditPrivate::drag() -{ - Q_Q(QLineEdit); - dndTimer.stop(); - QMimeData *data = new QMimeData; - data->setText(q->selectedText()); - QDrag *drag = new QDrag(q); - drag->setMimeData(data); - Qt::DropAction action = drag->start(); - if (action == Qt::MoveAction && !readOnly && drag->target() != q) { - int priorState = undoState; - removeSelectedText(); - finishChange(priorState); - } -} - #endif // QT_NO_DRAGANDDROP #ifndef QT_NO_CONTEXTMENU @@ -2676,37 +1957,39 @@ QMenu *QLineEdit::createStandardContextMenu() popup->setObjectName(QLatin1String("qt_edit_menu")); QAction *action = popup->addAction(QLineEdit::tr("&Undo") + ACCEL_KEY(QKeySequence::Undo)); - action->setEnabled(d->isUndoAvailable()); + action->setEnabled(d->control->isUndoAvailable()); connect(action, SIGNAL(triggered()), SLOT(undo())); action = popup->addAction(QLineEdit::tr("&Redo") + ACCEL_KEY(QKeySequence::Redo)); - action->setEnabled(d->isRedoAvailable()); + action->setEnabled(d->control->isRedoAvailable()); connect(action, SIGNAL(triggered()), SLOT(redo())); popup->addSeparator(); #ifndef QT_NO_CLIPBOARD action = popup->addAction(QLineEdit::tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut)); - action->setEnabled(!d->readOnly && d->hasSelectedText() && d->echoMode == QLineEdit::Normal); + action->setEnabled(!d->control->isReadOnly() && d->control->hasSelectedText() + && d->control->echoMode() == QLineEdit::Normal); connect(action, SIGNAL(triggered()), SLOT(cut())); action = popup->addAction(QLineEdit::tr("&Copy") + ACCEL_KEY(QKeySequence::Copy)); - action->setEnabled(d->hasSelectedText() && d->echoMode == QLineEdit::Normal); + action->setEnabled(d->control->hasSelectedText() + && d->control->echoMode() == QLineEdit::Normal); connect(action, SIGNAL(triggered()), SLOT(copy())); action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste)); - action->setEnabled(!d->readOnly && !QApplication::clipboard()->text().isEmpty()); + action->setEnabled(!d->control->isReadOnly() && !QApplication::clipboard()->text().isEmpty()); connect(action, SIGNAL(triggered()), SLOT(paste())); #endif action = popup->addAction(QLineEdit::tr("Delete")); - action->setEnabled(!d->readOnly && !d->text.isEmpty() && d->hasSelectedText()); + action->setEnabled(!d->control->isReadOnly() && !d->control->text().isEmpty() && d->control->hasSelectedText()); connect(action, SIGNAL(triggered()), SLOT(_q_deleteSelected())); popup->addSeparator(); action = popup->addAction(QLineEdit::tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll)); - action->setEnabled(!d->text.isEmpty() && !d->allSelected()); + action->setEnabled(!d->control->text().isEmpty() && !d->control->allSelected()); d->selectAllAction = action; connect(action, SIGNAL(triggered()), SLOT(selectAll())); @@ -2720,9 +2003,9 @@ QMenu *QLineEdit::createStandardContextMenu() #endif #if defined(Q_WS_WIN) - if (!d->readOnly && qt_use_rtl_extensions) { + if (!d->control->isReadOnly() && qt_use_rtl_extensions) { #else - if (!d->readOnly) { + if (!d->control->isReadOnly()) { #endif popup->addSeparator(); QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, popup); @@ -2736,806 +2019,26 @@ QMenu *QLineEdit::createStandardContextMenu() void QLineEdit::changeEvent(QEvent *ev) { Q_D(QLineEdit); - if(ev->type() == QEvent::ActivationChange) { + switch(ev->type()) + { + case QEvent::ActivationChange: if (!palette().isEqual(QPalette::Active, QPalette::Inactive)) update(); - } else if (ev->type() == QEvent::FontChange - || ev->type() == QEvent::StyleChange - || ev->type() == QEvent::LayoutDirectionChange) { - d->updateTextLayout(); - } - QWidget::changeEvent(ev); -} - -void QLineEditPrivate::_q_handleWindowActivate() -{ - Q_Q(QLineEdit); - if (!q->hasFocus() && q->hasSelectedText()) - q->deselect(); -} - -void QLineEditPrivate::_q_deleteSelected() -{ - Q_Q(QLineEdit); - if (!hasSelectedText()) - return; - - int priorState = undoState; - q->resetInputContext(); - removeSelectedText(); - separate(); - finishChange(priorState); -} - -void QLineEditPrivate::init(const QString& txt) -{ - Q_Q(QLineEdit); -#ifndef QT_NO_CURSOR - q->setCursor(Qt::IBeamCursor); -#endif - q->setFocusPolicy(Qt::StrongFocus); - q->setAttribute(Qt::WA_InputMethodEnabled); - // Specifies that this widget can use more, but is able to survive on - // less, horizontal space; and is fixed vertically. - q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::LineEdit)); - q->setBackgroundRole(QPalette::Base); - q->setAttribute(Qt::WA_KeyCompression); - q->setMouseTracking(true); - q->setAcceptDrops(true); - text = txt; - updateTextLayout(); - cursor = text.length(); - - q->setAttribute(Qt::WA_MacShowFocusRect); -} - -void QLineEditPrivate::updatePasswordEchoEditing(bool editing) -{ - Q_Q(QLineEdit); - passwordEchoEditing = editing; - q->setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(q)); - updateTextLayout(); - q->update(); -} - -void QLineEditPrivate::updateTextLayout() -{ - // replace certain non-printable characters with spaces (to avoid - // drawing boxes when using fonts that don't have glyphs for such - // characters) - Q_Q(QLineEdit); - QString str = q->displayText(); - QChar* uc = str.data(); - for (int i = 0; i < (int)str.length(); ++i) { - if ((uc[i] < 0x20 && uc[i] != 0x09) - || uc[i] == QChar::LineSeparator - || uc[i] == QChar::ParagraphSeparator - || uc[i] == QChar::ObjectReplacementCharacter) - uc[i] = QChar(0x0020); - } - textLayout.setFont(q->font()); - textLayout.setText(str); - QTextOption option; - option.setTextDirection(q->layoutDirection()); - option.setFlags(QTextOption::IncludeTrailingSpaces); - textLayout.setTextOption(option); - - textLayout.beginLayout(); - QTextLine l = textLayout.createLine(); - textLayout.endLayout(); - ascent = qRound(l.ascent()); -} - -int QLineEditPrivate::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const -{ - QRect cr = adjustedContentsRect(); - x-= cr.x() - hscroll + horizontalMargin; - QTextLine l = textLayout.lineAt(0); - return l.xToCursor(x, betweenOrOn); -} - -QRect QLineEditPrivate::cursorRect() const -{ - Q_Q(const QLineEdit); - QRect cr = adjustedContentsRect(); - int cix = cr.x() - hscroll + horizontalMargin; - QTextLine l = textLayout.lineAt(0); - int c = cursor; - if (preeditCursor != -1) - c += preeditCursor; - cix += qRound(l.cursorToX(c)); - int ch = qMin(cr.height(), q->fontMetrics().height() + 1); - int w = q->style()->pixelMetric(QStyle::PM_TextCursorWidth); - return QRect(cix-5, vscroll, w + 9, ch); -} - -QRect QLineEditPrivate::adjustedContentsRect() const -{ - Q_Q(const QLineEdit); - QStyleOptionFrameV2 opt; - q->initStyleOption(&opt); - QRect r = q->style()->subElementRect(QStyle::SE_LineEditContents, &opt, q); - r.setX(r.x() + leftTextMargin); - r.setY(r.y() + topTextMargin); - r.setRight(r.right() - rightTextMargin); - r.setBottom(r.bottom() - bottomTextMargin); - return r; -} - -bool QLineEditPrivate::fixup() // this function assumes that validate currently returns != Acceptable -{ -#ifndef QT_NO_VALIDATOR - if (validator) { - QString textCopy = text; - int cursorCopy = cursor; - validator->fixup(textCopy); - if (validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) { - if (textCopy != text || cursorCopy != cursor) - setText(textCopy, cursorCopy); - return true; - } - } -#endif - return false; -} - -void QLineEditPrivate::moveCursor(int pos, bool mark) -{ - Q_Q(QLineEdit); - if (pos != cursor) { - separate(); - if (maskData) - pos = pos > cursor ? nextMaskBlank(pos) : prevMaskBlank(pos); - } - bool fullUpdate = mark || hasSelectedText(); - if (mark) { - int anchor; - if (selend > selstart && cursor == selstart) - anchor = selend; - else if (selend > selstart && cursor == selend) - anchor = selstart; - else - anchor = cursor; - selstart = qMin(anchor, pos); - selend = qMax(anchor, pos); - updateTextLayout(); - } else { - deselect(); - } - if (fullUpdate) { - cursor = pos; - q->update(); - } else { - setCursorVisible(false); - cursor = pos; - setCursorVisible(true); - if (!adjustedContentsRect().contains(cursorRect())) - q->update(); - } - QStyleOptionFrameV2 opt; - q->initStyleOption(&opt); - if (mark && !q->style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, q)) - setCursorVisible(false); - if (mark || selDirty) { - selDirty = false; - emit q->selectionChanged(); - } - emitCursorPositionChanged(); -} - -void QLineEditPrivate::finishChange(int validateFromState, bool update, bool edited) -{ - Q_Q(QLineEdit); - bool lineDirty = selDirty; - if (textDirty) { - // do validation - bool wasValidInput = validInput; - validInput = true; -#ifndef QT_NO_VALIDATOR - if (validator) { - validInput = false; - QString textCopy = text; - int cursorCopy = cursor; - validInput = (validator->validate(textCopy, cursorCopy) != QValidator::Invalid); - if (validInput) { - if (text != textCopy) { - setText(textCopy, cursorCopy); - return; - } - cursor = cursorCopy; - } - } -#endif - if (validateFromState >= 0 && wasValidInput && !validInput) { - undo(validateFromState); - history.resize(undoState); - if (modifiedState > undoState) - modifiedState = -1; - validInput = true; - textDirty = false; - } - updateTextLayout(); - lineDirty |= textDirty; - if (textDirty) { - textDirty = false; - QString actualText = maskData ? stripString(text) : text; - if (edited) - emit q->textEdited(actualText); - q->updateMicroFocus(); -#ifndef QT_NO_COMPLETER - if (edited && completer && completer->completionMode() != QCompleter::InlineCompletion) - complete(-1); // update the popup on cut/paste/del -#endif - emit q->textChanged(actualText); - } -#ifndef QT_NO_ACCESSIBILITY - QAccessible::updateAccessibility(q, 0, QAccessible::ValueChanged); -#endif - } - if (selDirty) { - selDirty = false; - emit q->selectionChanged(); - } - if (lineDirty || update) - q->update(); - emitCursorPositionChanged(); -} - -void QLineEditPrivate::emitCursorPositionChanged() -{ - Q_Q(QLineEdit); - if (cursor != lastCursorPos) { - const int oldLast = lastCursorPos; - lastCursorPos = cursor; - emit q->cursorPositionChanged(oldLast, cursor); - } -} - -void QLineEditPrivate::setText(const QString& txt, int pos, bool edited) -{ - Q_Q(QLineEdit); - q->resetInputContext(); - deselect(); - QString oldText = text; - if (maskData) { - text = maskString(0, txt, true); - text += clearString(text.length(), maxLength - text.length()); - } else { - text = txt.isEmpty() ? txt : txt.left(maxLength); - } - history.clear(); - modifiedState = undoState = 0; - cursor = (pos < 0 || pos > text.length()) ? text.length() : pos; - textDirty = (oldText != text); - finishChange(-1, true, edited); -} - - -void QLineEditPrivate::setCursorVisible(bool visible) -{ - Q_Q(QLineEdit); - if ((bool)cursorVisible == visible) - return; - if (cursorTimer) - cursorVisible = visible; - QRect r = cursorRect(); - if (maskData) - q->update(); - else - q->update(r); -} - -void QLineEditPrivate::addCommand(const Command& cmd) -{ - if (separator && undoState && history[undoState-1].type != Separator) { - history.resize(undoState + 2); - history[undoState++] = Command(Separator, cursor, 0, selstart, selend); - } else { - history.resize(undoState + 1); - } - separator = false; - history[undoState++] = cmd; -} - -void QLineEditPrivate::insert(const QString& s) -{ - if (hasSelectedText()) - addCommand(Command(SetSelection, cursor, 0, selstart, selend)); - if (maskData) { - QString ms = maskString(cursor, s); - for (int i = 0; i < (int) ms.length(); ++i) { - addCommand (Command(DeleteSelection, cursor+i, text.at(cursor+i), -1, -1)); - addCommand(Command(Insert, cursor+i, ms.at(i), -1, -1)); - } - text.replace(cursor, ms.length(), ms); - cursor += ms.length(); - cursor = nextMaskBlank(cursor); - textDirty = true; - } else { - int remaining = maxLength - text.length(); - if (remaining != 0) { - text.insert(cursor, s.left(remaining)); - for (int i = 0; i < (int) s.left(remaining).length(); ++i) - addCommand(Command(Insert, cursor++, s.at(i), -1, -1)); - textDirty = true; - } - } -} - -void QLineEditPrivate::del(bool wasBackspace) -{ - if (cursor < (int) text.length()) { - if (hasSelectedText()) - addCommand(Command(SetSelection, cursor, 0, selstart, selend)); - addCommand (Command((CommandType)((maskData?2:0)+(wasBackspace?Remove:Delete)), cursor, text.at(cursor), -1, -1)); - if (maskData) { - text.replace(cursor, 1, clearString(cursor, 1)); - addCommand(Command(Insert, cursor, text.at(cursor), -1, -1)); - } else { - text.remove(cursor, 1); - } - textDirty = true; - } -} - -void QLineEditPrivate::removeSelectedText() -{ - if (selstart < selend && selend <= (int) text.length()) { - separate(); - int i ; - addCommand(Command(SetSelection, cursor, 0, selstart, selend)); - if (selstart <= cursor && cursor < selend) { - // cursor is within the selection. Split up the commands - // to be able to restore the correct cursor position - for (i = cursor; i >= selstart; --i) - addCommand (Command(DeleteSelection, i, text.at(i), -1, 1)); - for (i = selend - 1; i > cursor; --i) - addCommand (Command(DeleteSelection, i - cursor + selstart - 1, text.at(i), -1, -1)); - } else { - for (i = selend-1; i >= selstart; --i) - addCommand (Command(RemoveSelection, i, text.at(i), -1, -1)); - } - if (maskData) { - text.replace(selstart, selend - selstart, clearString(selstart, selend - selstart)); - for (int i = 0; i < selend - selstart; ++i) - addCommand(Command(Insert, selstart + i, text.at(selstart + i), -1, -1)); - } else { - text.remove(selstart, selend - selstart); - } - if (cursor > selstart) - cursor -= qMin(cursor, selend) - selstart; - deselect(); - textDirty = true; - - // adjust hscroll to avoid gap - const int minRB = qMax(0, -q_func()->fontMetrics().minRightBearing()); - updateTextLayout(); - const QTextLine line = textLayout.lineAt(0); - const int widthUsed = qRound(line.naturalTextWidth()) + 1 + minRB; - hscroll = qMin(hscroll, widthUsed); - } -} - -void QLineEditPrivate::parseInputMask(const QString &maskFields) -{ - int delimiter = maskFields.indexOf(QLatin1Char(';')); - if (maskFields.isEmpty() || delimiter == 0) { - if (maskData) { - delete [] maskData; - maskData = 0; - maxLength = 32767; - setText(QString()); - } - return; - } - - if (delimiter == -1) { - blank = QLatin1Char(' '); - inputMask = maskFields; - } else { - inputMask = maskFields.left(delimiter); - blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' '); - } - - // calculate maxLength / maskData length - maxLength = 0; - QChar c = 0; - for (int i=0; i<inputMask.length(); i++) { - c = inputMask.at(i); - if (i > 0 && inputMask.at(i-1) == QLatin1Char('\\')) { - maxLength++; - continue; - } - if (c != QLatin1Char('\\') && c != QLatin1Char('!') && - c != QLatin1Char('<') && c != QLatin1Char('>') && - c != QLatin1Char('{') && c != QLatin1Char('}') && - c != QLatin1Char('[') && c != QLatin1Char(']')) - maxLength++; - } - - delete [] maskData; - maskData = new MaskInputData[maxLength]; - - MaskInputData::Casemode m = MaskInputData::NoCaseMode; - c = 0; - bool s; - bool escape = false; - int index = 0; - for (int i = 0; i < inputMask.length(); i++) { - c = inputMask.at(i); - if (escape) { - s = true; - maskData[index].maskChar = c; - maskData[index].separator = s; - maskData[index].caseMode = m; - index++; - escape = false; - } else if (c == QLatin1Char('<')) { - m = MaskInputData::Lower; - } else if (c == QLatin1Char('>')) { - m = MaskInputData::Upper; - } else if (c == QLatin1Char('!')) { - m = MaskInputData::NoCaseMode; - } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) { - switch (c.unicode()) { - case 'A': - case 'a': - case 'N': - case 'n': - case 'X': - case 'x': - case '9': - case '0': - case 'D': - case 'd': - case '#': - case 'H': - case 'h': - case 'B': - case 'b': - s = false; - break; - case '\\': - escape = true; - default: - s = true; - break; - } - - if (!escape) { - maskData[index].maskChar = c; - maskData[index].separator = s; - maskData[index].caseMode = m; - index++; - } - } - } - setText(text); -} - - -/* checks if the key is valid compared to the inputMask */ -bool QLineEditPrivate::isValidInput(QChar key, QChar mask) const -{ - switch (mask.unicode()) { - case 'A': - if (key.isLetter()) - return true; break; - case 'a': - if (key.isLetter() || key == blank) - return true; + case QEvent::FontChange: + d->control->setFont(font()); break; - case 'N': - if (key.isLetterOrNumber()) - return true; - break; - case 'n': - if (key.isLetterOrNumber() || key == blank) - return true; - break; - case 'X': - if (key.isPrint()) - return true; - break; - case 'x': - if (key.isPrint() || key == blank) - return true; - break; - case '9': - if (key.isNumber()) - return true; - break; - case '0': - if (key.isNumber() || key == blank) - return true; - break; - case 'D': - if (key.isNumber() && key.digitValue() > 0) - return true; - break; - case 'd': - if ((key.isNumber() && key.digitValue() > 0) || key == blank) - return true; - break; - case '#': - if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == blank) - return true; - break; - case 'B': - if (key == QLatin1Char('0') || key == QLatin1Char('1')) - return true; - break; - case 'b': - if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == blank) - return true; - break; - case 'H': - if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F'))) - return true; + case QEvent::StyleChange: + d->control->setPasswordCharacter(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter)); + update(); break; - case 'h': - if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == blank) - return true; + case QEvent::LayoutDirectionChange: + d->control->setLayoutDirection(layoutDirection()); break; default: break; } - return false; -} - -bool QLineEditPrivate::hasAcceptableInput(const QString &str) const -{ -#ifndef QT_NO_VALIDATOR - QString textCopy = str; - int cursorCopy = cursor; - if (validator && validator->validate(textCopy, cursorCopy) - != QValidator::Acceptable) - return false; -#endif - - if (!maskData) - return true; - - if (str.length() != maxLength) - return false; - - for (int i=0; i < maxLength; ++i) { - if (maskData[i].separator) { - if (str.at(i) != maskData[i].maskChar) - return false; - } else { - if (!isValidInput(str.at(i), maskData[i].maskChar)) - return false; - } - } - return true; -} - -/* - Applies the inputMask on \a str starting from position \a pos in the mask. \a clear - specifies from where characters should be gotten when a separator is met in \a str - true means - that blanks will be used, false that previous input is used. - Calling this when no inputMask is set is undefined. -*/ -QString QLineEditPrivate::maskString(uint pos, const QString &str, bool clear) const -{ - if (pos >= (uint)maxLength) - return QString::fromLatin1(""); - - QString fill; - fill = clear ? clearString(0, maxLength) : text; - - int strIndex = 0; - QString s = QString::fromLatin1(""); - int i = pos; - while (i < maxLength) { - if (strIndex < str.length()) { - if (maskData[i].separator) { - s += maskData[i].maskChar; - if (str[(int)strIndex] == maskData[i].maskChar) - strIndex++; - ++i; - } else { - if (isValidInput(str[(int)strIndex], maskData[i].maskChar)) { - switch (maskData[i].caseMode) { - case MaskInputData::Upper: - s += str[(int)strIndex].toUpper(); - break; - case MaskInputData::Lower: - s += str[(int)strIndex].toLower(); - break; - default: - s += str[(int)strIndex]; - } - ++i; - } else { - // search for separator first - int n = findInMask(i, true, true, str[(int)strIndex]); - if (n != -1) { - if (str.length() != 1 || i == 0 || (i > 0 && (!maskData[i-1].separator || maskData[i-1].maskChar != str[(int)strIndex]))) { - s += fill.mid(i, n-i+1); - i = n + 1; // update i to find + 1 - } - } else { - // search for valid blank if not - n = findInMask(i, true, false, str[(int)strIndex]); - if (n != -1) { - s += fill.mid(i, n-i); - switch (maskData[n].caseMode) { - case MaskInputData::Upper: - s += str[(int)strIndex].toUpper(); - break; - case MaskInputData::Lower: - s += str[(int)strIndex].toLower(); - break; - default: - s += str[(int)strIndex]; - } - i = n + 1; // updates i to find + 1 - } - } - } - strIndex++; - } - } else - break; - } - - return s; -} - - - -/* - Returns a "cleared" string with only separators and blank chars. - Calling this when no inputMask is set is undefined. -*/ -QString QLineEditPrivate::clearString(uint pos, uint len) const -{ - if (pos >= (uint)maxLength) - return QString(); - - QString s; - int end = qMin((uint)maxLength, pos + len); - for (int i=pos; i<end; i++) - if (maskData[i].separator) - s += maskData[i].maskChar; - else - s += blank; - - return s; -} - -/* - Strips blank parts of the input in a QLineEdit when an inputMask is set, - separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1". -*/ -QString QLineEditPrivate::stripString(const QString &str) const -{ - if (!maskData) - return str; - - QString s; - int end = qMin(maxLength, (int)str.length()); - for (int i=0; i < end; i++) - if (maskData[i].separator) - s += maskData[i].maskChar; - else - if (str[i] != blank) - s += str[i]; - - return s; -} - -/* searches forward/backward in maskData for either a separator or a blank */ -int QLineEditPrivate::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const -{ - if (pos >= maxLength || pos < 0) - return -1; - - int end = forward ? maxLength : -1; - int step = forward ? 1 : -1; - int i = pos; - - while (i != end) { - if (findSeparator) { - if (maskData[i].separator && maskData[i].maskChar == searchChar) - return i; - } else { - if (!maskData[i].separator) { - if (searchChar.isNull()) - return i; - else if (isValidInput(searchChar, maskData[i].maskChar)) - return i; - } - } - i += step; - } - return -1; -} - -void QLineEditPrivate::undo(int until) -{ - if (!isUndoAvailable()) - return; - deselect(); - while (undoState && undoState > until) { - Command& cmd = history[--undoState]; - switch (cmd.type) { - case Insert: - text.remove(cmd.pos, 1); - cursor = cmd.pos; - break; - case SetSelection: - selstart = cmd.selStart; - selend = cmd.selEnd; - cursor = cmd.pos; - break; - case Remove: - case RemoveSelection: - text.insert(cmd.pos, cmd.uc); - cursor = cmd.pos + 1; - break; - case Delete: - case DeleteSelection: - text.insert(cmd.pos, cmd.uc); - cursor = cmd.pos; - break; - case Separator: - continue; - } - if (until < 0 && undoState) { - Command& next = history[undoState-1]; - if (next.type != cmd.type && next.type < RemoveSelection - && (cmd.type < RemoveSelection || next.type == Separator)) - break; - } - } - textDirty = true; - emitCursorPositionChanged(); -} - -void QLineEditPrivate::redo() { - if (!isRedoAvailable()) - return; - deselect(); - while (undoState < (int)history.size()) { - Command& cmd = history[undoState++]; - switch (cmd.type) { - case Insert: - text.insert(cmd.pos, cmd.uc); - cursor = cmd.pos + 1; - break; - case SetSelection: - selstart = cmd.selStart; - selend = cmd.selEnd; - cursor = cmd.pos; - break; - case Remove: - case Delete: - case RemoveSelection: - case DeleteSelection: - text.remove(cmd.pos, 1); - selstart = cmd.selStart; - selend = cmd.selEnd; - cursor = cmd.pos; - break; - case Separator: - selstart = cmd.selStart; - selend = cmd.selEnd; - cursor = cmd.pos; - break; - } - if (undoState < (int)history.size()) { - Command& next = history[undoState]; - if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator - && (next.type < RemoveSelection || cmd.type == Separator)) - break; - } - } - textDirty = true; - emitCursorPositionChanged(); + QWidget::changeEvent(ev); } /*! diff --git a/src/gui/widgets/qlineedit.h b/src/gui/widgets/qlineedit.h index a97dc9a..32ef6a4 100644 --- a/src/gui/widgets/qlineedit.h +++ b/src/gui/widgets/qlineedit.h @@ -268,9 +268,14 @@ private: Q_DECLARE_PRIVATE(QLineEdit) Q_PRIVATE_SLOT(d_func(), void _q_handleWindowActivate()) Q_PRIVATE_SLOT(d_func(), void _q_deleteSelected()) + Q_PRIVATE_SLOT(d_func(), void _q_textEdited(const QString &)) + Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged(int, int)) #ifndef QT_NO_COMPLETER Q_PRIVATE_SLOT(d_func(), void _q_completionHighlighted(QString)) #endif +#ifdef QT_KEYPAD_NAVIGATION + Q_PRIVATE_SLOT(d_func(), void _q_editFocusChange(bool)) +#endif }; #endif // QT_NO_LINEEDIT diff --git a/src/gui/widgets/qlineedit_p.cpp b/src/gui/widgets/qlineedit_p.cpp new file mode 100644 index 0000000..d907233 --- /dev/null +++ b/src/gui/widgets/qlineedit_p.cpp @@ -0,0 +1,268 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://www.qtsoftware.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qlineedit.h" +#include "qlineedit_p.h" + +#ifndef QT_NO_LINEEDIT + +#include "qabstractitemview.h" +#include "qclipboard.h" +#ifndef QT_NO_ACCESSIBILITY +#include "qaccessible.h" +#endif +#ifndef QT_NO_IM +#include "qinputcontext.h" +#include "qlist.h" +#endif + +QT_BEGIN_NAMESPACE + +const int QLineEditPrivate::verticalMargin(1); +const int QLineEditPrivate::horizontalMargin(2); + +int QLineEditPrivate::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const +{ + QRect cr = adjustedContentsRect(); + x-= cr.x() - hscroll + horizontalMargin; + return control->xToPos(x, betweenOrOn); +} + +QRect QLineEditPrivate::cursorRect() const +{ + QRect cr = adjustedContentsRect(); + int cix = cr.x() - hscroll + horizontalMargin; + QRect crect = control->cursorRect(); + crect.moveTo(crect.topLeft() + QPoint(cix, vscroll)); + return crect; +} + +#ifndef QT_NO_COMPLETER + +void QLineEditPrivate::_q_completionHighlighted(QString newText) +{ + Q_Q(QLineEdit); + if (control->completer()->completionMode() != QCompleter::InlineCompletion) { + q->setText(newText); + } else { + int c = control->cursor(); + QString text = control->text(); + q->setText(text.left(c) + newText.mid(c)); + control->moveCursor(control->end(), false); + control->moveCursor(c, true); + } +} + +#endif // QT_NO_COMPLETER + +void QLineEditPrivate::_q_clipboardChanged() +{ +} + +void QLineEditPrivate::_q_handleWindowActivate() +{ + Q_Q(QLineEdit); + if (!q->hasFocus() && control->hasSelectedText()) + control->deselect(); +} + +void QLineEditPrivate::_q_deleteSelected() +{ +} + +void QLineEditPrivate::_q_textEdited(const QString &text) +{ + Q_Q(QLineEdit); +#ifndef QT_NO_COMPLETER + if (control->completer() && + control->completer()->completionMode() != QCompleter::InlineCompletion) + control->complete(-1); // update the popup on cut/paste/del +#endif + emit q->textEdited(text); +} + +void QLineEditPrivate::_q_cursorPositionChanged(int from, int to) +{ + Q_Q(QLineEdit); + q->update(); + emit q->cursorPositionChanged(from, to); +} + +#ifdef QT_KEYPAD_NAVIGATION +void QLineEditPrivate::_q_editFocusChange(bool e) +{ + Q_Q(QLineEdit); + q->setEditFocus(e); +} +#endif + +void QLineEditPrivate::init(const QString& txt) +{ + Q_Q(QLineEdit); + control = new QLineControl(txt); + QObject::connect(control, SIGNAL(textChanged(const QString &)), + q, SIGNAL(textChanged(const QString &))); + QObject::connect(control, SIGNAL(textEdited(const QString &)), + q, SLOT(_q_textEdited(const QString &))); + QObject::connect(control, SIGNAL(cursorPositionChanged(int, int)), + q, SLOT(_q_cursorPositionChanged(int, int))); + QObject::connect(control, SIGNAL(selectionChanged()), + q, SIGNAL(selectionChanged())); + QObject::connect(control, SIGNAL(accepted()), + q, SIGNAL(returnPressed())); + QObject::connect(control, SIGNAL(editingFinished()), + q, SIGNAL(editingFinished())); +#ifdef QT_KEYPAD_NAVIGATION + QObject::connect(control, SIGNAL(editFocusChange(bool)), + q, SLOT(_q_editFocusChange(bool))); +#endif + + // for now, going completely overboard with updates. + QObject::connect(control, SIGNAL(selectionChanged()), + q, SLOT(update())); + + QObject::connect(control, SIGNAL(displayTextChanged(const QString &)), + q, SLOT(update())); + + QObject::connect(control, SIGNAL(updateNeeded(const QRect &)), + q, SLOT(update())); + control->setPasswordCharacter(q->style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter)); +#ifndef QT_NO_CURSOR + q->setCursor(Qt::IBeamCursor); +#endif + q->setFocusPolicy(Qt::StrongFocus); + q->setAttribute(Qt::WA_InputMethodEnabled); + // Specifies that this widget can use more, but is able to survive on + // less, horizontal space; and is fixed vertically. + q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::LineEdit)); + q->setBackgroundRole(QPalette::Base); + q->setAttribute(Qt::WA_KeyCompression); + q->setMouseTracking(true); + q->setAcceptDrops(true); + + q->setAttribute(Qt::WA_MacShowFocusRect); +} + +QRect QLineEditPrivate::adjustedContentsRect() const +{ + Q_Q(const QLineEdit); + QStyleOptionFrameV2 opt; + q->initStyleOption(&opt); + QRect r = q->style()->subElementRect(QStyle::SE_LineEditContents, &opt, q); + r.setX(r.x() + leftTextMargin); + r.setY(r.y() + topTextMargin); + r.setRight(r.right() - rightTextMargin); + r.setBottom(r.bottom() - bottomTextMargin); + return r; +} + +void QLineEditPrivate::setCursorVisible(bool visible) +{ + Q_Q(QLineEdit); + if ((bool)cursorVisible == visible) + return; + cursorVisible = visible; + QRect r = cursorRect(); + if (control->inputMask().isEmpty()) + q->update(r); + else + q->update(); +} + +void QLineEditPrivate::updatePasswordEchoEditing(bool editing) +{ + Q_Q(QLineEdit); + control->updatePasswordEchoEditing(editing); + q->setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod()); +} + +/*! + This function is not intended as polymorphic usage. Just a shared code + fragment that calls QInputContext::mouseHandler for this + class. +*/ +bool QLineEditPrivate::sendMouseEventToInputContext( QMouseEvent *e ) +{ +#if !defined QT_NO_IM + Q_Q(QLineEdit); + if ( control->composeMode() ) { + int tmp_cursor = xToPos(e->pos().x()); + int mousePos = tmp_cursor - control->cursor(); + if ( mousePos < 0 || mousePos > control->preeditAreaText().length() ) { + mousePos = -1; + // don't send move events outside the preedit area + if ( e->type() == QEvent::MouseMove ) + return true; + } + + QInputContext *qic = q->inputContext(); + if ( qic ) + // may be causing reset() in some input methods + qic->mouseHandler(mousePos, e); + if (!control->preeditAreaText().isEmpty()) + return true; + } +#else + Q_UNUSED(e); +#endif + + return false; +} + +#ifndef QT_NO_DRAGANDDROP +void QLineEditPrivate::drag() +{ + Q_Q(QLineEdit); + dndTimer.stop(); + QMimeData *data = new QMimeData; + data->setText(control->selectedText()); + QDrag *drag = new QDrag(q); + drag->setMimeData(data); + Qt::DropAction action = drag->start(); + if (action == Qt::MoveAction && !control->isReadOnly() && drag->target() != q) + control->removeSelection(); +} + +#endif // QT_NO_DRAGANDDROP + +QT_END_NAMESPACE + +#endif diff --git a/src/gui/widgets/qlineedit_p.h b/src/gui/widgets/qlineedit_p.h index 7a4ff26..976e31f 100644 --- a/src/gui/widgets/qlineedit_p.h +++ b/src/gui/widgets/qlineedit_p.h @@ -65,6 +65,8 @@ #include "QtCore/qpointer.h" #include "QtGui/qlineedit.h" +#include "private/qlinecontrol_p.h" + QT_BEGIN_NAMESPACE class QLineEditPrivate : public QWidgetPrivate @@ -73,167 +75,67 @@ class QLineEditPrivate : public QWidgetPrivate public: QLineEditPrivate() - : cursor(0), preeditCursor(0), cursorTimer(0), frame(1), - cursorVisible(0), hideCursor(false), separator(0), readOnly(0), - dragEnabled(0), contextMenuEnabled(1), echoMode(0), textDirty(0), - selDirty(0), validInput(1), alignment(Qt::AlignLeading | Qt::AlignVCenter), ascent(0), - maxLength(32767), hscroll(0), vscroll(0), lastCursorPos(-1), maskData(0), - modifiedState(0), undoState(0), selstart(0), selend(0), userInput(false), - emitingEditingFinished(false), passwordEchoEditing(false) -#ifndef QT_NO_COMPLETER - , completer(0) -#endif - , leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0) - { - } + : control(0), frame(1), contextMenuEnabled(1), cursorVisible(0), + dragEnabled(0), hscroll(0), vscroll(0), + alignment(Qt::AlignLeading | Qt::AlignVCenter), + leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0) + { + } ~QLineEditPrivate() { - delete [] maskData; } + + QLineControl *control; + +#ifndef QT_NO_CONTEXTMENU + QPointer<QAction> selectAllAction; +#endif void init(const QString&); - QString text; - int cursor; - int preeditCursor; - int cursorTimer; // -1 for non blinking cursor. + int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; + QRect cursorRect() const; + void setCursorVisible(bool visible); + + void updatePasswordEchoEditing(bool); + + inline bool shouldEnableInputMethod() const + { + return !control->isReadOnly() && (control->echoMode() == QLineEdit::Normal || control->echoMode() == QLineEdit::PasswordEchoOnEdit); + } + QPoint tripleClick; QBasicTimer tripleClickTimer; uint frame : 1; + uint contextMenuEnabled : 1; uint cursorVisible : 1; - uint hideCursor : 1; // used to hide the cursor inside preedit areas - uint separator : 1; - uint readOnly : 1; uint dragEnabled : 1; - uint contextMenuEnabled : 1; - uint echoMode : 2; - uint textDirty : 1; - uint selDirty : 1; - uint validInput : 1; - uint alignment; - int ascent; - int maxLength; int hscroll; int vscroll; - int lastCursorPos; - -#ifndef QT_NO_CONTEXTMENU - QPointer<QAction> selectAllAction; -#endif + uint alignment; + static const int verticalMargin; + static const int horizontalMargin; - inline void emitCursorPositionChanged(); bool sendMouseEventToInputContext(QMouseEvent *e); - void finishChange(int validateFromState = -1, bool update = false, bool edited = true); - - QPointer<QValidator> validator; - struct MaskInputData { - enum Casemode { NoCaseMode, Upper, Lower }; - QChar maskChar; // either the separator char or the inputmask - bool separator; - Casemode caseMode; - }; - QString inputMask; - QChar blank; - MaskInputData *maskData; - inline int nextMaskBlank(int pos) { - int c = findInMask(pos, true, false); - separator |= (c != pos); - return (c != -1 ? c : maxLength); - } - inline int prevMaskBlank(int pos) { - int c = findInMask(pos, false, false); - separator |= (c != pos); - return (c != -1 ? c : 0); - } - - void setCursorVisible(bool visible); - - - // undo/redo handling - enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection }; - struct Command { - inline Command() {} - inline Command(CommandType t, int p, QChar c, int ss, int se) : type(t),uc(c),pos(p),selStart(ss),selEnd(se) {} - uint type : 4; - QChar uc; - int pos, selStart, selEnd; - }; - int modifiedState; - int undoState; - QVector<Command> history; - void addCommand(const Command& cmd); - void insert(const QString& s); - void del(bool wasBackspace = false); - void remove(int pos); - - inline void separate() { separator = true; } - void undo(int until = -1); - void redo(); - inline bool isUndoAvailable() const { return !readOnly && undoState; } - inline bool isRedoAvailable() const { return !readOnly && undoState < (int)history.size(); } - - // selection - int selstart, selend; - inline bool allSelected() const { return !text.isEmpty() && selstart == 0 && selend == (int)text.length(); } - inline bool hasSelectedText() const { return !text.isEmpty() && selend > selstart; } - inline void deselect() { selDirty |= (selend > selstart); selstart = selend = 0; } - void removeSelectedText(); -#ifndef QT_NO_CLIPBOARD - void copy(bool clipboard = true) const; -#endif - inline bool inSelection(int x) const - { if (selstart >= selend) return false; - int pos = xToPos(x, QTextLine::CursorOnCharacter); return pos >= selstart && pos < selend; } - - // masking - void parseInputMask(const QString &maskFields); - bool isValidInput(QChar key, QChar mask) const; - bool hasAcceptableInput(const QString &text) const; - QString maskString(uint pos, const QString &str, bool clear = false) const; - QString clearString(uint pos, uint len) const; - QString stripString(const QString &str) const; - int findInMask(int pos, bool forward, bool findSeparator, QChar searchChar = QChar()) const; - - // input methods - bool composeMode() const { return !textLayout.preeditAreaText().isEmpty(); } - - // complex text layout - QTextLayout textLayout; - void updateTextLayout(); - void moveCursor(int pos, bool mark = false); - void setText(const QString& txt, int pos = -1, bool edited = true); - int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; - QRect cursorRect() const; - bool fixup(); - QRect adjustedContentsRect() const; -#ifndef QT_NO_DRAGANDDROP - // drag and drop - QPoint dndPos; - QBasicTimer dndTimer; - void drag(); -#endif - + void _q_clipboardChanged(); void _q_handleWindowActivate(); void _q_deleteSelected(); - bool userInput; - bool emitingEditingFinished; - + void _q_textEdited(const QString &); + void _q_cursorPositionChanged(int, int); #ifdef QT_KEYPAD_NAVIGATION - QBasicTimer deleteAllTimer; // keypad navigation - QString origText; + void _q_editFocusChange(bool); #endif - bool passwordEchoEditing; - void updatePasswordEchoEditing(bool editing); - #ifndef QT_NO_COMPLETER - QPointer<QCompleter> completer; - void complete(int key = -1); void _q_completionHighlighted(QString); - bool advanceToEnabledItem(int n); +#endif +#ifndef QT_NO_DRAGANDDROP + QPoint dndPos; + QBasicTimer dndTimer; + void drag(); #endif int leftTextMargin; diff --git a/src/gui/widgets/qmainwindowlayout.cpp b/src/gui/widgets/qmainwindowlayout.cpp index 3936a67..55afa70 100644 --- a/src/gui/widgets/qmainwindowlayout.cpp +++ b/src/gui/widgets/qmainwindowlayout.cpp @@ -1988,6 +1988,9 @@ void QMainWindowLayout::timerEvent(QTimerEvent *e) if (movingSeparatorOrigin == movingSeparatorPos) return; + //when moving the separator, we need to update the previous position + parentWidget()->update(layoutState.dockAreaLayout.separatorRegion()); + layoutState = savedState; layoutState.dockAreaLayout.separatorMove(movingSeparator, movingSeparatorOrigin, movingSeparatorPos); diff --git a/src/gui/widgets/qmdisubwindow.cpp b/src/gui/widgets/qmdisubwindow.cpp index 24dea37..e8de957 100644 --- a/src/gui/widgets/qmdisubwindow.cpp +++ b/src/gui/widgets/qmdisubwindow.cpp @@ -1066,7 +1066,7 @@ void QMdiSubWindowPrivate::createSystemMenu() addToSystemMenu(CloseAction, QMdiSubWindow::tr("&Close"), SLOT(close())); actions[CloseAction]->setIcon(style->standardIcon(QStyle::SP_TitleBarCloseButton, 0, q)); #if !defined(QT_NO_SHORTCUT) - actions[CloseAction]->setShortcut(QKeySequence::Close); + actions[CloseAction]->setShortcuts(QKeySequence::Close); #endif updateActions(); } diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index 99f3880..ccf81f8 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -204,6 +204,8 @@ void QMenuPrivate::updateActionRects() const Q_Q(const QMenu); if (!itemsDirty) return; + + q->ensurePolished(); //let's reinitialize the buffer actionRects.resize(actions.count()); @@ -225,9 +227,17 @@ void QMenuPrivate::updateActionRects() const dh = popupGeometry(QApplication::desktop()->screenNumber(q)).height(), y = 0; QStyle *style = q->style(); - const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, 0, q), - vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, 0, q), - icone = style->pixelMetric(QStyle::PM_SmallIconSize, 0, q); + QStyleOption opt; + opt.init(q); + const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, &opt, q), + vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, &opt, q), + icone = style->pixelMetric(QStyle::PM_SmallIconSize, &opt, q); + const int fw = style->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, q); + const int deskFw = style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, &opt, q); + + const int sfcMargin = style->sizeFromContents(QStyle::CT_Menu, &opt, QApplication::globalStrut(), q).width() - QApplication::globalStrut().width(); + const int min_column_width = q->minimumWidth() - (sfcMargin + leftmargin + rightmargin + 2 * (fw + hmargin)); + const int tearoffHeight = tearoff ? style->pixelMetric(QStyle::PM_MenuTearoffHeight, &opt, q) : 0; //for compatability now - will have to refactor this away.. tabWidth = 0; @@ -300,10 +310,10 @@ void QMenuPrivate::updateActionRects() const if (!sz.isEmpty()) { - max_column_width = qMax(max_column_width, sz.width()); + max_column_width = qMax(min_column_width, qMax(max_column_width, sz.width())); //wrapping if (!scroll && - y+sz.height()+vmargin > dh - (style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { + y+sz.height()+vmargin > dh - (deskFw * 2)) { ncols++; y = vmargin; } @@ -316,10 +326,9 @@ void QMenuPrivate::updateActionRects() const max_column_width += tabWidth; //finally add in the tab width //calculate position - const int fw = style->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q); const int base_y = vmargin + fw + topmargin + (scroll ? scroll->scrollOffset : 0) + - (tearoff ? style->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, q) : 0); + tearoffHeight; int x = hmargin + fw + leftmargin; y = base_y; @@ -328,7 +337,7 @@ void QMenuPrivate::updateActionRects() const if (rect.isNull()) continue; if (!scroll && - y+rect.height() > dh - (style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { + y+rect.height() > dh - deskFw * 2) { x += max_column_width + hmargin; y = base_y; } @@ -1698,14 +1707,9 @@ QRect QMenu::actionGeometry(QAction *act) const QSize QMenu::sizeHint() const { Q_D(const QMenu); - ensurePolished(); d->updateActionRects(); QSize s; - QStyleOption opt(0); - opt.rect = rect(); - opt.palette = palette(); - opt.state = QStyle::State_None; for (int i = 0; i < d->actionRects.count(); ++i) { const QRect &rect = d->actionRects.at(i); if (rect.isNull()) @@ -1718,15 +1722,11 @@ QSize QMenu::sizeHint() const // Note that the action rects calculated above already include // the top and left margins, so we only need to add margins for // the bottom and right. - if (const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, this)) { - s.rwidth() += fw; - s.rheight() += fw; - } - - s.rwidth() += style()->pixelMetric(QStyle::PM_MenuHMargin, &opt, this); - s.rheight() += style()->pixelMetric(QStyle::PM_MenuVMargin, &opt, this); - - s += QSize(d->rightmargin, d->bottommargin); + QStyleOption opt(0); + opt.init(this); + const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, this); + s.rwidth() += style()->pixelMetric(QStyle::PM_MenuHMargin, &opt, this) + fw + d->rightmargin; + s.rheight() += style()->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) + fw + d->bottommargin; return style()->sizeFromContents(QStyle::CT_Menu, &opt, s.expandedTo(QApplication::globalStrut()), this); @@ -2721,7 +2721,7 @@ void QMenu::mouseMoveEvent(QMouseEvent *e) QAction *action = d->actionAt(e->pos()); if (!action) { - if (d->hasHadMouse && !rect().contains(e->pos())) + if (d->hasHadMouse) d->setCurrentAction(0); return; } else if(e->buttons()) { @@ -3013,12 +3013,19 @@ bool QMenu::separatorsCollapsible() const void QMenu::setSeparatorsCollapsible(bool collapse) { Q_D(QMenu); + if (d->collapsibleSeparators == collapse) + return; + d->collapsibleSeparators = collapse; d->itemsDirty = 1; if (isVisible()) { d->updateActionRects(); update(); } +#ifdef Q_WS_MAC + if (d->mac_menu) + d->syncSeparatorsCollapsible(collapse); +#endif } #ifdef QT3_SUPPORT diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm index 77e98c4..e6239f4 100644 --- a/src/gui/widgets/qmenu_mac.mm +++ b/src/gui/widgets/qmenu_mac.mm @@ -458,7 +458,8 @@ OSStatus qt_mac_menu_event(EventHandlerCallRef er, EventRef event, void *) int merged = 0; const QMenuPrivate::QMacMenuPrivate *mac_menu = qmenu->d_func()->mac_menu; - for(int i = 0; i < mac_menu->actionItems.size(); ++i) { + const int ActionItemsCount = mac_menu->actionItems.size(); + for(int i = 0; i < ActionItemsCount; ++i) { QMacMenuAction *action = mac_menu->actionItems.at(i); if (action->action->isSeparator()) { bool hide = false; @@ -972,7 +973,7 @@ void Q_GUI_EXPORT qt_mac_set_menubar_merge(bool b) { qt_mac_no_menubar_merge = ! /***************************************************************************** QMenu bindings *****************************************************************************/ -QMenuPrivate::QMacMenuPrivate::QMacMenuPrivate(QMenuPrivate *menu) : menu(0), qmenu(menu) +QMenuPrivate::QMacMenuPrivate::QMacMenuPrivate() : menu(0) { } @@ -1300,61 +1301,22 @@ QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action) #else int itemIndex = [menu indexOfItem:item]; Q_ASSERT(itemIndex != -1); - - // Separator handling: Menu items and separators can be added to a QMenu in - // any order (for example, add all the separators first and then "fill inn" - // the menu items). Create NSMenuItem seperatorItems for the Qt separators, - // and make sure that there are no double separators and no seprators - // at the top or bottom of the menu. - bool itemIsSeparator = action->action->isSeparator(); - bool previousItemIsSeparator = false; - if (itemIndex > 0) { - if ([[menu itemAtIndex : itemIndex - 1] isSeparatorItem]) - previousItemIsSeparator = true; - } - bool nexItemIsSeparator = false; - if (itemIndex > 0 && itemIndex < [menu numberOfItems] -1) { - if ([[menu itemAtIndex : itemIndex + 1] isSeparatorItem]) - nexItemIsSeparator = true; - } - bool itemIsAtBottomOfMenu = (itemIndex == [menu numberOfItems] - 1); - bool itemIsAtTopOfMenu = (itemIndex == 0); - - - if (itemIsSeparator) { - // Create separators items for actions that are now separators + if (action->action->isSeparator()) { action->menuItem = [NSMenuItem separatorItem]; [action->menuItem retain]; - - // Hide duplicate/top/bottom separators. - if (qmenu->collapsibleSeparators && (previousItemIsSeparator || itemIsAtBottomOfMenu || itemIsAtTopOfMenu)) { - [action->menuItem setHidden : true]; - } - [menu insertItem: action->menuItem atIndex:itemIndex]; [menu removeItem:item]; [item release]; item = action->menuItem; return; - } else { - // Create standard menu items for actions that are no longer separators - if ([item isSeparatorItem]) { - action->menuItem = createNSMenuItem(action->action->text()); - [menu insertItem:action->menuItem atIndex:itemIndex]; - [menu removeItem:item]; - [item release]; - item = action->menuItem; - } - - // Show separators that should now be visible since a non-separator - // item (the current item) was added. - if (previousItemIsSeparator) { - [[menu itemAtIndex : itemIndex - 1] setHidden : false]; - } else if (itemIsAtTopOfMenu && nexItemIsSeparator) { - [[menu itemAtIndex : itemIndex + 1] setHidden : false]; - } + } else if ([item isSeparatorItem]) { + // I'm no longer a separator... + action->menuItem = createNSMenuItem(action->action->text()); + [menu insertItem:action->menuItem atIndex:itemIndex]; + [menu removeItem:item]; + [item release]; + item = action->menuItem; } - #endif //find text (and accel) @@ -1376,8 +1338,9 @@ QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action) accel = qt_mac_menu_merge_accel(action); } } + // Show multiple key sequences as part of the menu text. if (accel.count() > 1) - text += QLatin1String(" (****)"); //just to denote a multi stroke shortcut + text += QLatin1String(" (") + accel.toString(QKeySequence::NativeText) + QLatin1String(")"); QString finalString = qt_mac_removeMnemonics(text); @@ -1459,14 +1422,15 @@ QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action) data.whichData |= kMenuItemDataCmdKey; data.whichData |= kMenuItemDataCmdKeyModifiers; data.whichData |= kMenuItemDataCmdKeyGlyph; - if (!accel.isEmpty()) { + if (accel.count() == 1) { qt_mac_get_accel(accel[0], (quint32*)&data.cmdKeyModifiers, (quint32*)&data.cmdKeyGlyph); if (data.cmdKeyGlyph == 0) data.cmdKey = (UniChar)accel[0]; } #else [item setSubmenu:0]; - if (!accel.isEmpty()) { + // No key equivalent set for multiple key QKeySequence. + if (accel.count() == 1) { [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)]; [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)]; } else { @@ -1538,7 +1502,7 @@ QMenuPrivate::macMenu(OSMenuRef merge) if (mac_menu && mac_menu->menu) return mac_menu->menu; if (!mac_menu) - mac_menu = new QMacMenuPrivate(this); + mac_menu = new QMacMenuPrivate; mac_menu->menu = qt_mac_create_menu(q); if (merge) { #ifndef QT_MAC_USE_COCOA @@ -1550,12 +1514,31 @@ QMenuPrivate::macMenu(OSMenuRef merge) QList<QAction*> items = q->actions(); for(int i = 0; i < items.count(); i++) mac_menu->addAction(items[i], 0, this); + syncSeparatorsCollapsible(collapsibleSeparators); return mac_menu->menu; } /*! \internal */ +void +QMenuPrivate::syncSeparatorsCollapsible(bool collapse) +{ +#ifndef QT_MAC_USE_COCOA + if (collapse) + ChangeMenuAttributes(mac_menu->menu, kMenuAttrCondenseSeparators, 0); + else + ChangeMenuAttributes(mac_menu->menu, 0, kMenuAttrCondenseSeparators); +#else + qt_mac_menu_collapseSeparators(mac_menu->menu, collapse); +#endif +} + + + +/*! + \internal +*/ void QMenuPrivate::setMacMenuEnabled(bool enable) { if (!macMenu(0)) diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h index 4e428fe..8697771 100644 --- a/src/gui/widgets/qmenu_p.h +++ b/src/gui/widgets/qmenu_p.h @@ -263,9 +263,8 @@ public: struct QMacMenuPrivate { QList<QMacMenuAction*> actionItems; OSMenuRef menu; - QMenuPrivate *qmenu; - QMacMenuPrivate(QMenuPrivate *menu); - ~QMacMenuPrivate(); + QMacMenuPrivate(); + ~QMacMenuPrivate(); bool merged(const QAction *action) const; void addAction(QAction *, QMacMenuAction* =0, QMenuPrivate *qmenu = 0); @@ -285,6 +284,7 @@ public: } *mac_menu; OSMenuRef macMenu(OSMenuRef merge); void setMacMenuEnabled(bool enable = true); + void syncSeparatorsCollapsible(bool collapsible); static QHash<OSMenuRef, OSMenuRef> mergeMenuHash; static QHash<OSMenuRef, QMenuMergeList*> mergeMenuItemsHash; #endif diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp index 6b93879..389b65f 100644 --- a/src/gui/widgets/qmenubar.cpp +++ b/src/gui/widgets/qmenubar.cpp @@ -272,6 +272,9 @@ QRect QMenuBarPrivate::actionRect(QAction *act) const //makes sure the geometries are up-to-date const_cast<QMenuBarPrivate*>(this)->updateGeometries(); + if (index >= actionRects.count()) + return QRect(); // that can happen in case of native menubar + QRect ret = actionRects.at(index); return QStyle::visualRect(q->layoutDirection(), q->rect(), ret); } @@ -446,13 +449,12 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const continue; //we don't really position these! } else { const QString s = action->text(); - if(!s.isEmpty()) { - sz = fm.size(Qt::TextShowMnemonic, s); - } - QIcon is = action->icon(); + // If an icon is set, only the icon is visible if (!is.isNull()) sz = sz.expandedTo(QSize(icone, icone)); + else if (!s.isEmpty()) + sz = fm.size(Qt::TextShowMnemonic, s); } //let the style modify the above size.. @@ -717,7 +719,7 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti application examples} also provide menus using these classes. \sa QMenu, QShortcut, QAction, - {http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/index.html}{Introduction to Apple Human Interface Guidelines}, + {http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/XHIGIntro.html}{Introduction to Apple Human Interface Guidelines}, {fowler}{GUI Design Handbook: Menu Bar}, {Menus Example} */ @@ -1758,6 +1760,9 @@ void QMenuBarPrivate::_q_internalShortcutActivated(int id) activateAction(act, QAction::Trigger); //100 is the same as the default value in QPushButton::animateClick autoReleaseTimer.start(100, q); + } else if (act && q->style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, q)) { + // When we open a menu using a shortcut, we should end up in keyboard state + setKeyboardMode(true); } } diff --git a/src/gui/widgets/qprogressbar.cpp b/src/gui/widgets/qprogressbar.cpp index 6593cd6..7e40c0d 100644 --- a/src/gui/widgets/qprogressbar.cpp +++ b/src/gui/widgets/qprogressbar.cpp @@ -190,10 +190,11 @@ bool QProgressBarPrivate::repaintRequired() const with setValue(). The progress bar can be rewound to the beginning with reset(). - If minimum and maximum both are set to 0, the bar shows a busy indicator - instead of a percentage of steps. This is useful, for example, when using - QFtp or QHttp to download items when they are unable to determine the - size of the item being downloaded. + If minimum and maximum both are set to 0, the bar shows a busy + indicator instead of a percentage of steps. This is useful, for + example, when using QFtp or QNetworkAccessManager to download + items when they are unable to determine the size of the item being + downloaded. \table \row \o \inlineimage macintosh-progressbar.png Screenshot of a Macintosh style progress bar diff --git a/src/gui/widgets/qtabbar.cpp b/src/gui/widgets/qtabbar.cpp index 690e624..6b027b1 100644 --- a/src/gui/widgets/qtabbar.cpp +++ b/src/gui/widgets/qtabbar.cpp @@ -87,13 +87,17 @@ void QTabBarPrivate::updateMacBorderMetrics() // TODO: get metrics to preserve the bottom value // TODO: test tab bar position - // push the black line at the bottom of the menu bar down to the client are so we can paint over it + OSWindowRef window = qt_mac_window_for(q); + + // push base line separator down to the client are so we can paint over it (Carbon) metrics.top = (documentMode && q->isVisible()) ? 1 : 0; metrics.bottom = 0; metrics.left = 0; metrics.right = 0; - - qt_mac_updateContentBorderMetricts(qt_mac_window_for(q), metrics); + qt_mac_updateContentBorderMetricts(window, metrics); + + // hide the base line separator if the tabs have docuemnt mode enabled (Cocoa) + qt_mac_showBaseLineSeparator(window, !documentMode); } #endif } diff --git a/src/gui/widgets/qtextedit.cpp b/src/gui/widgets/qtextedit.cpp index e80df92..0a41d74 100644 --- a/src/gui/widgets/qtextedit.cpp +++ b/src/gui/widgets/qtextedit.cpp @@ -114,7 +114,7 @@ QTextEditPrivate::QTextEditPrivate() showCursorOnInitialShow = true; inDrag = false; #ifdef Q_WS_WIN - singleFingerPanEnabled = true; + setSingleFingerPanEnabled(true); #endif } @@ -183,8 +183,6 @@ void QTextEditPrivate::init(const QString &html) #ifndef QT_NO_CURSOR viewport->setCursor(Qt::IBeamCursor); #endif - panGesture = new QPanGesture(q); - QObject::connect(panGesture, SIGNAL(triggered()), q, SLOT(_q_gestureTriggered())); } void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect) @@ -2617,26 +2615,6 @@ void QTextEdit::ensureCursorVisible() d->control->ensureCursorVisible(); } -void QTextEditPrivate::_q_gestureTriggered() -{ - Q_Q(QTextEdit); - QPanGesture *g = qobject_cast<QPanGesture*>(q->sender()); - if (!g) - return; - QScrollBar *hBar = q->horizontalScrollBar(); - QScrollBar *vBar = q->verticalScrollBar(); - QPoint delta = g->pos() - (g->lastPos().isNull() ? g->pos() : g->lastPos()); - if (!delta.isNull()) { - if (QApplication::isRightToLeft()) - delta.rx() *= -1; - int newX = hBar->value() - delta.x(); - int newY = vBar->value() - delta.y(); - hbar->setValue(newX); - vbar->setValue(newY); - } -} - - /*! \enum QTextEdit::KeyboardAction diff --git a/src/gui/widgets/qtextedit.h b/src/gui/widgets/qtextedit.h index 9e10e07..617822a 100644 --- a/src/gui/widgets/qtextedit.h +++ b/src/gui/widgets/qtextedit.h @@ -414,7 +414,6 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_currentCharFormatChanged(const QTextCharFormat &)) Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars()) Q_PRIVATE_SLOT(d_func(), void _q_ensureVisible(const QRectF &)) - Q_PRIVATE_SLOT(d_func(), void _q_gestureTriggered()) friend class QTextEditControl; friend class QTextDocument; friend class QTextControl; diff --git a/src/gui/widgets/qtextedit_p.h b/src/gui/widgets/qtextedit_p.h index 249331e..3d14af6 100644 --- a/src/gui/widgets/qtextedit_p.h +++ b/src/gui/widgets/qtextedit_p.h @@ -70,7 +70,6 @@ QT_BEGIN_NAMESPACE #ifndef QT_NO_TEXTEDIT class QMimeData; -class QPanGesture; class QTextEditPrivate : public QAbstractScrollAreaPrivate { Q_DECLARE_PUBLIC(QTextEdit) @@ -129,9 +128,6 @@ public: QString anchorToScrollToWhenVisible; - void _q_gestureTriggered(); - QPanGesture *panGesture; - #ifdef QT_KEYPAD_NAVIGATION QBasicTimer deleteAllTimer; #endif diff --git a/src/gui/widgets/qvalidator.h b/src/gui/widgets/qvalidator.h index ce78959..5c27d1d 100644 --- a/src/gui/widgets/qvalidator.h +++ b/src/gui/widgets/qvalidator.h @@ -61,7 +61,7 @@ class Q_GUI_EXPORT QValidator : public QObject { Q_OBJECT public: - explicit QValidator(QObject * parent); + explicit QValidator(QObject * parent=0); ~QValidator(); enum State { @@ -100,7 +100,7 @@ class Q_GUI_EXPORT QIntValidator : public QValidator Q_PROPERTY(int top READ top WRITE setTop) public: - explicit QIntValidator(QObject * parent); + explicit QIntValidator(QObject * parent=0); QIntValidator(int bottom, int top, QObject * parent); ~QIntValidator(); diff --git a/src/gui/widgets/qworkspace.cpp b/src/gui/widgets/qworkspace.cpp index 2833c08..3184140 100644 --- a/src/gui/widgets/qworkspace.cpp +++ b/src/gui/widgets/qworkspace.cpp @@ -110,11 +110,11 @@ bool QMDIControl::event(QEvent *event) QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt, helpEvent->pos(), this); if (ctrl == QStyle::SC_MdiCloseButton) - QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Close")); + QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Close"), this); else if (ctrl == QStyle::SC_MdiMinButton) - QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Minimize")); + QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Minimize"), this); else if (ctrl == QStyle::SC_MdiNormalButton) - QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Restore Down")); + QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Restore Down"), this); else QToolTip::hideText(); #endif // QT_NO_TOOLTIP diff --git a/src/gui/widgets/widgets.pri b/src/gui/widgets/widgets.pri index 2d809a1..8f24fac 100644 --- a/src/gui/widgets/widgets.pri +++ b/src/gui/widgets/widgets.pri @@ -30,6 +30,7 @@ HEADERS += \ widgets/qlcdnumber.h \ widgets/qlineedit.h \ widgets/qlineedit_p.h \ + widgets/qlinecontrol_p.h \ widgets/qmainwindow.h \ widgets/qmainwindowlayout_p.h \ widgets/qmdiarea.h \ @@ -101,7 +102,9 @@ SOURCES += \ widgets/qgroupbox.cpp \ widgets/qlabel.cpp \ widgets/qlcdnumber.cpp \ + widgets/qlineedit_p.cpp \ widgets/qlineedit.cpp \ + widgets/qlinecontrol.cpp \ widgets/qmainwindow.cpp \ widgets/qmainwindowlayout.cpp \ widgets/qmdiarea.cpp \ |