diff options
author | David Boddie <dboddie@trolltech.com> | 2009-07-07 13:00:14 (GMT) |
---|---|---|
committer | David Boddie <dboddie@trolltech.com> | 2009-07-07 13:00:14 (GMT) |
commit | f5392a4290e5f7ae2bdf268c1fa8c037e776fdae (patch) | |
tree | d3cc657639b8784dbc22eae2bae5e58e62db7a2f /src/gui | |
parent | 0044b3c968f5023f502e3574c96d4e4df0de865d (diff) | |
parent | 2a834d39a69430058df3916392afab064ca941ee (diff) | |
download | Qt-f5392a4290e5f7ae2bdf268c1fa8c037e776fdae.zip Qt-f5392a4290e5f7ae2bdf268c1fa8c037e776fdae.tar.gz Qt-f5392a4290e5f7ae2bdf268c1fa8c037e776fdae.tar.bz2 |
Merge branch 'master' of git@scm.dev.nokia.troll.no:qt/qt
Conflicts:
src/network/socket/qlocalsocket.cpp
Diffstat (limited to 'src/gui')
159 files changed, 6122 insertions, 4126 deletions
diff --git a/src/gui/accessible/qaccessible_win.cpp b/src/gui/accessible/qaccessible_win.cpp index ccb2673..bfacb94 100644 --- a/src/gui/accessible/qaccessible_win.cpp +++ b/src/gui/accessible/qaccessible_win.cpp @@ -177,14 +177,14 @@ void QAccessible::updateAccessibility(QObject *o, int who, Event reason) return; } - QByteArray soundName; + QString soundName; switch (reason) { case PopupMenuStart: - soundName = "MenuPopup"; + soundName = QLatin1String("MenuPopup"); break; case MenuCommand: - soundName = "MenuCommand"; + soundName = QLatin1String("MenuCommand"); break; case Alert: @@ -194,13 +194,13 @@ void QAccessible::updateAccessibility(QObject *o, int who, Event reason) if (mb) { switch (mb->icon()) { case QMessageBox::Warning: - soundName = "SystemExclamation"; + soundName = QLatin1String("SystemExclamation"); break; case QMessageBox::Critical: - soundName = "SystemHand"; + soundName = QLatin1String("SystemHand"); break; case QMessageBox::Information: - soundName = "SystemAsterisk"; + soundName = QLatin1String("SystemAsterisk"); break; default: break; @@ -208,7 +208,7 @@ void QAccessible::updateAccessibility(QObject *o, int who, Event reason) } else #endif // QT_NO_MESSAGEBOX { - soundName = "SystemAsterisk"; + soundName = QLatin1String("SystemAsterisk"); } } @@ -219,20 +219,16 @@ void QAccessible::updateAccessibility(QObject *o, int who, Event reason) if (soundName.size()) { #ifndef QT_NO_SETTINGS - QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + - QString::fromLatin1(soundName.constData()), QSettings::NativeFormat); + QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + soundName, + QSettings::NativeFormat); QString file = settings.value(QLatin1String(".Current/.")).toString(); #else - QString file; + QString file; #endif - if (!file.isEmpty()) { - QT_WA({ - PlaySoundW(reinterpret_cast<const wchar_t *> (QString::fromLatin1(soundName).utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT ); - } , { - PlaySoundA(soundName.constData(), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT ); - }); - } - } + if (!file.isEmpty()) { + PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT); + } + } if (!isActive()) return; diff --git a/src/gui/dialogs/qdialog.cpp b/src/gui/dialogs/qdialog.cpp index 0288cd9..bb6c6d6 100644 --- a/src/gui/dialogs/qdialog.cpp +++ b/src/gui/dialogs/qdialog.cpp @@ -762,8 +762,7 @@ void QDialog::setVisible(bool visible) #ifdef Q_WS_WIN if (d->mainDef && isActiveWindow()) { BOOL snapToDefault = false; - if ( QT_WA_INLINE( SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0, &snapToDefault, 0) , - SystemParametersInfoA(SPI_GETSNAPTODEFBUTTON, 0, &snapToDefault, 0) )) { + if (SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0, &snapToDefault, 0)) { if (snapToDefault) QCursor::setPos(d->mainDef->mapToGlobal(d->mainDef->rect().center())); } diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index f6a8602..849f4b3 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -209,25 +209,30 @@ Q_GUI_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook /*! \enum QFileDialog::Option - \value ShowDirsOnly Only show directories in the file dialog. By default both files and - directories are shown. (Valid only in the \l Directory file mode.) - \value DontResolveSymlinks Don't resolve symlinks in the file dialog. By default symlinks - are resolved. - \value DontConfirmOverwrite Don't ask for confirmation if an existing file is selected. - By default confirmation is requested. - \value DontUseNativeDialog Don't use the native file dialog. By default on Mac OS X, - the native file dialog is used unless you use a subclass of QFileDialog that contains the - Q_OBJECT macro. + \value ShowDirsOnly Only show directories in the file dialog. By + default both files and directories are shown. (Valid only in the + \l Directory file mode.) + + \value DontResolveSymlinks Don't resolve symlinks in the file + dialog. By default symlinks are resolved. + + \value DontConfirmOverwrite Don't ask for confirmation if an + existing file is selected. By default confirmation is requested. + + \value DontUseNativeDialog Don't use the native file dialog. By + default, the native file dialog is used unless you use a subclass + of QFileDialog that contains the Q_OBJECT macro. + \value ReadOnly Indicates that the model is readonly. - \value HideNameFilterDetails Indicates if the is hidden or not. + \value HideNameFilterDetails Indicates if the is hidden or not. This value is obsolete and does nothing since Qt 4.5: - \value DontUseSheet In previous versions of Qt, the static functions would - create a sheet by default if the static function was given a parent. This - is no longer supported in Qt 4.5, The static functions will always be an - application modal dialog. If you want to use sheets, use - QFileDialog::open() instead. + \value DontUseSheet In previous versions of Qt, the static + functions would create a sheet by default if the static function + was given a parent. This is no longer supported in Qt 4.5, The + static functions will always be an application modal dialog. If + you want to use sheets, use QFileDialog::open() instead. */ diff --git a/src/gui/dialogs/qfiledialog_p.h b/src/gui/dialogs/qfiledialog_p.h index 654b3bb..d798f9d 100644 --- a/src/gui/dialogs/qfiledialog_p.h +++ b/src/gui/dialogs/qfiledialog_p.h @@ -187,8 +187,7 @@ public: #ifndef Q_OS_WINCE DWORD maxLength; QString drive = path.left(3); - if (QT_WA_INLINE(::GetVolumeInformationW(reinterpret_cast<const WCHAR *>(drive.utf16()), NULL, 0, NULL, &maxLength, NULL, NULL, 0), - ::GetVolumeInformationA(drive.toLocal8Bit().constData(), NULL, 0, NULL, &maxLength, NULL, NULL, 0)) == FALSE) + if (::GetVolumeInformation(reinterpret_cast<const wchar_t *>(drive.utf16()), NULL, 0, NULL, &maxLength, NULL, NULL, 0) == FALSE) return -1; return maxLength; #else diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp index 4cb31f5..6883bf9 100644 --- a/src/gui/dialogs/qfiledialog_win.cpp +++ b/src/gui/dialogs/qfiledialog_win.cpp @@ -70,8 +70,8 @@ typedef struct qt_priv_browseinfo { HWND hwndOwner; LPCITEMIDLIST pidlRoot; - LPTSTR pszDisplayName; - LPCTSTR lpszTitle; + LPWSTR pszDisplayName; + LPCWSTR lpszTitle; UINT ulFlags; BFFCALLBACK lpfn; LPARAM lParam; @@ -90,6 +90,9 @@ typedef LPITEMIDLIST (WINAPI *PtrSHBrowseForFolder)(BROWSEINFO*); static PtrSHBrowseForFolder ptrSHBrowseForFolder = 0; typedef BOOL (WINAPI *PtrSHGetPathFromIDList)(LPITEMIDLIST,LPWSTR); static PtrSHGetPathFromIDList ptrSHGetPathFromIDList = 0; +typedef HRESULT (WINAPI *PtrSHGetMalloc)(LPMALLOC *); +static PtrSHGetMalloc ptrSHGetMalloc = 0; + QT_BEGIN_NAMESPACE @@ -111,20 +114,20 @@ static void qt_win_resolve_libs() #endif triedResolve = true; - if (!(QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based)) { #if !defined(Q_WS_WINCE) - QLibrary lib(QLatin1String("shell32")); - ptrSHBrowseForFolder = (PtrSHBrowseForFolder) lib.resolve("SHBrowseForFolderW"); - ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList) lib.resolve("SHGetPathFromIDListW"); + QLibrary lib(QLatin1String("shell32")); + ptrSHBrowseForFolder = (PtrSHBrowseForFolder) lib.resolve("SHBrowseForFolderW"); + ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList) lib.resolve("SHGetPathFromIDListW"); + ptrSHGetMalloc = (PtrSHGetMalloc) lib.resolve("SHGetMalloc"); #else - // CE stores them in a different lib and does not use unicode version - HINSTANCE handle = LoadLibraryW(L"Ceshell"); - ptrSHBrowseForFolder = (PtrSHBrowseForFolder)GetProcAddress(handle, L"SHBrowseForFolder"); - ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)GetProcAddress(handle, L"SHGetPathFromIDList"); - if (ptrSHBrowseForFolder && ptrSHGetPathFromIDList) - qt_priv_ptr_valid = true; + // CE stores them in a different lib and does not use unicode version + HINSTANCE handle = LoadLibraryW(L"Ceshell"); + ptrSHBrowseForFolder = (PtrSHBrowseForFolder)GetProcAddress(handle, L"SHBrowseForFolder"); + ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)GetProcAddress(handle, L"SHGetPathFromIDList"); + ptrSHGetMalloc = (PtrSHGetMalloc)GetProcAddress(handle, L"SHGetMalloc"); + if (ptrSHBrowseForFolder && ptrSHGetPathFromIDList && ptrSHGetMalloc) + qt_priv_ptr_valid = true; #endif - } } } @@ -186,95 +189,15 @@ static QString qt_win_selected_filter(const QString &filter, DWORD idx) return qt_win_make_filters_list(filter).at((int)idx - 1); } -#ifndef Q_WS_WINCE -// Static vars for OFNA funcs: -static QByteArray aInitDir; -static QByteArray aInitSel; -static QByteArray aTitle; -static QByteArray aFilter; -// Use ANSI strings and API - -// If you change this, then make sure you change qt_win_make_OFN (below) too -static OPENFILENAMEA *qt_win_make_OFNA(QWidget *parent, - const QString &initialSelection, - const QString &initialDirectory, - const QString &title, - const QString &filters, - QFileDialog::FileMode mode, - QFileDialog::Options options) -{ - if (parent) - parent = parent->window(); - else - parent = QApplication::activeWindow(); - - aTitle = title.toLocal8Bit(); - aInitDir = QDir::toNativeSeparators(initialDirectory).toLocal8Bit(); - if (initialSelection.isEmpty()) { - aInitSel = ""; - } else { - aInitSel = QDir::toNativeSeparators(initialSelection).toLocal8Bit(); - aInitSel.replace('<', ""); - aInitSel.replace('>', ""); - aInitSel.replace('\"', ""); - aInitSel.replace('|', ""); - } - int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen; - aInitSel.resize(maxLen + 1); // make room for return value - aFilter = filters.toLocal8Bit(); - - OPENFILENAMEA* ofn = new OPENFILENAMEA; - memset(ofn, 0, sizeof(OPENFILENAMEA)); - -#if defined(Q_CC_BOR) && (WINVER >= 0x0500) && (_WIN32_WINNT >= 0x0500) - // according to the MSDN, this should also be necessary for MSVC, but - // OPENFILENAME_SIZE_VERSION_400A is in not Microsoft header, as it seems - if (QApplication::winVersion()==Qt::WV_NT || QApplication::winVersion()&Qt::WV_DOS_based) { - ofn->lStructSize = OPENFILENAME_SIZE_VERSION_400A; - } else { - ofn->lStructSize = sizeof(OPENFILENAMEA); - } -#else - ofn->lStructSize = sizeof(OPENFILENAMEA); -#endif - Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); - ofn->hwndOwner = parent ? parent->winId() : 0; - ofn->lpstrFilter = aFilter; - ofn->lpstrFile = aInitSel.data(); - ofn->nMaxFile = maxLen; - ofn->lpstrInitialDir = aInitDir.data(); - ofn->lpstrTitle = aTitle.data(); - ofn->Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER); - - if (mode == QFileDialog::ExistingFile || - mode == QFileDialog::ExistingFiles) - ofn->Flags |= (OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST); - if (mode == QFileDialog::ExistingFiles) - ofn->Flags |= (OFN_ALLOWMULTISELECT); - if (!(options & QFileDialog::DontConfirmOverwrite)) - ofn->Flags |= OFN_OVERWRITEPROMPT; - - return ofn; -} - -static void qt_win_clean_up_OFNA(OPENFILENAMEA **ofn) -{ - delete *ofn; - *ofn = 0; -} -#endif - static QString tFilters, tTitle, tInitDir; -#ifdef UNICODE -// If you change this, then make sure you change qt_win_make_OFNA (above) too static OPENFILENAME* qt_win_make_OFN(QWidget *parent, const QString& initialSelection, const QString& initialDirectory, const QString& title, const QString& filters, QFileDialog::FileMode mode, - QFileDialog::Options options) + QFileDialog::Options options) { if (parent) parent = parent->window(); @@ -286,14 +209,14 @@ static OPENFILENAME* qt_win_make_OFN(QWidget *parent, tTitle = title; QString initSel = QDir::toNativeSeparators(initialSelection); if (!initSel.isEmpty()) { - initSel.remove(QLatin1Char('<')); - initSel.remove(QLatin1Char('>')); - initSel.remove(QLatin1Char('\"')); - initSel.remove(QLatin1Char('|')); + initSel.remove(QLatin1Char('<')); + initSel.remove(QLatin1Char('>')); + initSel.remove(QLatin1Char('\"')); + initSel.remove(QLatin1Char('|')); } int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen; - TCHAR *tInitSel = new TCHAR[maxLen+1]; + wchar_t *tInitSel = new wchar_t[maxLen + 1]; if (initSel.length() > 0 && initSel.length() <= maxLen) memcpy(tInitSel, initSel.utf16(), (initSel.length()+1)*sizeof(QChar)); else @@ -302,24 +225,14 @@ static OPENFILENAME* qt_win_make_OFN(QWidget *parent, OPENFILENAME* ofn = new OPENFILENAME; memset(ofn, 0, sizeof(OPENFILENAME)); -#if defined(Q_CC_BOR) && (WINVER >= 0x0500) && (_WIN32_WINNT >= 0x0500) - // according to the MSDN, this should also be necessary for MSVC, but - // OPENFILENAME_SIZE_VERSION_400 is in not Microsoft header, as it seems - if (QApplication::winVersion()==Qt::WV_NT || QApplication::winVersion()&Qt::WV_DOS_based) { - ofn->lStructSize= OPENFILENAME_SIZE_VERSION_400; - } else { - ofn->lStructSize = sizeof(OPENFILENAME); - } -#else ofn->lStructSize = sizeof(OPENFILENAME); -#endif Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); ofn->hwndOwner = parent ? parent->winId() : 0; - ofn->lpstrFilter = (TCHAR *)tFilters.utf16(); + ofn->lpstrFilter = (wchar_t*)tFilters.utf16(); ofn->lpstrFile = tInitSel; ofn->nMaxFile = maxLen; - ofn->lpstrInitialDir = (TCHAR *)tInitDir.utf16(); - ofn->lpstrTitle = (TCHAR *)tTitle.utf16(); + ofn->lpstrInitialDir = (wchar_t*)tInitDir.utf16(); + ofn->lpstrTitle = (wchar_t*)tTitle.utf16(); ofn->Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER); if (mode == QFileDialog::ExistingFile || mode == QFileDialog::ExistingFiles) @@ -332,7 +245,6 @@ static OPENFILENAME* qt_win_make_OFN(QWidget *parent, return ofn; } - static void qt_win_clean_up_OFN(OPENFILENAME **ofn) { delete [] (*ofn)->lpstrFile; @@ -340,8 +252,6 @@ static void qt_win_clean_up_OFN(OPENFILENAME **ofn) *ofn = 0; } -#endif // UNICODE - extern void qt_win_eatMouseMove(); QString qt_win_get_open_file_name(const QFileDialogArgs &args, @@ -377,35 +287,20 @@ QString qt_win_get_open_file_name(const QFileDialogArgs &args, modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); - QT_WA({ - // Use Unicode strings and API - OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::ExistingFile, - args.options); - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetOpenFileName(ofn)) { - result = QString::fromUtf16((ushort*)ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - } - qt_win_clean_up_OFN(&ofn); - } , { - // Use ANSI strings and API - OPENFILENAMEA* ofn = qt_win_make_OFNA(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::ExistingFile, - args.options); - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetOpenFileNameA(ofn)) { - result = QString::fromLocal8Bit(ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - } - qt_win_clean_up_OFNA(&ofn); - }); + + OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, + args.directory, args.caption, + qt_win_filter(args.filter), + QFileDialog::ExistingFile, + args.options); + if (idx) + ofn->nFilterIndex = idx + 1; + if (GetOpenFileName(ofn)) { + result = QString::fromWCharArray(ofn->lpstrFile); + selFilIdx = ofn->nFilterIndex; + } + qt_win_clean_up_OFN(&ofn); + QApplicationPrivate::leaveModal(&modal_widget); qt_win_eatMouseMove(); @@ -422,7 +317,7 @@ QString qt_win_get_open_file_name(const QFileDialogArgs &args, QString qt_win_get_save_file_name(const QFileDialogArgs &args, QString *initialDirectory, - QString *selectedFilter) + QString *selectedFilter) { QString result; @@ -470,41 +365,22 @@ QString qt_win_get_save_file_name(const QFileDialogArgs &args, } } - QT_WA({ - // Use Unicode strings and API - OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::AnyFile, - args.options); - - ofn->lpstrDefExt = (TCHAR *)defaultSaveExt.utf16(); - - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetSaveFileName(ofn)) { - result = QString::fromUtf16((ushort*)ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - } - qt_win_clean_up_OFN(&ofn); - } , { - // Use ANSI strings and API - OPENFILENAMEA *ofn = qt_win_make_OFNA(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::AnyFile, - args.options); - QByteArray asciiExt = defaultSaveExt.toAscii(); - ofn->lpstrDefExt = asciiExt.data(); - - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetSaveFileNameA(ofn)) { - result = QString::fromLocal8Bit(ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - } - qt_win_clean_up_OFNA(&ofn); - }); + OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection, + args.directory, args.caption, + qt_win_filter(args.filter), + QFileDialog::AnyFile, + args.options); + + ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16(); + + if (idx) + ofn->nFilterIndex = idx + 1; + if (GetSaveFileName(ofn)) { + result = QString::fromWCharArray(ofn->lpstrFile); + selFilIdx = ofn->nFilterIndex; + } + qt_win_clean_up_OFN(&ofn); + #if defined(Q_WS_WINCE) int semIndex = result.indexOf(QLatin1Char(';')); if (semIndex >= 0) @@ -558,73 +434,40 @@ QStringList qt_win_get_open_file_names(const QFileDialogArgs &args, modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); - QT_WA({ - OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::ExistingFiles, - args.options); - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetOpenFileName(ofn)) { - QString fileOrDir = QString::fromUtf16((ushort*)ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - int offset = fileOrDir.length() + 1; - if (ofn->lpstrFile[offset] == 0) { - // Only one file selected; has full path - fi.setFile(fileOrDir); - QString res = fi.absoluteFilePath(); - if (!res.isEmpty()) - result.append(res); - } - else { - // Several files selected; first string is path - dir.setPath(fileOrDir); - QString f; - while(!(f = QString::fromUtf16((ushort*)ofn->lpstrFile+offset)).isEmpty()) { - fi.setFile(dir, f); - QString res = fi.absoluteFilePath(); - if (!res.isEmpty()) - result.append(res); - offset += f.length() + 1; - } - } + + OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection, + args.directory, args.caption, + qt_win_filter(args.filter), + QFileDialog::ExistingFiles, + args.options); + if (idx) + ofn->nFilterIndex = idx + 1; + if (GetOpenFileName(ofn)) { + QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile); + selFilIdx = ofn->nFilterIndex; + int offset = fileOrDir.length() + 1; + if (ofn->lpstrFile[offset] == 0) { + // Only one file selected; has full path + fi.setFile(fileOrDir); + QString res = fi.absoluteFilePath(); + if (!res.isEmpty()) + result.append(res); } - qt_win_clean_up_OFN(&ofn); - } , { - OPENFILENAMEA* ofn = qt_win_make_OFNA(args.parent, args.selection, - args.directory, args.caption, - qt_win_filter(args.filter), - QFileDialog::ExistingFiles, - args.options); - if (idx) - ofn->nFilterIndex = idx + 1; - if (GetOpenFileNameA(ofn)) { - QByteArray fileOrDir(ofn->lpstrFile); - selFilIdx = ofn->nFilterIndex; - int offset = fileOrDir.length() + 1; - if (ofn->lpstrFile[offset] == '\0') { - // Only one file selected; has full path - fi.setFile(QString::fromLocal8Bit(fileOrDir)); + else { + // Several files selected; first string is path + dir.setPath(fileOrDir); + QString f; + while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) { + fi.setFile(dir, f); QString res = fi.absoluteFilePath(); if (!res.isEmpty()) result.append(res); + offset += f.length() + 1; } - else { - // Several files selected; first string is path - dir.setPath(QString::fromLocal8Bit(fileOrDir)); - QByteArray f; - while (!(f = QByteArray(ofn->lpstrFile + offset)).isEmpty()) { - fi.setFile(dir, QString::fromLocal8Bit(f)); - QString res = fi.absoluteFilePath(); - if (!res.isEmpty()) - result.append(res); - offset += f.length() + 1; - } - } - qt_win_clean_up_OFNA(&ofn); } - }); + } + qt_win_clean_up_OFN(&ofn); + QApplicationPrivate::leaveModal(&modal_widget); qt_win_eatMouseMove(); @@ -647,34 +490,20 @@ static int __stdcall winGetExistDirCallbackProc(HWND hwnd, if (uMsg == BFFM_INITIALIZED && lpData != 0) { QString *initDir = (QString *)(lpData); if (!initDir->isEmpty()) { - // ### Lars asks: is this correct for the A version???? - QT_WA({ - SendMessage(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initDir->utf16())); - } , { - SendMessageA(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initDir->utf16())); - }); + SendMessage(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initDir->utf16())); } } else if (uMsg == BFFM_SELCHANGED) { - QT_WA({ - qt_win_resolve_libs(); - TCHAR path[MAX_PATH]; + qt_win_resolve_libs(); + if (ptrSHGetPathFromIDList) { + wchar_t path[MAX_PATH]; ptrSHGetPathFromIDList(LPITEMIDLIST(lParam), path); - QString tmpStr = QString::fromUtf16((ushort*)path); + QString tmpStr = QString::fromWCharArray(path); if (!tmpStr.isEmpty()) SendMessage(hwnd, BFFM_ENABLEOK, 1, 1); else SendMessage(hwnd, BFFM_ENABLEOK, 0, 0); SendMessage(hwnd, BFFM_SETSTATUSTEXT, 1, LPARAM(path)); - } , { - char path[MAX_PATH]; - SHGetPathFromIDListA(LPITEMIDLIST(lParam), path); - QString tmpStr = QString::fromLocal8Bit(path); - if (!tmpStr.isEmpty()) - SendMessageA(hwnd, BFFM_ENABLEOK, 1, 1); - else - SendMessageA(hwnd, BFFM_ENABLEOK, 0, 0); - SendMessageA(hwnd, BFFM_SETSTATUSTEXT, 1, LPARAM(path)); - }); + } } return 0; } @@ -700,116 +529,49 @@ QString qt_win_get_existing_directory(const QFileDialogArgs &args) modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); -#if !defined(Q_WS_WINCE) - QT_WA({ - qt_win_resolve_libs(); - QString initDir = QDir::toNativeSeparators(args.directory); - TCHAR path[MAX_PATH]; - TCHAR initPath[MAX_PATH]; - initPath[0] = 0; - path[0] = 0; - tTitle = args.caption; - BROWSEINFO bi; - Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); - bi.hwndOwner = (parent ? parent->winId() : 0); - bi.pidlRoot = NULL; - //### This does not seem to be respected? - the dialog always displays "Browse for folder" - bi.lpszTitle = (TCHAR*)tTitle.utf16(); - bi.pszDisplayName = initPath; - bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; - bi.lpfn = winGetExistDirCallbackProc; - bi.lParam = LPARAM(&initDir); - if (ptrSHBrowseForFolder) { - LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder(&bi); - if (pItemIDList && ptrSHGetPathFromIDList) { - ptrSHGetPathFromIDList(pItemIDList, path); - IMalloc *pMalloc; - if (SHGetMalloc(&pMalloc) != NOERROR) - result = QString(); - else { - pMalloc->Free(pItemIDList); - pMalloc->Release(); - result = QString::fromUtf16((ushort*)path); - } - } else - result = QString(); - } - tTitle = QString(); - } , { - QString initDir = QDir::toNativeSeparators(args.directory); - char path[MAX_PATH]; - char initPath[MAX_PATH]; - QByteArray ctitle = args.caption.toLocal8Bit(); - initPath[0]=0; - path[0]=0; - BROWSEINFOA bi; - Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); - bi.hwndOwner = (parent ? parent->winId() : 0); - bi.pidlRoot = NULL; - bi.lpszTitle = ctitle; - bi.pszDisplayName = initPath; - bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; - bi.lpfn = winGetExistDirCallbackProc; - bi.lParam = LPARAM(&initDir); - LPITEMIDLIST pItemIDList = SHBrowseForFolderA(&bi); - if (pItemIDList) { - SHGetPathFromIDListA(pItemIDList, path); - IMalloc *pMalloc; - if (SHGetMalloc(&pMalloc) != NOERROR) - result = QString(); - else { - pMalloc->Free(pItemIDList); - pMalloc->Release(); - result = QString::fromLocal8Bit(path); - } - } else - result = QString(); - }); -#else - qt_win_resolve_libs(); + QString initDir = QDir::toNativeSeparators(args.directory); - TCHAR path[MAX_PATH]; - TCHAR initPath[MAX_PATH]; - memset(initPath, 0 , MAX_PATH*sizeof(TCHAR)); - memset(path, 0, MAX_PATH*sizeof(TCHAR)); + wchar_t path[MAX_PATH]; + wchar_t initPath[MAX_PATH]; + initPath[0] = 0; + path[0] = 0; tTitle = args.caption; + +#if !defined(Q_WS_WINCE) + BROWSEINFO bi; +#else qt_BROWSEINFO bi; +#endif + Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); bi.hwndOwner = (parent ? parent->winId() : 0); bi.pidlRoot = NULL; - bi.lpszTitle = (TCHAR*)tTitle.utf16(); + //### This does not seem to be respected? - the dialog always displays "Browse for folder" + bi.lpszTitle = (wchar_t*)tTitle.utf16(); bi.pszDisplayName = initPath; bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; bi.lpfn = winGetExistDirCallbackProc; bi.lParam = LPARAM(&initDir); + + qt_win_resolve_libs(); if (ptrSHBrowseForFolder) { LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder((BROWSEINFO*)&bi); - if (pItemIDList && ptrSHGetPathFromIDList) { + if (pItemIDList) { ptrSHGetPathFromIDList(pItemIDList, path); IMalloc *pMalloc; - if (SHGetMalloc(&pMalloc) != NOERROR) - result = QString(); - else { + if (ptrSHGetMalloc(&pMalloc) == NOERROR) { pMalloc->Free(pItemIDList); pMalloc->Release(); - result = QString::fromUtf16((ushort*)path); + result = QString::fromWCharArray(path); } - } else - result = QString(); + } } tTitle = QString(); -#endif QApplicationPrivate::leaveModal(&modal_widget); qt_win_eatMouseMove(); - // Due to a bug on Windows Me, we need to reset the current - // directory - if ((QSysInfo::WindowsVersion == QSysInfo::WV_98 || QSysInfo::WindowsVersion == QSysInfo::WV_Me) - && QDir::currentPath() != currentDir) - QDir::setCurrent(currentDir); - if (!result.isEmpty()) result.replace(QLatin1Char('\\'), QLatin1Char('/')); return result; diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index 347a084..e523ec3 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -296,22 +296,14 @@ static QString qt_GetLongPathName(const QString &strShortPath) #else QString longSection = QDir::toNativeSeparators(section); #endif - QT_WA({ - WIN32_FIND_DATAW findData; - h = ::FindFirstFileW((wchar_t *)longSection.utf16(), &findData); - if (h != INVALID_HANDLE_VALUE) - longPath.append(QString::fromUtf16((ushort*)findData.cFileName)); - } , { - WIN32_FIND_DATAA findData; - h = ::FindFirstFileA(section.toLocal8Bit(), &findData); - if (h != INVALID_HANDLE_VALUE) - longPath.append(QString::fromLocal8Bit(findData.cFileName)); - }); - if (h == INVALID_HANDLE_VALUE) { + WIN32_FIND_DATA findData; + h = ::FindFirstFile((wchar_t*)longSection.utf16(), &findData); + if (h != INVALID_HANDLE_VALUE) { + longPath.append(QString::fromWCharArray(findData.cFileName)); + ::FindClose(h); + } else { longPath.append(section); break; - } else { - ::FindClose(h); } } if (it != constEnd) diff --git a/src/gui/dialogs/qpagesetupdialog_win.cpp b/src/gui/dialogs/qpagesetupdialog_win.cpp index 136f939..a84a7ce 100644 --- a/src/gui/dialogs/qpagesetupdialog_win.cpp +++ b/src/gui/dialogs/qpagesetupdialog_win.cpp @@ -81,8 +81,7 @@ int QPageSetupDialog::exec() HGLOBAL hDevMode; int devModeSize; if (!ep->globalDevMode) { - QT_WA( { devModeSize = sizeof(DEVMODEW) + ((DEVMODEW *) ep->devMode)->dmDriverExtra; }, - { devModeSize = sizeof(DEVMODEA) + ((DEVMODEA *) ep->devMode)->dmDriverExtra; }); + devModeSize = sizeof(DEVMODE) + ep->devMode->dmDriverExtra; hDevMode = GlobalAlloc(GHND, devModeSize); if (hDevMode) { void *dest = GlobalLock(hDevMode); diff --git a/src/gui/dialogs/qprintdialog_win.cpp b/src/gui/dialogs/qprintdialog_win.cpp index e89ce90..115cd8d 100644 --- a/src/gui/dialogs/qprintdialog_win.cpp +++ b/src/gui/dialogs/qprintdialog_win.cpp @@ -77,27 +77,18 @@ public: QWin32PrintEnginePrivate *ep; }; -#ifndef Q_OS_WINCE -// If you change this function, make sure you also change the unicode equivalent -template <class PrintDialog, class DeviceMode> -static PrintDialog *qt_win_make_PRINTDLG(QWidget *parent, - QPrintDialog *pdlg, - QPrintDialogPrivate *d, HGLOBAL *tempDevNames) +static void qt_win_setup_PRINTDLGEX(PRINTDLGEX *pd, QWidget *parent, + QPrintDialog *pdlg, + QPrintDialogPrivate *d, HGLOBAL *tempDevNames) { - PrintDialog *pd = new PrintDialog; - memset(pd, 0, sizeof(PrintDialog)); - pd->lStructSize = sizeof(PrintDialog); - - void *devMode = sizeof(DeviceMode) == sizeof(DEVMODEA) - ? (void *) d->ep->devModeA() - : (void *) d->ep->devModeW(); + DEVMODE *devMode = d->ep->devMode; if (devMode) { - int size = sizeof(DeviceMode) + ((DeviceMode *) devMode)->dmDriverExtra; + int size = sizeof(DEVMODE) + devMode->dmDriverExtra; pd->hDevMode = GlobalAlloc(GHND, size); { void *dest = GlobalLock(pd->hDevMode); - memcpy(dest, d->ep->devMode, size); + memcpy(dest, devMode, size); GlobalUnlock(pd->hDevMode); } } else { @@ -130,37 +121,31 @@ static PrintDialog *qt_win_make_PRINTDLG(QWidget *parent, if (pd->nMinPage==0 && pd->nMaxPage==0) pd->Flags |= PD_NOPAGENUMS; + // we don't have a 'current page' notion in the QPrinter API yet. + // Neither do we support more than one page range, so limit those + // options + pd->Flags |= PD_NOCURRENTPAGE; + pd->nStartPage = START_PAGE_GENERAL; + pd->nPageRanges = 1; + pd->nMaxPageRanges = 1; + if (d->ep->printToFile) pd->Flags |= PD_PRINTTOFILE; Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); pd->hwndOwner = parent ? parent->winId() : 0; - pd->nFromPage = qMax(pdlg->fromPage(), pdlg->minPage()); - pd->nToPage = (pdlg->toPage() > 0) ? qMin(pdlg->toPage(), pdlg->maxPage()) : 1; + pd->lpPageRanges[0].nFromPage = qMax(pdlg->fromPage(), pdlg->minPage()); + pd->lpPageRanges[0].nToPage = (pdlg->toPage() > 0) ? qMin(pdlg->toPage(), pdlg->maxPage()) : 1; pd->nCopies = d->ep->num_copies; - - return pd; -} -#endif // Q_OS_WINCE - -// If you change this function, make sure you also change the ansi equivalent -template <typename T> -static void qt_win_clean_up_PRINTDLG(T **pd) -{ - delete *pd; - *pd = 0; } - -// If you change this function, make sure you also change the ansi equivalent -template <typename T> -static void qt_win_read_back_PRINTDLG(T *pd, QPrintDialog *pdlg, QPrintDialogPrivate *d) +static void qt_win_read_back_PRINTDLGEX(PRINTDLGEX *pd, QPrintDialog *pdlg, QPrintDialogPrivate *d) { if (pd->Flags & PD_SELECTION) { pdlg->setPrintRange(QPrintDialog::Selection); pdlg->setFromTo(0, 0); } else if (pd->Flags & PD_PAGENUMS) { pdlg->setPrintRange(QPrintDialog::PageRange); - pdlg->setFromTo(pd->nFromPage, pd->nToPage); + pdlg->setFromTo(pd->lpPageRanges[0].nFromPage, pd->lpPageRanges[0].nToPage); } else { pdlg->setPrintRange(QPrintDialog::AllPages); pdlg->setFromTo(0, 0); @@ -234,34 +219,36 @@ int QPrintDialogPrivate::openWindowsPrintDialogModally() HGLOBAL *tempDevNames = ep->createDevNames(); - bool result; bool done; - void *pd = QT_WA_INLINE( - (void*)(qt_win_make_PRINTDLG<PRINTDLGW, DEVMODEW>(parent, q, this, tempDevNames)), - (void*)(qt_win_make_PRINTDLG<PRINTDLGA, DEVMODEA>(parent, q, this, tempDevNames)) - ); + bool result; + bool doPrinting; + + PRINTPAGERANGE pageRange; + PRINTDLGEX pd; + memset(&pd, 0, sizeof(PRINTDLGEX)); + pd.lStructSize = sizeof(PRINTDLGEX); + pd.lpPageRanges = &pageRange; + qt_win_setup_PRINTDLGEX(&pd, parent, q, this, tempDevNames); do { done = true; - QT_WA({ - PRINTDLGW *pdw = reinterpret_cast<PRINTDLGW *>(pd); - result = PrintDlgW(pdw); - if ((pdw->Flags & PD_PAGENUMS) && (pdw->nFromPage > pdw->nToPage)) - done = false; - if (result && pdw->hDC == 0) - result = false; - else if (!result) - done = true; - }, { - PRINTDLGA *pda = reinterpret_cast<PRINTDLGA *>(pd); - result = PrintDlgA(pda); - if ((pda->Flags & PD_PAGENUMS) && (pda->nFromPage > pda->nToPage)) + doPrinting = false; + result = (PrintDlgEx(&pd) == S_OK); + if (result && (pd.dwResultAction == PD_RESULT_PRINT + || pd.dwResultAction == PD_RESULT_APPLY)) + { + doPrinting = (pd.dwResultAction == PD_RESULT_PRINT); + if ((pd.Flags & PD_PAGENUMS) + && (pd.lpPageRanges[0].nFromPage > pd.lpPageRanges[0].nToPage)) + { + pd.lpPageRanges[0].nFromPage = 1; + pd.lpPageRanges[0].nToPage = 1; done = false; - if (result && pda->hDC == 0) + } + if (pd.hDC == 0) result = false; - else if (!result) - done = true; - }); + } + if (!done) { QMessageBox::warning(0, QPrintDialog::tr("Print"), QPrintDialog::tr("The 'From' value cannot be greater than the 'To' value."), @@ -274,16 +261,10 @@ int QPrintDialogPrivate::openWindowsPrintDialogModally() qt_win_eatMouseMove(); // write values back... - if (result) { - QT_WA({ - PRINTDLGW *pdw = reinterpret_cast<PRINTDLGW *>(pd); - qt_win_read_back_PRINTDLG(pdw, q, this); - qt_win_clean_up_PRINTDLG(&pdw); - }, { - PRINTDLGA *pda = reinterpret_cast<PRINTDLGA *>(pd); - qt_win_read_back_PRINTDLG(pda, q, this); - qt_win_clean_up_PRINTDLG(&pda); - }); + if (result && (pd.dwResultAction == PD_RESULT_PRINT + || pd.dwResultAction == PD_RESULT_APPLY)) + { + qt_win_read_back_PRINTDLGEX(&pd, q, this); // update printer validity printer->d_func()->validPrinter = !ep->name.isEmpty(); } @@ -291,9 +272,9 @@ int QPrintDialogPrivate::openWindowsPrintDialogModally() // Cleanup... GlobalFree(tempDevNames); - q->done(result); + q->done(result && doPrinting); - return result; + return result && doPrinting; } void QPrintDialog::setVisible(bool visible) diff --git a/src/gui/dialogs/qprogressdialog.cpp b/src/gui/dialogs/qprogressdialog.cpp index cd8d83f..15a48c2 100644 --- a/src/gui/dialogs/qprogressdialog.cpp +++ b/src/gui/dialogs/qprogressdialog.cpp @@ -626,7 +626,7 @@ int QProgressDialog::value() const \warning If the progress dialog is modal (see QProgressDialog::QProgressDialog()), - this function calls QApplication::processEvents(), so take care that + setValue() calls QApplication::processEvents(), so take care that this does not cause undesirable re-entrancy in your code. For example, don't use a QProgressDialog inside a paintEvent()! diff --git a/src/gui/dialogs/qwizard.cpp b/src/gui/dialogs/qwizard.cpp index 3fdea54..a7dccd8 100644 --- a/src/gui/dialogs/qwizard.cpp +++ b/src/gui/dialogs/qwizard.cpp @@ -1251,13 +1251,7 @@ void QWizardPrivate::updateMinMaxSizes(const QWizardLayoutInfo &info) extraHeight = vistaHelper->titleBarSize() + vistaHelper->topOffset(); #endif QSize minimumSize = mainLayout->totalMinimumSize() + QSize(0, extraHeight); - QSize maximumSize; - bool skipMaxSize = false; -#if defined(Q_WS_WIN) - if (QSysInfo::WindowsVersion <= QSysInfo::WV_Me) // ### See Tasks 164078 and 161660 - skipMaxSize = true; -#endif - maximumSize = mainLayout->totalMaximumSize(); + QSize maximumSize = mainLayout->totalMaximumSize(); if (info.header && headerWidget->maximumWidth() != QWIDGETSIZE_MAX) { minimumSize.setWidth(headerWidget->maximumWidth()); maximumSize.setWidth(headerWidget->maximumWidth()); @@ -1276,13 +1270,11 @@ void QWizardPrivate::updateMinMaxSizes(const QWizardLayoutInfo &info) } if (q->maximumWidth() == maximumWidth) { maximumWidth = maximumSize.width(); - if (!skipMaxSize) - q->setMaximumWidth(maximumWidth); + q->setMaximumWidth(maximumWidth); } if (q->maximumHeight() == maximumHeight) { maximumHeight = maximumSize.height(); - if (!skipMaxSize) - q->setMaximumHeight(maximumHeight); + q->setMaximumHeight(maximumHeight); } } diff --git a/src/gui/embedded/qkbdlinuxinput_qws.cpp b/src/gui/embedded/qkbdlinuxinput_qws.cpp index d5720f7..e552731 100644 --- a/src/gui/embedded/qkbdlinuxinput_qws.cpp +++ b/src/gui/embedded/qkbdlinuxinput_qws.cpp @@ -47,6 +47,7 @@ #include <QStringList> #include <qplatformdefs.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <errno.h> #include <termios.h> diff --git a/src/gui/embedded/qkbdsl5000_qws.cpp b/src/gui/embedded/qkbdsl5000_qws.cpp index 36cb903..cf82c10 100644 --- a/src/gui/embedded/qkbdsl5000_qws.cpp +++ b/src/gui/embedded/qkbdsl5000_qws.cpp @@ -51,6 +51,8 @@ #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> @@ -207,14 +209,14 @@ QWSSL5000KeyboardHandler::QWSSL5000KeyboardHandler(const QString &device) numLock = false; sharp_kbdctl_modifstat st; - int dev = ::open(device.isEmpty()?"/dev/sharp_kbdctl":device.toLocal8Bit().constData(), O_RDWR); + 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; - ::close(dev); + QT_CLOSE(dev); } } diff --git a/src/gui/embedded/qkbdtty_qws.cpp b/src/gui/embedded/qkbdtty_qws.cpp index 33777eb..8c1e79b 100644 --- a/src/gui/embedded/qkbdtty_qws.cpp +++ b/src/gui/embedded/qkbdtty_qws.cpp @@ -47,6 +47,7 @@ #include <QStringList> #include <qplatformdefs.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <errno.h> #include <termios.h> @@ -213,6 +214,9 @@ QWSTtyKbPrivate::~QWSTtyKbPrivate() ::ioctl(m_tty_fd, KDSKBMODE, m_originalKbdMode); #endif tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr); + + // we're leaking m_tty_fd here? + //QT_CLOSE(m_tty_fd); } } diff --git a/src/gui/embedded/qkbdvfb_qws.cpp b/src/gui/embedded/qkbdvfb_qws.cpp index 082aac1..a44183b 100644 --- a/src/gui/embedded/qkbdvfb_qws.cpp +++ b/src/gui/embedded/qkbdvfb_qws.cpp @@ -55,6 +55,7 @@ #include <qwindowsystem_qws.h> #include <qsocketnotifier.h> #include <qapplication.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN QT_BEGIN_NAMESPACE @@ -69,13 +70,13 @@ QVFbKeyboardHandler::QVFbKeyboardHandler(const QString &device) kbdBufferLen = sizeof(QVFbKeyData) * 5; kbdBuffer = new unsigned char [kbdBufferLen]; - if ((kbdFD = open(terminalName.toLatin1().constData(), O_RDONLY | O_NDELAY)) < 0) { + if ((kbdFD = QT_OPEN(terminalName.toLatin1().constData(), O_RDONLY | O_NDELAY)) < 0) { qWarning("Cannot open %s (%s)", terminalName.toLatin1().constData(), strerror(errno)); } else { // Clear pending input char buf[2]; - while (read(kbdFD, buf, 1) > 0) { } + while (QT_READ(kbdFD, buf, 1) > 0) { } notifier = new QSocketNotifier(kbdFD, QSocketNotifier::Read, this); connect(notifier, SIGNAL(activated(int)),this, SLOT(readKeyboardData())); @@ -85,7 +86,7 @@ QVFbKeyboardHandler::QVFbKeyboardHandler(const QString &device) QVFbKeyboardHandler::~QVFbKeyboardHandler() { if (kbdFD >= 0) - close(kbdFD); + QT_CLOSE(kbdFD); delete [] kbdBuffer; } @@ -94,7 +95,7 @@ void QVFbKeyboardHandler::readKeyboardData() { int n; do { - n = read(kbdFD, kbdBuffer+kbdIdx, kbdBufferLen - kbdIdx); + n = QT_READ(kbdFD, kbdBuffer+kbdIdx, kbdBufferLen - kbdIdx); if (n > 0) kbdIdx += n; } while (n > 0); diff --git a/src/gui/embedded/qkbdvr41xx_qws.cpp b/src/gui/embedded/qkbdvr41xx_qws.cpp index 03c2a67..6d8299b 100644 --- a/src/gui/embedded/qkbdvr41xx_qws.cpp +++ b/src/gui/embedded/qkbdvr41xx_qws.cpp @@ -52,6 +52,7 @@ #include <errno.h> #include <qsocketnotifier.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN QT_BEGIN_NAMESPACE @@ -95,7 +96,7 @@ QWSVr41xxKbPrivate::QWSVr41xxKbPrivate(QWSVr41xxKeyboardHandler *h, const QStrin buttonFD = -1; notifier = 0; - buttonFD = open(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0);; + buttonFD = QT_OPEN(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0);; if (buttonFD < 0) { qWarning("Cannot open %s\n", qPrintable(terminalName)); return; @@ -115,7 +116,7 @@ QWSVr41xxKbPrivate::QWSVr41xxKbPrivate(QWSVr41xxKeyboardHandler *h, const QStrin QWSVr41xxKbPrivate::~QWSVr41xxKbPrivate() { if (buttonFD > 0) { - ::close(buttonFD); + QT_CLOSE(buttonFD); buttonFD = -1; } delete notifier; @@ -127,7 +128,7 @@ void QWSVr41xxKbPrivate::readKeyboardData() { int n = 0; do { - n = read(buttonFD, kbdBuffer+kbdIdx, kbdBufferLen - kbdIdx); + n = QT_READ(buttonFD, kbdBuffer+kbdIdx, kbdBufferLen - kbdIdx); if (n > 0) kbdIdx += n; } while (n > 0); diff --git a/src/gui/embedded/qkbdyopy_qws.cpp b/src/gui/embedded/qkbdyopy_qws.cpp index 5c9d28d..edb732c 100644 --- a/src/gui/embedded/qkbdyopy_qws.cpp +++ b/src/gui/embedded/qkbdyopy_qws.cpp @@ -60,6 +60,8 @@ #include <linux/fb.h> #include <linux/yopy_button.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN + extern "C" { int getpgid(int); } @@ -105,7 +107,7 @@ QWSYopyKbPrivate::QWSYopyKbPrivate(QWSYopyKeyboardHandler *h, const QString &dev buttonFD = -1; notifier = 0; - buttonFD = ::open(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0); + buttonFD = QT_OPEN(terminalName.toLatin1().constData(), O_RDWR | O_NDELAY, 0); if (buttonFD < 0) { qWarning("Cannot open %s\n", qPrintable(terminalName)); return; @@ -177,10 +179,10 @@ void QWSYopyKbPrivate::readKeyboardData() case 40: k=Qt::Key_Up; break; // prev case 45: k=Qt::Key_Down; break; // next case 35: if(!press) { - fd = open("/proc/sys/pm/sleep",O_RDWR,0); + fd = QT_OPEN("/proc/sys/pm/sleep",O_RDWR,0); if(fd >= 0) { - write(fd,&c,sizeof(c)); - close(fd); + QT_WRITE(fd,&c,sizeof(c)); + QT_CLOSE(fd); // // Updates all widgets. // diff --git a/src/gui/embedded/qlock.cpp b/src/gui/embedded/qlock.cpp index c23608f..305832c 100644 --- a/src/gui/embedded/qlock.cpp +++ b/src/gui/embedded/qlock.cpp @@ -73,6 +73,8 @@ union semun { #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 @@ -134,7 +136,7 @@ QLock::QLock(const QString &filename, char id, bool create) #ifdef Q_NO_SEMAPHORE data->file = QString(filename+id).toLocal8Bit().constData(); for(int x = 0; x < 2; x++) { - data->id = open(data->file, O_RDWR | (x ? O_CREAT : 0), S_IRWXU); + data->id = QT_OPEN(data->file, O_RDWR | (x ? O_CREAT : 0), S_IRWXU); if(data->id != -1 || !create) { data->owned = x; break; @@ -177,7 +179,7 @@ QLock::~QLock() unlock(); #ifdef Q_NO_SEMAPHORE if(isValid()) { - close(data->id); + QT_CLOSE(data->id); if(data->owned) unlink(data->file); } diff --git a/src/gui/embedded/qmousebus_qws.cpp b/src/gui/embedded/qmousebus_qws.cpp index a88ca5b..0b674b6 100644 --- a/src/gui/embedded/qmousebus_qws.cpp +++ b/src/gui/embedded/qmousebus_qws.cpp @@ -47,6 +47,7 @@ #include "qsocketnotifier.h" #include "qapplication.h" +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <unistd.h> #include <stdlib.h> @@ -119,9 +120,9 @@ QWSBusMouseHandlerPrivate::QWSBusMouseHandlerPrivate(QWSBusMouseHandler *h, mouseDev = QLatin1String("/dev/mouse"); obstate = -1; mouseFD = -1; - mouseFD = open(mouseDev.toLocal8Bit(), O_RDWR | O_NDELAY); + mouseFD = QT_OPEN(mouseDev.toLocal8Bit(), O_RDWR | O_NDELAY); if (mouseFD < 0) - mouseFD = open(mouseDev.toLocal8Bit(), O_RDONLY | O_NDELAY); + mouseFD = QT_OPEN(mouseDev.toLocal8Bit(), O_RDONLY | O_NDELAY); if (mouseFD < 0) qDebug("Cannot open %s (%s)", qPrintable(mouseDev), strerror(errno)); @@ -130,7 +131,7 @@ QWSBusMouseHandlerPrivate::QWSBusMouseHandlerPrivate(QWSBusMouseHandler *h, usleep(50000); char buf[100]; // busmouse driver will not read if bufsize < 3, YYD - while (read(mouseFD, buf, 100) > 0) { } // eat unwanted replies + while (QT_READ(mouseFD, buf, 100) > 0) { } // eat unwanted replies mouseIdx = 0; @@ -142,7 +143,7 @@ QWSBusMouseHandlerPrivate::~QWSBusMouseHandlerPrivate() { if (mouseFD >= 0) { tcflush(mouseFD,TCIFLUSH); // yyd. - close(mouseFD); + QT_CLOSE(mouseFD); } } @@ -167,7 +168,7 @@ void QWSBusMouseHandlerPrivate::readMouseData() for (;;) { if (mouseBufSize - mouseIdx < 3) break; - n = read(mouseFD, mouseBuf+mouseIdx, 3); + n = QT_READ(mouseFD, mouseBuf+mouseIdx, 3); if (n != 3) break; mouseIdx += 3; diff --git a/src/gui/embedded/qmouselinuxtp_qws.cpp b/src/gui/embedded/qmouselinuxtp_qws.cpp index 1b4d96e..e64407e 100644 --- a/src/gui/embedded/qmouselinuxtp_qws.cpp +++ b/src/gui/embedded/qmouselinuxtp_qws.cpp @@ -47,6 +47,7 @@ #include "qtimer.h" #include "qapplication.h" #include "qscreen_qws.h" +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <unistd.h> #include <stdlib.h> @@ -190,7 +191,7 @@ QWSLinuxTPMouseHandlerPrivate::QWSLinuxTPMouseHandlerPrivate(QWSLinuxTPMouseHand } else { mousedev = device; } - if ((mouseFD = open(mousedev.toLatin1().constData(), O_RDONLY | O_NDELAY)) < 0) { + if ((mouseFD = QT_OPEN(mousedev.toLatin1().constData(), O_RDONLY | O_NDELAY)) < 0) { qWarning("Cannot open %s (%s)", qPrintable(mousedev), strerror(errno)); return; } @@ -205,7 +206,7 @@ QWSLinuxTPMouseHandlerPrivate::QWSLinuxTPMouseHandlerPrivate(QWSLinuxTPMouseHand QWSLinuxTPMouseHandlerPrivate::~QWSLinuxTPMouseHandlerPrivate() { if (mouseFD >= 0) - close(mouseFD); + QT_CLOSE(mouseFD); } void QWSLinuxTPMouseHandlerPrivate::suspend() @@ -233,7 +234,7 @@ void QWSLinuxTPMouseHandlerPrivate::readMouseData() int n; do { - n = read(mouseFD, mouseBuf+mouseIdx, mouseBufSize-mouseIdx); + n = QT_READ(mouseFD, mouseBuf+mouseIdx, mouseBufSize-mouseIdx); if (n > 0) mouseIdx += n; } while (n > 0 && mouseIdx < mouseBufSize); diff --git a/src/gui/embedded/qmousepc_qws.cpp b/src/gui/embedded/qmousepc_qws.cpp index a9f2bc8..317bb8a 100644 --- a/src/gui/embedded/qmousepc_qws.cpp +++ b/src/gui/embedded/qmousepc_qws.cpp @@ -55,6 +55,7 @@ #include "qfile.h" #include "qtextstream.h" #include "qstringlist.h" +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <unistd.h> #include <stdlib.h> @@ -107,7 +108,7 @@ public: { if (fd != f) { f = fd; - close(fd); + QT_CLOSE(fd); } } @@ -170,7 +171,7 @@ public: } static const uchar initseq[] = { 243, 200, 243, 100, 243, 80 }; static const uchar query[] = { 0xf2 }; - if (write(fd, initseq, sizeof(initseq))!=sizeof(initseq)) { + if (QT_WRITE(fd, initseq, sizeof(initseq))!=sizeof(initseq)) { badness = 100; return; } @@ -180,12 +181,12 @@ public: perror("QWSPcMouseSubHandler_intellimouse: post-init tcflush"); #endif } - if (write(fd, query, sizeof(query))!=sizeof(query)) { + if (QT_WRITE(fd, query, sizeof(query))!=sizeof(query)) { badness = 100; return; } usleep(10000); - n = read(fd, reply, 20); + n = QT_READ(fd, reply, 20); if (n > 0) { goodness = 10; switch (reply[n-1]) { @@ -256,13 +257,13 @@ public: perror("QWSPcMouseSubHandler_mouseman: initial tcflush"); #endif } - write(fd,"",1); + QT_WRITE(fd,"",1); usleep(50000); - write(fd,"@EeI!",5); + QT_WRITE(fd,"@EeI!",5); usleep(10000); static const char ibuf[] = { 246, 244 }; - write(fd,ibuf,1); - write(fd,ibuf+1,1); + QT_WRITE(fd,ibuf,1); + QT_WRITE(fd,ibuf+1,1); if (tcflush(fd,TCIOFLUSH) == -1) { #ifdef QWS_MOUSE_DEBUG perror("QWSPcMouseSubHandler_mouseman: tcflush"); @@ -271,7 +272,7 @@ public: usleep(10000); char buf[100]; - while (read(fd, buf, 100) > 0) { } // eat unwanted replies + while (QT_READ(fd, buf, 100) > 0) { } // eat unwanted replies } int tryData() @@ -350,7 +351,7 @@ private: for (int n = 0; n < 4; n++) { setflags(CSTOPB | speed[n]); - write(fd, "*q", 2); + QT_WRITE(fd, "*q", 2); usleep(10000); } } @@ -369,7 +370,7 @@ public: { setflags(B1200|CS8|CSTOPB); // 60Hz - if (write(fd, "R", 1)!=1) { + if (QT_WRITE(fd, "R", 1)!=1) { badness = 100; return; } @@ -418,7 +419,7 @@ public: { setflags(B1200|CS7); // 60Hz - if (write(fd, "R", 1)!=1) { + if (QT_WRITE(fd, "R", 1)!=1) { badness = 100; return; } @@ -648,25 +649,25 @@ void QWSPcMouseHandlerPrivate::openDevices() if (drv == QLatin1String("intellimouse")) { if (dev.isEmpty()) dev = "/dev/psaux"; - fd = open(dev, O_RDWR | O_NDELAY); + fd = QT_OPEN(dev, O_RDWR | O_NDELAY); if (fd >= 0) sub[nsub++] = new QWSPcMouseSubHandler_intellimouse(fd); } else if (drv == QLatin1String("microsoft")) { if (dev.isEmpty()) dev = "/dev/ttyS0"; - fd = open(dev, O_RDWR | O_NDELAY); + fd = QT_OPEN(dev, O_RDWR | O_NDELAY); if (fd >= 0) sub[nsub++] = new QWSPcMouseSubHandler_ms(fd); } else if (drv == QLatin1String("mousesystems")) { if (dev.isEmpty()) dev = "/dev/ttyS0"; - fd = open(dev, O_RDWR | O_NDELAY); + fd = QT_OPEN(dev, O_RDWR | O_NDELAY); if (fd >= 0) sub[nsub++] = new QWSPcMouseSubHandler_mousesystems(fd); } else if (drv == QLatin1String("mouseman")) { if (dev.isEmpty()) dev = "/dev/psaux"; - fd = open(dev, O_RDWR | O_NDELAY); + fd = QT_OPEN(dev, O_RDWR | O_NDELAY); if (fd >= 0) sub[nsub++] = new QWSPcMouseSubHandler_mouseman(fd); } @@ -677,12 +678,12 @@ void QWSPcMouseHandlerPrivate::openDevices() dev.constData(), strerror(errno)); } else { // Try automatically - fd = open("/dev/psaux", O_RDWR | O_NDELAY); + fd = QT_OPEN("/dev/psaux", O_RDWR | O_NDELAY); if (fd >= 0) { sub[nsub++] = new QWSPcMouseSubHandler_intellimouse(fd); notify(fd); } - fd = open("/dev/input/mice", O_RDWR | O_NDELAY); + fd = QT_OPEN("/dev/input/mice", O_RDWR | O_NDELAY); if (fd >= 0) { sub[nsub++] = new QWSPcMouseSubHandler_intellimouse(fd); notify(fd); @@ -694,7 +695,7 @@ void QWSPcMouseHandlerPrivate::openDevices() #if 0 const char fn[4][11] = { "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3" }; for (int ch = 0; ch < 4; ++ch) { - fd = open(fn[ch], O_RDWR | O_NDELAY); + fd = QT_OPEN(fn[ch], O_RDWR | O_NDELAY); if (fd >= 0) { //sub[nsub++] = new QWSPcMouseSubHandler_intellimouse(fd); sub[nsub++] = new QWSPcMouseSubHandler_mousesystems(fd); diff --git a/src/gui/embedded/qmousevfb_qws.cpp b/src/gui/embedded/qmousevfb_qws.cpp index 17d051f..dd553bc 100644 --- a/src/gui/embedded/qmousevfb_qws.cpp +++ b/src/gui/embedded/qmousevfb_qws.cpp @@ -54,6 +54,7 @@ #include <qsocketnotifier.h> #include <qapplication.h> #include <qtimer.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN QT_BEGIN_NAMESPACE @@ -64,7 +65,7 @@ QVFbMouseHandler::QVFbMouseHandler(const QString &driver, const QString &device) if (device.isEmpty()) mouseDev = QLatin1String("/dev/vmouse"); - mouseFD = open(mouseDev.toLatin1().constData(), O_RDWR | O_NDELAY); + mouseFD = QT_OPEN(mouseDev.toLatin1().constData(), O_RDWR | O_NDELAY); if (mouseFD == -1) { perror("QVFbMouseHandler::QVFbMouseHandler"); qWarning("QVFbMouseHander: Unable to open device %s", @@ -74,7 +75,7 @@ QVFbMouseHandler::QVFbMouseHandler(const QString &driver, const QString &device) // Clear pending input char buf[2]; - while (read(mouseFD, buf, 1) > 0) { } + while (QT_READ(mouseFD, buf, 1) > 0) { } mouseIdx = 0; @@ -85,7 +86,7 @@ QVFbMouseHandler::QVFbMouseHandler(const QString &driver, const QString &device) QVFbMouseHandler::~QVFbMouseHandler() { if (mouseFD >= 0) - close(mouseFD); + QT_CLOSE(mouseFD); } void QVFbMouseHandler::resume() @@ -102,7 +103,7 @@ void QVFbMouseHandler::readMouseData() { int n; do { - n = read(mouseFD, mouseBuf+mouseIdx, mouseBufSize-mouseIdx); + n = QT_READ(mouseFD, mouseBuf+mouseIdx, mouseBufSize-mouseIdx); if (n > 0) mouseIdx += n; } while (n > 0); diff --git a/src/gui/embedded/qmousevr41xx_qws.cpp b/src/gui/embedded/qmousevr41xx_qws.cpp index 8748055..b7491d9 100644 --- a/src/gui/embedded/qmousevr41xx_qws.cpp +++ b/src/gui/embedded/qmousevr41xx_qws.cpp @@ -49,6 +49,7 @@ #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> @@ -144,7 +145,7 @@ QWSVr41xxMouseHandlerPrivate::QWSVr41xxMouseHandlerPrivate(QWSVr41xxMouseHandler else dev = options.first(); - if ((mouseFD = open(dev.toLocal8Bit().constData(), O_RDONLY)) < 0) { + if ((mouseFD = QT_OPEN(dev.toLocal8Bit().constData(), O_RDONLY)) < 0) { qWarning("Cannot open %s (%s)", qPrintable(dev), strerror(errno)); return; } @@ -167,7 +168,7 @@ QWSVr41xxMouseHandlerPrivate::QWSVr41xxMouseHandlerPrivate(QWSVr41xxMouseHandler QWSVr41xxMouseHandlerPrivate::~QWSVr41xxMouseHandlerPrivate() { if (mouseFD >= 0) - close(mouseFD); + QT_CLOSE(mouseFD); } void QWSVr41xxMouseHandlerPrivate::suspend() @@ -190,9 +191,9 @@ void QWSVr41xxMouseHandlerPrivate::sendRelease() bool QWSVr41xxMouseHandlerPrivate::getSample() { - const int n = read(mouseFD, - reinterpret_cast<uchar*>(currSample) + currLength, - sizeof(currSample) - currLength); + const int n = QT_READ(mouseFD, + reinterpret_cast<uchar*>(currSample) + currLength, + sizeof(currSample) - currLength); if (n > 0) currLength += n; diff --git a/src/gui/embedded/qmouseyopy_qws.cpp b/src/gui/embedded/qmouseyopy_qws.cpp index 7b1141a..3a541d3 100644 --- a/src/gui/embedded/qmouseyopy_qws.cpp +++ b/src/gui/embedded/qmouseyopy_qws.cpp @@ -46,6 +46,7 @@ #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> @@ -103,7 +104,7 @@ void QWSYopyMouseHandler::suspend() QWSYopyMouseHandlerPrivate::QWSYopyMouseHandlerPrivate(QWSYopyMouseHandler *h) : handler(h) { - if ((mouseFD = open("/dev/ts", O_RDONLY)) < 0) { + if ((mouseFD = QT_OPEN("/dev/ts", O_RDONLY)) < 0) { qWarning("Cannot open /dev/ts (%s)", strerror(errno)); return; } else { @@ -118,7 +119,7 @@ QWSYopyMouseHandlerPrivate::QWSYopyMouseHandlerPrivate(QWSYopyMouseHandler *h) QWSYopyMouseHandlerPrivate::~QWSYopyMouseHandlerPrivate() { if (mouseFD >= 0) - close(mouseFD); + QT_CLOSE(mouseFD); } #define YOPY_XPOS(d) (d[1]&0x3FF) @@ -156,7 +157,7 @@ void QWSYopyMouseHandlerPrivate::readMouseData() int ret; - ret=read(mouseFD,&yopDat,sizeof(yopDat)); + ret=QT_READ(mouseFD,&yopDat,sizeof(yopDat)); if(ret) { data.status= (YOPY_PRES(yopDat)) ? 1 : 0; diff --git a/src/gui/embedded/qscreenlinuxfb_qws.cpp b/src/gui/embedded/qscreenlinuxfb_qws.cpp index 42c4fcd..2845842 100644 --- a/src/gui/embedded/qscreenlinuxfb_qws.cpp +++ b/src/gui/embedded/qscreenlinuxfb_qws.cpp @@ -46,6 +46,7 @@ #include "qwsdisplay_qws.h" #include "qpixmap.h" #include <private/qwssignalhandler_p.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <unistd.h> #include <stdlib.h> @@ -122,12 +123,12 @@ void QLinuxFbScreenPrivate::openTty() if (ttyDevice.isEmpty()) { for (const char * const *dev = devs; *dev; ++dev) { - ttyfd = ::open(*dev, O_RDWR); + ttyfd = QT_OPEN(*dev, O_RDWR); if (ttyfd != -1) break; } } else { - ttyfd = ::open(ttyDevice.toAscii().constData(), O_RDWR); + ttyfd = QT_OPEN(ttyDevice.toAscii().constData(), O_RDWR); } if (ttyfd == -1) @@ -144,7 +145,7 @@ void QLinuxFbScreenPrivate::openTty() // No blankin' screen, no blinkin' cursor!, no cursor! const char termctl[] = "\033[9;0]\033[?33l\033[?25l\033[?1c"; - ::write(ttyfd, termctl, sizeof(termctl)); + QT_WRITE(ttyfd, termctl, sizeof(termctl)); } void QLinuxFbScreenPrivate::closeTty() @@ -157,9 +158,9 @@ void QLinuxFbScreenPrivate::closeTty() // Blankin' screen, blinkin' cursor! const char termctl[] = "\033[9;15]\033[?33h\033[?25h\033[?0c"; - ::write(ttyfd, termctl, sizeof(termctl)); + QT_WRITE(ttyfd, termctl, sizeof(termctl)); - ::close(ttyfd); + QT_CLOSE(ttyfd); ttyfd = -1; } @@ -281,7 +282,7 @@ bool QLinuxFbScreen::connect(const QString &displaySpec) dev = QLatin1String("/dev/fb0"); if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0) - d_ptr->fd = open(dev.toLatin1().constData(), O_RDWR); + d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR); if (d_ptr->fd == -1) { if (QApplication::type() == QApplication::GuiServer) { perror("QScreenLinuxFb::connect"); @@ -289,7 +290,7 @@ bool QLinuxFbScreen::connect(const QString &displaySpec) return false; } if (access(dev.toLatin1().constData(), R_OK) == 0) - d_ptr->fd = open(dev.toLatin1().constData(), O_RDONLY); + d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY); } fb_fix_screeninfo finfo; @@ -681,7 +682,7 @@ bool QLinuxFbScreen::initDevice() #ifdef __i386__ // Now init mtrr if(!::getenv("QWS_NOMTRR")) { - int mfd=open("/proc/mtrr",O_WRONLY,0); + int mfd=QT_OPEN("/proc/mtrr",O_WRONLY,0); // MTRR entry goes away when file is closed - i.e. // hopefully when QWS is killed if(mfd != -1) { @@ -702,6 +703,9 @@ bool QLinuxFbScreen::initDevice() //sentry.base,sentry.size,strerror(errno)); } } + + // Should we close mfd here? + //QT_CLOSE(mfd); } #endif if ((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4) || (finfo.visual==FB_VISUAL_DIRECTCOLOR)) diff --git a/src/gui/embedded/qsoundqss_qws.cpp b/src/gui/embedded/qsoundqss_qws.cpp index ac0ac9d..a45d0fe 100644 --- a/src/gui/embedded/qsoundqss_qws.cpp +++ b/src/gui/embedded/qsoundqss_qws.cpp @@ -53,6 +53,7 @@ #include <qtimer.h> #include <qpointer.h> #include <qendian.h> +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <unistd.h> #include <stdlib.h> @@ -1137,7 +1138,7 @@ void QWSSoundServerPrivate::sendCompletedSignals() int QWSSoundServerPrivate::openFile(int wid, int sid, const QString& filename) { stopFile(wid, sid); // close and re-open. - int f = ::open(QFile::encodeName(filename), O_RDONLY|O_NONBLOCK); + int f = QT_OPEN(QFile::encodeName(filename), O_RDONLY|O_NONBLOCK); if (f == -1) { // XXX check ferror, check reason. qDebug("Failed opening \"%s\"",filename.toLatin1().data()); @@ -1157,7 +1158,7 @@ bool QWSSoundServerPrivate::openDevice() { if (fd < 0) { if( silent ) { - fd = ::open( "/dev/null", O_WRONLY ); + fd = QT_OPEN( "/dev/null", O_WRONLY ); // Emulate write to audio device int delay = 1000*(sound_buffer_size>>(sound_stereo+sound_16bit))/sound_speed/2; timerId = startTimer(delay); @@ -1168,7 +1169,7 @@ bool QWSSoundServerPrivate::openDevice() // Don't block open right away. // bool openOkay = false; - if ((fd = ::open("/dev/dsp", O_WRONLY|O_NONBLOCK)) != -1) { + if ((fd = QT_OPEN("/dev/dsp", O_WRONLY|O_NONBLOCK)) != -1) { int flags = fcntl(fd, F_GETFL); flags &= ~O_NONBLOCK; openOkay = (fcntl(fd, F_SETFL, flags) == 0); @@ -1222,7 +1223,7 @@ bool QWSSoundServerPrivate::openDevice() // // Check system volume // - int mixerHandle = ::open( "/dev/mixer", O_RDWR|O_NONBLOCK ); + int mixerHandle = QT_OPEN( "/dev/mixer", O_RDWR|O_NONBLOCK ); if ( mixerHandle >= 0 ) { int volume; ioctl( mixerHandle, MIXER_READ(0), &volume ); diff --git a/src/gui/embedded/qtransportauth_qws.cpp b/src/gui/embedded/qtransportauth_qws.cpp index 05dce11..8523e27 100644 --- a/src/gui/embedded/qtransportauth_qws.cpp +++ b/src/gui/embedded/qtransportauth_qws.cpp @@ -56,6 +56,7 @@ #include "qlibraryinfo.h" #include "qfile.h" #include "qdebug.h" +#include <private/qcore_unix_p.h> // overrides QT_OPEN #include <syslog.h> #include <unistd.h> @@ -572,7 +573,7 @@ bool QTransportAuth::authorizeRequest( QTransportAuth::Data &d, const QString &r //get cmdline from proc/pid/cmdline snprintf( cmdlinePath, BUF_SIZE, "/proc/%d/cmdline", d.processId ); - int cmdlineFd = open( cmdlinePath, O_RDONLY ); + int cmdlineFd = QT_OPEN( cmdlinePath, O_RDONLY ); if ( cmdlineFd == -1 ) { qWarning( "SXE:- Error encountered in opening /proc/%u/cmdline: %s", @@ -581,13 +582,13 @@ bool QTransportAuth::authorizeRequest( QTransportAuth::Data &d, const QString &r } else { - if ( -1 == ::read(cmdlineFd, cmdline, BUF_SIZE - 1 ) ) + if ( -1 == QT_READ(cmdlineFd, cmdline, BUF_SIZE - 1 ) ) { qWarning( "SXE:- Error encountered in reading /proc/%u/cmdline : %s", d.processId, strerror(errno) ); snprintf( cmdline, BUF_SIZE, "%s", "Unknown" ); } - close( cmdlineFd ); + QT_CLOSE( cmdlineFd ); } syslog( LOG_ERR | LOG_LOCAL6, "%s // PID:%u // ProgId:%u // Exe:%s // Request:%s // Cmdline:%s", diff --git a/src/gui/embedded/qunixsocket.cpp b/src/gui/embedded/qunixsocket.cpp index 070d3cf..57a4a11 100644 --- a/src/gui/embedded/qunixsocket.cpp +++ b/src/gui/embedded/qunixsocket.cpp @@ -46,6 +46,7 @@ #include <QtCore/qsocketnotifier.h> #include <QtCore/qqueue.h> #include <QtCore/qdatetime.h> +#include "private/qcore_unix_p.h" // overrides QT_OPEN #ifdef QUNIXSOCKET_DEBUG #include <QtCore/qdebug.h> @@ -131,7 +132,7 @@ struct QUnixSocketRightsPrivate : public QSharedData #ifdef QUNIXSOCKET_DEBUG int closerv = #endif - ::close(fd); + QT_CLOSE(fd); #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocketRightsPrivate: Unable to close managed" @@ -162,7 +163,7 @@ QUnixSocketRights::QUnixSocketRights(int fd) if(-1 == fd) { d->fd = -1; } else { - d->fd = ::dup(fd); + d->fd = qt_safe_dup(fd); #ifdef QUNIXSOCKET_DEBUG if(-1 == d->fd) { qDebug() << "QUnixSocketRights: Unable to duplicate fd " @@ -232,7 +233,7 @@ int QUnixSocketRights::dupFd() const { if(-1 == d->fd) return -1; - int rv = ::dup(d->fd); + int rv = qt_safe_dup(d->fd); #ifdef QUNIXSOCKET_DEBUG if(-1 == rv) @@ -825,7 +826,7 @@ public: int numFds = (h->cmsg_len - CMSG_LEN(0)) / sizeof(int); for(int ii = 0; ii < numFds; ++ii) - ::close(fds[ii]); + QT_CLOSE(fds[ii]); } h = (::cmsghdr *)CMSG_NXTHDR(&(message), h); @@ -1017,7 +1018,7 @@ connect_error: // Cleanup failed connection #ifdef QUNIXSOCKET_DEBUG int closerv = #endif - ::close(d->fd); + QT_CLOSE(d->fd); #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocket: Unable to close file descriptor after " @@ -1762,7 +1763,12 @@ void QUnixSocketPrivate::readActivated() message.msg_controllen = ancillaryBufferCapacity(); message.msg_control = ancillaryBuffer; - int recvrv = ::recvmsg(fd, &message, 0); + int flags = 0; +#ifdef MSG_CMSG_CLOEXEC + flags = MSG_CMSG_CLOEXEC; +#endif + + int recvrv = ::recvmsg(fd, &message, flags); #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Received message (" << recvrv << ')'; #endif diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index a304027..a5ee7e6 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -323,6 +323,10 @@ performance reasons, these notifications are disabled by default. You must enable this flag to receive notifications for position and transform changes. This flag was introduced in Qt 4.6. + + \value ItemAcceptsInputMethod The item supports input methods typically + used for Asian languages. + This flag was introduced in Qt 4.6. */ /*! @@ -1486,6 +1490,12 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) d_ptr->scene->d_func()->needSortTopLevelItems = 1; } + if ((flags & ItemAcceptsInputMethod) != (oldFlags & ItemAcceptsInputMethod)) { + // Update input method sensitivity in any views. + if (d_ptr->scene) + d_ptr->scene->d_func()->updateInputMethodSensitivityInViews(); + } + if (d_ptr->scene) { d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true, @@ -2282,6 +2292,36 @@ void QGraphicsItem::setAcceptsHoverEvents(bool enabled) setAcceptHoverEvents(enabled); } +/*! \since 4.6 + + Returns true if an item accepts touch events (QTouchEvent); otherwise, returns false. By + default, items do not accept touch events. + + \sa setAcceptTouchEvents() +*/ +bool QGraphicsItem::acceptTouchEvents() const +{ + return d_ptr->acceptTouchEvents; +} + +/*! + \since 4.6 + + If \a enabled is true, this item will accept touch events; + otherwise, it will ignore them. By default, items do not accept + touch events. +*/ +void QGraphicsItem::setAcceptTouchEvents(bool enabled) +{ + if (d_ptr->acceptTouchEvents == quint32(enabled)) + return; + d_ptr->acceptTouchEvents = quint32(enabled); + if (d_ptr->acceptTouchEvents && d_ptr->scene && d_ptr->scene->d_func()->allItemsIgnoreTouchEvents) { + d_ptr->scene->d_func()->allItemsIgnoreTouchEvents = false; + d_ptr->scene->d_func()->enableTouchEventsOnViews(); + } +} + /*! Returns true if this item handles child events (i.e., all events intended for any of its children are instead sent to this item); @@ -9810,6 +9850,9 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) case QGraphicsItem::ItemSendsGeometryChanges: str = "ItemSendsGeometryChanges"; break; + case QGraphicsItem::ItemAcceptsInputMethod: + str = "ItemAcceptsInputMethod"; + break; } debug << str; return debug; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index aeb4691..d26110a 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -98,7 +98,8 @@ public: ItemStacksBehindParent = 0x100, ItemUsesExtendedStyleOption = 0x200, ItemHasNoContents = 0x400, - ItemSendsGeometryChanges = 0x800 + ItemSendsGeometryChanges = 0x800, + ItemAcceptsInputMethod = 0x1000 // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag. }; Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag) @@ -212,6 +213,8 @@ public: void setAcceptsHoverEvents(bool enabled); // obsolete bool acceptHoverEvents() const; void setAcceptHoverEvents(bool enabled); + bool acceptTouchEvents() const; + void setAcceptTouchEvents(bool enabled); bool handlesChildEvents() const; void setHandlesChildEvents(bool enabled); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index b9e7041..46ec6fe 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -54,6 +54,7 @@ // #include "qgraphicsitem.h" +#include "qset.h" #include "qpixmapcache.h" #include "qgraphicsview_p.h" @@ -153,6 +154,8 @@ public: isObject(0), ignoreVisible(0), ignoreOpacity(0), + acceptTouchEvents(0), + acceptedTouchBeginEvent(0), globalStackingOrder(-1), q_ptr(0) { @@ -174,7 +177,7 @@ public: void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const; void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const; - + // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4. virtual QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const; static bool movableAncestorIsSelected(const QGraphicsItem *item); @@ -243,7 +246,7 @@ public: } } } - + struct ExtraStruct { ExtraStruct(Extra type, QVariant value) : type(type), value(value) @@ -255,7 +258,7 @@ public: bool operator<(Extra extra) const { return type < extra; } }; - + QList<ExtraStruct> extras; QGraphicsItemCache *maybeExtraItemCache() const; @@ -384,7 +387,7 @@ public: int index; int depth; - // Packed 32 bits + // Packed 32 bytes quint32 acceptedMouseButtons : 5; quint32 visible : 1; quint32 explicitlyHidden : 1; @@ -401,8 +404,8 @@ public: quint32 cacheMode : 2; quint32 hasBoundingRegionGranularity : 1; quint32 isWidget : 1; - quint32 dirty : 1; - quint32 dirtyChildren : 1; + quint32 dirty : 1; + quint32 dirtyChildren : 1; quint32 localCollisionHack : 1; quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; @@ -412,7 +415,7 @@ public: quint32 fullUpdatePending : 1; // New 32 bits - quint32 flags : 12; + quint32 flags : 13; quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; @@ -421,7 +424,9 @@ public: quint32 isObject : 1; quint32 ignoreVisible : 1; quint32 ignoreOpacity : 1; - quint32 unused : 12; // feel free to use + quint32 acceptTouchEvents : 1; + quint32 acceptedTouchBeginEvent : 1; + quint32 unused : 9; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsproxywidget.cpp b/src/gui/graphicsview/qgraphicsproxywidget.cpp index 07ebb8c..5fac6cf 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget.cpp +++ b/src/gui/graphicsview/qgraphicsproxywidget.cpp @@ -275,7 +275,7 @@ void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneMouseEvent QWidget *embeddedMouseGrabberPtr = (QWidget *)embeddedMouseGrabber; QApplicationPrivate::sendMouseEvent(receiver, mouseEvent, alienWidget, widget, - &embeddedMouseGrabberPtr, lastWidgetUnderMouse); + &embeddedMouseGrabberPtr, lastWidgetUnderMouse, event->spontaneous()); embeddedMouseGrabber = embeddedMouseGrabberPtr; // Handle enter/leave events when last button is released from mouse @@ -451,6 +451,22 @@ void QGraphicsProxyWidgetPrivate::updateProxyGeometryFromWidget() /*! \internal +*/ +void QGraphicsProxyWidgetPrivate::updateProxyInputMethodAcceptanceFromWidget() +{ + Q_Q(QGraphicsProxyWidget); + if (!widget) + return; + + QWidget *focusWidget = widget->focusWidget(); + if (!focusWidget) + focusWidget = widget; + q->setFlag(QGraphicsItem::ItemAcceptsInputMethod, + focusWidget->testAttribute(Qt::WA_InputMethodEnabled)); +} + +/*! + \internal Embeds \a subWin as a subwindow of this proxy widget. \a subWin must be a top-level widget and a descendant of the widget managed by this proxy. A separate subproxy @@ -690,6 +706,8 @@ void QGraphicsProxyWidgetPrivate::setWidget_helper(QWidget *newWidget, bool auto updateProxyGeometryFromWidget(); + updateProxyInputMethodAcceptanceFromWidget(); + // Hook up the event filter to keep the state up to date. newWidget->installEventFilter(q); QObject::connect(newWidget, SIGNAL(destroyed()), q, SLOT(_q_removeWidgetSlot())); @@ -1303,8 +1321,8 @@ void QGraphicsProxyWidget::focusInEvent(QFocusEvent *event) if (d->widget && d->widget->focusWidget()) { d->widget->focusWidget()->setFocus(event->reason()); return; - } - break; + } + break; } } diff --git a/src/gui/graphicsview/qgraphicsproxywidget_p.h b/src/gui/graphicsview/qgraphicsproxywidget_p.h index ec5400a..fbc9f6c 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget_p.h +++ b/src/gui/graphicsview/qgraphicsproxywidget_p.h @@ -102,6 +102,8 @@ public: void updateWidgetGeometryFromProxy(); void updateProxyGeometryFromWidget(); + void updateProxyInputMethodAcceptanceFromWidget(); + QPointF mapToReceiver(const QPointF &pos, const QWidget *receiver) const; enum ChangeMode { diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 6c97886..0c3abd4 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -241,6 +241,8 @@ #include <QtGui/qstyleoption.h> #include <QtGui/qtooltip.h> #include <QtGui/qtransform.h> +#include <QtGui/qgesture.h> +#include <QtGui/qinputcontext.h> #include <private/qapplication_p.h> #include <private/qobject_p.h> #ifdef Q_WS_X11 @@ -358,7 +360,8 @@ QGraphicsScenePrivate::QGraphicsScenePrivate() painterStateProtection(true), sortCacheEnabled(false), updatingSortCache(false), - style(0) + style(0), + allItemsIgnoreTouchEvents(true) { } @@ -1357,6 +1360,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou // event is converted to a press. Known limitation: // Triple-clicking will not generate a doubleclick, though. QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress); + mousePress.spont = mouseEvent->spont; mousePress.accept(); mousePress.setButton(mouseEvent->button()); mousePress.setButtons(mouseEvent->buttons()); @@ -2942,6 +2946,7 @@ void QGraphicsScene::clear() d->largestUntransformableItem = QRectF(); d->allItemsIgnoreHoverEvents = true; d->allItemsUseDefaultCursor = true; + d->allItemsIgnoreTouchEvents = true; } /*! @@ -3119,6 +3124,12 @@ void QGraphicsScene::addItem(QGraphicsItem *item) } #endif //QT_NO_CURSOR + // Enable touch events if the item accepts touch events. + if (d->allItemsIgnoreTouchEvents && item->acceptTouchEvents()) { + d->allItemsIgnoreTouchEvents = false; + d->enableTouchEventsOnViews(); + } + // Update selection lists if (item->isSelected()) d->selectedItems << item; @@ -3165,6 +3176,8 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // Deliver post-change notification item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); + + d->updateInputMethodSensitivityInViews(); } /*! @@ -3440,6 +3453,8 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) // Deliver post-change notification item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); + + d->updateInputMethodSensitivityInViews(); } /*! @@ -3494,6 +3509,17 @@ void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReas d->lastFocusItem = d->focusItem; d->focusItem = 0; d->sendEvent(d->lastFocusItem, &event); + + if (d->lastFocusItem + && (d->lastFocusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) { + // Reset any visible preedit text + QInputMethodEvent imEvent; + d->sendEvent(d->lastFocusItem, &imEvent); + + // Close any external input method panel + for (int i = 0; i < d->views.size(); ++i) + d->views.at(i)->inputContext()->reset(); + } } if (item) { @@ -3506,6 +3532,8 @@ void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReas QFocusEvent event(QEvent::FocusIn, focusReason); d->sendEvent(item, &event); } + + d->updateInputMethodSensitivityInViews(); } /*! @@ -3689,7 +3717,7 @@ void QGraphicsScene::setForegroundBrush(const QBrush &brush) QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const { Q_D(const QGraphicsScene); - if (!d->focusItem) + if (!d->focusItem || !(d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) return QVariant(); const QTransform matrix = d->focusItem->sceneTransform(); QVariant value = d->focusItem->inputMethodQuery(query); @@ -3850,6 +3878,9 @@ bool QGraphicsScene::event(QEvent *event) case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverLeave: case QEvent::GraphicsSceneHoverMove: + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: // Reset the under-mouse list to ensure that this event gets fresh // item-under-mouse data. Be careful about this list; if people delete // items from inside event handlers, this list can quickly end up @@ -4003,6 +4034,11 @@ bool QGraphicsScene::event(QEvent *event) // geometries that do not have an explicit style set. update(); break; + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + d->touchEventHandler(static_cast<QTouchEvent *>(event)); + break; case QEvent::Timer: if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) { if (d->restartIndexTimer) { @@ -4644,16 +4680,16 @@ void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent) subclass to receive input method events for the scene. The default implementation forwards the event to the focusItem(). - If no item currently has focus, this function does nothing. + If no item currently has focus or the current focus item does not + accept input methods, this function does nothing. \sa QGraphicsItem::inputMethodEvent() */ void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event) { Q_D(QGraphicsScene); - if (!d->focusItem) - return; - d->sendEvent(d->focusItem, event); + if (d->focusItem && (d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) + d->sendEvent(d->focusItem, event); } /*! @@ -5863,6 +5899,259 @@ void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget) } } +/*! + \since 4.6 + + Sends event \a event to item \a item through possible event filters. + + The event is sent only if the item is enabled. + + Returns \c false if the event was filtered or if the item is disabled. + Otherwise returns the value that was returned from the event handler. + + \sa QGraphicsItem::sceneEvent(), QGraphicsItem::sceneEventFilter() +*/ +bool QGraphicsScene::sendEvent(QGraphicsItem *item, QEvent *event) +{ + Q_D(QGraphicsScene); + if (!item) { + qWarning("QGraphicsScene::sendEvent: cannot send event to a null item"); + return false; + } + if (item->scene() != this) { + qWarning("QGraphicsScene::sendEvent: item %p's scene (%p)" + " is different from this scene (%p)", + item, item->scene(), this); + return false; + } + return d->sendEvent(item, event); +} + +void QGraphicsScenePrivate::addView(QGraphicsView *view) +{ + views << view; +} + +void QGraphicsScenePrivate::removeView(QGraphicsView *view) +{ + views.removeAll(view); +} + +void QGraphicsScenePrivate::updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent) +{ + QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints(); + for (int i = 0; i < touchPoints.count(); ++i) { + QTouchEvent::TouchPoint &touchPoint = touchPoints[i]; + touchPoint.setRect(item->mapFromScene(touchPoint.sceneRect()).boundingRect()); + touchPoint.setStartPos(item->d_ptr->genericMapFromScene(touchPoint.startScenePos(), touchEvent->widget())); + touchPoint.setLastPos(item->d_ptr->genericMapFromScene(touchPoint.lastScenePos(), touchEvent->widget())); + } + touchEvent->setTouchPoints(touchPoints); +} + +int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos) +{ + int closestTouchPointId = -1; + qreal closestDistance = qreal(0.); + foreach (const QTouchEvent::TouchPoint &touchPoint, sceneCurrentTouchPoints) { + qreal distance = QLineF(scenePos, touchPoint.scenePos()).length(); + if (closestTouchPointId == -1|| distance < closestDistance) { + closestTouchPointId = touchPoint.id(); + closestDistance = distance; + } + } + return closestTouchPointId; +} + +void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent) +{ + typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints; + QHash<QGraphicsItem *, StatesAndTouchPoints> itemsNeedingEvents; + + for (int i = 0; i < sceneTouchEvent->touchPoints().count(); ++i) { + const QTouchEvent::TouchPoint &touchPoint = sceneTouchEvent->touchPoints().at(i); + + // update state + QGraphicsItem *item = 0; + if (touchPoint.state() == Qt::TouchPointPressed) { + if (sceneTouchEvent->deviceType() == QTouchEvent::TouchPad) { + // on touch-pad devices, send all touch points to the same item + item = itemForTouchPointId.isEmpty() + ? 0 + : itemForTouchPointId.constBegin().value(); + } + + if (!item) { + // determine which item this touch point will go to + cachedItemsUnderMouse = itemsAtPosition(touchPoint.screenPos().toPoint(), + touchPoint.scenePos(), + sceneTouchEvent->widget()); + item = cachedItemsUnderMouse.isEmpty() ? 0 : cachedItemsUnderMouse.first(); + } + + if (sceneTouchEvent->deviceType() == QTouchEvent::TouchScreen) { + // on touch-screens, combine this touch point with the closest one we find if it + // is a a direct descendent or ancestor ( + int closestTouchPointId = findClosestTouchPointId(touchPoint.scenePos()); + QGraphicsItem *closestItem = itemForTouchPointId.value(closestTouchPointId); + if (!item + || (closestItem + && (item->isAncestorOf(closestItem) + || closestItem->isAncestorOf(item)))) { + item = closestItem; + } + } + if (!item) + continue; + + itemForTouchPointId.insert(touchPoint.id(), item); + sceneCurrentTouchPoints.insert(touchPoint.id(), touchPoint); + } else if (touchPoint.state() == Qt::TouchPointReleased) { + item = itemForTouchPointId.take(touchPoint.id()); + if (!item) + continue; + + sceneCurrentTouchPoints.remove(touchPoint.id()); + } else { + item = itemForTouchPointId.value(touchPoint.id()); + if (!item) + continue; + Q_ASSERT(sceneCurrentTouchPoints.contains(touchPoint.id())); + sceneCurrentTouchPoints[touchPoint.id()] = touchPoint; + } + + StatesAndTouchPoints &statesAndTouchPoints = itemsNeedingEvents[item]; + statesAndTouchPoints.first |= touchPoint.state(); + statesAndTouchPoints.second.append(touchPoint); + } + + if (itemsNeedingEvents.isEmpty()) { + sceneTouchEvent->ignore(); + return; + } + + bool acceptSceneTouchEvent = false; + QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator it = itemsNeedingEvents.constBegin(); + const QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator end = itemsNeedingEvents.constEnd(); + for (; it != end; ++it) { + QGraphicsItem *item = it.key(); + + // determine event type from the state mask + QEvent::Type eventType; + switch (it.value().first) { + case Qt::TouchPointPressed: + // all touch points have pressed state + eventType = QEvent::TouchBegin; + break; + case Qt::TouchPointReleased: + // all touch points have released state + eventType = QEvent::TouchEnd; + break; + case Qt::TouchPointStationary: + // don't send the event if nothing changed + continue; + default: + // all other combinations + eventType = QEvent::TouchUpdate; + break; + } + + QTouchEvent touchEvent(eventType); + touchEvent.setWidget(sceneTouchEvent->widget()); + touchEvent.setDeviceType(sceneTouchEvent->deviceType()); + touchEvent.setModifiers(sceneTouchEvent->modifiers()); + touchEvent.setTouchPointStates(it.value().first); + touchEvent.setTouchPoints(it.value().second); + + switch (touchEvent.type()) { + case QEvent::TouchBegin: + { + // if the TouchBegin handler recurses, we assume that means the event + // has been implicitly accepted and continue to send touch events + item->d_ptr->acceptedTouchBeginEvent = true; + bool res = sendTouchBeginEvent(item, &touchEvent) + && touchEvent.isAccepted(); + acceptSceneTouchEvent = acceptSceneTouchEvent || res; + break; + } + default: + if (item->d_ptr->acceptedTouchBeginEvent) { + updateTouchPointsForItem(item, &touchEvent); + (void) sendEvent(item, &touchEvent); + acceptSceneTouchEvent = true; + } + break; + } + } + sceneTouchEvent->setAccepted(acceptSceneTouchEvent); +} + +bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEvent *touchEvent) +{ + Q_Q(QGraphicsScene); + + if (cachedItemsUnderMouse.isEmpty() || cachedItemsUnderMouse.first() != origin) { + const QTouchEvent::TouchPoint &firstTouchPoint = touchEvent->touchPoints().first(); + cachedItemsUnderMouse = itemsAtPosition(firstTouchPoint.screenPos().toPoint(), + firstTouchPoint.scenePos(), + touchEvent->widget()); + } + Q_ASSERT(cachedItemsUnderMouse.first() == origin); + + // Set focus on the topmost enabled item that can take focus. + bool setFocus = false; + foreach (QGraphicsItem *item, cachedItemsUnderMouse) { + if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) { + if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) { + setFocus = true; + if (item != q->focusItem()) + q->setFocusItem(item, Qt::MouseFocusReason); + break; + } + } + } + + // If nobody could take focus, clear it. + if (!stickyFocus && !setFocus) + q->setFocusItem(0, Qt::MouseFocusReason); + + bool res = false; + bool eventAccepted = touchEvent->isAccepted(); + foreach (QGraphicsItem *item, cachedItemsUnderMouse) { + // first, try to deliver the touch event + updateTouchPointsForItem(item, touchEvent); + bool acceptTouchEvents = item->acceptTouchEvents(); + touchEvent->setAccepted(acceptTouchEvents); + res = acceptTouchEvents && sendEvent(item, touchEvent); + eventAccepted = touchEvent->isAccepted(); + item->d_ptr->acceptedTouchBeginEvent = (res && eventAccepted); + touchEvent->spont = false; + if (res && eventAccepted) { + // the first item to accept the TouchBegin gets an implicit grab. + for (int i = 0; i < touchEvent->touchPoints().count(); ++i) { + const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i); + itemForTouchPointId[touchPoint.id()] = item; + } + break; + } + } + + touchEvent->setAccepted(eventAccepted); + return res; +} + +void QGraphicsScenePrivate::enableTouchEventsOnViews() +{ + foreach (QGraphicsView *view, views) + view->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true); +} + +void QGraphicsScenePrivate::updateInputMethodSensitivityInViews() +{ + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->updateInputMethodSensitivity(); +} + QT_END_NAMESPACE #include "moc_qgraphicsscene.cpp" diff --git a/src/gui/graphicsview/qgraphicsscene.h b/src/gui/graphicsview/qgraphicsscene.h index 1d4a617..6aaeb91 100644 --- a/src/gui/graphicsview/qgraphicsscene.h +++ b/src/gui/graphicsview/qgraphicsscene.h @@ -189,7 +189,7 @@ public: inline QGraphicsRectItem *addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen = QPen(), const QBrush &brush = QBrush()) { return addRect(QRectF(x, y, w, h), pen, brush); } void removeItem(QGraphicsItem *item); - + QGraphicsItem *focusItem() const; void setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason = Qt::OtherFocusReason); bool hasFocus() const; @@ -228,6 +228,8 @@ public: QGraphicsWidget *activeWindow() const; void setActiveWindow(QGraphicsWidget *widget); + bool sendEvent(QGraphicsItem *item, QEvent *event); + public Q_SLOTS: void update(const QRectF &rect = QRectF()); void invalidate(const QRectF &rect = QRectF(), SceneLayers layers = AllLayers); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 2f63e5b..dc720a7 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -57,6 +57,7 @@ #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW +#include "qgraphicssceneevent.h" #include "qgraphicsview.h" #include "qgraphicsscene_bsp_p.h" #include "qgraphicsitem_p.h" @@ -165,7 +166,7 @@ public: void grabKeyboard(QGraphicsItem *item); void ungrabKeyboard(QGraphicsItem *item, bool itemIsDying = false); void clearKeyboardGrabber(); - + QGraphicsItem *dragDropItem; QGraphicsWidget *enterWidget; Qt::DropAction lastDropAction; @@ -184,6 +185,9 @@ public: void storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event); QList<QGraphicsView *> views; + void addView(QGraphicsView *view); + void removeView(QGraphicsView *view); + bool painterStateProtection; QMultiMap<QGraphicsItem *, QGraphicsItem *> sceneEventFilters; @@ -247,7 +251,7 @@ public: static bool closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2); static inline bool closestItemFirst_withCache(const QGraphicsItem *item1, const QGraphicsItem *item2) - { + { return item1->d_ptr->globalStackingOrder < item2->d_ptr->globalStackingOrder; } static inline bool closestItemLast_withCache(const QGraphicsItem *item1, const QGraphicsItem *item2) @@ -303,6 +307,17 @@ public: void updatePalette(const QPalette &palette); QStyleOptionGraphicsItem styleOptionTmp; + + QMap<int, QTouchEvent::TouchPoint> sceneCurrentTouchPoints; + QMap<int, QGraphicsItem *> itemForTouchPointId; + static void updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent); + int findClosestTouchPointId(const QPointF &scenePos); + void touchEventHandler(QTouchEvent *touchEvent); + bool sendTouchBeginEvent(QGraphicsItem *item, QTouchEvent *touchEvent); + bool allItemsIgnoreTouchEvents; + void enableTouchEventsOnViews(); + + void updateInputMethodSensitivityInViews(); }; QT_END_NAMESPACE diff --git a/src/gui/graphicsview/qgraphicssceneevent.cpp b/src/gui/graphicsview/qgraphicssceneevent.cpp index 283010d..53019f2 100644 --- a/src/gui/graphicsview/qgraphicssceneevent.cpp +++ b/src/gui/graphicsview/qgraphicssceneevent.cpp @@ -76,14 +76,14 @@ received by the view (see \l{QGraphicsSceneMouseEvent::}{lastScreenPos()}, \l{QGraphicsSceneMouseEvent::}{lastScenePos()}, and - \l{QGraphicsSceneMouseEvent::}{lastPos()}). + \l{QGraphicsSceneMouseEvent::}{lastPos()}). \sa QEvent */ /*! \class QGraphicsSceneMouseEvent - \brief The QGraphicsSceneMouseEvent class provides mouse events + \brief The QGraphicsSceneMouseEvent class provides mouse events in the graphics view framework. \since 4.2 \ingroup multimedia @@ -106,7 +106,7 @@ /*! \class QGraphicsSceneWheelEvent - \brief The QGraphicsSceneWheelEvent class provides wheel events + \brief The QGraphicsSceneWheelEvent class provides wheel events in the graphics view framework. \brief The QGraphicsSceneWheelEvent class provides wheel events in the graphics view framework. @@ -157,7 +157,7 @@ /*! \class QGraphicsSceneHoverEvent - \brief The QGraphicsSceneHoverEvent class provides hover events + \brief The QGraphicsSceneHoverEvent class provides hover events in the graphics view framework. \since 4.2 \ingroup multimedia @@ -173,7 +173,7 @@ /*! \class QGraphicsSceneHelpEvent - \brief The QGraphicsSceneHelpEvent class provides events when a + \brief The QGraphicsSceneHelpEvent class provides events when a tooltip is requested. \since 4.2 \ingroup multimedia @@ -199,7 +199,7 @@ /*! \class QGraphicsSceneDragDropEvent \brief The QGraphicsSceneDragDropEvent class provides events for - drag and drop in the graphics view framework. + drag and drop in the graphics view framework. \since 4.2 \ingroup multimedia \ingroup graphicsview-api @@ -268,6 +268,10 @@ #include <QtCore/qpoint.h> #include <QtCore/qsize.h> #include <QtCore/qstring.h> +#include "qgraphicsview.h" +#include "qgraphicsitem.h" +#include <QtGui/qgesture.h> +#include <private/qevent_p.h> QT_BEGIN_NAMESPACE @@ -522,7 +526,7 @@ void QGraphicsSceneMouseEvent::setLastPos(const QPointF &pos) } /*! - Returns the last recorded mouse cursor position in scene + Returns the last recorded mouse cursor position in scene coordinates. The last recorded position is the position of the previous mouse event received by the view that created the event. @@ -545,7 +549,7 @@ void QGraphicsSceneMouseEvent::setLastScenePos(const QPointF &pos) } /*! - Returns the last recorded mouse cursor position in screen + Returns the last recorded mouse cursor position in screen coordinates. The last recorded position is the position of the previous mouse event received by the view that created the event. @@ -1275,7 +1279,7 @@ QGraphicsSceneDragDropEvent::~QGraphicsSceneDragDropEvent() /*! Returns the mouse position of the event relative to the view that sent the event. - + \sa QGraphicsView, screenPos(), scenePos() */ QPointF QGraphicsSceneDragDropEvent::pos() const @@ -1373,7 +1377,7 @@ void QGraphicsSceneDragDropEvent::setButtons(Qt::MouseButtons buttons) /*! Returns the keyboard modifiers that were pressed when the drag - and drop event was created. + and drop event was created. \sa Qt::KeyboardModifiers */ @@ -1428,7 +1432,7 @@ void QGraphicsSceneDragDropEvent::setPossibleActions(Qt::DropActions actions) The action must be one of the possible actions as defined by \c possibleActions(). - \sa Qt::DropAction, possibleActions() + \sa Qt::DropAction, possibleActions() */ Qt::DropAction QGraphicsSceneDragDropEvent::proposedAction() const diff --git a/src/gui/graphicsview/qgraphicssceneevent.h b/src/gui/graphicsview/qgraphicssceneevent.h index d493de3..b38e757 100644 --- a/src/gui/graphicsview/qgraphicssceneevent.h +++ b/src/gui/graphicsview/qgraphicssceneevent.h @@ -44,6 +44,10 @@ #include <QtCore/qcoreevent.h> #include <QtCore/qpoint.h> +#include <QtCore/qrect.h> +#include <QtGui/qpolygon.h> +#include <QtCore/qset.h> +#include <QtCore/qhash.h> QT_BEGIN_HEADER diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 1ba87ec..3b29552 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -280,12 +280,17 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < #include <QtGui/qpainter.h> #include <QtGui/qscrollbar.h> #include <QtGui/qstyleoption.h> +#include <QtGui/qinputcontext.h> #ifdef Q_WS_X11 #include <private/qt_x11_p.h> #endif +#include <private/qevent_p.h> + QT_BEGIN_NAMESPACE +bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); + inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for single precision { if (d <= (qreal) INT_MIN) @@ -295,6 +300,23 @@ inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for sing return d >= 0.0 ? int(d + 0.5) : int(d - int(d-1) + 0.5) + int(d-1); } +void QGraphicsViewPrivate::translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent) +{ + QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints(); + for (int i = 0; i < touchPoints.count(); ++i) { + QTouchEvent::TouchPoint &touchPoint = touchPoints[i]; + // the scene will set the item local pos, startPos, lastPos, and rect before delivering to + // an item, but for now those functions are returning the view's local coordinates + touchPoint.setSceneRect(d->mapToScene(touchPoint.rect())); + touchPoint.setStartScenePos(d->mapToScene(touchPoint.startPos())); + touchPoint.setLastScenePos(d->mapToScene(touchPoint.lastPos())); + + // screenPos, startScreenPos, lastScreenPos, and screenRect are already set + } + + touchEvent->setTouchPoints(touchPoints); +} + /*! \internal */ @@ -591,7 +613,10 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) lastMouseMoveScenePoint = mouseEvent.scenePos(); lastMouseMoveScreenPoint = mouseEvent.screenPos(); mouseEvent.setAccepted(false); - QApplication::sendEvent(scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(scene, &mouseEvent); + else + QApplication::sendEvent(scene, &mouseEvent); // Remember whether the last event was accepted or not. lastMouseEvent.setAccepted(mouseEvent.isAccepted()); @@ -993,6 +1018,22 @@ QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedReg } /*! + \internal + + Enables input methods for the view if and only if the current focus item of + the scene accepts input methods. Call function whenever that condition has + potentially changed. +*/ +void QGraphicsViewPrivate::updateInputMethodSensitivity() +{ + Q_Q(QGraphicsView); + q->setAttribute( + Qt::WA_InputMethodEnabled, + scene && scene->focusItem() + && scene->focusItem()->flags() & QGraphicsItem::ItemAcceptsInputMethod); +} + +/*! Constructs a QGraphicsView. \a parent is passed to QWidget's constructor. */ QGraphicsView::QGraphicsView(QWidget *parent) @@ -1488,7 +1529,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene) this, SLOT(updateScene(QList<QRectF>))); disconnect(d->scene, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(updateSceneRect(QRectF))); - d->scene->d_func()->views.removeAll(this); + d->scene->d_func()->removeView(this); d->connectedToScene = false; } @@ -1497,7 +1538,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene) connect(d->scene, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(updateSceneRect(QRectF))); d->updateSceneSlotReimplementedChecked = false; - d->scene->d_func()->views << this; + d->scene->d_func()->addView(this); d->recalculateContentSize(); d->lastCenterPoint = sceneRect().center(); d->keepLastCenterPoint = true; @@ -1507,9 +1548,15 @@ void QGraphicsView::setScene(QGraphicsScene *scene) || !d->scene->d_func()->allItemsUseDefaultCursor) { d->viewport->setMouseTracking(true); } + + // enable touch events if any items is interested in them + if (!d->scene->d_func()->allItemsIgnoreTouchEvents) + d->viewport->setAttribute(Qt::WA_AcceptTouchEvents); } else { d->recalculateContentSize(); } + + d->updateInputMethodSensitivity(); } /*! @@ -2589,6 +2636,11 @@ void QGraphicsView::setupViewport(QWidget *widget) || !d->scene->d_func()->allItemsUseDefaultCursor)) { widget->setMouseTracking(true); } + + // enable touch events if any items is interested in them + if (d->scene && !d->scene->d_func()->allItemsIgnoreTouchEvents) + widget->setAttribute(Qt::WA_AcceptTouchEvents); + widget->setAcceptDrops(acceptDrops()); } @@ -2706,6 +2758,23 @@ bool QGraphicsView::viewportEvent(QEvent *event) d->scene->d_func()->updateAll = false; } break; + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + { + if (!isEnabled()) + return false; + + if (d->scene && d->sceneInteractionAllowed) { + // Convert and deliver the touch event to the scene. + QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event); + touchEvent->setWidget(viewport()); + QGraphicsViewPrivate::translateTouchEvent(d, touchEvent); + (void) QApplication::sendEvent(d->scene, touchEvent); + } + + return true; + } default: break; } @@ -2879,6 +2948,7 @@ void QGraphicsView::dragMoveEvent(QDragMoveEvent *event) void QGraphicsView::focusInEvent(QFocusEvent *event) { Q_D(QGraphicsView); + d->updateInputMethodSensitivity(); QAbstractScrollArea::focusInEvent(event); if (d->scene) QApplication::sendEvent(d->scene, event); @@ -2964,7 +3034,10 @@ void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event) mouseEvent.setAccepted(false); mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); } /*! @@ -3003,7 +3076,10 @@ void QGraphicsView::mousePressEvent(QMouseEvent *event) mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); mouseEvent.setAccepted(false); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); // Update the original mouse event accepted state. bool isAccepted = mouseEvent.isAccepted(); @@ -3173,7 +3249,10 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event) mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); mouseEvent.setAccepted(false); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); // Update the last mouse event selected state. d->lastMouseEvent.setAccepted(mouseEvent.isAccepted()); @@ -3304,7 +3383,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) // Find all exposed items bool allItems = false; QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems); - + if (!itemList.isEmpty()) { // Generate the style options. const int numItems = itemList.size(); @@ -3632,6 +3711,39 @@ void QGraphicsView::resetTransform() setTransform(QTransform()); } +QPointF QGraphicsViewPrivate::mapToScene(const QPointF &point) const +{ + QPointF p = point; + p.rx() += horizontalScroll(); + p.ry() += verticalScroll(); + return identityMatrix ? p : matrix.inverted().map(p); +} + +QRectF QGraphicsViewPrivate::mapToScene(const QRectF &rect) const +{ + QPointF scrollOffset(horizontalScroll(), verticalScroll()); + QPointF tl = scrollOffset + rect.topLeft(); + QPointF tr = scrollOffset + rect.topRight(); + QPointF br = scrollOffset + rect.bottomRight(); + QPointF bl = scrollOffset + rect.bottomLeft(); + + QPolygonF poly; + poly.resize(4); + if (!identityMatrix) { + QTransform x = matrix.inverted(); + poly[0] = x.map(tl); + poly[1] = x.map(tr); + poly[2] = x.map(br); + poly[3] = x.map(bl); + } else { + poly[0] = tl; + poly[1] = tr; + poly[2] = br; + poly[3] = bl; + } + return poly.boundingRect(); +} + QT_END_NAMESPACE #include "moc_qgraphicsview.cpp" diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index 9551ff6..09d842d 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -177,6 +177,11 @@ public: QRegion exposedRegion; QList<QGraphicsItem *> findItems(const QRegion &exposedRegion, bool *allItems) const; + + QPointF mapToScene(const QPointF &point) const; + QRectF mapToScene(const QRectF &rect) const; + static void translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent); + void updateInputMethodSensitivity(); }; QT_END_NAMESPACE diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 0644ce9..86c0b48 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -971,15 +971,18 @@ void QGraphicsWidget::updateGeometry() deliver events related to state changes in the item. Because of this, it is very important that subclasses call the base implementation. - For example, QGraphicsWidget uses ItemVisibleChange to deliver \l Show and - \l Hide events, ItemPositionHasChanged to deliver \l Move events, and - ItemParentChange both to deliver \l ParentChange events, and for managing - the focus chain. + \a change specifies the type of change, and \a value is the new value. + + For example, QGraphicsWidget uses ItemVisibleChange to deliver + \l{QEvent::Show} {Show} and \l{QEvent::Hide}{Hide} events, + ItemPositionHasChanged to deliver \l{QEvent::Move}{Move} events, + and ItemParentChange both to deliver \l{QEvent::ParentChange} + {ParentChange} events, and for managing the focus chain. QGraphicsWidget enables the ItemSendsGeometryChanges flag by default in order to track position changes. - \sa propertyChange() + \sa QGraphicsItem::itemChange() */ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) { @@ -1211,7 +1214,8 @@ Qt::WindowFrameSection QGraphicsWidget::windowFrameSectionAt(const QPointF &pos) /*! \reimp - QGraphicsWidget handles the following events: + Handles the \a event. QGraphicsWidget handles the following + events: \table \o Event \o Usage \row \o Polish diff --git a/src/gui/image/qpixmap_win.cpp b/src/gui/image/qpixmap_win.cpp index 2c84ce7..56b53bd 100644 --- a/src/gui/image/qpixmap_win.cpp +++ b/src/gui/image/qpixmap_win.cpp @@ -179,13 +179,7 @@ QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format) BITMAP bitmap_info; memset(&bitmap_info, 0, sizeof(BITMAP)); - int res; - QT_WA({ - res = GetObjectW(bitmap, sizeof(BITMAP), &bitmap_info); - } , { - res = GetObjectA(bitmap, sizeof(BITMAP), &bitmap_info); - }); - + int res = GetObject(bitmap, sizeof(BITMAP), &bitmap_info); if (!res) { qErrnoWarning("QPixmap::fromWinHBITMAP(), failed to get bitmap info"); return QPixmap(); @@ -417,9 +411,9 @@ QPixmap convertHIconToPixmap( const HICON icon, bool large) QPixmap loadIconFromShell32( int resourceId, int size ) { #ifdef Q_OS_WINCE - HMODULE hmod = LoadLibrary((const wchar_t *) QString::fromLatin1("ceshell.dll").utf16()); + HMODULE hmod = LoadLibrary(L"ceshell.dll"); #else - HMODULE hmod = LoadLibraryA("shell32.dll"); + HMODULE hmod = LoadLibrary(L"shell32.dll"); #endif if( hmod ) { HICON iconHandle = (HICON)LoadImage(hmod, MAKEINTRESOURCE(resourceId), IMAGE_ICON, size, size, 0); diff --git a/src/gui/inputmethod/qwininputcontext_win.cpp b/src/gui/inputmethod/qwininputcontext_win.cpp index 3bbde89..741d8da 100644 --- a/src/gui/inputmethod/qwininputcontext_win.cpp +++ b/src/gui/inputmethod/qwininputcontext_win.cpp @@ -45,16 +45,11 @@ #include "qfont.h" #include "qwidget.h" #include "qapplication.h" -#include "qlibrary.h" #include "qevent.h" #include "qtextformat.h" //#define Q_IME_DEBUG -/* Active Input method support on Win95/98/NT */ -#include <objbase.h> -#include <initguid.h> - #ifdef Q_IME_DEBUG #include "qdebug.h" #endif @@ -218,25 +213,6 @@ static DWORD WM_MSIME_MOUSE = 0; QWinInputContext::QWinInputContext(QObject *parent) : QInputContext(parent), recursionGuard(false) { - if (QSysInfo::WindowsVersion < QSysInfo::WV_2000) { - // try to get the Active IMM COM object on Win95/98/NT, where english versions don't - // support the regular Windows input methods. - if (CoCreateInstance(CLSID_CActiveIMM, NULL, CLSCTX_INPROC_SERVER, - IID_IActiveIMMApp, (LPVOID *)&aimm) != S_OK) { - aimm = 0; - } - if (aimm && (aimm->QueryInterface(IID_IActiveIMMMessagePumpOwner, (LPVOID *)&aimmpump) != S_OK || - aimm->Activate(true) != S_OK)) { - aimm->Release(); - aimm = 0; - if (aimmpump) - aimmpump->Release(); - aimmpump = 0; - } - if (aimmpump) - aimmpump->Start(); - } - #ifndef Q_WS_WINCE QSysInfo::WinVersion ver = QSysInfo::windowsVersion(); if (ver & QSysInfo::WV_NT_based && ver >= QSysInfo::WV_VISTA) { @@ -262,25 +238,21 @@ QWinInputContext::QWinInputContext(QObject *parent) delete []lpList; } } else { - // figure out whether a RTL language is installed - typedef BOOL(WINAPI *PtrIsValidLanguageGroup)(DWORD,DWORD); - PtrIsValidLanguageGroup isValidLanguageGroup = (PtrIsValidLanguageGroup)QLibrary::resolve(QLatin1String("kernel32"), "IsValidLanguageGroup"); - if (isValidLanguageGroup) { - qt_use_rtl_extensions = isValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED) - || isValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED); - } - qt_use_rtl_extensions |= IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) - || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) + // figure out whether a RTL language is installed + qt_use_rtl_extensions = IsValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED) + || IsValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED) + || IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) + || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #ifdef LANG_SYRIAC - || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) + || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #endif - || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED); + || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED); } #else qt_use_rtl_extensions = false; #endif - WM_MSIME_MOUSE = QT_WA_INLINE(RegisterWindowMessage(L"MSIMEMouseOperation"), RegisterWindowMessageA("MSIMEMouseOperation")); + WM_MSIME_MOUSE = RegisterWindowMessage(L"MSIMEMouseOperation"); } QWinInputContext::~QWinInputContext() @@ -337,26 +309,13 @@ static void notifyIME(HIMC imc, DWORD dwAction, DWORD dwIndex, DWORD dwValue) ImmNotifyIME(imc, dwAction, dwIndex, dwValue); } -static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen, bool *unicode = 0) +static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen) { LONG len = 0; - if (unicode) - *unicode = true; if (aimm) aimm->GetCompositionStringW(himc, dwIndex, dBufLen, &len, lpbuf); else - { - if(QSysInfo::WindowsVersion != QSysInfo::WV_95) { - len = ImmGetCompositionStringW(himc, dwIndex, lpbuf, dBufLen); - } -#if !defined(Q_WS_WINCE) - else { - len = ImmGetCompositionStringA(himc, dwIndex, lpbuf, dBufLen); - if (unicode) - *unicode = false; - } -#endif - } + len = ImmGetCompositionString(himc, dwIndex, lpbuf, dBufLen); return len; } @@ -367,29 +326,28 @@ static int getCursorPosition(HIMC himc) static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLength = 0) { - static char *buffer = 0; + static wchar_t *buffer = 0; static int buflen = 0; int len = getCompositionString(himc, dwindex, 0, 0) + 1; if (!buffer || len > buflen) { delete [] buffer; buflen = qMin(len, 256); - buffer = new char[buflen]; + buffer = new wchar_t[buflen]; } - bool unicode = true; - len = getCompositionString(himc, dwindex, buffer, buflen, &unicode); + len = getCompositionString(himc, dwindex, buffer, buflen * sizeof(wchar_t)); if (selStart) { - static char *attrbuffer = 0; + static wchar_t *attrbuffer = 0; static int attrbuflen = 0; int attrlen = getCompositionString(himc, dwindex, 0, 0) + 1; if (!attrbuffer || attrlen> attrbuflen) { delete [] attrbuffer; attrbuflen = qMin(attrlen, 256); - attrbuffer = new char[attrbuflen]; + attrbuffer = new wchar_t[attrbuflen]; } - attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, attrbuflen); + attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, attrbuflen * sizeof(wchar_t)); *selStart = attrlen+1; *selLength = -1; for (int i = 0; i < attrlen; i++) { @@ -403,18 +361,8 @@ static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLe if (len <= 0) return QString(); - if (unicode) { - return QString((QChar *)buffer, len/sizeof(QChar)); - } - else { - buffer[len] = 0; - WCHAR *wc = new WCHAR[len+1]; - int l = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, - buffer, len, wc, len+1); - QString res = QString((QChar *)wc, l); - delete [] wc; - return res; - } + + return QString((QChar*)buffer, len / sizeof(QChar)); } void QWinInputContext::TranslateMessage(const MSG *msg) @@ -428,11 +376,7 @@ LRESULT QWinInputContext::DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPAR LRESULT retval; if (!aimm || aimm->OnDefWindowProc(hwnd, msg, wParam, lParam, &retval) != S_OK) { - QT_WA({ - retval = ::DefWindowProc(hwnd, msg, wParam, lParam); - } , { - retval = ::DefWindowProcA(hwnd,msg, wParam, lParam); - }); + retval = ::DefWindowProc(hwnd, msg, wParam, lParam); } return retval; } @@ -454,21 +398,13 @@ void QWinInputContext::update() HFONT hf; hf = f.handle(); - QT_WA({ - LOGFONT lf; - if (GetObject(hf, sizeof(lf), &lf)) - if (aimm) - aimm->SetCompositionFontW(imc, &lf); - else - ImmSetCompositionFont(imc, &lf); - } , { - LOGFONTA lf; - if (GetObjectA(hf, sizeof(lf), &lf)) - if (aimm) - aimm->SetCompositionFontA(imc, &lf); - else - ImmSetCompositionFontA(imc, &lf); - }); + LOGFONT lf; + if (GetObject(hf, sizeof(lf), &lf)) { + if (aimm) + aimm->SetCompositionFontW(imc, &lf); + else + ImmSetCompositionFont(imc, &lf); + } QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect(); diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index cb0037b..cefe8a5 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -127,6 +127,37 @@ void QAbstractItemViewPrivate::init() q->setAttribute(Qt::WA_InputMethodEnabled); } +void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index) +{ + //we take a persistent model index because the model might change by emitting signals + Q_Q(QAbstractItemView); + if (viewportEnteredNeeded || enteredIndex != index) { + viewportEnteredNeeded = false; + + if (index.isValid()) { + emit q->entered(index); +#ifndef QT_NO_STATUSTIP + QString statustip = model->data(index, Qt::StatusTipRole).toString(); + if (parent && !statustip.isEmpty()) { + QStatusTipEvent tip(statustip); + QApplication::sendEvent(parent, &tip); + } +#endif + } else { +#ifndef QT_NO_STATUSTIP + if (parent) { + QString emptyString; + QStatusTipEvent tip( emptyString ); + QApplication::sendEvent(parent, &tip); + } +#endif + emit q->viewportEntered(); + } + enteredIndex = index; + } +} + + /*! \class QAbstractItemView @@ -1557,7 +1588,7 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event) } #endif // QT_NO_DRAGANDDROP - QModelIndex index = indexAt(bottomRight); + QPersistentModelIndex index = indexAt(bottomRight); QModelIndex buddy = d->model->buddy(d->pressedIndex); if ((state() == EditingState && d->hasEditor(buddy)) || edit(index, NoEditTriggers, event)) @@ -1568,36 +1599,10 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event) else topLeft = bottomRight; - if (d->viewportEnteredNeeded || d->enteredIndex != index) { - d->viewportEnteredNeeded = false; - - // signal handlers may change the model - QPersistentModelIndex persistent = index; - if (persistent.isValid()) { - emit entered(persistent); -#ifndef QT_NO_STATUSTIP - QString statustip = d->model->data(persistent, Qt::StatusTipRole).toString(); - if (parent() && !statustip.isEmpty()) { - QStatusTipEvent tip(statustip); - QApplication::sendEvent(parent(), &tip); - } -#endif - } else { -#ifndef QT_NO_STATUSTIP - if (parent()) { - QString emptyString; - QStatusTipEvent tip(emptyString); - QApplication::sendEvent(parent(), &tip); - } -#endif - emit viewportEntered(); - } - d->enteredIndex = persistent; - index = persistent; - } + d->checkMouseMove(index); #ifndef QT_NO_DRAGANDDROP - if (index.isValid() + if (d->pressedIndex.isValid() && d->dragEnabled && (state() != DragSelectingState) && (event->buttons() != Qt::NoButton) @@ -1613,14 +1618,13 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event) // Do the normalize ourselves, since QRect::normalized() is flawed QRect selectionRect = QRect(topLeft, bottomRight); - QPersistentModelIndex persistent = index; setSelection(selectionRect, command); // set at the end because it might scroll the view - if (persistent.isValid() - && (persistent != d->selectionModel->currentIndex()) - && d->isIndexEnabled(persistent)) - d->selectionModel->setCurrentIndex(persistent, QItemSelectionModel::NoUpdate); + if (index.isValid() + && (index != d->selectionModel->currentIndex()) + && d->isIndexEnabled(index)) + d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate); } } @@ -2422,6 +2426,7 @@ void QAbstractItemView::verticalScrollbarValueChanged(int value) Q_D(QAbstractItemView); if (verticalScrollBar()->maximum() == value && d->model->canFetchMore(d->root)) d->model->fetchMore(d->root); + d->checkMouseMove(viewport()->mapFromGlobal(QCursor::pos())); } /*! @@ -2432,6 +2437,7 @@ void QAbstractItemView::horizontalScrollbarValueChanged(int value) Q_D(QAbstractItemView); if (horizontalScrollBar()->maximum() == value && d->model->canFetchMore(d->root)) d->model->fetchMore(d->root); + d->checkMouseMove(viewport()->mapFromGlobal(QCursor::pos())); } /*! diff --git a/src/gui/itemviews/qabstractitemview_p.h b/src/gui/itemviews/qabstractitemview_p.h index 030147b..c2c1f32 100644 --- a/src/gui/itemviews/qabstractitemview_p.h +++ b/src/gui/itemviews/qabstractitemview_p.h @@ -139,6 +139,9 @@ public: const QEvent *event) const; virtual void selectAll(QItemSelectionModel::SelectionFlags command); + void checkMouseMove(const QPersistentModelIndex &index); + inline void checkMouseMove(const QPoint &pos) { checkMouseMove(q_func()->indexAt(pos)); } + inline QItemSelectionModel::SelectionFlags selectionBehaviorFlags() const { switch (selectionBehavior) { diff --git a/src/gui/itemviews/qfileiconprovider.cpp b/src/gui/itemviews/qfileiconprovider.cpp index 3f7b53d..506b988 100644 --- a/src/gui/itemviews/qfileiconprovider.cpp +++ b/src/gui/itemviews/qfileiconprovider.cpp @@ -243,10 +243,10 @@ QIcon QFileIconProviderPrivate::getWinIcon(const QFileInfo &fileInfo) const //Get the small icon #ifndef Q_OS_WINCE - val = SHGetFileInfo((const WCHAR *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, + val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, sizeof(SHFILEINFO), SHGFI_ICON|SHGFI_SMALLICON|SHGFI_SYSICONINDEX|SHGFI_ADDOVERLAYS); #else - val = SHGetFileInfo((const WCHAR *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, + val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, sizeof(SHFILEINFO), SHGFI_SMALLICON|SHGFI_SYSICONINDEX); #endif if (val) { @@ -282,10 +282,10 @@ QIcon QFileIconProviderPrivate::getWinIcon(const QFileInfo &fileInfo) const //Get the big icon #ifndef Q_OS_WINCE - val = SHGetFileInfo((const WCHAR *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, + val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, sizeof(SHFILEINFO), SHGFI_ICON|SHGFI_LARGEICON|SHGFI_SYSICONINDEX|SHGFI_ADDOVERLAYS); #else - val = SHGetFileInfo((const WCHAR *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, + val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info, sizeof(SHFILEINFO), SHGFI_LARGEICON|SHGFI_SYSICONINDEX); #endif if (val) { @@ -357,9 +357,7 @@ QIcon QFileIconProvider::icon(const QFileInfo &info) const if (info.isRoot()) #if defined (Q_WS_WIN) && !defined(Q_WS_WINCE) { - uint type = DRIVE_UNKNOWN; - QT_WA({ type = GetDriveTypeW((wchar_t *)info.absoluteFilePath().utf16()); }, - { type = GetDriveTypeA(info.absoluteFilePath().toLocal8Bit()); }); + UINT type = GetDriveType((wchar_t *)info.absoluteFilePath().utf16()); switch (type) { case DRIVE_REMOVABLE: diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp index b35c30b..2419c18 100644 --- a/src/gui/itemviews/qheaderview.cpp +++ b/src/gui/itemviews/qheaderview.cpp @@ -522,31 +522,29 @@ int QHeaderView::length() const QSize QHeaderView::sizeHint() const { Q_D(const QHeaderView); - if (count() < 1) - return QSize(0, 0); if (d->cachedSizeHint.isValid()) return d->cachedSizeHint; - int width = 0; - int height = 0; + d->cachedSizeHint = QSize(0, 0); //reinitialize the cached size hint + const int sectionCount = count(); + // get size hint for the first n sections - int c = qMin(count(), 100); - for (int i = 0; i < c; ++i) { + int i = 0; + for (int checked = 0; checked < 100 && i < sectionCount; ++i) { if (isSectionHidden(i)) continue; + checked++; QSize hint = sectionSizeFromContents(i); - width = qMax(hint.width(), width); - height = qMax(hint.height(), height); + d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint); } // get size hint for the last n sections - c = qMax(count() - 100, c); - for (int j = count() - 1; j >= c; --j) { + i = qMax(i, sectionCount - 100 ); + for (int j = sectionCount - 1, checked = 0; j >= i && checked < 100; --j) { if (isSectionHidden(j)) continue; + checked++; QSize hint = sectionSizeFromContents(j); - width = qMax(hint.width(), width); - height = qMax(hint.height(), height); + d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint); } - d->cachedSizeHint = QSize(width, height); return d->cachedSizeHint; } @@ -2540,7 +2538,7 @@ QSize QHeaderView::sectionSizeFromContents(int logicalIndex) const if (opt.icon.isNull()) opt.icon = qvariant_cast<QPixmap>(variant); QSize size = style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this); - if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex) { + if (isSortIndicatorShown()) { int margin = style()->pixelMetric(QStyle::PM_HeaderMargin, &opt, this); if (d->orientation == Qt::Horizontal) size.rwidth() += size.height() + margin; diff --git a/src/gui/itemviews/qheaderview.h b/src/gui/itemviews/qheaderview.h index f752ae2..bf92667 100644 --- a/src/gui/itemviews/qheaderview.h +++ b/src/gui/itemviews/qheaderview.h @@ -221,7 +221,7 @@ protected: bool isIndexHidden(const QModelIndex &index) const; QModelIndex moveCursor(CursorAction, Qt::KeyboardModifiers); - void setSelection(const QRect&, QItemSelectionModel::SelectionFlags); + void setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags flags); QRegion visualRegionForSelection(const QItemSelection &selection) const; void initStyleOption(QStyleOptionHeader *option) const; diff --git a/src/gui/itemviews/qitemdelegate.cpp b/src/gui/itemviews/qitemdelegate.cpp index 264fa37..2dd5540 100644 --- a/src/gui/itemviews/qitemdelegate.cpp +++ b/src/gui/itemviews/qitemdelegate.cpp @@ -574,7 +574,7 @@ void QItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) con } /*! - Gets data drom the \a editor widget and stores it in the specified + Gets data from the \a editor widget and stores it in the specified \a model at the item \a index. The default implementation gets the value to be stored in the data diff --git a/src/gui/itemviews/qstyleditemdelegate.cpp b/src/gui/itemviews/qstyleditemdelegate.cpp index e528e58..edca724 100644 --- a/src/gui/itemviews/qstyleditemdelegate.cpp +++ b/src/gui/itemviews/qstyleditemdelegate.cpp @@ -508,7 +508,7 @@ void QStyledItemDelegate::setEditorData(QWidget *editor, const QModelIndex &inde } /*! - Gets data drom the \a editor widget and stores it in the specified + Gets data from the \a editor widget and stores it in the specified \a model at the item \a index. The default implementation gets the value to be stored in the data diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri index a1b982a..e6eff6e 100644 --- a/src/gui/kernel/kernel.pri +++ b/src/gui/kernel/kernel.pri @@ -41,7 +41,11 @@ HEADERS += \ kernel/qwidgetaction.h \ kernel/qwidgetaction_p.h \ kernel/qwindowdefs.h \ - kernel/qkeymapper_p.h + kernel/qkeymapper_p.h \ + kernel/qgesture.h \ + kernel/qgesture_p.h \ + kernel/qstandardgestures.h \ + kernel/qstandardgestures_p.h SOURCES += \ kernel/qaction.cpp \ @@ -70,7 +74,9 @@ SOURCES += \ kernel/qwhatsthis.cpp \ kernel/qwidget.cpp \ kernel/qwidgetaction.cpp \ - kernel/qkeymapper.cpp + kernel/qkeymapper.cpp \ + kernel/qgesture.cpp \ + kernel/qstandardgestures.cpp win32 { DEFINES += QT_NO_DIRECTDRAW @@ -164,24 +170,26 @@ embedded { qcocoaview_mac_p.h \ qcocoaapplication_mac_p.h \ qcocoaapplicationdelegate_mac_p.h \ + qmultitouch_mac_p.h OBJECTIVE_SOURCES += \ kernel/qcursor_mac.mm \ kernel/qdnd_mac.mm \ kernel/qsound_mac.mm \ kernel/qapplication_mac.mm \ - kernel/qwidget_mac.mm \ - kernel/qcocoapanel_mac.mm \ - kernel/qcocoaview_mac.mm \ - kernel/qcocoawindow_mac.mm \ - kernel/qcocoawindowdelegate_mac.mm \ + kernel/qwidget_mac.mm \ + kernel/qcocoapanel_mac.mm \ + kernel/qcocoaview_mac.mm \ + kernel/qcocoawindow_mac.mm \ + kernel/qcocoawindowdelegate_mac.mm \ kernel/qcocoamenuloader_mac.mm \ kernel/qcocoaapplication_mac.mm \ kernel/qcocoaapplicationdelegate_mac.mm \ kernel/qt_cocoa_helpers_mac.mm \ - kernel/qdesktopwidget_mac.mm \ + kernel/qdesktopwidget_mac.mm \ kernel/qeventdispatcher_mac.mm \ - kernel/qcocoawindowcustomthemeframe_mac.mm + kernel/qcocoawindowcustomthemeframe_mac.mm \ + kernel/qmultitouch_mac.mm \ HEADERS += \ kernel/qt_cocoa_helpers_mac_p.h \ diff --git a/src/gui/kernel/qaction.cpp b/src/gui/kernel/qaction.cpp index 59b00b8..4ee17f4 100644 --- a/src/gui/kernel/qaction.cpp +++ b/src/gui/kernel/qaction.cpp @@ -256,7 +256,9 @@ void QActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map) as described in the QMenuBar documentation. \value ApplicationSpecificRole This action should be put in the application menu with an application specific role \value AboutQtRole This action matches handles the "About Qt" menu item. - \value AboutRole This action should be placed where the "About" menu item is in the application menu. + \value AboutRole This action should be placed where the "About" menu item is in the application menu. The text of + the menu item will be set to "About <application name>". The application name is fetched from the + \c{Info.plist} file in the application's bundle (See \l{Deploying an Application on Mac OS X}). \value PreferencesRole This action should be placed where the "Preferences..." menu item is in the application menu. \value QuitRole This action should be placed where the Quit menu item is in the application menu. */ diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index 463d6ef..0e8978f 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -85,6 +85,7 @@ #include <stdlib.h> #include "qapplication_p.h" +#include "qevent_p.h" #include "qwidget_p.h" #include "qapplication.h" @@ -97,6 +98,8 @@ extern bool qt_wince_is_mobile(); //qguifunctions_wince.cpp extern bool qt_wince_is_pocket_pc(); //qguifunctions_wince.cpp #endif +#include "qdatetime.h" + //#define ALIEN_DEBUG static void initResources() @@ -848,12 +851,6 @@ void QApplicationPrivate::initialize() if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0) q->setAttribute(Qt::AA_NativeWindows); -#if defined(Q_WS_WIN) - // Alien is not currently working on Windows 98 - if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) - q->setAttribute(Qt::AA_NativeWindows); -#endif - #ifdef Q_WS_WINCE #ifdef QT_AUTO_MAXIMIZE_THRESHOLD autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD; @@ -881,6 +878,8 @@ void QApplicationPrivate::initialize() QApplicationPrivate::wheel_scroll_lines = 3; #endif #endif + + initializeMultitouch(); } /*! @@ -1031,6 +1030,8 @@ QApplication::~QApplication() delete QDragManager::self(); #endif + d->cleanupMultitouch(); + qt_cleanup(); if (QApplicationPrivate::widgetCount) @@ -1378,7 +1379,7 @@ void QApplication::setStyle(QStyle *style) #endif // QT_NO_STYLE_STYLESHEET QApplicationPrivate::app_style = style; QApplicationPrivate::app_style->setParent(qApp); // take ownership - + // take care of possible palette requirements of certain gui // styles. Do it before polishing the application since the style // might call QApplication::setPalette() itself @@ -2865,7 +2866,8 @@ QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint */ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event, QWidget *alienWidget, QWidget *nativeWidget, - QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver) + QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver, + bool spontaneous) { Q_ASSERT(receiver); Q_ASSERT(event); @@ -2918,7 +2920,11 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event, // We need this quard in case someone opens a modal dialog / popup. If that's the case // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver. const bool wasLeaveAfterRelease = leaveAfterRelease != 0; - bool result = QApplication::sendSpontaneousEvent(receiver, event); + bool result; + if (spontaneous) + result = QApplication::sendSpontaneousEvent(receiver, event); + else + result = QApplication::sendEvent(receiver, event); if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) { @@ -3559,20 +3565,18 @@ bool QApplication::notify(QObject *receiver, QEvent *e) QApplicationPrivate::mouse_buttons |= me->button(); else QApplicationPrivate::mouse_buttons &= ~me->button(); - } + } #if !defined(QT_NO_WHEELEVENT) || !defined(QT_NO_TABLETEVENT) - else if ( + else if (false # ifndef QT_NO_WHEELEVENT - e->type() == QEvent::Wheel -# else - false + || e->type() == QEvent::Wheel # endif # ifndef QT_NO_TABLETEVENT - || e->type() == QEvent::TabletMove - || e->type() == QEvent::TabletPress - || e->type() == QEvent::TabletRelease + || e->type() == QEvent::TabletMove + || e->type() == QEvent::TabletPress + || e->type() == QEvent::TabletRelease # endif - ) { + ) { QInputEvent *ie = static_cast<QInputEvent*>(e); QApplicationPrivate::modifier_buttons = ie->modifiers(); } @@ -3706,19 +3710,10 @@ bool QApplication::notify(QObject *receiver, QEvent *e) QPoint relpos = mouse->pos(); if (e->spontaneous()) { - if (e->type() == QEvent::MouseButtonPress) { - QWidget *fw = w; - while (fw) { - if (fw->isEnabled() - && QApplicationPrivate::shouldSetFocus(fw, Qt::ClickFocus)) { - fw->setFocus(Qt::MouseFocusReason); - break; - } - if (fw->isWindow()) - break; - fw = fw->parentWidget(); - } + QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, + Qt::ClickFocus, + Qt::MouseFocusReason); } if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) { @@ -3800,17 +3795,9 @@ bool QApplication::notify(QObject *receiver, QEvent *e) bool eventAccepted = wheel->isAccepted(); if (e->spontaneous()) { - QWidget *fw = w; - while (fw) { - if (fw->isEnabled() - && QApplicationPrivate::shouldSetFocus(fw, Qt::WheelFocus)) { - fw->setFocus(Qt::MouseFocusReason); - break; - } - if (fw->isWindow()) - break; - fw = fw->parentWidget(); - } + QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, + Qt::WheelFocus, + Qt::MouseFocusReason); } while (w) { @@ -4015,7 +4002,58 @@ bool QApplication::notify(QObject *receiver, QEvent *e) } break; #endif + case QEvent::TouchBegin: + // Note: TouchUpdate and TouchEnd events are never propagated + { + QWidget *widget = static_cast<QWidget *>(receiver); + QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e); + bool eventAccepted = touchEvent->isAccepted(); + if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) { + // give the widget focus if the focus policy allows it + QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget, + Qt::ClickFocus, + Qt::MouseFocusReason); + } + while (widget) { + // first, try to deliver the touch event + bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents); + touchEvent->setWidget(widget); + touchEvent->setAccepted(acceptTouchEvents); + res = acceptTouchEvents && d->notify_helper(widget, touchEvent); + eventAccepted = touchEvent->isAccepted(); + widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted); + touchEvent->spont = false; + if (res && eventAccepted) { + // the first widget to accept the TouchBegin gets an implicit grab. + for (int i = 0; i < touchEvent->touchPoints().count(); ++i) { + const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i); + d->widgetForTouchPointId[touchPoint.id()] = widget; + } + break; + } else if (widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) { + break; + } + widget = widget->parentWidget(); + d->updateTouchPointsForWidget(widget, touchEvent); + } + + touchEvent->setAccepted(eventAccepted); + break; + } + case QEvent::WinGesture: + { + // only propagate the first gesture event (after the GID_BEGIN) + QWidget *w = static_cast<QWidget *>(receiver); + while (w) { + e->ignore(); + res = d->notify_helper(w, e); + if ((res && e->isAccepted()) || w->isWindow()) + break; + w = w->parentWidget(); + } + break; + } default: res = d->notify_helper(receiver, e); break; @@ -4363,13 +4401,13 @@ HRESULT qt_CoCreateGuid(GUID* guid) { // We will use the following information to create the GUID // 1. absolute path to application - wchar_t tempFilename[512]; - if (!GetModuleFileNameW(0, tempFilename, 512)) + wchar_t tempFilename[MAX_PATH]; + if (!GetModuleFileName(0, tempFilename, MAX_PATH)) return S_FALSE; - unsigned int hash = qHash(QString::fromUtf16((const unsigned short *) tempFilename)); + unsigned int hash = qHash(QString::fromWCharArray(tempFilename)); guid->Data1 = hash; // 2. creation time of file - QFileInfo info(QString::fromUtf16((const unsigned short *) tempFilename)); + QFileInfo info(QString::fromWCharArray(tempFilename)); guid->Data2 = qHash(info.created().toTime_t()); // 3. current system time guid->Data3 = qHash(QDateTime::currentDateTime().toTime_t()); @@ -4403,10 +4441,10 @@ QSessionManager::QSessionManager(QApplication * app, QString &id, QString &key) GUID guid; CoCreateGuid(&guid); StringFromGUID2(guid, guidstr, 40); - id = QString::fromUtf16((ushort*)guidstr); + id = QString::fromWCharArray(guidstr); CoCreateGuid(&guid); StringFromGUID2(guid, guidstr, 40); - key = QString::fromUtf16((ushort*)guidstr); + key = QString::fromWCharArray(guidstr); #endif d->sessionId = id; d->sessionKey = key; @@ -4982,6 +5020,23 @@ Qt::LayoutDirection QApplication::keyboardInputDirection() return qt_keymapper_private()->keyboardInputDirection; } +void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget, + Qt::FocusPolicy focusPolicy, + Qt::FocusReason focusReason) +{ + QWidget *focusWidget = widget; + while (focusWidget) { + if (focusWidget->isEnabled() + && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) { + focusWidget->setFocus(focusReason); + break; + } + if (focusWidget->isWindow()) + break; + focusWidget = focusWidget->parentWidget(); + } +} + bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy) { QWidget *f = w; @@ -5126,6 +5181,213 @@ bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy) This normally takes some time. Does nothing on other platforms. */ +void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent) +{ + for (int i = 0; i < touchEvent->touchPoints().count(); ++i) { + QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i]; + + // preserve the sub-pixel resolution + QRectF rect = touchPoint.screenRect(); + const QPointF screenPos = rect.center(); + const QPointF delta = screenPos - screenPos.toPoint(); + + rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta); + touchPoint.setRect(rect); + touchPoint.setStartPos(widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta); + touchPoint.setLastPos(widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta); + } +} + +void QApplicationPrivate::initializeMultitouch() +{ + widgetForTouchPointId.clear(); + appCurrentTouchPoints.clear(); + + initializeMultitouch_sys(); +} + +void QApplicationPrivate::cleanupMultitouch() +{ + cleanupMultitouch_sys(); + + widgetForTouchPointId.clear(); + appCurrentTouchPoints.clear(); +} + +int QApplicationPrivate::findClosestTouchPointId(const QPointF &screenPos) +{ + int closestTouchPointId = -1; + qreal closestDistance = qreal(0.); + foreach (const QTouchEvent::TouchPoint &touchPoint, appCurrentTouchPoints) { + qreal distance = QLineF(screenPos, touchPoint.screenPos()).length(); + if (closestTouchPointId == -1 || distance < closestDistance) { + closestTouchPointId = touchPoint.id(); + closestDistance = distance; + } + } + return closestTouchPointId; +} + +void QApplicationPrivate::translateRawTouchEvent(QWidget *window, + QTouchEvent::DeviceType deviceType, + const QList<QTouchEvent::TouchPoint> &touchPoints) +{ + QApplicationPrivate *d = self; + QApplication *q = self->q_func(); + + typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints; + QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents; + + for (int i = 0; i < touchPoints.count(); ++i) { + QTouchEvent::TouchPoint touchPoint = touchPoints.at(i); + + // update state + QWidget *widget = 0; + switch (touchPoint.state()) { + case Qt::TouchPointPressed: + { + if (deviceType == QTouchEvent::TouchPad) { + // on touch-pads, send all touch points to the same widget + widget = d->widgetForTouchPointId.isEmpty() + ? 0 + : d->widgetForTouchPointId.constBegin().value(); + } + + if (!widget) { + // determine which widget this event will go to + if (!window) + window = q->topLevelAt(touchPoint.screenPos().toPoint()); + if (!window) + continue; + widget = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint())); + if (!widget) + widget = window; + } + + if (deviceType == QTouchEvent::TouchScreen) { + int closestTouchPointId = d->findClosestTouchPointId(touchPoint.screenPos()); + QWidget *closestWidget = d->widgetForTouchPointId.value(closestTouchPointId); + if (closestWidget + && (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) { + widget = closestWidget; + } + } + + d->widgetForTouchPointId[touchPoint.id()] = widget; + touchPoint.setStartScreenPos(touchPoint.screenPos()); + touchPoint.setLastScreenPos(touchPoint.screenPos()); + touchPoint.setStartNormalizedPos(touchPoint.normalizedPos()); + touchPoint.setLastNormalizedPos(touchPoint.normalizedPos()); + if (touchPoint.pressure() < qreal(0.)) + touchPoint.setPressure(qreal(1.)); + d->appCurrentTouchPoints.insert(touchPoint.id(), touchPoint); + break; + } + case Qt::TouchPointReleased: + { + widget = d->widgetForTouchPointId.take(touchPoint.id()); + if (!widget) + continue; + + QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.take(touchPoint.id()); + touchPoint.setStartScreenPos(previousTouchPoint.startScreenPos()); + touchPoint.setLastScreenPos(previousTouchPoint.screenPos()); + touchPoint.setStartNormalizedPos(previousTouchPoint.startNormalizedPos()); + touchPoint.setLastNormalizedPos(previousTouchPoint.normalizedPos()); + if (touchPoint.pressure() < qreal(0.)) + touchPoint.setPressure(qreal(0.)); + break; + } + default: + widget = d->widgetForTouchPointId.value(touchPoint.id()); + if (!widget) + continue; + + Q_ASSERT(d->appCurrentTouchPoints.contains(touchPoint.id())); + QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.value(touchPoint.id()); + touchPoint.setStartScreenPos(previousTouchPoint.startScreenPos()); + touchPoint.setLastScreenPos(previousTouchPoint.screenPos()); + touchPoint.setStartNormalizedPos(previousTouchPoint.startNormalizedPos()); + touchPoint.setLastNormalizedPos(previousTouchPoint.normalizedPos()); + if (touchPoint.pressure() < qreal(0.)) + touchPoint.setPressure(qreal(1.)); + d->appCurrentTouchPoints[touchPoint.id()] = touchPoint; + break; + } + Q_ASSERT(widget != 0); + + // make the *scene* functions return the same as the *screen* functions + touchPoint.setSceneRect(touchPoint.screenRect()); + touchPoint.setStartScenePos(touchPoint.startScreenPos()); + touchPoint.setLastScenePos(touchPoint.lastScreenPos()); + + StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[widget]; + maskAndPoints.first |= touchPoint.state(); + if (touchPoint.isPrimary()) + maskAndPoints.first |= Qt::TouchPointPrimary; + maskAndPoints.second.append(touchPoint); + } + + if (widgetsNeedingEvents.isEmpty()) + return; + + QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin(); + const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd(); + for (; it != end; ++it) { + QWidget *widget = it.key(); + if (!QApplicationPrivate::tryModalHelper(widget, 0)) + continue; + + QEvent::Type eventType; + switch (it.value().first & Qt::TouchPointStateMask) { + case Qt::TouchPointPressed: + eventType = QEvent::TouchBegin; + break; + case Qt::TouchPointReleased: + eventType = QEvent::TouchEnd; + break; + case Qt::TouchPointStationary: + // don't send the event if nothing changed + continue; + default: + eventType = QEvent::TouchUpdate; + break; + } + + QTouchEvent touchEvent(eventType, + deviceType, + q->keyboardModifiers(), + it.value().first, + it.value().second); + updateTouchPointsForWidget(widget, &touchEvent); + + switch (touchEvent.type()) { + case QEvent::TouchBegin: + { + // if the TouchBegin handler recurses, we assume that means the event + // has been implicitly accepted and continue to send touch events + widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent); + (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent); + break; + } + default: + if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) { + if (touchEvent.type() == QEvent::TouchEnd) + widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false); + (void) QApplication::sendSpontaneousEvent(widget, &touchEvent); + } + break; + } + } +} + +Q_GUI_EXPORT void qt_translateRawTouchEvent(QWidget *window, + QTouchEvent::DeviceType deviceType, + const QList<QTouchEvent::TouchPoint> &touchPoints) +{ + QApplicationPrivate::translateRawTouchEvent(window, deviceType, touchPoints); +} + QT_END_NAMESPACE #include "moc_qapplication.cpp" diff --git a/src/gui/kernel/qapplication.h b/src/gui/kernel/qapplication.h index b3bb1cd..19ae085 100644 --- a/src/gui/kernel/qapplication.h +++ b/src/gui/kernel/qapplication.h @@ -382,6 +382,9 @@ private: #if defined(Q_WS_MAC) || defined(Q_WS_X11) Q_PRIVATE_SLOT(d_func(), void _q_alertTimeOut()) #endif +#if defined(QT_RX71_MULTITOUCH) + Q_PRIVATE_SLOT(d_func(), void _q_readRX71MultiTouchEvents()) +#endif }; QT_END_NAMESPACE diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm index ca826b0..0884976 100644 --- a/src/gui/kernel/qapplication_mac.mm +++ b/src/gui/kernel/qapplication_mac.mm @@ -1069,7 +1069,7 @@ void qt_init(QApplicationPrivate *priv, int) if (GetCurrentProcess(&psn) == noErr) { // Jambi needs to transform itself since most people aren't "used" // to putting things in bundles, but other people may actually not - // want to tranform the process (running as a helper or somethng) + // want to tranform the process (running as a helper or something) // so don't do that for them. This means checking both LSUIElement // and LSBackgroundOnly. If you set them both... well, you // shouldn't do that. @@ -1367,29 +1367,6 @@ QWidget *QApplication::topLevelAt(const QPoint &p) #endif } -static QWidget *qt_mac_recursive_widgetAt(QWidget *widget, int x, int y) -{ - if (!widget) - return 0; - const QObjectList kids = widget->children(); - for(int i = kids.size()-1; i >= 0; --i) { - if ( QWidget *kid = qobject_cast<QWidget*>(kids.at(i)) ) { - if (kid->isVisible() && !kid->isTopLevel() && - !kid->testAttribute(Qt::WA_TransparentForMouseEvents)) { - const int wx=kid->x(), wy=kid->y(), - wx2=wx+kid->width(), wy2=wy+kid->height(); - if (x >= wx && y >= wy && x < wx2 && y < wy2) { - const QRegion mask = kid->mask(); - if (!mask.isEmpty() && !mask.contains(QPoint(x-wx, y-wy))) - continue; - return qt_mac_recursive_widgetAt(kid, x-wx, y-wy); - } - } - } - } - return widget; -} - /***************************************************************************** Main event loop *****************************************************************************/ @@ -1760,7 +1737,7 @@ QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event if(window) { HIViewRef hiview; if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) { - widget = QWidget::find((WId)hiview);; + widget = QWidget::find((WId)hiview); if (widget) { // Make sure we didn't pass over a widget with a "fake hole" in it. QWidget *otherWidget = QApplication::widgetAt(where.h, where.v); @@ -1877,9 +1854,10 @@ QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event tablet_button_state = new_tablet_button_state; QMacTabletHash *tabletHash = qt_mac_tablet_hash(); - if (!tabletHash->contains(tabletPointRec.deviceID)) { - qWarning("QCocoaView handleTabletEvent: This tablet device is unknown" - " (received no proximity event for it). Discarding event."); + if (!tabletHash->contains(tabletPointRec.deviceID) && t != QEvent::TabletRelease) { + // Never discard TabletRelease events as they may be delivered *after* TabletLeaveProximity events + qWarning("handleTabletEvent: This tablet device is unknown" + " (received no proximity event for it). Discarding event."); return false; } QTabletDeviceData &deviceData = tabletHash->operator[](tabletPointRec.deviceID); @@ -1921,8 +1899,13 @@ QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event tp, rotation, z, modifiers, deviceData.tabletUniqueID); QApplication::sendSpontaneousEvent(widget, &e); if (e.isAccepted()) { + if (t == QEvent::TabletPress) { + qt_button_down = widget; + } else if (t == QEvent::TabletRelease) { + qt_button_down = 0; + } #if defined(DEBUG_MOUSE_MAPS) - qDebug("Bail out early due to table acceptance"); + qDebug("Bail out early due to tablet acceptance"); #endif break; } @@ -2996,4 +2979,9 @@ void onApplicationChangedActivation( bool activated ) #endif } +void QApplicationPrivate::initializeMultitouch_sys() +{ } +void QApplicationPrivate::cleanupMultitouch_sys() +{ } + QT_END_NAMESPACE diff --git a/src/gui/kernel/qapplication_p.h b/src/gui/kernel/qapplication_p.h index 95b4fe5..db77b07 100644 --- a/src/gui/kernel/qapplication_p.h +++ b/src/gui/kernel/qapplication_p.h @@ -55,6 +55,7 @@ // #include "QtGui/qapplication.h" +#include "QtGui/qevent.h" #include "QtGui/qfont.h" #include "QtGui/qcursor.h" #include "QtGui/qregion.h" @@ -77,11 +78,10 @@ class QClipboard; class QGraphicsScene; class QGraphicsSystem; class QInputContext; -class QKeyEvent; -class QMouseEvent; class QObject; -class QWheelEvent; class QWidget; +class QGestureManager; +class QSocketNotifier; extern bool qt_is_gui_used; #ifndef QT_NO_CLIPBOARD @@ -189,6 +189,114 @@ extern "C" { } #endif +#if defined(Q_WS_WIN) +typedef BOOL (WINAPI *qt_RegisterTouchWindowPtr)(HWND, ULONG); +typedef BOOL (WINAPI *qt_GetTouchInputInfoPtr)(HANDLE, UINT, PVOID, int); +typedef BOOL (WINAPI *qt_CloseTouchInputHandlePtr)(HANDLE); + +#ifndef WM_GESTURE + +#define WM_GESTURE 0x0119 +#define WM_GESTURE_NOTIFY 0x011A + +DECLARE_HANDLE(HGESTUREINFO); + +#define GF_BEGIN 0x00000001 +#define GF_INERTIA 0x00000002 +#define GF_END 0x00000004 + +/* + * Gesture IDs + */ +#define GID_BEGIN 1 +#define GID_END 2 +#define GID_ZOOM 3 +#define GID_PAN 4 +#define GID_ROTATE 5 +#define GID_TWOFINGERTAP 6 +#define GID_ROLLOVER 7 + +typedef struct tagGESTUREINFO { + UINT cbSize; // size, in bytes, of this structure (including variable length Args field) + DWORD dwFlags; // see GF_* flags + DWORD dwID; // gesture ID, see GID_* defines + HWND hwndTarget; // handle to window targeted by this gesture + POINTS ptsLocation; // current location of this gesture + DWORD dwInstanceID; // internally used + DWORD dwSequenceID; // internally used + ULONGLONG ullArguments; // arguments for gestures whose arguments fit in 8 BYTES + UINT cbExtraArgs; // size, in bytes, of extra arguments, if any, that accompany this gesture +} GESTUREINFO, *PGESTUREINFO; +typedef GESTUREINFO const * PCGESTUREINFO; + +typedef struct tagGESTURENOTIFYSTRUCT { + UINT cbSize; // size, in bytes, of this structure + DWORD dwFlags; // unused + HWND hwndTarget; // handle to window targeted by the gesture + POINTS ptsLocation; // starting location + DWORD dwInstanceID; // internally used +} GESTURENOTIFYSTRUCT, *PGESTURENOTIFYSTRUCT; + +/* + * Gesture argument helpers + * - Angle should be a double in the range of -2pi to +2pi + * - Argument should be an unsigned 16-bit value + */ +#define GID_ROTATE_ANGLE_TO_ARGUMENT(_arg_) ((USHORT)((((_arg_) + 2.0 * 3.14159265) / (4.0 * 3.14159265)) * 65535.0)) +#define GID_ROTATE_ANGLE_FROM_ARGUMENT(_arg_) ((((double)(_arg_) / 65535.0) * 4.0 * 3.14159265) - 2.0 * 3.14159265) + +typedef struct tagGESTURECONFIG { + DWORD dwID; // gesture ID + DWORD dwWant; // settings related to gesture ID that are to be turned on + DWORD dwBlock; // settings related to gesture ID that are to be turned off +} GESTURECONFIG, *PGESTURECONFIG; + +#define GC_ALLGESTURES 0x00000001 +#define GC_ZOOM 0x00000001 +#define GC_PAN 0x00000001 +#define GC_PAN_WITH_SINGLE_FINGER_VERTICALLY 0x00000002 +#define GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY 0x00000004 +#define GC_PAN_WITH_GUTTER 0x00000008 +#define GC_PAN_WITH_INERTIA 0x00000010 +#define GC_ROTATE 0x00000001 +#define GC_TWOFINGERTAP 0x00000001 +#define GC_ROLLOVER 0x00000001 +#define GESTURECONFIGMAXCOUNT 256 // Maximum number of gestures that can be included + // in a single call to SetGestureConfig / GetGestureConfig + + + +#define GCF_INCLUDE_ANCESTORS 0x00000001 // If specified, GetGestureConfig returns consolidated configuration + // for the specified window and it's parent window chain + +typedef BOOL (*PtrGetGestureInfo)(HGESTUREINFO hGestureInfo, PGESTUREINFO pGestureInfo); +typedef BOOL (*PtrGetGestureExtraArgs)(HGESTUREINFO hGestureInfo, UINT cbExtraArgs, PBYTE pExtraArgs); +typedef BOOL (*PtrCloseGestureInfoHandle)(HGESTUREINFO hGestureInfo); +typedef BOOL (*PtrSetGestureConfig)(HWND hwnd, DWORD dwReserved, UINT cIDs, + PGESTURECONFIG pGestureConfig, + UINT cbSize); +typedef BOOL (*PtrGetGestureConfig)(HWND hwnd, DWORD dwReserved, + DWORD dwFlags, PUINT pcIDs, + PGESTURECONFIG pGestureConfig, + UINT cbSize); + +typedef BOOL (*PtrBeginPanningFeedback)(HWND hwnd); +typedef BOOL (*PtrUpdatePanningFeedback)(HWND hwnd, LONG, LONG, BOOL); +typedef BOOL (*PtrEndPanningFeedback)(HWND hwnd, BOOL); + +#endif // WM_GESTURE +#endif // Q_WS_WIN + +class QPanGesture; +class QPinchGesture; +struct StandardGestures +{ + QPanGesture *pan; + QPinchGesture *pinch; + StandardGestures() : pan(0), pinch(0) { } +}; + + class QScopedLoopLevelCounter { QThreadData *threadData; @@ -427,20 +535,84 @@ public: QEvent::Type type, Qt::MouseButtons buttons, QWidget *buttonDown, QWidget *alienWidget); static bool sendMouseEvent(QWidget *receiver, QMouseEvent *event, QWidget *alienWidget, - QWidget *native, QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver); + QWidget *native, QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver, + bool spontaneous = true); #if defined(Q_WS_WIN) || defined(Q_WS_X11) void sendSyntheticEnterLeave(QWidget *widget); #endif + QMap<int, QWidget *> widgetForTouchPointId; + QMap<int, QTouchEvent::TouchPoint> appCurrentTouchPoints; + static void updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent); + void initializeMultitouch(); + void initializeMultitouch_sys(); + void cleanupMultitouch(); + void cleanupMultitouch_sys(); + int findClosestTouchPointId(const QPointF &screenPos); + void appendTouchPoint(const QTouchEvent::TouchPoint &touchPoint); + void removeTouchPoint(int touchPointId); + static void translateRawTouchEvent(QWidget *widget, + QTouchEvent::DeviceType deviceType, + const QList<QTouchEvent::TouchPoint> &touchPoints); + +#if defined(Q_WS_WIN) + static qt_RegisterTouchWindowPtr RegisterTouchWindow; + static qt_GetTouchInputInfoPtr GetTouchInputInfo; + static qt_CloseTouchInputHandlePtr CloseTouchInputHandle; + + QHash<DWORD, int> touchInputIDToTouchPointID; + QList<QTouchEvent::TouchPoint> appAllTouchPoints; + bool translateTouchEvent(const MSG &msg); + + typedef QMap<QWidget*, StandardGestures> WidgetStandardGesturesMap; + WidgetStandardGesturesMap widgetGestures; + ulong lastGestureId; + + PtrGetGestureInfo GetGestureInfo; + PtrGetGestureExtraArgs GetGestureExtraArgs; + PtrCloseGestureInfoHandle CloseGestureInfoHandle; + PtrSetGestureConfig SetGestureConfig; + PtrGetGestureConfig GetGestureConfig; + PtrBeginPanningFeedback BeginPanningFeedback; + PtrUpdatePanningFeedback UpdatePanningFeedback; + PtrEndPanningFeedback EndPanningFeedback; +#endif + +#ifdef QT_RX71_MULTITOUCH + bool hasRX71MultiTouch; + + struct RX71TouchPointState { + QSocketNotifier *socketNotifier; + QTouchEvent::TouchPoint touchPoint; + + int minX, maxX, scaleX; + int minY, maxY, scaleY; + int minZ, maxZ; + }; + QList<RX71TouchPointState> allRX71TouchPoints; + + bool readRX71MultiTouchEvents(int deviceNumber); + void fakeMouseEventFromRX71TouchEvent(); + void _q_readRX71MultiTouchEvents(); +#endif + private: #ifdef Q_WS_QWS QMap<const QScreen*, QRect> maxWindowRects; #endif static QApplicationPrivate *self; + + static void giveFocusAccordingToFocusPolicy(QWidget *w, + Qt::FocusPolicy focusPolicy, + Qt::FocusReason focusReason); static bool shouldSetFocus(QWidget *w, Qt::FocusPolicy policy); }; +Q_GUI_EXPORT void qt_translateRawTouchEvent(QWidget *window, + QTouchEvent::DeviceType deviceType, + const QList<QTouchEvent::TouchPoint> &touchPoints); + QT_END_NAMESPACE #endif // QAPPLICATION_P_H diff --git a/src/gui/kernel/qapplication_qws.cpp b/src/gui/kernel/qapplication_qws.cpp index 0567a1d..f568438 100644 --- a/src/gui/kernel/qapplication_qws.cpp +++ b/src/gui/kernel/qapplication_qws.cpp @@ -3746,4 +3746,9 @@ void QApplication::setArgs(int c, char **v) d->argv = v; } +void QApplicationPrivate::initializeMultitouch_sys() +{ } +void QApplicationPrivate::cleanupMultitouch_sys() +{ } + QT_END_NAMESPACE diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 324fac7..13f19a3 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -88,6 +88,9 @@ extern void qt_wince_hide_taskbar(HWND hwnd); //defined in qguifunctions_wince.c #include "qdebug.h" #include <private/qkeymapper_p.h> #include <private/qlocale_p.h> +#include "qevent_p.h" +#include "qstandardgestures.h" +#include "qstandardgestures_p.h" //#define ALIEN_DEBUG @@ -112,24 +115,37 @@ extern void qt_wince_hide_taskbar(HWND hwnd); //defined in qguifunctions_wince.c # include <winable.h> #endif +#ifndef WM_TOUCH +# define WM_TOUCH 0x0240 -#ifndef FLASHW_STOP -typedef struct { - UINT cbSize; - HWND hwnd; +# define TOUCHEVENTF_MOVE 0x0001 +# define TOUCHEVENTF_DOWN 0x0002 +# define TOUCHEVENTF_UP 0x0004 +# define TOUCHEVENTF_INRANGE 0x0008 +# define TOUCHEVENTF_PRIMARY 0x0010 +# define TOUCHEVENTF_NOCOALESCE 0x0020 +# define TOUCHEVENTF_PEN 0x0040 +# define TOUCHEVENTF_PALM 0x0080 + +# define TOUCHINPUTMASKF_TIMEFROMSYSTEM 0x0001 +# define TOUCHINPUTMASKF_EXTRAINFO 0x0002 +# define TOUCHINPUTMASKF_CONTACTAREA 0x0004 + +typedef struct tagTOUCHINPUT +{ + LONG x; + LONG y; + HANDLE hSource; + DWORD dwID; DWORD dwFlags; - UINT uCount; - DWORD dwTimeout; -} FLASHWINFO, *PFLASHWINFO; -#define FLASHW_STOP 0 -#define FLASHW_CAPTION 0x00000001 -#define FLASHW_TRAY 0x00000002 -#define FLASHW_ALL (FLASHW_CAPTION | FLASHW_TRAY) -#define FLASHW_TIMER 0x00000004 -#define FLASHW_TIMERNOFG 0x0000000C -#endif /* FLASHW_STOP */ -typedef BOOL (WINAPI *PtrFlashWindowEx)(PFLASHWINFO pfwi); -static PtrFlashWindowEx pFlashWindowEx = 0; + DWORD dwMask; + DWORD dwTime; + ULONG_PTR dwExtraInfo; + DWORD cxContact; + DWORD cyContact; +} TOUCHINPUT, *PTOUCHINPUT; + +#endif #include <windowsx.h> #include <limits.h> @@ -240,10 +256,6 @@ QTabletDeviceData currentTabletPointer; // from qregion_win.cpp extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom); -Q_CORE_EXPORT bool winPeekMessage(MSG* msg, HWND hWnd, UINT wMsgFilterMin, - UINT wMsgFilterMax, UINT wRemoveMsg); -Q_CORE_EXPORT bool winPostMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); - // support for on-the-fly changes of the XP theme engine #ifndef WM_THEMECHANGED #define WM_THEMECHANGED 0x031A @@ -270,7 +282,7 @@ Q_CORE_EXPORT bool winPostMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPa #define GET_KEYSTATE_WPARAM(wParam) (LOWORD(wParam)) #endif -// support for multi-media-keys on ME/2000/XP +// support for multi-media-keys #ifndef WM_APPCOMMAND #define WM_APPCOMMAND 0x0319 @@ -343,8 +355,6 @@ Q_CORE_EXPORT bool winPostMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPa #endif // WM_APPCOMMAND -static UINT WM95_MOUSEWHEEL = 0; - #if (_WIN32_WINNT < 0x0400) // This struct is defined in winuser.h if the _WIN32_WINNT >= 0x0400 -- in the // other cases we have to define it on our own. @@ -443,6 +453,7 @@ public: bool translateConfigEvent(const MSG &msg); bool translateCloseEvent(const MSG &msg); bool translateTabletEvent(const MSG &msg, PACKET *localPacketBuf, int numPackets); + bool translateGestureEvent(const MSG &msg); void repolishStyle(QStyle &style); inline void showChildren(bool spontaneous) { d_func()->showChildren(spontaneous); } inline void hideChildren(bool spontaneous) { d_func()->hideChildren(spontaneous); } @@ -511,14 +522,13 @@ static void qt_set_windows_color_resources() pal.setColor(QPalette::Inactive, QPalette::Light, pal.light().color()); pal.setColor(QPalette::Inactive, QPalette::Dark, pal.dark().color()); - if (QSysInfo::WindowsVersion != QSysInfo::WV_NT && QSysInfo::WindowsVersion != QSysInfo::WV_95) { - if (pal.midlight() == pal.button()) - pal.setColor(QPalette::Midlight, pal.button().color().lighter(110)); - if (pal.background() != pal.base()) { - pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Window)); - pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Text)); - } + if (pal.midlight() == pal.button()) + pal.setColor(QPalette::Midlight, pal.button().color().lighter(110)); + if (pal.background() != pal.base()) { + pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Window)); + pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Text)); } + const QColor bg = pal.background().color(); const QColor fg = pal.foreground().color(), btn = pal.button().color(); QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2, @@ -569,35 +579,18 @@ static void qt_set_windows_color_resources() static void qt_set_windows_font_resources() { #ifndef Q_WS_WINCE - QFont menuFont; - QFont messageFont; - QFont statusFont; - QFont titleFont; - QFont iconTitleFont; - QT_WA({ - NONCLIENTMETRICS ncm; - ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONTW); - SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0); - menuFont = qt_LOGFONTtoQFont(ncm.lfMenuFont,true); - messageFont = qt_LOGFONTtoQFont(ncm.lfMessageFont,true); - statusFont = qt_LOGFONTtoQFont(ncm.lfStatusFont,true); - titleFont = qt_LOGFONTtoQFont(ncm.lfCaptionFont,true); - LOGFONTW lfIconTitleFont; - SystemParametersInfoW(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0); - iconTitleFont = qt_LOGFONTtoQFont(lfIconTitleFont,true); - } , { - // A version - NONCLIENTMETRICSA ncm; - ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICSA, lfMessageFont) + sizeof(LOGFONTA); - SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0); - menuFont = qt_LOGFONTtoQFont((LOGFONT&)ncm.lfMenuFont,true); - messageFont = qt_LOGFONTtoQFont((LOGFONT&)ncm.lfMessageFont,true); - statusFont = qt_LOGFONTtoQFont((LOGFONT&)ncm.lfStatusFont,true); - titleFont = qt_LOGFONTtoQFont((LOGFONT&)ncm.lfCaptionFont,true); - LOGFONTA lfIconTitleFont; - SystemParametersInfoA(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0); - iconTitleFont = qt_LOGFONTtoQFont((LOGFONT&)lfIconTitleFont,true); - }); + NONCLIENTMETRICS ncm; + ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT); + SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0); + + QFont menuFont = qt_LOGFONTtoQFont(ncm.lfMenuFont, true); + QFont messageFont = qt_LOGFONTtoQFont(ncm.lfMessageFont, true); + QFont statusFont = qt_LOGFONTtoQFont(ncm.lfStatusFont, true); + QFont titleFont = qt_LOGFONTtoQFont(ncm.lfCaptionFont, true); + + LOGFONT lfIconTitleFont; + SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0); + QFont iconTitleFont = qt_LOGFONTtoQFont(lfIconTitleFont, true); QApplication::setFont(menuFont, "QMenu"); QApplication::setFont(menuFont, "QMenuBar"); @@ -625,26 +618,13 @@ static void qt_set_windows_font_resources() static void qt_win_read_cleartype_settings() { + UINT result = 0; #ifdef Q_OS_WINCE - UINT result; - BOOL ok; - ok = SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0); - if (ok) - qt_cleartype_enabled = result; + if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0)) + qt_cleartype_enabled = result; #else - QT_WA({ - UINT result; - BOOL ok; - ok = SystemParametersInfoW(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0); - if (ok) - qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE); - }, { - UINT result; - BOOL ok; - ok = SystemParametersInfoA(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0); - if (ok) - qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE); - }); + if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0)) + qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE); #endif } @@ -662,10 +642,10 @@ void QApplicationPrivate::initializeWidgetPaletteHash() QPalette pal = *QApplicationPrivate::sys_pal; QColor menuCol(qt_colorref2qrgb(GetSysColor(COLOR_MENU))); QColor menuText(qt_colorref2qrgb(GetSysColor(COLOR_MENUTEXT))); - BOOL isFlat = 0; + BOOL isFlat = false; if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) - SystemParametersInfo(0x1022 /*SPI_GETFLATMENU*/, 0, &isFlat, 0); + SystemParametersInfo(SPI_GETFLATMENU, 0, &isFlat, 0); QPalette menu(pal); // we might need a special color group for the menu. menu.setColor(QPalette::Active, QPalette::Button, menuCol); @@ -680,8 +660,7 @@ void QApplicationPrivate::initializeWidgetPaletteHash() QColor(qt_colorref2qrgb(GetSysColor( (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based) - && isFlat ? COLOR_MENUHILIGHT - : COLOR_HIGHLIGHT)))); + && isFlat ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT)))); menu.setColor(QPalette::Disabled, QPalette::HighlightedText, disabled); menu.setColor(QPalette::Disabled, QPalette::Button, menu.color(QPalette::Active, QPalette::Button)); @@ -697,10 +676,8 @@ void QApplicationPrivate::initializeWidgetPaletteHash() menu.color(QPalette::Active, QPalette::Highlight)); menu.setColor(QPalette::Inactive, QPalette::HighlightedText, menu.color(QPalette::Active, QPalette::HighlightedText)); - - if (QSysInfo::WindowsVersion != QSysInfo::WV_NT && QSysInfo::WindowsVersion != QSysInfo::WV_95) - menu.setColor(QPalette::Inactive, QPalette::ButtonText, - pal.color(QPalette::Inactive, QPalette::Dark)); + menu.setColor(QPalette::Inactive, QPalette::ButtonText, + pal.color(QPalette::Inactive, QPalette::Dark)); QApplication::setPalette(menu, "QMenu"); if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP @@ -717,11 +694,10 @@ void QApplicationPrivate::initializeWidgetPaletteHash() qt_init() - initializes Qt for Windows *****************************************************************************/ -typedef BOOL (WINAPI *PtrUpdateLayeredWindow)(HWND hwnd, HDC hdcDst, const POINT *pptDst, - const SIZE *psize, HDC hdcSrc, const POINT *pptSrc, COLORREF crKey, - const Q_BLENDFUNCTION *pblend, DWORD dwflags); -static PtrUpdateLayeredWindow ptrUpdateLayeredWindow = 0; - +typedef BOOL (WINAPI *PtrSetProcessDPIAware) (VOID); +static PtrSetProcessDPIAware ptrSetProcessDPIAware = 0; +PtrUpdateLayeredWindow ptrUpdateLayeredWindow = 0; +PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect = 0; static BOOL WINAPI qt_updateLayeredWindowIndirect(HWND hwnd, const Q_UPDATELAYEREDWINDOWINFO *info) { return (*ptrUpdateLayeredWindow)(hwnd, info->hdcDst, info->pptDst, info->psize, info->hdcSrc, @@ -786,46 +762,30 @@ void qt_init(QApplicationPrivate *priv, int) #endif qApp->setObjectName(priv->appName()); -#if !defined(Q_WS_WINCE) // default font - HFONT hfont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); - QFont f(QLatin1String("MS Sans Serif"),8); - int result = 0; - QT_WA({ - LOGFONT lf; - if (result = GetObject(hfont, sizeof(lf), &lf)) - f = qt_LOGFONTtoQFont((LOGFONT&)lf,true); - } , { - LOGFONTA lf; - if (result = GetObjectA(hfont, sizeof(lf), &lf)) - f = qt_LOGFONTtoQFont((LOGFONT&)lf,true); - }); - if (result - && QSysInfo::WindowsVersion >= QSysInfo::WV_2000 - && QSysInfo::WindowsVersion <= QSysInfo::WV_NT_based - && f.family() == QLatin1String("MS Shell Dlg")) - f.setFamily(QLatin1String("MS Shell Dlg 2")); - QApplicationPrivate::setSystemFont(f); -#else //Q_WS_WINCE - LOGFONT lf; - HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT); - int result = 0; - result = GetObject(stockFont, sizeof(lf), &lf); - QFont font = qt_LOGFONTtoQFont(lf, true); - if (result) - QApplicationPrivate::setSystemFont(font); -#endif //Q_WS_WINCE +#ifndef Q_WS_WINCE + HGDIOBJ stockFont = GetStockObject(DEFAULT_GUI_FONT); +#else + HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT); +#endif + + LOGFONT lf; + GetObject(stockFont, sizeof(lf), &lf); + QFont systemFont = qt_LOGFONTtoQFont(lf, true); + +#ifndef Q_WS_WINCE + if (systemFont.family() == QLatin1String("MS Shell Dlg")) { + systemFont.setFamily(QLatin1String("MS Shell Dlg 2")); + } +#endif + + QApplicationPrivate::setSystemFont(systemFont); // QFont::locale_init(); ### Uncomment when it does something on Windows if (QApplication::desktopSettingsAware()) qt_set_windows_resources(); - QT_WA({ - WM95_MOUSEWHEEL = RegisterWindowMessage(L"MSWHEEL_ROLLMSG"); - } , { - WM95_MOUSEWHEEL = RegisterWindowMessageA("MSWHEEL_ROLLMSG"); - }); initWinTabFunctions(); QApplicationPrivate::inputContext = new QWinInputContext(0); @@ -846,7 +806,39 @@ void qt_init(QApplicationPrivate *priv, int) if (ptrUpdateLayeredWindow && !ptrUpdateLayeredWindowIndirect) ptrUpdateLayeredWindowIndirect = qt_updateLayeredWindowIndirect; -#endif + + // Notify Vista and Windows 7 that we support highter DPI settings + if (ptrSetProcessDPIAware = (PtrSetProcessDPIAware) + QLibrary::resolve(QLatin1String("user32"), "SetProcessDPIAware")) + ptrSetProcessDPIAware(); +#endif + + priv->lastGestureId = 0; + + priv->GetGestureInfo = + (PtrGetGestureInfo)QLibrary::resolve(QLatin1String("user32"), + "GetGestureInfo"); + priv->GetGestureExtraArgs = + (PtrGetGestureExtraArgs)QLibrary::resolve(QLatin1String("user32"), + "GetGestureExtraArgs"); + priv->CloseGestureInfoHandle = + (PtrCloseGestureInfoHandle)QLibrary::resolve(QLatin1String("user32"), + "CloseGestureInfoHandle"); + priv->SetGestureConfig = + (PtrSetGestureConfig)QLibrary::resolve(QLatin1String("user32"), + "SetGestureConfig"); + priv->GetGestureConfig = + (PtrGetGestureConfig)QLibrary::resolve(QLatin1String("user32"), + "GetGestureConfig"); + priv->BeginPanningFeedback = + (PtrBeginPanningFeedback)QLibrary::resolve(QLatin1String("uxtheme"), + "BeginPanningFeedback"); + priv->UpdatePanningFeedback = + (PtrUpdatePanningFeedback)QLibrary::resolve(QLatin1String("uxtheme"), + "UpdatePanningFeedback"); + priv->EndPanningFeedback = + (PtrEndPanningFeedback)QLibrary::resolve(QLatin1String("uxtheme"), + "EndPanningFeedback"); } /***************************************************************************** @@ -922,7 +914,7 @@ const QString qt_reg_winclass(QWidget *w) // register window class if (w->inherits("QTipLabel") || w->inherits("QAlphaWidget")) { if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) { - style |= 0x00020000; // CS_DROPSHADOW + style |= CS_DROPSHADOW; } cname = QLatin1String("QToolTip"); } else { @@ -940,7 +932,7 @@ const QString qt_reg_winclass(QWidget *w) // register window class #endif if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) - style |= 0x00020000; // CS_DROPSHADOW + style |= CS_DROPSHADOW; icon = false; } else { cname = QLatin1String("QWidget"); @@ -960,10 +952,10 @@ const QString qt_reg_winclass(QWidget *w) // register window class // unique ID on WinCE to make sure we can // move the windows to the front when starting // a second instance. - wchar_t uniqueAppID[256]; - GetModuleFileNameW(0, uniqueAppID, 255); - cname = QString::number(RegisterWindowMessageW( - (const wchar_t *) QString::fromUtf16((const ushort *)uniqueAppID).toLower().replace(QLatin1Char('\\'), + wchar_t uniqueAppID[MAX_PATH]; + GetModuleFileName(0, uniqueAppID, MAX_PATH); + cname = QString::number(RegisterWindowMessage( + (const wchar_t *) QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1Char('\\'), QLatin1Char('_')).utf16())); #endif @@ -975,15 +967,9 @@ const QString qt_reg_winclass(QWidget *w) // register window class static int classExists = -1; if (classExists == -1) { - QT_WA({ - WNDCLASS wcinfo; - classExists = GetClassInfo(qWinAppInst(), (TCHAR*)cname.utf16(), &wcinfo); - classExists = classExists && wcinfo.lpfnWndProc != QtWndProc; - }, { - WNDCLASSA wcinfo; - classExists = GetClassInfoA(qWinAppInst(), cname.toLatin1(), &wcinfo); - classExists = classExists && wcinfo.lpfnWndProc != QtWndProc; - }); + WNDCLASS wcinfo; + classExists = GetClassInfo((HINSTANCE)qWinAppInst(), (wchar_t*)cname.utf16(), &wcinfo); + classExists = classExists && wcinfo.lpfnWndProc != QtWndProc; } if (classExists) @@ -992,69 +978,31 @@ const QString qt_reg_winclass(QWidget *w) // register window class if (winclassNames()->contains(cname)) // already registered in our list return cname; - ATOM atom; + WNDCLASS wc; + wc.style = style; + wc.lpfnWndProc = (WNDPROC)QtWndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = qWinAppInst(); + if (icon) { + wc.hIcon = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE); #ifndef Q_WS_WINCE - HBRUSH bgBrush = (HBRUSH)GetSysColorBrush(COLOR_WINDOW); - QT_WA({ - WNDCLASS wc; - wc.style = style; - wc.lpfnWndProc = (WNDPROC)QtWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = qWinAppInst(); - if (icon) { - wc.hIcon = LoadIcon(qWinAppInst(), L"IDI_ICON1"); - if (!wc.hIcon) - wc.hIcon = LoadIcon(0, IDI_APPLICATION); - } else { - wc.hIcon = 0; - } - wc.hCursor = 0; - wc.hbrBackground= bgBrush; - wc.lpszMenuName = 0; - wc.lpszClassName= (TCHAR*)cname.utf16(); - atom = RegisterClass(&wc); - } , { - WNDCLASSA wc; - wc.style = style; - wc.lpfnWndProc = (WNDPROC)QtWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = qWinAppInst(); - if (icon) { - wc.hIcon = LoadIconA(qWinAppInst(), (char*)"IDI_ICON1"); - if (!wc.hIcon) - wc.hIcon = LoadIconA(0, (char*)IDI_APPLICATION); - } else { - wc.hIcon = 0; - } - wc.hCursor = 0; - wc.hbrBackground= bgBrush; - wc.lpszMenuName = 0; - QByteArray tempArray = cname.toLatin1(); - wc.lpszClassName= tempArray; - atom = RegisterClassA(&wc); - }); + if (!wc.hIcon) + wc.hIcon = (HICON)LoadImage(0, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED); +#endif + } else { + wc.hIcon = 0; + } + wc.hCursor = 0; +#ifndef Q_WS_WINCE + wc.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_WINDOW); #else - WNDCLASS wc; - wc.style = style; - wc.lpfnWndProc = (WNDPROC)QtWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = qWinAppInst(); - if (icon) { - wc.hIcon = LoadIcon(qWinAppInst(), L"IDI_ICON1"); -// if (!wc.hIcon) -// wc.hIcon = LoadIcon(0, IDI_APPLICATION); - } else { - wc.hIcon = 0; - } - wc.hCursor = 0; - wc.hbrBackground= 0; - wc.lpszMenuName = 0; - wc.lpszClassName= (TCHAR*)cname.utf16(); - atom = RegisterClass(&wc); + wc.hbrBackground = 0; #endif + wc.lpszMenuName = 0; + wc.lpszClassName = (wchar_t*)cname.utf16(); + + ATOM atom = RegisterClass(&wc); #ifndef QT_NO_DEBUG if (!atom) @@ -1076,11 +1024,7 @@ static void unregWinClasses() WinClassNameHash *hash = winclassNames(); QHash<QString, int>::ConstIterator it = hash->constBegin(); while (it != hash->constEnd()) { - QT_WA({ - UnregisterClass((TCHAR*)it.key().utf16(), qWinAppInst()); - } , { - UnregisterClassA(it.key().toLatin1(), qWinAppInst()); - }); + UnregisterClass((wchar_t*)it.key().utf16(), qWinAppInst()); ++it; } hash->clear(); @@ -1297,16 +1241,10 @@ void QApplication::beep() static void alert_widget(QWidget *widget, int duration) { - bool stopFlash = duration < 0; - - if (!pFlashWindowEx) { #ifndef Q_OS_WINCE - QLibrary themeLib(QLatin1String("user32")); - pFlashWindowEx = (PtrFlashWindowEx)themeLib.resolve("FlashWindowEx"); -#endif - } + bool stopFlash = duration < 0; - if (pFlashWindowEx && widget && (!widget->isActiveWindow() || stopFlash)) { + if (widget && (!widget->isActiveWindow() || stopFlash)) { DWORD timeOut = GetCaretBlinkTime(); if (timeOut <= 0) timeOut = 250; @@ -1324,8 +1262,9 @@ static void alert_widget(QWidget *widget, int duration) info.dwTimeout = stopFlash ? 0 : timeOut; info.uCount = stopFlash ? 0 : flashCount; - pFlashWindowEx(&info); + FlashWindowEx(&info); } +#endif } void QApplication::alert(QWidget *widget, int duration) @@ -1686,7 +1625,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam // Sometimes we only get a WM_MOUSEMOVE message // and sometimes we get both a WM_MOUSEMOVE and // a WM_LBUTTONDOWN/UP, this creates a spurious mouse - // press/release event, using the winPeekMessage + // press/release event, using the PeekMessage // will help us fix this. This leaves us with a // question: // This effectively kills using the mouse AND the @@ -1696,18 +1635,19 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam bool is_mouse_move = (message == WM_MOUSEMOVE); if (is_mouse_move) { MSG msg1; - if (winPeekMessage(&msg1, msg.hwnd, WM_MOUSEFIRST, - WM_MOUSELAST, PM_NOREMOVE)) + if (PeekMessage(&msg1, msg.hwnd, WM_MOUSEFIRST, + WM_MOUSELAST, PM_NOREMOVE)) next_is_button = (msg1.message == WM_LBUTTONUP || msg1.message == WM_LBUTTONDOWN); } if (!is_mouse_move || (is_mouse_move && !next_is_button)) qt_tabletChokeMouse = false; } - } else if (message == WM95_MOUSEWHEEL) { - result = widget->translateWheelEvent(msg); } else { switch (message) { + case WM_TOUCH: + result = getQApplicationPrivateInternal()->translateTouchEvent(msg); + break; case WM_KEYDOWN: // keyboard event case WM_SYSKEYDOWN: qt_keymapper_private()->updateKeyMap(msg); @@ -1733,7 +1673,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam case WM_IME_KEYDOWN: case WM_CHAR: { MSG msg1; - bool anyMsg = winPeekMessage(&msg1, msg.hwnd, 0, 0, PM_NOREMOVE); + bool anyMsg = PeekMessage(&msg1, msg.hwnd, 0, 0, PM_NOREMOVE); if (anyMsg && msg1.message == WM_DEADCHAR) { result = true; // consume event since there is a dead char next break; @@ -1933,11 +1873,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam #ifndef QT_NO_WHATSTHIS QWhatsThis::enterWhatsThisMode(); #endif - QT_WA({ - DefWindowProc(hwnd, WM_NCPAINT, 1, 0); - } , { - DefWindowProcA(hwnd, WM_NCPAINT, 1, 0); - }); + DefWindowProc(hwnd, WM_NCPAINT, 1, 0); break; #if defined(QT_NON_COMMERCIAL) QT_NC_SYSCOMMAND @@ -1999,8 +1935,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam break; if (!msg.wParam) { - QString area = QT_WA_INLINE(QString::fromUtf16((unsigned short *)msg.lParam), - QString::fromLocal8Bit((char*)msg.lParam)); + QString area = QString::fromWCharArray((wchar_t*)msg.lParam); if (area == QLatin1String("intl")) { QLocalePrivate::updateSystemPrivate(); if (!widget->testAttribute(Qt::WA_SetLocale)) @@ -2378,11 +2313,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam text = widget->objectName(); ret = qMin<int>(wParam - 1, text.size()); text.resize(ret); - QT_WA({ - memcpy((void *)lParam, text.utf16(), (text.size() + 1) * 2); - }, { - memcpy((void *)lParam, text.toLocal8Bit().data(), text.size() + 1); - }); + memcpy((void *)lParam, text.utf16(), (text.size() + 1) * sizeof(ushort)); delete acc; } if (!ret) { @@ -2470,11 +2401,11 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam #ifndef Q_WS_WINCE case WM_INPUTLANGCHANGE: { - char info[7]; - if (!GetLocaleInfoA(MAKELCID(lParam, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, info, 6)) { + wchar_t info[7]; + if (!GetLocaleInfo(MAKELCID(lParam, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, info, 6)) { inputcharset = CP_ACP; } else { - inputcharset = QString::fromLatin1(info).toInt(); + inputcharset = QString::fromWCharArray(info).toInt(); } QKeyMapper::changeKeyboard(); break; @@ -2568,6 +2499,10 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam } result = false; break; + case WM_GESTURE: + widget->translateGestureEvent(msg); + result = true; + break; default: result = false; // event was not processed break; @@ -2670,8 +2605,7 @@ bool qt_try_modal(QWidget *widget, MSG *msg, int& ret) if (type != WM_NCHITTEST) #endif if ((type >= WM_MOUSEFIRST && type <= WM_MOUSELAST) || - type == WM_MOUSEWHEEL || type == (int)WM95_MOUSEWHEEL || - type == WM_MOUSEHWHEEL || + type == WM_MOUSEWHEEL || type == WM_MOUSEHWHEEL || type == WM_MOUSELEAVE || (type >= WM_KEYFIRST && type <= WM_KEYLAST) #ifndef Q_WS_WINCE @@ -2911,19 +2845,10 @@ void qt_win_eatMouseMove() // reset button state MSG msg = {0, 0, 0, 0, 0, 0, 0}; - QT_WA( { - while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE)) - ; - if (msg.message == WM_MOUSEMOVE) - PostMessage(msg.hwnd, msg.message, 0, msg.lParam); - }, { - MSG msg; - msg.message = 0; - while (PeekMessageA(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE)) - ; - if (msg.message == WM_MOUSEMOVE) - PostMessageA(msg.hwnd, msg.message, 0, msg.lParam); - } ); + while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE)) + ; + if (msg.message == WM_MOUSEMOVE) + PostMessage(msg.hwnd, msg.message, 0, msg.lParam); } // In DnD, the mouse release event never appears, so the @@ -2958,8 +2883,8 @@ bool QETWidget::translateMouseEvent(const MSG &msg) // Compress mouse move events if (msg.message == WM_MOUSEMOVE) { MSG mouseMsg; - while (winPeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEFIRST, - WM_MOUSELAST, PM_NOREMOVE)) { + while (PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEFIRST, + WM_MOUSELAST, PM_NOREMOVE)) { if (mouseMsg.message == WM_MOUSEMOVE) { #define PEEKMESSAGE_IS_BROKEN 1 #ifdef PEEKMESSAGE_IS_BROKEN @@ -2970,12 +2895,12 @@ bool QETWidget::translateMouseEvent(const MSG &msg) // key release events (kls 2003-05-13): MSG keyMsg; bool done = false; - while (winPeekMessage(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST, - PM_NOREMOVE)) { + while (PeekMessage(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST, + PM_NOREMOVE)) { if (keyMsg.time < mouseMsg.time) { if ((keyMsg.lParam & 0xC0000000) == 0x40000000) { - winPeekMessage(&keyMsg, 0, keyMsg.message, - keyMsg.message, PM_REMOVE); + PeekMessage(&keyMsg, 0, keyMsg.message, + keyMsg.message, PM_REMOVE); } else { done = true; break; @@ -3001,8 +2926,8 @@ bool QETWidget::translateMouseEvent(const MSG &msg) msgPtr->wParam = mouseMsg.wParam; msgPtr->pt = mouseMsg.pt; // Remove the mouse move message - winPeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEMOVE, - WM_MOUSEMOVE, PM_REMOVE); + PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEMOVE, + WM_MOUSEMOVE, PM_REMOVE); } else { break; // there was no more WM_MOUSEMOVE event } @@ -3216,7 +3141,7 @@ bool QETWidget::translateMouseEvent(const MSG &msg) POINT widgetpt = gpos; ScreenToClient(hwndTarget, &widgetpt); LPARAM lParam = MAKELPARAM(widgetpt.x, widgetpt.y); - winPostMessage(hwndTarget, msg.message, msg.wParam, lParam); + PostMessage(hwndTarget, msg.message, msg.wParam, lParam); } } else if (type == QEvent::MouseButtonRelease && button == Qt::RightButton && QApplication::activePopupWidget() == activePopupWidget) { @@ -3583,14 +3508,8 @@ static void initWinTabFunctions() QLibrary library(QLatin1String("wintab32")); if (library.load()) { - QT_WA({ - ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW"); - ptrWTGet = (PtrWTGet)library.resolve("WTGetW"); - } , { - ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoA"); - ptrWTGet = (PtrWTGet)library.resolve("WTGetA"); - }); - + ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW"); + ptrWTGet = (PtrWTGet)library.resolve("WTGetW"); ptrWTEnable = (PtrWTEnable)library.resolve("WTEnable"); ptrWTOverlap = (PtrWTEnable)library.resolve("WTOverlap"); ptrWTPacketsGet = (PtrWTPacketsGet)library.resolve("WTPacketsGet"); @@ -3764,6 +3683,60 @@ bool QETWidget::translateCloseEvent(const MSG &) return d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent); } +bool QETWidget::translateGestureEvent(const MSG &msg) +{ + GESTUREINFO gi; + 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((HGESTUREINFO)msg.lParam, &gi); + + const QPoint widgetPos = QPoint(gi.ptsLocation.x, gi.ptsLocation.y); + QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos); + if (alienWidget && alienWidget->internalWinId()) + alienWidget = 0; + QWidget *widget = alienWidget ? alienWidget : this; + + QWinGestureEvent 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. + break; + case GID_END: + event.gestureType = QWinGestureEvent::GestureEnd; + break; + case GID_ZOOM: + event.gestureType = QWinGestureEvent::Pinch; + break; + case GID_PAN: + event.gestureType = QWinGestureEvent::Pan; + break; + case GID_ROTATE: + case GID_TWOFINGERTAP: + case GID_ROLLOVER: + default: + break; + } + if (event.gestureType != QWinGestureEvent::None) + qt_sendSpontaneousEvent(widget, &event); + } else { + DWORD dwErr = GetLastError(); + if (dwErr > 0) + qWarning() << "translateGestureEvent: error = " << dwErr; + } + qAppPriv->CloseGestureInfoHandle((HGESTUREINFO)msg.lParam); + return true; +} + void QApplication::setCursorFlashTime(int msecs) { @@ -3817,11 +3790,7 @@ void QApplication::setWheelScrollLines(int n) #ifdef SPI_SETWHEELSCROLLLINES if (n < 0) n = 0; - QT_WA({ - SystemParametersInfo(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0); - } , { - SystemParametersInfoA(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0); - }); + SystemParametersInfo(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0); #else QApplicationPrivate::wheel_scroll_lines = n; #endif @@ -3831,11 +3800,7 @@ int QApplication::wheelScrollLines() { #ifdef SPI_GETWHEELSCROLLLINES uint i = 3; - QT_WA({ - SystemParametersInfo(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0); - } , { - SystemParametersInfoA(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0); - }); + SystemParametersInfo(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0); if (i > INT_MAX) i = INT_MAX; return i; @@ -3880,8 +3845,7 @@ bool QApplication::isEffectEnabled(Qt::UIEffect effect) if (QColormap::instance().depth() < 16) return false; - if (!effect_override && desktopSettingsAware() - && !(QSysInfo::WindowsVersion == QSysInfo::WV_95 || QSysInfo::WindowsVersion == QSysInfo::WV_NT)) { + if (!effect_override && desktopSettingsAware()) { // we know that they can be used when we are here BOOL enabled = false; UINT api; @@ -3890,33 +3854,22 @@ bool QApplication::isEffectEnabled(Qt::UIEffect effect) api = SPI_GETMENUANIMATION; break; case Qt::UI_FadeMenu: - if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) - return false; api = SPI_GETMENUFADE; break; case Qt::UI_AnimateCombo: api = SPI_GETCOMBOBOXANIMATION; break; case Qt::UI_AnimateTooltip: - if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) - api = SPI_GETMENUANIMATION; - else - api = SPI_GETTOOLTIPANIMATION; + api = SPI_GETTOOLTIPANIMATION; break; case Qt::UI_FadeTooltip: - if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) - return false; api = SPI_GETTOOLTIPFADE; break; default: api = SPI_GETUIEFFECTS; break; } - QT_WA({ - SystemParametersInfo(api, 0, &enabled, 0); - } , { - SystemParametersInfoA(api, 0, &enabled, 0); - }); + SystemParametersInfo(api, 0, &enabled, 0); return enabled; } @@ -3965,4 +3918,91 @@ void QSessionManager::cancel() #endif //QT_NO_SESSIONMANAGER + +qt_RegisterTouchWindowPtr QApplicationPrivate::RegisterTouchWindow = 0; +qt_GetTouchInputInfoPtr QApplicationPrivate::GetTouchInputInfo = 0; +qt_CloseTouchInputHandlePtr QApplicationPrivate::CloseTouchInputHandle = 0; + +void QApplicationPrivate::initializeMultitouch_sys() +{ + QLibrary library(QLatin1String("user32")); + RegisterTouchWindow = static_cast<qt_RegisterTouchWindowPtr>(library.resolve("RegisterTouchWindow")); + GetTouchInputInfo = static_cast<qt_GetTouchInputInfoPtr>(library.resolve("GetTouchInputInfo")); + CloseTouchInputHandle = static_cast<qt_CloseTouchInputHandlePtr>(library.resolve("CloseTouchInputHandle")); + + touchInputIDToTouchPointID.clear(); +} + +void QApplicationPrivate::cleanupMultitouch_sys() +{ + touchInputIDToTouchPointID.clear(); +} + +bool QApplicationPrivate::translateTouchEvent(const MSG &msg) +{ + Q_Q(QApplication); + + QWidget *widgetForHwnd = QWidget::find(msg.hwnd); + if (!widgetForHwnd) + return false; + + QRect screenGeometry = q->desktop()->screenGeometry(widgetForHwnd); + + QList<QTouchEvent::TouchPoint> touchPoints; + + QVector<TOUCHINPUT> winTouchInputs(msg.wParam); + memset(winTouchInputs.data(), 0, sizeof(TOUCHINPUT) * winTouchInputs.count()); + Qt::TouchPointStates allStates = 0; + QApplicationPrivate::GetTouchInputInfo((HANDLE) msg.lParam, msg.wParam, winTouchInputs.data(), sizeof(TOUCHINPUT)); + for (int i = 0; i < winTouchInputs.count(); ++i) { + const TOUCHINPUT &touchInput = winTouchInputs.at(i); + + int touchPointID = touchInputIDToTouchPointID.value(touchInput.dwID, -1); + if (touchPointID == -1) { + touchPointID = touchInputIDToTouchPointID.count(); + touchInputIDToTouchPointID.insert(touchInput.dwID, touchPointID); + } + + QTouchEvent::TouchPoint touchPoint(touchPointID); + + // update state + QPointF screenPos(qreal(touchInput.x) / qreal(100.), qreal(touchInput.y) / qreal(100.)); + QRectF screenRect; + if (touchInput.dwMask & TOUCHINPUTMASKF_CONTACTAREA) + screenRect.setSize(QSizeF(qreal(touchInput.cxContact) / qreal(100.), + qreal(touchInput.cyContact) / qreal(100.))); + screenRect.moveCenter(screenPos); + + Qt::TouchPointStates state; + if (touchInput.dwFlags & TOUCHEVENTF_DOWN) { + state = Qt::TouchPointPressed; + } else if (touchInput.dwFlags & TOUCHEVENTF_UP) { + state = Qt::TouchPointReleased; + } else { + state = (screenPos == touchPoint.screenPos() + ? Qt::TouchPointStationary + : Qt::TouchPointMoved); + } + if (touchInput.dwFlags & TOUCHEVENTF_PRIMARY) + state |= Qt::TouchPointPrimary; + touchPoint.setState(state); + touchPoint.setScreenRect(screenRect); + touchPoint.setNormalizedPos(QPointF(screenPos.x() / screenGeometry.width(), + screenPos.y() / screenGeometry.height())); + + allStates |= state; + + touchPoints.append(touchPoint); + } + QApplicationPrivate::CloseTouchInputHandle((HANDLE) msg.lParam); + + if ((allStates & Qt::TouchPointStateMask) == Qt::TouchPointReleased) { + // all touch points released, forget the ids we've seen, they may not be reused + touchInputIDToTouchPointID.clear(); + } + + translateRawTouchEvent(widgetForHwnd, QTouchEvent::TouchScreen, touchPoints); + return true; +} + QT_END_NAMESPACE diff --git a/src/gui/kernel/qapplication_x11.cpp b/src/gui/kernel/qapplication_x11.cpp index 2704987..5ef6b2e 100644 --- a/src/gui/kernel/qapplication_x11.cpp +++ b/src/gui/kernel/qapplication_x11.cpp @@ -128,6 +128,12 @@ extern "C" { #include <private/qbackingstore_p.h> +#ifdef QT_RX71_MULTITOUCH +# include <qsocketnotifier.h> +# include <linux/input.h> +# include <errno.h> +#endif + #if _POSIX_VERSION+0 < 200112L && !defined(Q_OS_BSD4) # define QT_NO_UNSETENV #endif @@ -3220,6 +3226,7 @@ int QApplication::x11ProcessEvent(XEvent* event) { Q_D(QApplication); QScopedLoopLevelCounter loopLevelCounter(d->threadData); + #ifdef ALIEN_DEBUG //qDebug() << "QApplication::x11ProcessEvent:" << event->type; #endif @@ -4490,7 +4497,6 @@ bool QETWidget::translateMouseEvent(const XEvent *event) QMouseEvent e(type, pos, globalPos, button, buttons, modifiers); QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver); - if (type == QEvent::MouseButtonPress && button == Qt::RightButton && (openPopupCount == oldOpenPopupCount)) { @@ -5104,6 +5110,7 @@ bool QETWidget::translatePropertyEvent(const XEvent *event) return true; } + // // Paint event translation // @@ -6005,4 +6012,225 @@ void QSessionManager::requestPhase2() #endif // QT_NO_SESSIONMANAGER +#if defined(QT_RX71_MULTITOUCH) + +static inline int testBit(const char *array, int bit) +{ + return (array[bit/8] & (1<<(bit%8))); +} + +static int openRX71Device(const QByteArray &deviceName) +{ + int fd = open(deviceName, O_RDONLY | O_NONBLOCK); + if (fd == -1) { + fd = -errno; + return fd; + } + + // fetch the event type mask and check that the device reports absolute coordinates + char eventTypeMask[(EV_MAX + sizeof(char) - 1) * sizeof(char) + 1]; + memset(eventTypeMask, 0, sizeof(eventTypeMask)); + if (ioctl(fd, EVIOCGBIT(0, sizeof(eventTypeMask)), eventTypeMask) < 0) { + close(fd); + return -1; + } + if (!testBit(eventTypeMask, EV_ABS)) { + close(fd); + return -1; + } + + // make sure that we can get the absolute X and Y positions from the device + char absMask[(ABS_MAX + sizeof(char) - 1) * sizeof(char) + 1]; + memset(absMask, 0, sizeof(absMask)); + if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absMask)), absMask) < 0) { + close(fd); + return -1; + } + if (!testBit(absMask, ABS_X) || !testBit(absMask, ABS_Y)) { + close(fd); + return -1; + } + + return fd; +} + +void QApplicationPrivate::initializeMultitouch_sys() +{ + Q_Q(QApplication); + + QByteArray deviceName = QByteArray("/dev/input/event"); + int currentDeviceNumber = 0; + for (;;) { + int fd = openRX71Device(QByteArray(deviceName + QByteArray::number(currentDeviceNumber++))); + if (fd == -ENOENT) { + // no more devices + break; + } + if (fd < 0) { + // not a touch device + continue; + } + + struct input_absinfo abs_x, abs_y, abs_z; + ioctl(fd, EVIOCGABS(ABS_X), &abs_x); + ioctl(fd, EVIOCGABS(ABS_Y), &abs_y); + ioctl(fd, EVIOCGABS(ABS_Z), &abs_z); + + int deviceNumber = allRX71TouchPoints.count(); + + QSocketNotifier *socketNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, q); + QObject::connect(socketNotifier, SIGNAL(activated(int)), q, SLOT(_q_readRX71MultiTouchEvents())); + + RX71TouchPointState touchPointState = { + socketNotifier, + QTouchEvent::TouchPoint(deviceNumber), + + abs_x.minimum, abs_x.maximum, q->desktop()->screenGeometry().width(), + abs_y.minimum, abs_y.maximum, q->desktop()->screenGeometry().height(), + abs_z.minimum, abs_z.maximum + }; + allRX71TouchPoints.append(touchPointState); + } + + hasRX71MultiTouch = allRX71TouchPoints.count() > 1; + if (!hasRX71MultiTouch) { + for (int i = 0; i < allRX71TouchPoints.count(); ++i) { + QSocketNotifier *socketNotifier = allRX71TouchPoints.at(i).socketNotifier; + close(socketNotifier->socket()); + delete socketNotifier; + } + allRX71TouchPoints.clear(); + } +} + +void QApplicationPrivate::cleanupMultitouch_sys() +{ + hasRX71MultiTouch = false; + for (int i = 0; i < allRX71TouchPoints.count(); ++i) { + QSocketNotifier *socketNotifier = allRX71TouchPoints.at(i).socketNotifier; + close(socketNotifier->socket()); + delete socketNotifier; + } + allRX71TouchPoints.clear(); +} + +bool QApplicationPrivate::readRX71MultiTouchEvents(int deviceNumber) +{ + RX71TouchPointState &touchPointState = allRX71TouchPoints[deviceNumber]; + QSocketNotifier *socketNotifier = touchPointState.socketNotifier; + int fd = socketNotifier->socket(); + + QTouchEvent::TouchPoint &touchPoint = touchPointState.touchPoint; + + bool down = touchPoint.state() != Qt::TouchPointReleased; + if (down) + touchPoint.setState(Qt::TouchPointStationary); + + bool changed = false; + for (;;) { + struct input_event inputEvent; + int bytesRead = read(fd, &inputEvent, sizeof(inputEvent)); + if (bytesRead <= 0) + break; + if (bytesRead != sizeof(inputEvent)) { + qWarning("Qt: INTERNAL ERROR: short read in readRX71MultiTouchEvents()"); + return false; + } + + switch (inputEvent.type) { + case EV_SYN: + changed = true; + switch (touchPoint.state()) { + case Qt::TouchPointPressed: + case Qt::TouchPointReleased: + // make sure we don't compress pressed and releases with any other events + return changed; + default: + break; + } + continue; + case EV_KEY: + case EV_ABS: + break; + default: + qWarning("Qt: WARNING: unknown event type %d on multitouch device", inputEvent.type); + continue; + } + + QPointF screenPos = touchPoint.screenPos(); + switch (inputEvent.code) { + case BTN_TOUCH: + if (!down && inputEvent.value != 0) + touchPoint.setState(Qt::TouchPointPressed); + else if (down && inputEvent.value == 0) + touchPoint.setState(Qt::TouchPointReleased); + break; + case ABS_TOOL_WIDTH: + case ABS_VOLUME: + case ABS_PRESSURE: + // ignore for now + break; + case ABS_X: + { + qreal newValue = ((qreal(inputEvent.value - touchPointState.minX) + / qreal(touchPointState.maxX - touchPointState.minX)) + * touchPointState.scaleX); + screenPos.rx() = newValue; + touchPoint.setScreenPos(screenPos); + break; + } + case ABS_Y: + { + qreal newValue = ((qreal(inputEvent.value - touchPointState.minY) + / qreal(touchPointState.maxY - touchPointState.minY)) + * touchPointState.scaleY); + screenPos.ry() = newValue; + touchPoint.setScreenPos(screenPos); + break; + } + case ABS_Z: + { + // map Z (signal strength) to pressure for now + qreal newValue = (qreal(inputEvent.value - touchPointState.minZ) + / qreal(touchPointState.maxZ - touchPointState.minZ)); + touchPoint.setPressure(newValue); + break; + } + default: + qWarning("Qt: WARNING: unknown event code %d on multitouch device", inputEvent.code); + continue; + } + } + + if (down && touchPoint.state() != Qt::TouchPointReleased) + touchPoint.setState(changed ? Qt::TouchPointMoved : Qt::TouchPointStationary); + + return changed; +} + +void QApplicationPrivate::_q_readRX71MultiTouchEvents() +{ + // read touch events from all devices + bool changed = false; + for (int i = 0; i < allRX71TouchPoints.count(); ++i) + changed = readRX71MultiTouchEvents(i) || changed; + if (!changed) + return; + + QList<QTouchEvent::TouchPoint> touchPoints; + for (int i = 0; i < allRX71TouchPoints.count(); ++i) + touchPoints.append(allRX71TouchPoints.at(i).touchPoint); + + translateRawTouchEvent(0, QTouchEvent::TouchScreen, touchPoints); +} + +#else // !QT_RX71_MULTITOUCH + +void QApplicationPrivate::initializeMultitouch_sys() +{ } +void QApplicationPrivate::cleanupMultitouch_sys() +{ } + +#endif // QT_RX71_MULTITOUCH + QT_END_NAMESPACE diff --git a/src/gui/kernel/qclipboard_win.cpp b/src/gui/kernel/qclipboard_win.cpp index 09b5448..f5aa088 100644 --- a/src/gui/kernel/qclipboard_win.cpp +++ b/src/gui/kernel/qclipboard_win.cpp @@ -200,7 +200,7 @@ HRESULT QtCeGetClipboard(IDataObject** obj) if (clipData == 0) { clipData = GetClipboardData(CF_UNICODETEXT); if (clipData != 0) - clipText = QString::fromUtf16((unsigned short *)clipData); + clipText = QString::fromWCharArray((wchar_t *)clipData); } else { clipText = QString::fromLatin1((const char*)clipData); } @@ -325,13 +325,7 @@ bool QClipboard::event(QEvent *e) } if (propagate && d->nextClipboardViewer) { - QT_WA({ - SendMessage(d->nextClipboardViewer, m->message, - m->wParam, m->lParam); - } , { - SendMessageA(d->nextClipboardViewer, m->message, - m->wParam, m->lParam); - }); + SendMessage(d->nextClipboardViewer, m->message, m->wParam, m->lParam); } return true; diff --git a/src/gui/kernel/qcocoaview_mac.mm b/src/gui/kernel/qcocoaview_mac.mm index 3d0bafa..64cdae6 100644 --- a/src/gui/kernel/qcocoaview_mac.mm +++ b/src/gui/kernel/qcocoaview_mac.mm @@ -49,6 +49,7 @@ #include <private/qt_cocoa_helpers_mac_p.h> #include <private/qdnd_p.h> #include <private/qmacinputcontext_p.h> +#include <private/qmultitouch_mac_p.h> #include <qscrollarea.h> #include <qhash.h> @@ -556,6 +557,13 @@ extern "C" { return !qwidget->testAttribute(Qt::WA_MacNoClickThrough); } +- (NSView *)hitTest:(NSPoint)aPoint +{ + if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) + return nil; // You cannot hit a transparent for mouse event widget. + return [super hitTest:aPoint]; +} + - (void)updateTrackingAreas { QMacCocoaAutoReleasePool pool; @@ -709,7 +717,7 @@ extern "C" { } - (void)rightMouseDown:(NSEvent *)theEvent -{ +{ bool mouseOK = qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonPress, Qt::RightButton); if (!mouseOK) @@ -792,16 +800,6 @@ extern "C" { Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]); QWidget *widgetToGetMouse = qwidget; - if (widgetToGetMouse->testAttribute(Qt::WA_TransparentForMouseEvents)) { - // Simulate passing the event through since Cocoa doesn't do that for us. - // Start by building a tree up. - NSView *candidateView = [self viewUnderTransparentForMouseView:self - widget:widgetToGetMouse - withWindowPoint:windowPoint]; - if (candidateView != nil) { - widgetToGetMouse = QWidget::find(WId(candidateView)); - } - } // Mouse wheel deltas seem to tick in at increments of 0.1. Qt widgets // expect the delta to be a multiple of 120. @@ -868,6 +866,62 @@ extern "C" { [super tabletPoint:tabletEvent]; } +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 +- (void)touchesBeganWithEvent:(NSEvent *)event; +{ + bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents); + qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all)); +} + +- (void)touchesMovedWithEvent:(NSEvent *)event; +{ + bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents); + qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all)); +} + +- (void)touchesEndedWithEvent:(NSEvent *)event; +{ + bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents); + qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all)); +} + +- (void)touchesCancelledWithEvent:(NSEvent *)event; +{ + bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents); + qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all)); +} + +- (void)magnifyWithEvent:(NSEvent *)event; +{ + Q_UNUSED(event); +// qDebug() << "magnifyWithEvent"; +} + +- (void)rotateWithEvent:(NSEvent *)event; +{ + Q_UNUSED(event); +// qDebug() << "rotateWithEvent"; +} + +- (void)swipeWithEvent:(NSEvent *)event; +{ + Q_UNUSED(event); +// qDebug() << "swipeWithEvent"; +} + +- (void)beginGestureWithEvent:(NSEvent *)event; +{ + Q_UNUSED(event); +// qDebug() << "beginGestureWithEvent"; +} + +- (void)endGestureWithEvent:(NSEvent *)event; +{ + Q_UNUSED(event); +// qDebug() << "endGestureWithEvent"; +} +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + - (void)frameDidChange:(NSNotification *)note { Q_UNUSED(note); diff --git a/src/gui/kernel/qcocoawindowdelegate_mac.mm b/src/gui/kernel/qcocoawindowdelegate_mac.mm index 9b49efc..3905e21 100644 --- a/src/gui/kernel/qcocoawindowdelegate_mac.mm +++ b/src/gui/kernel/qcocoawindowdelegate_mac.mm @@ -132,7 +132,12 @@ static void cleanupCocoaWindowDelegate() qwidget->setAttribute(Qt::WA_PendingResizeEvent, true); } else { QResizeEvent qre(newSize, oldSize); - qt_sendSpontaneousEvent(qwidget, &qre); + if (qwidget->testAttribute(Qt::WA_PendingResizeEvent)) { + qwidget->setAttribute(Qt::WA_PendingResizeEvent, false); + QApplication::sendEvent(qwidget, &qre); + } else { + qt_sendSpontaneousEvent(qwidget, &qre); + } } } diff --git a/src/gui/kernel/qcursor_win.cpp b/src/gui/kernel/qcursor_win.cpp index f0dc108..db00835 100644 --- a/src/gui/kernel/qcursor_win.cpp +++ b/src/gui/kernel/qcursor_win.cpp @@ -317,54 +317,50 @@ void QCursorData::update() phand_bits, phandm_bits }; - unsigned short *sh; + wchar_t *sh = 0; switch (cshape) { // map to windows cursor case Qt::ArrowCursor: - sh = (unsigned short*)IDC_ARROW; + sh = IDC_ARROW; break; case Qt::UpArrowCursor: - sh = (unsigned short*)IDC_UPARROW; + sh = IDC_UPARROW; break; case Qt::CrossCursor: - sh = (unsigned short*)IDC_CROSS; + sh = IDC_CROSS; break; case Qt::WaitCursor: - sh = (unsigned short*)IDC_WAIT; + sh = IDC_WAIT; break; case Qt::IBeamCursor: - sh = (unsigned short*)IDC_IBEAM; + sh = IDC_IBEAM; break; case Qt::SizeVerCursor: - sh = (unsigned short*)IDC_SIZENS; + sh = IDC_SIZENS; break; case Qt::SizeHorCursor: - sh = (unsigned short*)IDC_SIZEWE; + sh = IDC_SIZEWE; break; case Qt::SizeBDiagCursor: - sh = (unsigned short*)IDC_SIZENESW; + sh = IDC_SIZENESW; break; case Qt::SizeFDiagCursor: - sh = (unsigned short*)IDC_SIZENWSE; + sh = IDC_SIZENWSE; break; case Qt::SizeAllCursor: - sh = (unsigned short*)IDC_SIZEALL; + sh = IDC_SIZEALL; break; case Qt::ForbiddenCursor: - sh = (unsigned short*)IDC_NO; + sh = IDC_NO; break; case Qt::WhatsThisCursor: - sh = (unsigned short*)IDC_HELP; + sh = IDC_HELP; break; case Qt::BusyCursor: - sh = (unsigned short*)IDC_APPSTARTING; + sh = IDC_APPSTARTING; break; case Qt::PointingHandCursor: - if ((QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) > QSysInfo::WV_95 || - (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) > QSysInfo::WV_NT) { - sh = (unsigned short*)IDC_HAND; - break; - } - // fall through + sh = IDC_HAND; + break; case Qt::BlankCursor: case Qt::SplitVCursor: case Qt::SplitHCursor: @@ -480,13 +476,7 @@ void QCursorData::update() qWarning("QCursor::update: Invalid cursor shape %d", cshape); return; } - // ### From MSDN: - // ### LoadCursor has been superseded by the LoadImage function. - QT_WA({ - hcurs = LoadCursorW(0, reinterpret_cast<const TCHAR *>(sh)); - } , { - hcurs = LoadCursorA(0, reinterpret_cast<const char*>(sh)); - }); + hcurs = (HCURSOR)LoadImage(0, sh, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED); } QT_END_NAMESPACE diff --git a/src/gui/kernel/qdesktopwidget_win.cpp b/src/gui/kernel/qdesktopwidget_win.cpp index aa290c4..fb176b7 100644 --- a/src/gui/kernel/qdesktopwidget_win.cpp +++ b/src/gui/kernel/qdesktopwidget_win.cpp @@ -152,41 +152,27 @@ void QDesktopWidgetPrivate::init(QDesktopWidget *that) rects = new QVector<QRect>(); workrects = new QVector<QRect>(); + screenCount = 0; #ifndef Q_OS_WINCE - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - screenCount = 0; - // Trying to get the function pointers to Win98/2000 only functions - QLibrary user32Lib(QLatin1String("user32")); - if (!user32Lib.load()) - return; + QLibrary user32Lib(QLatin1String("user32")); + if (user32Lib.load()) { enumDisplayMonitors = (EnumFunc)user32Lib.resolve("EnumDisplayMonitors"); - QT_WA({ - getMonitorInfo = (InfoFunc)user32Lib.resolve("GetMonitorInfoW"); - } , { - getMonitorInfo = (InfoFunc)user32Lib.resolve("GetMonitorInfoA"); - }); - - if (!enumDisplayMonitors || !getMonitorInfo) { - screenCount = GetSystemMetrics(80); // SM_CMONITORS - rects->resize(screenCount); - for (int i = 0; i < screenCount; ++i) - rects->replace(i, that->rect()); - return; - } - // Calls enumCallback - enumDisplayMonitors(0, 0, enumCallback, 0); - enumDisplayMonitors = 0; - getMonitorInfo = 0; - } else { - rects->resize(1); - rects->replace(0, that->rect()); - workrects->resize(1); - workrects->replace(0, that->rect()); + getMonitorInfo = (InfoFunc)user32Lib.resolve("GetMonitorInfoW"); } -#else - screenCount = 0; + if (!enumDisplayMonitors || !getMonitorInfo) { + screenCount = GetSystemMetrics(80); // SM_CMONITORS + rects->resize(screenCount); + for (int i = 0; i < screenCount; ++i) + rects->replace(i, that->rect()); + return; + } + // Calls enumCallback + enumDisplayMonitors(0, 0, enumCallback, 0); + enumDisplayMonitors = 0; + getMonitorInfo = 0; +#else QLibrary coreLib(QLatin1String("coredll")); if (coreLib.load()) { // CE >= 4.0 case @@ -307,70 +293,61 @@ const QRect QDesktopWidget::availableGeometry(int screen) const for(int i=0; i < d->workrects->size(); ++i) qt_get_sip_info((*d->workrects)[i]); #endif - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - if (screen < 0 || screen >= d->screenCount) - screen = d->primaryScreen; + if (screen < 0 || screen >= d->screenCount) + screen = d->primaryScreen; - return d->workrects->at(screen); - } else { - return d->workrects->at(d->primaryScreen); - } + return d->workrects->at(screen); } const QRect QDesktopWidget::screenGeometry(int screen) const { const QDesktopWidgetPrivate *d = d_func(); - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - if (screen < 0 || screen >= d->screenCount) - screen = d->primaryScreen; + if (screen < 0 || screen >= d->screenCount) + screen = d->primaryScreen; - return d->rects->at(screen); - } else { - return d->rects->at(d->primaryScreen); - } + return d->rects->at(screen); } int QDesktopWidget::screenNumber(const QWidget *widget) const { Q_D(const QDesktopWidget); - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - if (!widget) - return d->primaryScreen; - QRect frame = widget->frameGeometry(); - if (!widget->isWindow()) - frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0))); - - int maxSize = -1; - int maxScreen = -1; - - for (int i = 0; i < d->screenCount; ++i) { - QRect sect = d->rects->at(i).intersected(frame); - int size = sect.width() * sect.height(); - if (size > maxSize && sect.width() > 0 && sect.height() > 0) { - maxSize = size; - maxScreen = i; - } - } - return maxScreen; - } else { + if (!widget) return d->primaryScreen; + + QRect frame = widget->frameGeometry(); + if (!widget->isWindow()) + frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0))); + + int maxSize = -1; + int maxScreen = -1; + + for (int i = 0; i < d->screenCount; ++i) { + QRect sect = d->rects->at(i).intersected(frame); + int size = sect.width() * sect.height(); + if (size > maxSize && sect.width() > 0 && sect.height() > 0) { + maxSize = size; + maxScreen = i; + } } + + return maxScreen; } int QDesktopWidget::screenNumber(const QPoint &point) const { Q_D(const QDesktopWidget); + int closestScreen = -1; - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - int shortestDistance = INT_MAX; - for (int i = 0; i < d->screenCount; ++i) { - int thisDistance = d->pointToRect(point, d->rects->at(i)); - if (thisDistance < shortestDistance) { - shortestDistance = thisDistance; - closestScreen = i; - } + int shortestDistance = INT_MAX; + + for (int i = 0; i < d->screenCount; ++i) { + int thisDistance = d->pointToRect(point, d->rects->at(i)); + if (thisDistance < shortestDistance) { + shortestDistance = thisDistance; + closestScreen = i; } } + return closestScreen; } diff --git a/src/gui/kernel/qdnd_mac.mm b/src/gui/kernel/qdnd_mac.mm index b244d84..99399da 100644 --- a/src/gui/kernel/qdnd_mac.mm +++ b/src/gui/kernel/qdnd_mac.mm @@ -405,12 +405,12 @@ bool QWidgetPrivate::qt_mac_dnd_event(uint kind, DragRef dragRef) SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDEEvent.dropAction())); if (!qDEEvent.isAccepted()) - // The widget is simply not interrested in this + // The widget is simply not interested in this // drag. So tell carbon this by returning 'false'. We will then // not receive any further move, drop or leave events for this widget. return false; else { - // Documentation states that a drag move event is sendt immidiatly after + // Documentation states that a drag move event is sent immediately after // a drag enter event. So we do that. This will honor widgets overriding // 'dragMoveEvent' only, and not 'dragEnterEvent' QDragMoveEvent qDMEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata, diff --git a/src/gui/kernel/qdnd_win.cpp b/src/gui/kernel/qdnd_win.cpp index 99c960c..70f89d2 100644 --- a/src/gui/kernel/qdnd_win.cpp +++ b/src/gui/kernel/qdnd_win.cpp @@ -154,9 +154,9 @@ QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium) #ifdef QDND_DEBUG qDebug("QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium)"); #ifndef Q_OS_WINCE - char buf[256] = {0}; - GetClipboardFormatNameA(pformatetc->cfFormat, buf, 255); - qDebug("CF = %d : %s", pformatetc->cfFormat, buf); + wchar_t buf[256] = {0}; + GetClipboardFormatName(pformatetc->cfFormat, buf, 255); + qDebug("CF = %d : %s", pformatetc->cfFormat, QString::fromWCharArray(buf)); #endif #endif @@ -398,52 +398,47 @@ void QOleDropSource::createCursors() int h = cpm.height(); if (!pm.isNull()) { - int x1 = qMin(-hotSpot.x(),0); - int x2 = qMax(pm.width()-hotSpot.x(),cpm.width()); - int y1 = qMin(-hotSpot.y(),0); - int y2 = qMax(pm.height()-hotSpot.y(),cpm.height()); + int x1 = qMin(-hotSpot.x(), 0); + int x2 = qMax(pm.width() - hotSpot.x(), cpm.width()); + int y1 = qMin(-hotSpot.y(), 0); + int y2 = qMax(pm.height() - hotSpot.y(), cpm.height()); - w = x2-x1+1; - h = y2-y1+1; + w = x2 - x1 + 1; + h = y2 - y1 + 1; } QRect srcRect = pm.rect(); QPoint pmDest = QPoint(qMax(0, -hotSpot.x()), qMax(0, -hotSpot.y())); QPoint newHotSpot = hotSpot; -#if !defined(Q_OS_WINCE) || defined(GWES_ICONCURS) - bool limitedCursorSize = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) - || (QSysInfo::WindowsVersion == QSysInfo::WV_NT) - || (QSysInfo::WindowsVersion == QSysInfo::WV_CE); - - if (limitedCursorSize) { - // Limited cursor size - int reqw = GetSystemMetrics(SM_CXCURSOR); - int reqh = GetSystemMetrics(SM_CYCURSOR); - - QPoint hotspotInPM = newHotSpot - pmDest; - if (reqw < w) { - // Not wide enough - move objectpm right - qreal r = qreal(newHotSpot.x()) / w; - newHotSpot = QPoint(int(r * reqw), newHotSpot.y()); - if (newHotSpot.x() + cpm.width() > reqw) - newHotSpot.setX(reqw - cpm.width()); - - srcRect = QRect(QPoint(hotspotInPM.x() - newHotSpot.x(), srcRect.top()), QSize(reqw, srcRect.height())); - } - if (reqh < h) { - qreal r = qreal(newHotSpot.y()) / h; - newHotSpot = QPoint(newHotSpot.x(), int(r * reqh)); - if (newHotSpot.y() + cpm.height() > reqh) - newHotSpot.setY(reqh - cpm.height()); - - srcRect = QRect(QPoint(srcRect.left(), hotspotInPM.y() - newHotSpot.y()), QSize(srcRect.width(), reqh)); - } - // Always use system cursor size - w = reqw; - h = reqh; +#if defined(Q_OS_WINCE) + // Limited cursor size + int reqw = GetSystemMetrics(SM_CXCURSOR); + int reqh = GetSystemMetrics(SM_CYCURSOR); + + QPoint hotspotInPM = newHotSpot - pmDest; + if (reqw < w) { + // Not wide enough - move objectpm right + qreal r = qreal(newHotSpot.x()) / w; + newHotSpot = QPoint(int(r * reqw), newHotSpot.y()); + if (newHotSpot.x() + cpm.width() > reqw) + newHotSpot.setX(reqw - cpm.width()); + + srcRect = QRect(QPoint(hotspotInPM.x() - newHotSpot.x(), srcRect.top()), QSize(reqw, srcRect.height())); } + if (reqh < h) { + qreal r = qreal(newHotSpot.y()) / h; + newHotSpot = QPoint(newHotSpot.x(), int(r * reqh)); + if (newHotSpot.y() + cpm.height() > reqh) + newHotSpot.setY(reqh - cpm.height()); + + srcRect = QRect(QPoint(srcRect.left(), hotspotInPM.y() - newHotSpot.y()), QSize(srcRect.width(), reqh)); + } + // Always use system cursor size + w = reqw; + h = reqh; #endif + QPixmap newCursor(w, h); if (!pm.isNull()) { newCursor.fill(QColor(0, 0, 0, 0)); diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp index 12bbc7d..4fc3643 100644 --- a/src/gui/kernel/qevent.cpp +++ b/src/gui/kernel/qevent.cpp @@ -49,6 +49,7 @@ #include "qmime.h" #include "qdnd_p.h" #include "qevent_p.h" +#include "qgesture.h" QT_BEGIN_NAMESPACE @@ -83,6 +84,13 @@ QInputEvent::~QInputEvent() \sa QApplication::keyboardModifiers() */ +/*! \fn void QInputEvent::setModifiers(Qt::KeyboardModifiers modifiers) + + \internal + + Sets the keyboard modifiers flags for this event. +*/ + /*! \class QMouseEvent \ingroup events @@ -106,6 +114,10 @@ QInputEvent::~QInputEvent() propagated up the parent widget chain until a widget accepts it with accept(), or an event filter consumes it. + \note If a mouse event is propagated to a \l{QWidget}{widget} for + which Qt::WA_NoMousePropagation has been set, that mouse event + will not be propagated further up the parent widget chain. + The state of the keyboard modifier keys can be found by calling the \l{QInputEvent::modifiers()}{modifiers()} function, inhertied from QInputEvent. @@ -3518,4 +3530,504 @@ QMenubarUpdatedEvent::QMenubarUpdatedEvent(QMenuBar * const menuBar) #endif +/*! \class QTouchEvent + \brief The QTouchEvent class contains parameters that describe a touch event +. + \since 4.6 + \ingroup events + + Touch events occur when pressing, releasing, or moving one or more + touch points on a touch device (such as a touch-screen or + track-pad), and if the widget has the Qt::WA_AcceptTouchEvents + attribute. + + All touch events are of type QEvent::TouchBegin, + QEvent::TouchUpdate, or QEvent::TouchEnd. The touchPoints() + function returns a list of all touch points contained in the event. + Information about each touch point can be retreived using the + QTouchEvent::TouchPoint class. + + Similar to QMouseEvent, Qt automatically grabs each touch point on + the first press inside a widget; the widget will receive all + updates for the touch point until it is released. Note that it is + possible for a widget to receive events for multiple touch points, + and that multiple widgets may be receiving touch events at the same + time. + + A touch event contains a special accept flag that indicates + whether the receiver wants the event. By default, the event is + accepted. You should call ignore() if the touch event is not handled by + your widget. A QEvent::TouchBegin event is propagated up the parent widget + chain until a widget accepts it with accept(), or an event filter + consumes it. If the QEvent::TouchBegin event is neither accepted nor consumed, + then mouse events are simulated from the state of the first touch + point. + + The Qt::TouchPointState enum describes the different states that a + touch point may have. + + QTouchEvent::TouchPoint Qt::TouchPointState Qt::WA_AcceptTouchEvents +*/ + +/*! \enum Qt::TouchPointState + \since 4.6 + + This enum represents the state of a touch point at the time the + QTouchEvent occurred. + + \value TouchPointPressed The touch point is now pressed. + \value TouchPointMoved The touch point moved. + \value TouchPointStationary The touch point did not move. + \value TouchPointReleased The touch point was released. + + \omitvalue TouchPointStateMask + \omitvalue TouchPointPrimary +*/ + +/*! \class QTouchEvent::TouchPoint + \brief The QTouchEvent::TouchPoint class provide information about a touch point in a QTouchEvent. + \since 4.6 +*/ + +/*! \enum QTouchEvent::DeviceType + \since 4.6 + + This enum represents the type of device that generated a QTouchEvent. + + \value TouchScreen In this type of device, the touch surface and display are integrated. This + means the surface and display typically have the same size, such that there + is a direct relationship between the touch points' physical positions and the + coordinate reported by QTouchEvent::TouchPoint. As a result, Qt allows the + user to interact directly with multiple QWidgets and QGraphicsItems at the + same time. + + \value TouchPad In this type of device, the touch surface is separate from the display. There + is not a direct relationship between the physical touch location and the + on-screen coordinates. Instead, they are calculated relative to the current + mouse position, and the user must use the touch-pad to move this reference + point. Unlike touch-screens, Qt allows users to only interact with a single + QWidget or QGraphicsItem at a time. +*/ + +/*! + Constructs a QTouchEvent with the given \a eventType, \a deviceType, and \a touchPoints. + The \a touchPointStates and \a modifiers are the current touch point states and keyboard + modifiers at the time of the event. +*/ +QTouchEvent::QTouchEvent(QEvent::Type eventType, + QTouchEvent::DeviceType deviceType, + Qt::KeyboardModifiers modifiers, + Qt::TouchPointStates touchPointStates, + const QList<QTouchEvent::TouchPoint> &touchPoints) + : QInputEvent(eventType, modifiers), + _widget(0), + _deviceType(deviceType), + _touchPointStates(touchPointStates), + _touchPoints(touchPoints) +{ } + +/*! + Destroys the QTouchEvent. +*/ +QTouchEvent::~QTouchEvent() +{ } + +/*! \fn QWidget *QTouchEvent::widget() const + + Returns the widget on which the event occurred. +*/ + + +/*! \fn Qt::TouchPointStates QTouchEvent::touchPointStates() const + + Returns a bitwise OR of all the touch point states for this event. +*/ + +/*! \fn const QList<QTouchEvent::TouchPoint> &QTouchEvent::touchPoints() const + + Returns the list of touch points contained in the touch event. +*/ + +/*! \fn void QTouchEvent::setWidget(QWidget *widget) + + \internal + + Sets the widget for this event. +*/ + +/*! \fn void QTouchEvent::setTouchPointStates(Qt::TouchPointStates touchPointStates) + + \internal + + Sets a bitwise OR of all the touch point states for this event. +*/ + +/*! \fn void QTouchEvent::setTouchPoints(const QList<QTouchEvent::TouchPoint> &touchPoints) + + \internal + + Sets the list of touch points for this event. +*/ + +/*! \internal + + Constructs a QTouchEvent::TouchPoint for use in a QTouchEvent. +*/ +QTouchEvent::TouchPoint::TouchPoint(int id) + : d(new QTouchEventTouchPointPrivate(id)) +{ } + +/*! \internal + + Constructs a copy of \a other. +*/ +QTouchEvent::TouchPoint::TouchPoint(const QTouchEvent::TouchPoint &other) + : d(other.d) +{ + d->ref.ref(); +} + +/*! \internal + + Destroys the QTouchEvent::TouchPoint. +*/ +QTouchEvent::TouchPoint::~TouchPoint() +{ + if (!d->ref.deref()) + delete d; +} + +/*! + Returns the id number of this touch point. + + Id numbers are globally sequential, starting at zero, meaning the + first touch point in the application has id 0, the second has id 1, + and so on. +*/ +int QTouchEvent::TouchPoint::id() const +{ + return d->id; +} + +/*! + Returns the current state of this touch point. +*/ +Qt::TouchPointState QTouchEvent::TouchPoint::state() const +{ + return Qt::TouchPointState(int(d->state) & Qt::TouchPointStateMask); +} + +/*! + Returns true if this touch point is the primary touch point. The primary touch point is the + point for which the windowing system generates mouse events. +*/ +bool QTouchEvent::TouchPoint::isPrimary() const +{ + return (d->state & Qt::TouchPointPrimary) != 0; +} + +/*! + Returns the position of this touch point, relative to the widget + or item that received the event. +*/ +QPointF QTouchEvent::TouchPoint::pos() const +{ + return d->rect.center(); +} + +/*! + Returns the scene position of this touch point. +*/ +QPointF QTouchEvent::TouchPoint::scenePos() const +{ + return d->sceneRect.center(); +} + +/*! + Returns the screen position of this touch point. +*/ +QPointF QTouchEvent::TouchPoint::screenPos() const +{ + return d->screenRect.center(); +} + +/*! + Returns the position of this touch point. The coordinates are normalized to size of the touch + device, i.e. (0,0) is the top-left corner and (1,1) is the bottom-right corner. +*/ +QPointF QTouchEvent::TouchPoint::normalizedPos() const +{ + return d->normalizedPos; +} + +/*! + Returns the starting position of this touch point, relative to the + widget that received the event. +*/ +QPointF QTouchEvent::TouchPoint::startPos() const +{ + return d->startPos; +} + +/*! + Returns the starting scene position of this touch point. +*/ +QPointF QTouchEvent::TouchPoint::startScenePos() const +{ + return d->startScenePos; +} + +/*! + Returns the starting screen position of this touch point. +*/ +QPointF QTouchEvent::TouchPoint::startScreenPos() const +{ + return d->startScreenPos; +} + +/*! + Returns the starting position of this touch point. The coordinates are normalized to size of + the touch device, i.e. (0,0) is the top-left corner and (1,1) is the bottom-right corner. +*/ +QPointF QTouchEvent::TouchPoint::startNormalizedPos() const +{ + return d->startNormalizedPos; +} + +/*! + Returns the position of this touch point from the previous touch + event, relative to the widget that received the event. +*/ +QPointF QTouchEvent::TouchPoint::lastPos() const +{ + return d->lastPos; +} + +/*! + Returns the scene position of this touch point from the previous + touch event. +*/ +QPointF QTouchEvent::TouchPoint::lastScenePos() const +{ + return d->lastScenePos; +} + +/*! + Returns the screen position of this touch point from the previous + touch event. +*/ +QPointF QTouchEvent::TouchPoint::lastScreenPos() const +{ + return d->lastScreenPos; +} + +/*! + Returns the position of this touch point from the previous touch event. The coordinates are + normalized to size of the touch device, i.e. (0,0) is the top-left corner and (1,1) is the + bottom-right corner. +*/ +QPointF QTouchEvent::TouchPoint::lastNormalizedPos() const +{ + return d->lastNormalizedPos; +} + +/*! + Returns the rect for this touch point. The rect is centered around the point returned by pos(). + Note this function returns an empty rect if the device does not report touch point sizes. +*/ +QRectF QTouchEvent::TouchPoint::rect() const +{ + return d->rect; +} + +/*! + Returns the rect for this touch point in scene coordinates. +*/ +QRectF QTouchEvent::TouchPoint::sceneRect() const +{ + return d->sceneRect; +} + +/*! + Returns the rect for this touch point in screen coordinates. +*/ +QRectF QTouchEvent::TouchPoint::screenRect() const +{ + return d->screenRect; +} + +/*! + Returns the pressure of this touch point. The return value is in + the range 0.0 to 1.0. +*/ +qreal QTouchEvent::TouchPoint::pressure() const +{ + return d->pressure; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setId(int id) +{ + if (d->ref != 1) + d = d->detach(); + d->id = id; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setState(Qt::TouchPointStates state) +{ + if (d->ref != 1) + d = d->detach(); + d->state = state; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setPos(const QPointF &pos) +{ + if (d->ref != 1) + d = d->detach(); + d->rect.moveCenter(pos); +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setScenePos(const QPointF &scenePos) +{ + if (d->ref != 1) + d = d->detach(); + d->sceneRect.moveCenter(scenePos); +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setScreenPos(const QPointF &screenPos) +{ + if (d->ref != 1) + d = d->detach(); + d->screenRect.moveCenter(screenPos); +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setNormalizedPos(const QPointF &normalizedPos) +{ + if (d->ref != 1) + d = d->detach(); + d->normalizedPos = normalizedPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setStartPos(const QPointF &startPos) +{ + if (d->ref != 1) + d = d->detach(); + d->startPos = startPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setStartScenePos(const QPointF &startScenePos) +{ + if (d->ref != 1) + d = d->detach(); + d->startScenePos = startScenePos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setStartScreenPos(const QPointF &startScreenPos) +{ + if (d->ref != 1) + d = d->detach(); + d->startScreenPos = startScreenPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setStartNormalizedPos(const QPointF &startNormalizedPos) +{ + if (d->ref != 1) + d = d->detach(); + d->startNormalizedPos = startNormalizedPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setLastPos(const QPointF &lastPos) +{ + if (d->ref != 1) + d = d->detach(); + d->lastPos = lastPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setLastScenePos(const QPointF &lastScenePos) +{ + if (d->ref != 1) + d = d->detach(); + d->lastScenePos = lastScenePos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setLastScreenPos(const QPointF &lastScreenPos) +{ + if (d->ref != 1) + d = d->detach(); + d->lastScreenPos = lastScreenPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setLastNormalizedPos(const QPointF &lastNormalizedPos) +{ + if (d->ref != 1) + d = d->detach(); + d->lastNormalizedPos = lastNormalizedPos; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setRect(const QRectF &rect) +{ + if (d->ref != 1) + d = d->detach(); + d->rect = rect; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setSceneRect(const QRectF &sceneRect) +{ + if (d->ref != 1) + d = d->detach(); + d->sceneRect = sceneRect; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setScreenRect(const QRectF &screenRect) +{ + if (d->ref != 1) + d = d->detach(); + d->screenRect = screenRect; +} + +/*! \internal */ +void QTouchEvent::TouchPoint::setPressure(qreal pressure) +{ + if (d->ref != 1) + d = d->detach(); + d->pressure = pressure; +} + +/*! \internal */ +QTouchEvent::TouchPoint &QTouchEvent::TouchPoint::operator=(const QTouchEvent::TouchPoint &other) +{ + other.d->ref.ref(); + if (!d->ref.deref()) + delete d; + d = other.d; + return *this; +} + +/*! \fn QTouchEvent::DeviceType QTouchEvent::deviceType() const + Returns the touch device Type, which is of type + \l {QTouchEvent::DeviceType} {DeviceType}. + */ + +/*! \fn void QTouchEvent::setDeviceType(DeviceType deviceType) + Sets the device type to \a deviceType, which is of type + \l {QTouchEvent::DeviceType} {DeviceType}. + */ + + QT_END_NAMESPACE diff --git a/src/gui/kernel/qevent.h b/src/gui/kernel/qevent.h index c2cb05f..11843cb 100644 --- a/src/gui/kernel/qevent.h +++ b/src/gui/kernel/qevent.h @@ -52,6 +52,8 @@ #include <QtGui/qmime.h> #include <QtGui/qdrag.h> #include <QtCore/qvariant.h> +#include <QtCore/qmap.h> +#include <QtCore/qset.h> QT_BEGIN_HEADER @@ -60,6 +62,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QAction; +class QGesture; class Q_GUI_EXPORT QInputEvent : public QEvent { @@ -67,6 +70,7 @@ public: QInputEvent(Type type, Qt::KeyboardModifiers modifiers = Qt::NoModifier); ~QInputEvent(); inline Qt::KeyboardModifiers modifiers() const { return modState; } + inline void setModifiers(Qt::KeyboardModifiers modifiers) { modState = modifiers; } protected: Qt::KeyboardModifiers modState; }; @@ -719,6 +723,101 @@ inline bool operator==(QKeyEvent *e, QKeySequence::StandardKey key){return (e ? inline bool operator==(QKeySequence::StandardKey key, QKeyEvent *e){return (e ? e->matches(key) : false);} #endif // QT_NO_SHORTCUT +class QTouchEventTouchPointPrivate; +class Q_GUI_EXPORT QTouchEvent : public QInputEvent +{ +public: + class Q_GUI_EXPORT TouchPoint + { + public: + TouchPoint(int id = -1); + TouchPoint(const QTouchEvent::TouchPoint &other); + ~TouchPoint(); + + int id() const; + + Qt::TouchPointState state() const; + bool isPrimary() const; + + QPointF pos() const; + QPointF startPos() const; + QPointF lastPos() const; + + QPointF scenePos() const; + QPointF startScenePos() const; + QPointF lastScenePos() const; + + QPointF screenPos() const; + QPointF startScreenPos() const; + QPointF lastScreenPos() const; + + QPointF normalizedPos() const; + QPointF startNormalizedPos() const; + QPointF lastNormalizedPos() const; + + QRectF rect() const; + QRectF sceneRect() const; + QRectF screenRect() const; + + qreal pressure() const; + + // internal + void setId(int id); + void setState(Qt::TouchPointStates state); + void setPos(const QPointF &pos); + void setScenePos(const QPointF &scenePos); + void setScreenPos(const QPointF &screenPos); + void setNormalizedPos(const QPointF &normalizedPos); + void setStartPos(const QPointF &startPos); + void setStartScenePos(const QPointF &startScenePos); + void setStartScreenPos(const QPointF &startScreenPos); + void setStartNormalizedPos(const QPointF &startNormalizedPos); + void setLastPos(const QPointF &lastPos); + void setLastScenePos(const QPointF &lastScenePos); + void setLastScreenPos(const QPointF &lastScreenPos); + void setLastNormalizedPos(const QPointF &lastNormalizedPos); + void setRect(const QRectF &rect); + void setSceneRect(const QRectF &sceneRect); + void setScreenRect(const QRectF &screenRect); + void setPressure(qreal pressure); + QTouchEvent::TouchPoint &operator=(const QTouchEvent::TouchPoint &other); + + private: + QTouchEventTouchPointPrivate *d; + }; + + enum DeviceType { + TouchScreen, + TouchPad + }; + + QTouchEvent(QEvent::Type eventType, + QTouchEvent::DeviceType deviceType = TouchScreen, + Qt::KeyboardModifiers modifiers = Qt::NoModifier, + Qt::TouchPointStates touchPointStates = 0, + const QList<QTouchEvent::TouchPoint> &touchPoints = QList<QTouchEvent::TouchPoint>()); + ~QTouchEvent(); + + inline QWidget *widget() const { return _widget; } + inline QTouchEvent::DeviceType deviceType() const { return _deviceType; } + inline Qt::TouchPointStates touchPointStates() const { return _touchPointStates; } + inline const QList<QTouchEvent::TouchPoint> &touchPoints() const { return _touchPoints; } + + // internal + inline void setWidget(QWidget *widget) { _widget = widget; } + inline void setDeviceType(DeviceType deviceType) { _deviceType = deviceType; } + inline void setTouchPointStates(Qt::TouchPointStates touchPointStates) { _touchPointStates = touchPointStates; } + inline void setTouchPoints(const QList<QTouchEvent::TouchPoint> &touchPoints) { _touchPoints = touchPoints; } + +protected: + QWidget *_widget; + QTouchEvent::DeviceType _deviceType; + Qt::TouchPointStates _touchPointStates; + QList<QTouchEvent::TouchPoint> _touchPoints; + + friend class QApplicationPrivate; +}; + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/gui/kernel/qevent_p.h b/src/gui/kernel/qevent_p.h index 9cc1e81..67441ea 100644 --- a/src/gui/kernel/qevent_p.h +++ b/src/gui/kernel/qevent_p.h @@ -43,6 +43,7 @@ #define QEVENT_P_H #include <QtCore/qglobal.h> +#include <QtGui/qevent.h> QT_BEGIN_NAMESPACE @@ -89,6 +90,51 @@ protected: friend class QMouseEvent; }; +class QTouchEventTouchPointPrivate +{ +public: + inline QTouchEventTouchPointPrivate(int id) + : ref(1), + id(id), + state(Qt::TouchPointReleased), + pressure(qreal(-1.)) + { } + + inline QTouchEventTouchPointPrivate *detach() + { + QTouchEventTouchPointPrivate *d = new QTouchEventTouchPointPrivate(*this); + d->ref = 1; + if (!this->ref.deref()) + delete this; + return d; + } + + QAtomicInt ref; + int id; + Qt::TouchPointStates state; + QRectF rect, sceneRect, screenRect; + QPointF normalizedPos, + startPos, startScenePos, startScreenPos, startNormalizedPos, + lastPos, lastScenePos, lastScreenPos, lastNormalizedPos; + qreal pressure; +}; + +class QWinGestureEvent : public QEvent +{ +public: + enum Type { + None, + GestureEnd, + Pan, + Pinch + }; + + QWinGestureEvent() : QEvent(QEvent::WinGesture), gestureType(None), sequenceId(0) { } + Type gestureType; + QPoint position; + ulong sequenceId; +}; + QT_END_NAMESPACE #endif // QEVENT_P_H diff --git a/src/gui/kernel/qgesture.cpp b/src/gui/kernel/qgesture.cpp new file mode 100644 index 0000000..d53b419 --- /dev/null +++ b/src/gui/kernel/qgesture.cpp @@ -0,0 +1,296 @@ +/**************************************************************************** +** +** 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 "qgesture.h" +#include <private/qgesture_p.h> +#include "qgraphicsitem.h" + +QT_BEGIN_NAMESPACE + + +class QEventFilterProxyGraphicsItem : public QGraphicsItem +{ +public: + QEventFilterProxyGraphicsItem(QGesture *g) + : gesture(g) + { + } + bool sceneEventFilter(QGraphicsItem *, QEvent *event) + { + return gesture ? gesture->filterEvent(event) : false; + } + QRectF boundingRect() const { return QRectF(); } + void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*) { } + +private: + QGesture *gesture; +}; + +/*! + \class QGesture + \since 4.6 + + \brief The QGesture class is the base class for implementing custom + gestures. + + This class represents both an object that recognizes a gesture out of a set + of input events (a gesture recognizer), and a gesture object itself that + can be used to get extended information about the triggered gesture. + + The class has a list of properties that can be queried by the user to get + some gesture-specific parameters (for example, an offset of a Pan gesture). + + Usually gesture recognizer implements a state machine, storing its state + internally in the recognizer object. The recognizer receives input events + through the \l{QGesture::}{filterEvent()} virtual function and decides + whether the event should change the state of the recognizer by emitting an + appropriate signal. + + Input events should be either fed to the recognizer one by one with a + filterEvent() function, or the gesture recognizer should be attached to an + object it filters events for by specifying it as a parent object. The + QGesture object installs itself as an event filter to the parent object + automatically, the unsetObject() function should be used to remove an event + filter from the parent object. To make a + gesture that operates on a QGraphicsItem, both the appropriate QGraphicsView + should be passed as a parent object and setGraphicsItem() functions should + be used to attach a gesture to a graphics item. + + This is a base class, to create a custom gesture type, you should subclass + it and implement its pure virtual functions. + + \sa QPanGesture, QTapAndHoldGesture +*/ + +/*! \fn bool QGesture::filterEvent(QEvent *event) + + Parses input \a event and emits a signal when detects a gesture. + + In your reimplementation of this function, if you want to filter the \a + event out, i.e. stop it being handled further, return true; otherwise + return false; + + This is a pure virtual function that needs to be implemented in subclasses. +*/ + +/*! \fn void QGesture::started() + + The signal is emitted when the gesture is started. Extended information + about the gesture is contained in the signal sender object. + + In addition to started(), a triggered() signal should also be emitted. +*/ + +/*! \fn void QGesture::triggered() + + The signal is emitted when the gesture is detected. Extended information + about the gesture is contained in the signal sender object. +*/ + +/*! \fn void QGesture::finished() + + The signal is emitted when the gesture is finished. Extended information + about the gesture is contained in the signal sender object. +*/ + +/*! \fn void QGesture::cancelled() + + The signal is emitted when the gesture is cancelled, for example the reset() + function is called while the gesture was in the process of emitting a + triggered() signal. Extended information about the gesture is contained in + the sender object. +*/ + + +/*! + Creates a new gesture handler object and marks it as a child of \a parent. + + The \a parent object is also the default event source for the gesture, + meaning that the gesture installs itself as an event filter for the \a + parent. + + \sa setGraphicsItem() +*/ +QGesture::QGesture(QObject *parent) + : QObject(*new QGesturePrivate, parent) +{ + if (parent) + installEventFilter(parent); +} + +/*! \internal + */ +QGesture::QGesture(QGesturePrivate &dd, QObject *parent) + : QObject(dd, parent) +{ + if (parent) + installEventFilter(parent); +} + +/*! + Destroys the gesture object. +*/ +QGesture::~QGesture() +{ +} + +/*! \internal + */ +bool QGesture::eventFilter(QObject *receiver, QEvent *event) +{ + Q_D(QGesture); + if (d->graphicsItem && receiver == parent()) + return false; + return filterEvent(event); +} + +/*! + \property QGesture::state + + \brief The current state of the gesture. +*/ + +/*! + Returns the gesture recognition state. + */ +Qt::GestureState QGesture::state() const +{ + return d_func()->state; +} + +/*! + 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; +} + +/*! + \property QGesture::pos + + \brief The current position of the gesture (if relevant). +*/ +QPoint QGesture::pos() const +{ + return d_func()->pos; +} + +void QGesture::setPos(const QPoint &point) +{ + d_func()->pos = point; +} + +/*! + Sets the \a graphicsItem the gesture is filtering events for. + + The gesture will install an event filter to the \a graphicsItem and + redirect them to the filterEvent() function. + + \sa graphicsItem() +*/ +void QGesture::setGraphicsItem(QGraphicsItem *graphicsItem) +{ + Q_D(QGesture); + if (d->graphicsItem && d->eventFilterProxyGraphicsItem) + d->graphicsItem->removeSceneEventFilter(d->eventFilterProxyGraphicsItem); + d->graphicsItem = graphicsItem; + if (!d->eventFilterProxyGraphicsItem) + d->eventFilterProxyGraphicsItem = new QEventFilterProxyGraphicsItem(this); + if (graphicsItem) + graphicsItem->installSceneEventFilter(d->eventFilterProxyGraphicsItem); +} + +/*! + Returns the graphics item the gesture is filtering events for. + + \sa setGraphicsItem() +*/ +QGraphicsItem* QGesture::graphicsItem() const +{ + return d_func()->graphicsItem; +} + +/*! \fn void QGesture::reset() + + 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. +*/ +void QGesture::reset() +{ + if (state() != Qt::NoGesture) + emit cancelled(); + setState(Qt::NoGesture); +} + +QT_END_NAMESPACE diff --git a/src/gui/kernel/qgesture.h b/src/gui/kernel/qgesture.h new file mode 100644 index 0000000..cc46916 --- /dev/null +++ b/src/gui/kernel/qgesture.h @@ -0,0 +1,110 @@ +/**************************************************************************** +** +** 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 QGESTURE_H +#define QGESTURE_H + +#include "qobject.h" +#include "qlist.h" +#include "qdatetime.h" +#include "qpoint.h" +#include "qrect.h" +#include "qmetatype.h" + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class QGraphicsItem; +class QGesturePrivate; +class Q_GUI_EXPORT QGesture : public QObject +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QGesture) + + 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(); + + virtual bool filterEvent(QEvent *event) = 0; + + void setGraphicsItem(QGraphicsItem *); + QGraphicsItem *graphicsItem() const; + + 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*); + +Q_SIGNALS: + void started(); + void triggered(); + void finished(); + void cancelled(); + +private: + friend class QWidget; +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QGESTURE_H diff --git a/src/gui/kernel/qgesture_p.h b/src/gui/kernel/qgesture_p.h new file mode 100644 index 0000000..99f572f --- /dev/null +++ b/src/gui/kernel/qgesture_p.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** 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 QGESTURE_P_H +#define QGESTURE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qrect.h" +#include "qpoint.h" +#include "qdatetime.h" +#include "qgesture.h" +#include "private/qobject_p.h" + +QT_BEGIN_NAMESPACE + +class QObject; +class QGraphicsItem; +class QGesturePrivate : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QGesture) + +public: + QGesturePrivate() + : graphicsItem(0), eventFilterProxyGraphicsItem(0), state(Qt::NoGesture) + { + } + + 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 + +#endif // QGESTURE_P_H diff --git a/src/gui/kernel/qguifunctions_wince.cpp b/src/gui/kernel/qguifunctions_wince.cpp index c986117..011c726 100644 --- a/src/gui/kernel/qguifunctions_wince.cpp +++ b/src/gui/kernel/qguifunctions_wince.cpp @@ -215,13 +215,7 @@ int qt_wince_GetDIBits(HDC /*hdc*/ , HBITMAP hSourceBitmap, uint, uint, LPVOID l return ret; } -bool qt_wince_TextOutW(HDC hdc, int x, int y, LPWSTR lpString, UINT c) -{ - return ExtTextOutW(hdc, x, y, 0, NULL, lpString, c, NULL); -} - - -HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCTSTR, LPCTSTR file, LPCTSTR params, LPCTSTR dir, int showCmd) +HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd) { SHELLEXECUTEINFO info; info.hwnd = hwnd; @@ -253,17 +247,11 @@ COLORREF qt_wince_PALETTEINDEX( WORD /*wPaletteIndex*/) return 0; } -BOOL qt_wince_TextOut( HDC hdc, int nXStart, int nYStart, LPCTSTR lpString, int cbString ) -{ - return ExtTextOut( hdc, nXStart, nYStart - 16, 0, NULL, lpString, cbString, NULL ); -} - // Internal Qt ----------------------------------------------------- bool qt_wince_is_platform(const QString &platformString) { - TCHAR tszPlatform[64]; - if (SystemParametersInfo(SPI_GETPLATFORMTYPE, - sizeof(tszPlatform)/sizeof(*tszPlatform),tszPlatform,0)) - if (0 == _tcsicmp(reinterpret_cast<const wchar_t *> (platformString.utf16()), tszPlatform)) + wchar_t tszPlatform[64]; + if (SystemParametersInfo(SPI_GETPLATFORMTYPE, sizeof(tszPlatform) / sizeof(wchar_t), tszPlatform, 0)) + if (0 == _tcsicmp(reinterpret_cast<const wchar_t *> (platformString.utf16()), tszPlatform)) return true; return false; } @@ -316,8 +304,8 @@ void qt_wince_maximize(QWidget *widget) void qt_wince_minimize(HWND hwnd) { - uint exstyle = GetWindowLongW(hwnd, GWL_EXSTYLE); - uint style = GetWindowLongW(hwnd, GWL_STYLE); + uint exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); + uint style = GetWindowLong(hwnd, GWL_STYLE); RECT rect; RECT crect = {0,0,0,0}; GetWindowRect(hwnd, &rect); diff --git a/src/gui/kernel/qguifunctions_wince.h b/src/gui/kernel/qguifunctions_wince.h index bcf2004..234c8c6 100644 --- a/src/gui/kernel/qguifunctions_wince.h +++ b/src/gui/kernel/qguifunctions_wince.h @@ -73,10 +73,6 @@ int qt_wince_GetDIBits(HDC, HBITMAP, uint, uint, void*, LPBITMAPINFO, uint); // QWidget #define SW_SHOWMINIMIZED SW_MINIMIZE -// QPaintEngine -bool qt_wince_TextOutW(HDC, int, int, LPWSTR, UINT); -#define TextOutW(a,b,c,d,e) qt_wince_TextOutW(a,b,c,d,e) - // QRegion #define ALTERNATE 0 #define WINDING 1 @@ -128,7 +124,7 @@ typedef struct tagTTPOLYCURVE #define TT_PRIM_CSPLINE 3 #define ANSI_VAR_FONT 12 -HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCTSTR operation, LPCTSTR file, LPCTSTR params, LPCTSTR dir, int showCmd); +HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd); #define ShellExecute(a,b,c,d,e,f) qt_wince_ShellExecute(a,b,c,d,e,f) @@ -150,8 +146,6 @@ HWND qt_wince_SetClipboardViewer( // Graphics --------------------------------------------------------- COLORREF qt_wince_PALETTEINDEX( WORD wPaletteIndex ); #define PALETTEINDEX(a) qt_wince_PALETTEINDEX(a) -BOOL qt_wince_TextOut( HDC hdc, int nXStart, int nYStart, LPCTSTR lpString, int cbString ); -#define TextOut(a,b,c,d,e) qt_wince_TextOut(a,b,c,d,e) #endif // Q_OS_WINCE #endif // QGUIFUNCTIONS_WCE_H diff --git a/src/gui/kernel/qkeymapper_win.cpp b/src/gui/kernel/qkeymapper_win.cpp index e40dfa0..3d53f31 100644 --- a/src/gui/kernel/qkeymapper_win.cpp +++ b/src/gui/kernel/qkeymapper_win.cpp @@ -57,9 +57,7 @@ QT_BEGIN_NAMESPACE // Implemented elsewhere extern "C" LRESULT CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM); -Q_CORE_EXPORT bool winPostMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -Q_CORE_EXPORT bool winPeekMessage(MSG* msg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, - UINT wRemoveMsg); + extern Q_CORE_EXPORT QLocale qt_localeFromLCID(LCID id); #ifndef LANG_PASHTO #define LANG_PASHTO 0x63 @@ -467,12 +465,7 @@ static inline int toKeyOrUnicode(int vk, int scancode, unsigned char *kbdBuffer, Q_ASSERT(vk > 0 && vk < 256); int code = 0; QChar unicodeBuffer[5]; - int res = 0; - if (QSysInfo::WindowsVersion < QSysInfo::WV_NT) - res = ToAscii(vk, scancode, kbdBuffer, reinterpret_cast<LPWORD>(unicodeBuffer), 0); - else - res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0); - + int res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0); if (res) code = unicodeBuffer[0].toUpper().unicode(); @@ -504,38 +497,6 @@ static inline int asciiToKeycode(char a, int state) return a & 0xff; } -static int inputcharset = CP_ACP; -static inline QChar wmchar_to_unicode(DWORD c) -{ - // qt_winMB2QString is the generalization of this function. - QT_WA({ - return QChar((ushort)c); - } , { - char mb[2]; - mb[0] = c & 0xff; - mb[1] = 0; - WCHAR wc[1]; - MultiByteToWideChar(inputcharset, MB_PRECOMPOSED, mb, -1, wc, 1); - return QChar(wc[0]); - }); -} - -static inline QChar imechar_to_unicode(DWORD c) -{ - // qt_winMB2QString is the generalization of this function. - QT_WA({ - return QChar((ushort)c); - } , { - char mb[3]; - mb[0] = (c >> 8) & 0xff; - mb[1] = c & 0xff; - mb[2] = 0; - WCHAR wc[1]; - MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, mb, -1, wc, 1); - return QChar(wc[0]); - }); -} - static inline bool isModifierKey(int code) { return (code >= Qt::Key_Shift) && (code <= Qt::Key_ScrollLock); @@ -635,43 +596,15 @@ void QKeyMapperPrivate::clearMappings() /* MAKELCID()'s first argument is a WORD, and GetKeyboardLayout() * returns a DWORD. */ -// LCID newLCID = MAKELCID(DWORD(GetKeyboardLayout(0)), SORT_DEFAULT); + + LCID newLCID = MAKELCID((DWORD)GetKeyboardLayout(0), SORT_DEFAULT); // keyboardInputLocale = qt_localeFromLCID(newLCID); - LCID newLCID = MAKELCID( - reinterpret_cast<long>(GetKeyboardLayout(0)), - SORT_DEFAULT - ); - keyboardInputLocale = qt_localeFromLCID(newLCID); + bool bidi = false; -#ifdef UNICODE - if (QSysInfo::WindowsVersion >= QSysInfo::WV_2000) { - WCHAR wchLCIDFontSig[16]; - if (GetLocaleInfoW(newLCID, - LOCALE_FONTSIGNATURE, - &wchLCIDFontSig[0], - (sizeof(wchLCIDFontSig)/sizeof(WCHAR))) - && (wchLCIDFontSig[7] & (WCHAR)0x0800)) + wchar_t LCIDFontSig[16]; + if (GetLocaleInfo(newLCID, LOCALE_FONTSIGNATURE, LCIDFontSig, sizeof(LCIDFontSig) / sizeof(wchar_t)) + && (LCIDFontSig[7] & (wchar_t)0x0800)) bidi = true; - } else -#endif //UNICODE - { - if (newLCID == 0x0859 || //Sindhi (Arabic script) - newLCID == 0x0460) //Kashmiri (Arabic script) - bidi = true;; - - switch (PRIMARYLANGID(newLCID)) - { - case LANG_ARABIC: - case LANG_HEBREW: - case LANG_URDU: - case LANG_FARSI: - case LANG_PASHTO: - //case LANG_UIGHUR: - case LANG_SYRIAC: - case LANG_DIVEHI: - bidi = true; - } - } keyboardInputDirection = bidi ? Qt::RightToLeft : Qt::LeftToRight; } @@ -760,7 +693,7 @@ void QKeyMapperPrivate::updatePossibleKeyCodes(unsigned char *kbdBuffer, quint32 keyLayout[vk_key]->qtKey[8] = fallbackKey; // If this vk_key a Dead Key - if (MapVirtualKey(vk_key, 2) & 0x80008000) { // (High-order dead key on Win 95 is 0x8000) + if (MapVirtualKey(vk_key, 2) & 0x80000000) { // Push a Space, then the original key through the low-level ToAscii functions. // We do this because these functions (ToAscii / ToUnicode) will alter the internal state of // the keyboard driver By doing the following, we set the keyboard driver state back to what @@ -837,13 +770,13 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool bool isNumpad = (msg.wParam >= VK_NUMPAD0 && msg.wParam <= VK_NUMPAD9); quint32 nModifiers = 0; - if (QSysInfo::WindowsVersion < QSysInfo::WV_NT || QSysInfo::WindowsVersion & QSysInfo::WV_CE_based) { +#if defined(QT_OS_WINCE) nModifiers |= (GetKeyState(VK_SHIFT ) < 0 ? ShiftAny : 0); nModifiers |= (GetKeyState(VK_CONTROL) < 0 ? ControlAny : 0); nModifiers |= (GetKeyState(VK_MENU ) < 0 ? AltAny : 0); nModifiers |= (GetKeyState(VK_LWIN ) < 0 ? MetaLeft : 0); nModifiers |= (GetKeyState(VK_RWIN ) < 0 ? MetaRight : 0); - } else { +#else // Map native modifiers to some bit representation nModifiers |= (GetKeyState(VK_LSHIFT ) & 0x80 ? ShiftLeft : 0); nModifiers |= (GetKeyState(VK_RSHIFT ) & 0x80 ? ShiftRight : 0); @@ -857,7 +790,8 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool nModifiers |= (GetKeyState(VK_CAPITAL ) & 0x01 ? CapsLock : 0); nModifiers |= (GetKeyState(VK_NUMLOCK ) & 0x01 ? NumLock : 0); nModifiers |= (GetKeyState(VK_SCROLL ) & 0x01 ? ScrollLock : 0); - } +#endif // QT_OS_WINCE + if (msg.lParam & ExtendedKey) nModifiers |= msg.lParam & ExtendedKey; @@ -870,12 +804,12 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool // Now we know enough to either have MapVirtualKey or our own keymap tell us if it's a deadkey bool isDeadKey = isADeadKey(msg.wParam, state) - || MapVirtualKey(msg.wParam, 2) & 0x80008000; // High-order on 95 is 0x8000 + || MapVirtualKey(msg.wParam, 2) & 0x80000000; // A multi-character key not found by our look-ahead if (msgType == WM_CHAR) { QString s; - QChar ch = wmchar_to_unicode(msg.wParam); + QChar ch = QChar((ushort)msg.wParam); if (!ch.isNull()) s += ch; @@ -886,7 +820,7 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool // Input method characters not found by our look-ahead else if (msgType == WM_IME_CHAR) { QString s; - QChar ch = imechar_to_unicode(msg.wParam); + QChar ch = QChar((ushort)msg.wParam); if (!ch.isNull()) s += ch; @@ -1050,11 +984,9 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool : msgType == WM_IME_KEYDOWN ? WM_IME_CHAR : WM_SYSCHAR); QChar uch; - if (winPeekMessage(&wm_char, 0, charType, charType, PM_REMOVE)) { + if (PeekMessage(&wm_char, 0, charType, charType, PM_REMOVE)) { // Found a ?_CHAR - uch = charType == WM_IME_CHAR - ? imechar_to_unicode(wm_char.wParam) - : wmchar_to_unicode(wm_char.wParam); + uch = QChar((ushort)wm_char.wParam); if (msgType == WM_SYSKEYDOWN && uch.isLetter() && (msg.lParam & KF_ALTDOWN)) uch = uch.toLower(); // (See doc of WM_SYSCHAR) Alt-letter if (!code && !uch.row()) @@ -1067,7 +999,7 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool // to find the correct key using the current message parameters & keyboard state. if (uch.isNull() && msgType == WM_IME_KEYDOWN) { BYTE keyState[256]; - WCHAR newKey[3] = {0}; + wchar_t newKey[3] = {0}; GetKeyboardState(keyState); int val = ToUnicode(vk_key, scancode, keyState, newKey, 2, 0); if (val == 1) { @@ -1085,18 +1017,10 @@ bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool uch = QChar(QLatin1Char(0x7f)); // Windows doesn't know this one. } else { if (msgType != WM_SYSKEYDOWN || !code) { - UINT map; - QT_WA({ - map = MapVirtualKey(msg.wParam, 2); - } , { - map = MapVirtualKeyA(msg.wParam, 2); - // High-order bit is 0x8000 on '95 - if (map & 0x8000) - map = (map^0x8000)|0x80000000; - }); + UINT map = MapVirtualKey(msg.wParam, 2); // If the high bit of the return value is set, it's a deadkey if (!(map & 0x80000000)) - uch = wmchar_to_unicode((DWORD)map); + uch = QChar((ushort)map); } } if (!code && !uch.row()) @@ -1237,6 +1161,8 @@ bool QKeyMapper::sendKeyEvent(QWidget *widget, bool grab, if (QApplicationPrivate::instance()->qt_tryAccelEvent(widget, &a)) return true; } +#else + Q_UNUSED(grab); #endif if (!widget->isEnabled()) return false; diff --git a/src/gui/kernel/qlayout.cpp b/src/gui/kernel/qlayout.cpp index 3a3feb2..e750088 100644 --- a/src/gui/kernel/qlayout.cpp +++ b/src/gui/kernel/qlayout.cpp @@ -61,7 +61,10 @@ static int menuBarHeightForWidth(QWidget *menubar, int w) int result = menubar->heightForWidth(qMax(w, menubar->minimumWidth())); if (result != -1) return result; - result = menubar->sizeHint().height(); + result = menubar->sizeHint() + .expandedTo(menubar->minimumSize()) + .expandedTo(menubar->minimumSizeHint()) + .boundedTo(menubar->maximumSize()).height(); if (result != -1) return result; } diff --git a/src/gui/kernel/qmime_win.cpp b/src/gui/kernel/qmime_win.cpp index bc15638..c7559d8 100644 --- a/src/gui/kernel/qmime_win.cpp +++ b/src/gui/kernel/qmime_win.cpp @@ -281,11 +281,7 @@ QWindowsMime::~QWindowsMime() */ int QWindowsMime::registerMimeType(const QString &mime) { -#ifdef Q_OS_WINCE int f = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (mime.utf16())); -#else - int f = RegisterClipboardFormatA(mime.toLocal8Bit()); -#endif if (!f) qErrnoWarning("QWindowsMime::registerMimeType: Failed to register clipboard format"); @@ -401,9 +397,9 @@ QStringList QWindowsMime::allMimesForFormats(IDataObject *pDataObj) while (S_OK == fmtenum->Next(1, &fmtetc, 0)) { #if defined(QMIME_DEBUG) && !defined(Q_OS_WINCE) qDebug("QWindowsMime::allMimesForFormats()"); - char buf[256] = {0}; - GetClipboardFormatNameA(fmtetc.cfFormat, buf, 255); - qDebug("CF = %d : %s", fmtetc.cfFormat, buf); + wchar_t buf[256] = {0}; + GetClipboardFormatName(fmtetc.cfFormat, buf, 255); + qDebug("CF = %d : %s", fmtetc.cfFormat, QString::fromWCharArray(buf)); #endif for (int i=mimes.size()-1; i>=0; --i) { QString format = mimes.at(i)->mimeForFormat(fmtetc); @@ -504,7 +500,7 @@ bool QWindowsMimeText::convertFromMime(const FORMATETC &formatetc, const QMimeDa ++u; } res.truncate(ri); - const int byteLength = res.length()*2; + const int byteLength = res.length() * sizeof(ushort); QByteArray r(byteLength + 2, '\0'); memcpy(r.data(), res.unicode(), byteLength); r[byteLength] = 0; @@ -549,7 +545,7 @@ QVariant QWindowsMimeText::convertToMime(const QString &mime, LPDATAOBJECT pData QString str; QByteArray data = getData(CF_UNICODETEXT, pDataObj); if (!data.isEmpty()) { - str = QString::fromUtf16((const unsigned short *)data.data()); + str = QString::fromWCharArray((const wchar_t *)data.data()); str.replace(QLatin1String("\r\n"), QLatin1String("\n")); } else { data = getData(CF_TEXT, pDataObj); @@ -620,11 +616,7 @@ bool QWindowsMimeURI::convertFromMime(const FORMATETC &formatetc, const QMimeDat for (int i=0; i<urls.size(); i++) { QString fn = QDir::toNativeSeparators(urls.at(i).toLocalFile()); if (!fn.isEmpty()) { - QT_WA({ - size += sizeof(TCHAR)*(fn.length()+1); - } , { - size += fn.toLocal8Bit().length()+1; - }); + size += sizeof(ushort) * (fn.length() + 1); fileNames.append(fn); } } @@ -636,36 +628,22 @@ bool QWindowsMimeURI::convertFromMime(const FORMATETC &formatetc, const QMimeDat d->fNC = true; char* files = ((char*)d) + d->pFiles; - QT_WA({ - d->fWide = true; - TCHAR* f = (TCHAR*)files; - for (int i=0; i<fileNames.size(); i++) { - int l = fileNames.at(i).length(); - memcpy(f, fileNames.at(i).utf16(), l*sizeof(TCHAR)); - f += l; - *f++ = 0; - } - *f = 0; - } , { - d->fWide = false; - char* f = files; - for (int i=0; i<fileNames.size(); i++) { - QByteArray c = fileNames.at(i).toLocal8Bit(); - if (!c.isEmpty()) { - int l = c.length(); - memcpy(f, c.constData(), l); - f += l; - *f++ = 0; - } - } - *f = 0; - }); + d->fWide = true; + wchar_t* f = (wchar_t*)files; + for (int i=0; i<fileNames.size(); i++) { + int l = fileNames.at(i).length(); + memcpy(f, fileNames.at(i).utf16(), l * sizeof(ushort)); + f += l; + *f++ = 0; + } + *f = 0; + return setData(result, pmedium); } else if (getCf(formatetc) == CF_INETURL_W) { QList<QUrl> urls = mimeData->urls(); QByteArray result; QString url = urls.at(0).toString(); - result = QByteArray((const char *)url.utf16(), url.length() * 2); + result = QByteArray((const char *)url.utf16(), url.length() * sizeof(ushort)); result.append('\0'); result.append('\0'); return setData(result, pmedium); @@ -720,15 +698,15 @@ QVariant QWindowsMimeURI::convertToMime(const QString &mimeType, LPDATAOBJECT pD LPDROPFILES hdrop = (LPDROPFILES)data.data(); if (hdrop->fWide) { - const ushort* filesw = (const ushort*)(data.data() + hdrop->pFiles); - int i=0; + const wchar_t* filesw = (const wchar_t *)(data.data() + hdrop->pFiles); + int i = 0; while (filesw[i]) { - QString fileurl = QString::fromUtf16(filesw+i); + QString fileurl = QString::fromWCharArray(filesw + i); urls += QUrl::fromLocalFile(fileurl); i += fileurl.length()+1; } } else { - const char* files = (const char*)data.data() + hdrop->pFiles; + const char* files = (const char *)data.data() + hdrop->pFiles; int i=0; while (files[i]) { urls += QUrl::fromLocalFile(QString::fromLocal8Bit(files+i)); @@ -744,7 +722,7 @@ QVariant QWindowsMimeURI::convertToMime(const QString &mimeType, LPDATAOBJECT pD QByteArray data = getData(CF_INETURL_W, pDataObj); if (data.isEmpty()) return QVariant(); - return QUrl(QString::fromUtf16((const unsigned short *)data.constData())); + return QUrl(QString::fromWCharArray((const wchar_t *)data.constData())); } else if (canGetData(CF_INETURL, pDataObj)) { QByteArray data = getData(CF_INETURL, pDataObj); if (data.isEmpty()) @@ -913,11 +891,7 @@ private: QWindowsMimeImage::QWindowsMimeImage() { -#ifdef Q_OS_WINCE - CF_PNG = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (QString::fromLatin1("PNG").utf16())); -#else - CF_PNG = RegisterClipboardFormatA("PNG"); -#endif + CF_PNG = RegisterClipboardFormat(L"PNG"); } QVector<FORMATETC> QWindowsMimeImage::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const @@ -1114,7 +1088,7 @@ bool QBuiltInMimes::convertFromMime(const FORMATETC &formatetc, const QMimeData ++u; } res.truncate(ri); - const int byteLength = res.length()*2; + const int byteLength = res.length() * sizeof(ushort); QByteArray r(byteLength + 2, '\0'); memcpy(r.data(), res.unicode(), byteLength); r[byteLength] = 0; @@ -1154,8 +1128,8 @@ QVariant QBuiltInMimes::convertToMime(const QString &mimeType, IDataObject *pDat qDebug("QBuiltInMimes::convertToMime()"); #endif if (mimeType == QLatin1String("text/html") && preferredType == QVariant::String) { - // text/html is in wide chars on windows (compatible with mozillia) - val = QString::fromUtf16((const unsigned short *)data.data()); + // text/html is in wide chars on windows (compatible with Mozilla) + val = QString::fromWCharArray((const wchar_t *)data.data()); } else { val = data; // it should be enough to return the data and let QMimeData do the rest. } @@ -1280,11 +1254,7 @@ bool QLastResortMimes::canConvertToMime(const QString &mimeType, IDataObject *pD { if (isCustomMimeType(mimeType)) { QString clipFormat = customMimeType(mimeType); -#ifdef Q_OS_WINCE int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16())); -#else - int cf = RegisterClipboardFormatA(clipFormat.toLocal8Bit()); -#endif return canGetData(cf, pDataObj); } else if (formats.keys(mimeType).isEmpty()) { // if it is not in there then register it an see if we can get it @@ -1304,11 +1274,7 @@ QVariant QLastResortMimes::convertToMime(const QString &mimeType, IDataObject *p QByteArray data; if (isCustomMimeType(mimeType)) { QString clipFormat = customMimeType(mimeType); -#ifdef Q_OS_WINCE int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16())); -#else - int cf = RegisterClipboardFormatA(clipFormat.toLocal8Bit()); -#endif data = getData(cf, pDataObj); } else if (formats.keys(mimeType).isEmpty()) { int cf = QWindowsMime::registerMimeType(mimeType); @@ -1325,46 +1291,38 @@ QVariant QLastResortMimes::convertToMime(const QString &mimeType, IDataObject *p QString QLastResortMimes::mimeForFormat(const FORMATETC &formatetc) const { QString format = formats.value(getCf(formatetc)); - if (format.isEmpty()) { - QByteArray ba; - QString clipFormat; - int len; - QT_WA({ - ba.resize(256*2); - len = GetClipboardFormatNameW(getCf(formatetc), (TCHAR*)ba.data(), 255); - if (len) - clipFormat = QString::fromUtf16((ushort *)ba.data(), len); - } , { - ba.resize(256); - len = GetClipboardFormatNameA(getCf(formatetc), ba.data(), 255); - if (len) - clipFormat = QString::fromLocal8Bit(ba.data(), len); - }); - if (len) { + if (!format.isEmpty()) + return format; + + wchar_t buffer[256]; + int len = GetClipboardFormatName(getCf(formatetc), buffer, 256); + + if (len) { + QString clipFormat = QString::fromWCharArray(buffer, len); #ifndef QT_NO_DRAGANDDROP - if (QInternalMimeData::canReadData(clipFormat)) - format = clipFormat; - else if((formatetc.cfFormat >= 0xC000)){ - //create the mime as custom. not registered. - if (!excludeList.contains(clipFormat, Qt::CaseInsensitive)) { - //check if this is a mime type - bool ianaType = false; - int sz = ianaTypes.size(); - for (int i = 0; i < sz; i++) { - if (clipFormat.startsWith(ianaTypes[i], Qt::CaseInsensitive)) { - ianaType = true; - break; - } + if (QInternalMimeData::canReadData(clipFormat)) + format = clipFormat; + else if((formatetc.cfFormat >= 0xC000)){ + //create the mime as custom. not registered. + if (!excludeList.contains(clipFormat, Qt::CaseInsensitive)) { + //check if this is a mime type + bool ianaType = false; + int sz = ianaTypes.size(); + for (int i = 0; i < sz; i++) { + if (clipFormat.startsWith(ianaTypes[i], Qt::CaseInsensitive)) { + ianaType = true; + break; } - if (!ianaType) - format = QLatin1String(x_qt_windows_mime) + clipFormat + QLatin1Char('\"'); - else - format = clipFormat; } + if (!ianaType) + format = QLatin1String(x_qt_windows_mime) + clipFormat + QLatin1Char('\"'); + else + format = clipFormat; } -#endif //QT_NO_DRAGANDDROP } +#endif //QT_NO_DRAGANDDROP } + return format; } diff --git a/src/gui/kernel/qmultitouch_mac.mm b/src/gui/kernel/qmultitouch_mac.mm new file mode 100644 index 0000000..3fe85a9 --- /dev/null +++ b/src/gui/kernel/qmultitouch_mac.mm @@ -0,0 +1,219 @@ +/**************************************************************************** +** +** 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 <private/qmultitouch_mac_p.h> +#include <qcursor.h> + +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + +QT_BEGIN_NAMESPACE + +#ifdef QT_MAC_USE_COCOA + +QHash<int, QCocoaTouch*> QCocoaTouch::_currentTouches; +QPointF QCocoaTouch::_screenReferencePos; +QPointF QCocoaTouch::_trackpadReferencePos; +int QCocoaTouch::_idAssignmentCount = 0; +int QCocoaTouch::_touchCount = 0; +bool QCocoaTouch::_updateInternalStateOnly = true; + +QCocoaTouch::QCocoaTouch(NSTouch *nstouch) +{ + if (_currentTouches.size() == 0) + _idAssignmentCount = 0; + + _touchPoint.setId(_idAssignmentCount++); + _touchPoint.setPressure(1.0); + _identity = int([nstouch identity]); + _currentTouches.insert(_identity, this); + updateTouchData(nstouch, NSTouchPhaseBegan); +} + +QCocoaTouch::~QCocoaTouch() +{ + _currentTouches.remove(_identity); +} + +void QCocoaTouch::updateTouchData(NSTouch *nstouch, NSTouchPhase phase) +{ + if (_touchCount == 1) + _touchPoint.setState(toTouchPointState(phase) | Qt::TouchPointPrimary); + else + _touchPoint.setState(toTouchPointState(phase)); + + // From the normalized position on the trackpad, calculate + // where on screen the touchpoint should be according to the + // reference position: + NSPoint npos = [nstouch normalizedPosition]; + QPointF qnpos = QPointF(npos.x, 1 - npos.y); + _touchPoint.setNormalizedPos(qnpos); + + if (_touchPoint.id() == 0 && phase == NSTouchPhaseBegan) { + _trackpadReferencePos = qnpos; + _screenReferencePos = QCursor::pos(); + } + + NSSize dsize = [nstouch deviceSize]; + float ppiX = (qnpos.x() - _trackpadReferencePos.x()) * dsize.width; + float ppiY = (qnpos.y() - _trackpadReferencePos.y()) * dsize.height; + QPointF relativePos = _trackpadReferencePos - QPointF(ppiX, ppiY); + _touchPoint.setScreenPos(_screenReferencePos - relativePos); +} + +QCocoaTouch *QCocoaTouch::findQCocoaTouch(NSTouch *nstouch) +{ + int identity = int([nstouch identity]); + if (_currentTouches.contains(identity)) + return _currentTouches.value(identity); + return 0; +} + +Qt::TouchPointState QCocoaTouch::toTouchPointState(NSTouchPhase nsState) +{ + Qt::TouchPointState qtState = Qt::TouchPointReleased; + switch (nsState) { + case NSTouchPhaseBegan: + qtState = Qt::TouchPointPressed; + break; + case NSTouchPhaseMoved: + qtState = Qt::TouchPointMoved; + break; + case NSTouchPhaseStationary: + qtState = Qt::TouchPointStationary; + break; + case NSTouchPhaseEnded: + case NSTouchPhaseCancelled: + qtState = Qt::TouchPointReleased; + break; + default: + break; + } + return qtState; +} + +QList<QTouchEvent::TouchPoint> +QCocoaTouch::getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch) +{ + QMap<int, QTouchEvent::TouchPoint> touchPoints; + NSSet *ended = [event touchesMatchingPhase:NSTouchPhaseEnded | NSTouchPhaseCancelled inView:nil]; + NSSet *active = [event + touchesMatchingPhase:NSTouchPhaseBegan | NSTouchPhaseMoved | NSTouchPhaseStationary + inView:nil]; + _touchCount = [active count]; + + // First: remove touches that were ended by the user. If we are + // currently not accepting single touches, a corresponding 'begin' + // has never been send to the app for these events. + // So should therefore not send the following removes either. + + for (int i=0; i<int([ended count]); ++i) { + NSTouch *touch = [[ended allObjects] objectAtIndex:i]; + QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch); + if (qcocoaTouch) { + qcocoaTouch->updateTouchData(touch, [touch phase]); + if (!_updateInternalStateOnly) + touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint); + delete qcocoaTouch; + } + } + + bool wasUpdateInternalStateOnly = _updateInternalStateOnly; + _updateInternalStateOnly = !acceptSingleTouch && _touchCount < 2; + + // Next: update, or create, existing touches. + // We always keep track of all touch points, even + // when not accepting single touches. + + for (int i=0; i<int([active count]); ++i) { + NSTouch *touch = [[active allObjects] objectAtIndex:i]; + QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch); + if (!qcocoaTouch) + qcocoaTouch = new QCocoaTouch(touch); + else + qcocoaTouch->updateTouchData(touch, wasUpdateInternalStateOnly ? NSTouchPhaseBegan : [touch phase]); + if (!_updateInternalStateOnly) + touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint); + } + + // Next: sadly, we need to check that our touch hash is in + // sync with cocoa. This is typically not the case after a system + // gesture happend (like a four-finger-swipe to show expose). + + if (_touchCount != _currentTouches.size()) { + // Remove all instances, and basically start from scratch: + touchPoints.clear(); + QList<QCocoaTouch *> list = _currentTouches.values(); + foreach (QCocoaTouch *qcocoaTouch, _currentTouches.values()) { + if (!_updateInternalStateOnly) { + qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased); + touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint); + } + delete qcocoaTouch; + } + _currentTouches.clear(); + _updateInternalStateOnly = !acceptSingleTouch; + return touchPoints.values(); + } + + // Finally: If this call _started_ to reject single + // touches, we need to fake a relase for the remaining + // touch now (and refake a begin for it later, if needed). + + if (_updateInternalStateOnly && !wasUpdateInternalStateOnly && !_currentTouches.isEmpty()) { + QCocoaTouch *qcocoaTouch = _currentTouches.values().first(); + qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased); + touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint); + // Since this last touch also will end up beeing the first + // touch (if the user adds a second finger without lifting + // the first), we promote it to be the primary touch: + qcocoaTouch->_touchPoint.setId(0); + _idAssignmentCount = 1; + } + + return touchPoints.values(); +} + +#endif + +QT_END_NAMESPACE + +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + diff --git a/src/gui/kernel/qmultitouch_mac_p.h b/src/gui/kernel/qmultitouch_mac_p.h new file mode 100644 index 0000000..3fa8f6c --- /dev/null +++ b/src/gui/kernel/qmultitouch_mac_p.h @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#ifndef QMULTITOUCH_MAC_P_H +#define QMULTITOUCH_MAC_P_H + +#ifdef QT_MAC_USE_COCOA +#import <Cocoa/Cocoa.h> +#endif + +#include <qevent.h> +#include <qhash.h> +#include <QtCore> + +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + +QT_BEGIN_NAMESPACE + +#ifdef QT_MAC_USE_COCOA + +class QCocoaTouch +{ + public: + static QList<QTouchEvent::TouchPoint> getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch); + static void setMouseInDraggingState(bool inDraggingState); + + private: + static QHash<int, QCocoaTouch*> _currentTouches; + static QPointF _screenReferencePos; + static QPointF _trackpadReferencePos; + static int _idAssignmentCount; + static int _touchCount; + static bool _updateInternalStateOnly; + + QTouchEvent::TouchPoint _touchPoint; + int _identity; + + QCocoaTouch(NSTouch *nstouch); + ~QCocoaTouch(); + + void updateTouchData(NSTouch *nstouch, NSTouchPhase phase); + static QCocoaTouch *findQCocoaTouch(NSTouch *nstouch); + static Qt::TouchPointState toTouchPointState(NSTouchPhase nsState); +}; + +#endif // QT_MAC_USE_COCOA + +QT_END_NAMESPACE + +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + +#endif // QMULTITOUCH_MAC_P_H + diff --git a/src/gui/kernel/qsound_win.cpp b/src/gui/kernel/qsound_win.cpp index 7330d4b..82854ae 100644 --- a/src/gui/kernel/qsound_win.cpp +++ b/src/gui/kernel/qsound_win.cpp @@ -77,13 +77,8 @@ public: QAuServerWindows::QAuServerWindows(QObject* parent) : QAuServer(parent), current(0) { - QT_WA({ - mutex = CreateMutexW(0, 0, 0); - event = CreateEventW(0, FALSE, FALSE, 0); - } , { - mutex = CreateMutexA(0, 0, 0); - event = CreateEventA(0, FALSE, FALSE, 0); - }); + mutex = CreateMutex(0, 0, 0); + event = CreateEvent(0, FALSE, FALSE, 0); } QAuServerWindows::~QAuServerWindows() @@ -133,13 +128,9 @@ DWORD WINAPI SoundPlayProc(LPVOID param) if (loops == -1) flags |= SND_LOOP; - QT_WA({ - PlaySoundW((TCHAR*)filename.utf16(), 0, flags); - } , { - PlaySoundA(QFile::encodeName(filename).data(), 0, flags); - }); - if (sound && loops == 1) - server->decLoop(sound); + PlaySound((wchar_t*)filename.utf16(), 0, flags); + if (sound && loops == 1) + server->decLoop(sound); // GUI thread continues, but we are done as well. SetEvent(event); @@ -148,18 +139,13 @@ DWORD WINAPI SoundPlayProc(LPVOID param) QPointer<QSound> guarded_sound = sound; SetEvent(event); - for (int l = 0; l < loops && server->current; ++l) { - QT_WA( { - PlaySoundW( (TCHAR*)filename.utf16(), 0, SND_FILENAME|SND_SYNC ); - } , { - PlaySoundA( QFile::encodeName(filename).data(), 0, - SND_FILENAME|SND_SYNC ); - } ); - - if (guarded_sound) - server->decLoop(guarded_sound); - } - server->current = 0; + for (int l = 0; l < loops && server->current; ++l) { + PlaySound((wchar_t*)filename.utf16(), 0, SND_FILENAME | SND_SYNC); + + if (guarded_sound) + server->decLoop(guarded_sound); + } + server->current = 0; } ReleaseMutex(mutex); @@ -169,7 +155,7 @@ DWORD WINAPI SoundPlayProc(LPVOID param) void QAuServerWindows::playHelper(const QString &filename, int loop, QSound *snd) { if (loop == 0) - return; + return; // busy? if (WaitForSingleObject(mutex, 0) == WAIT_TIMEOUT) return; diff --git a/src/gui/kernel/qstandardgestures.cpp b/src/gui/kernel/qstandardgestures.cpp new file mode 100644 index 0000000..c8b11c5 --- /dev/null +++ b/src/gui/kernel/qstandardgestures.cpp @@ -0,0 +1,254 @@ +/**************************************************************************** +** +** 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 "qstandardgestures.h" +#include "qstandardgestures_p.h" + +#include <qabstractscrollarea.h> +#include <qscrollbar.h> +#include <private/qapplication_p.h> + +QT_BEGIN_NAMESPACE + +/*! + \class QPanGesture + \since 4.6 + + \brief The QPanGesture class represents a Pan gesture, + providing additional information related to panning. +*/ + +/*! + Creates a new Pan gesture handler object and marks it as a child of \a + parent. + + On some platform like Windows it's necessary to provide a non-null widget + as \a parent to get native gesture support. +*/ +QPanGesture::QPanGesture(QWidget *parent) + : QGesture(*new QPanGesturePrivate, parent) +{ +#ifdef Q_WS_WIN + if (parent) { + QApplicationPrivate* getQApplicationPrivateInternal(); + QApplicationPrivate *qAppPriv = getQApplicationPrivateInternal(); + qAppPriv->widgetGestures[parent].pan = this; + } +#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; + break; + case QEvent::ParentChange: + if (QWidget *w = qobject_cast<QWidget*>(parent())) + getQApplicationPrivateInternal()->widgetGestures[w].pan = this; + break; + default: + break; + } +#endif + return QObject::event(event); +} + +/*! \internal */ +bool QPanGesture::filterEvent(QEvent *event) +{ + Q_D(QPanGesture); + if (!event->spontaneous()) + 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; + } 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(); + } + 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(); + } + } + return false; +} + +/*! \internal */ +void QPanGesture::reset() +{ + Q_D(QPanGesture); + d->touchPoints.clear(); +} + +/*! + \property QPanGesture::totalOffset + + Specifies a total pan offset since the start of the gesture. +*/ +QSize QPanGesture::totalOffset() const +{ + QPoint pt = pos() - startPos(); + return QSize(pt.x(), pt.y()); +} + +/*! + \property QPanGesture::lastOffset + + Specifies a pan offset since the last time the gesture was + triggered. +*/ +QSize QPanGesture::lastOffset() const +{ + QPoint pt = pos() - lastPos(); + return QSize(pt.x(), pt.y()); +} + +/*! + \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; +} + +/*! \internal */ +void QTapAndHoldGesture::reset() +{ + Q_D(QTapAndHoldGesture); + if (state() != Qt::NoGesture) + emit cancelled(); + setState(Qt::NoGesture); + d->timer.stop(); + d->iteration = 0; +} + +QT_END_NAMESPACE diff --git a/src/gui/kernel/qstandardgestures.h b/src/gui/kernel/qstandardgestures.h new file mode 100644 index 0000000..db96ef6 --- /dev/null +++ b/src/gui/kernel/qstandardgestures.h @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** 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 QSTANDARDGESTURES_H +#define QSTANDARDGESTURES_H + +#include "qevent.h" +#include "qbasictimer.h" +#include "qdebug.h" + +#include "qgesture.h" + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class QPanGesturePrivate; +class Q_GUI_EXPORT QPanGesture : public QGesture +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QPanGesture) + + Q_PROPERTY(QSize totalOffset READ totalOffset) + Q_PROPERTY(QSize lastOffset READ lastOffset) + +public: + QPanGesture(QWidget *parent); + + bool filterEvent(QEvent *event); + void reset(); + + QSize totalOffset() const; + QSize lastOffset() const; + +protected: + bool event(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 + +#endif // QSTANDARDGESTURES_H diff --git a/src/gui/kernel/qstandardgestures_p.h b/src/gui/kernel/qstandardgestures_p.h new file mode 100644 index 0000000..bb11c9f --- /dev/null +++ b/src/gui/kernel/qstandardgestures_p.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** 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 QSTANDARDGESTURES_P_H +#define QSTANDARDGESTURES_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qevent.h" +#include "qbasictimer.h" +#include "qdebug.h" + +#include "qgesture.h" +#include "qgesture_p.h" + +QT_BEGIN_NAMESPACE + +class QPanGesturePrivate : public QGesturePrivate +{ + Q_DECLARE_PUBLIC(QPanGesture) + +public: + QPanGesturePrivate() { } + + QList<QTouchEvent::TouchPoint> touchPoints; +}; + +class QTapAndHoldGesturePrivate : public QGesturePrivate +{ + Q_DECLARE_PUBLIC(QTapAndHoldGesture) + +public: + QTapAndHoldGesturePrivate() + : iteration(0) { } + + QBasicTimer timer; + int iteration; + static const int iterationCount; + static const int iterationTimeout; +}; + +QT_END_NAMESPACE + +#endif // QSTANDARDGESTURES_P_H diff --git a/src/gui/kernel/qt_cocoa_helpers_mac.mm b/src/gui/kernel/qt_cocoa_helpers_mac.mm index f5f381e..073a00e 100644 --- a/src/gui/kernel/qt_cocoa_helpers_mac.mm +++ b/src/gui/kernel/qt_cocoa_helpers_mac.mm @@ -894,50 +894,6 @@ bool qt_mac_handleMouseEvent(void * /* NSView * */view, void * /* NSEvent * */ev NSPoint localPoint = [tmpView convertPoint:windowPoint fromView:nil]; QPoint qlocalPoint(localPoint.x, localPoint.y); - if (widgetToGetMouse->testAttribute(Qt::WA_TransparentForMouseEvents)) { - // Simulate passing the event through since Cocoa doesn't do that for us. - // Start by building a tree up. - NSView *candidateView = [theView viewUnderTransparentForMouseView:tmpView - widget:widgetToGetMouse - withWindowPoint:windowPoint]; - if (candidateView != nil) { - // Fast-track our views, since dispatching trough the normal ways - // would just end up going through here anyway. - if ([candidateView isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) { - return qt_mac_handleMouseEvent(candidateView, theEvent, eventType, button); - } else { - switch (eventType) { - default: - qWarning("not handled! %d", eventType); - break; - case QEvent::MouseMove: - [candidateView mouseMoved:theEvent]; - break; - case QEvent::MouseButtonPress: - if (button == Qt::LeftButton) - [candidateView mouseDown:theEvent]; - else if (button == Qt::RightButton) - [candidateView rightMouseDown:theEvent]; - else - [candidateView otherMouseDown:theEvent]; - break; - case QEvent::MouseButtonRelease: - if (button == Qt::LeftButton) - [candidateView mouseUp:theEvent]; - else if (button == Qt::RightButton) - [candidateView rightMouseUp:theEvent]; - else - [candidateView otherMouseUp:theEvent]; - break; - } - return true; // We've done the dispatching, no need go further. - } - } - // Nothing below me return false - return false; - } - - EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([theEvent eventRef])); if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent)) return true; diff --git a/src/gui/kernel/qwhatsthis.cpp b/src/gui/kernel/qwhatsthis.cpp index 067c783..f38b0f6 100644 --- a/src/gui/kernel/qwhatsthis.cpp +++ b/src/gui/kernel/qwhatsthis.cpp @@ -226,7 +226,9 @@ QWhatsThat::QWhatsThat(const QString& txt, QWidget* parent, QWidget *showTextFor text); } #if defined(Q_WS_WIN) - if ((QSysInfo::WindowsVersion&QSysInfo::WV_NT_based) > QSysInfo::WV_2000) { + if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP + && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) + { BOOL shadow; SystemParametersInfo(SPI_GETDROPSHADOW, 0, &shadow, 0); shadowWidth = shadow ? 0 : 6; @@ -302,7 +304,9 @@ void QWhatsThat::paintEvent(QPaintEvent*) { bool drawShadow = true; #if defined(Q_WS_WIN) - if ((QSysInfo::WindowsVersion&QSysInfo::WV_NT_based) > QSysInfo::WV_2000) { + if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP + && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) + { BOOL shadow; SystemParametersInfo(SPI_GETDROPSHADOW, 0, &shadow, 0); drawShadow = !shadow; diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 8c6e0a7..611cb44 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -82,6 +82,8 @@ #include "private/qstyle_p.h" #include "private/qinputcontext_p.h" #include "qfileinfo.h" +#include "qstandardgestures.h" +#include "qstandardgestures_p.h" #if defined (Q_WS_WIN) # include <private/qwininputcontext_p.h> @@ -107,6 +109,7 @@ #include "private/qgraphicsproxywidget_p.h" #include "QtGui/qabstractscrollarea.h" #include "private/qabstractscrollarea_p.h" +#include "private/qevent_p.h" #include "private/qgraphicssystem_p.h" @@ -860,8 +863,8 @@ void QWidget::setAutoFillBackground(bool enabled) \list \o X11: This feature relies on the use of an X server that supports ARGB visuals and a compositing window manager. - \o Windows: This feature requires Windows 2000 or later. The widget needs to have - the Qt::FramelessWindowHint window flag set for the translucency to work. + \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set + for the translucency to work. \endlist @@ -7474,11 +7477,13 @@ bool QWidget::event(QEvent *event) case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: case QEvent::ContextMenu: #ifndef QT_NO_WHEELEVENT case QEvent::Wheel: #endif - return false; default: break; } @@ -7873,6 +7878,96 @@ bool QWidget::event(QEvent *event) d->needWindowChange = false; break; #endif + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + { + QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event); + const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first(); + if (touchPoint.isPrimary()) + break; + + // fake a mouse event! + QEvent::Type eventType = QEvent::None; + switch (touchEvent->type()) { + case QEvent::TouchBegin: + eventType = QEvent::MouseButtonPress; + break; + case QEvent::TouchUpdate: + eventType = QEvent::MouseMove; + break; + case QEvent::TouchEnd: + eventType = QEvent::MouseButtonRelease; + break; + default: + Q_ASSERT(!true); + break; + } + if (eventType == QEvent::None) + break; + + QMouseEvent mouseEvent(eventType, + touchPoint.pos().toPoint(), + touchPoint.screenPos().toPoint(), + Qt::LeftButton, + Qt::LeftButton, + touchEvent->modifiers()); + (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(); @@ -9881,6 +9976,12 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on) } break; + case Qt::WA_AcceptTouchEvents: +#if defined(Q_WS_WIN) || defined(Q_WS_MAC) + if (on) + d->registerTouchWindow(); +#endif + break; default: break; } @@ -9911,8 +10012,8 @@ bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const By default the value of this property is 1.0. - This feature is available on Embedded Linux, Mac OS X, X11 platforms that - support the Composite extension, and Windows 2000 and later. + This feature is available on Embedded Linux, Mac OS X, Windows, + and X11 platforms that support the Composite extension. This feature is not available on Windows CE. diff --git a/src/gui/kernel/qwidget.h b/src/gui/kernel/qwidget.h index 975da5a..bc9952c 100644 --- a/src/gui/kernel/qwidget.h +++ b/src/gui/kernel/qwidget.h @@ -95,6 +95,7 @@ class QIcon; class QWindowSurface; class QLocale; class QGraphicsProxyWidget; +class QGestureManager; #if defined(Q_WS_X11) class QX11Info; #endif diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index 88dc73f..b0531ec 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -1369,6 +1369,14 @@ OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, // Set dropWidget to zero, so qt_mac_dnd_event // doesn't get called a second time below: dropWidget = 0; + } else if (ekind == kEventControlDragLeave) { + dropWidget = QDragManager::self()->currentTarget(); + if (dropWidget) { + dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag); + } + // Set dropWidget to zero, so qt_mac_dnd_event + // doesn't get called a second time below: + dropWidget = 0; } } } @@ -2132,11 +2140,10 @@ void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWin if ((popup || type == Qt::Tool || type == Qt::ToolTip) && !q->isModal()) { [windowRef setHidesOnDeactivate:YES]; - [windowRef setHasShadow:YES]; } else { [windowRef setHidesOnDeactivate:NO]; } - + [windowRef setHasShadow:YES]; Q_UNUSED(parentWidget); Q_UNUSED(dialog); @@ -2481,9 +2488,10 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO setFocus_sys(); if (!topLevel && initializeWindow) setWSGeometry(); - if (destroyid) qt_mac_destructView(destroyid); + if (q->testAttribute(Qt::WA_AcceptTouchEvents)) + registerTouchWindow(); } /*! @@ -2690,10 +2698,15 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) createWinId(); if (q->isWindow()) { #ifndef QT_MAC_USE_COCOA - if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) { - mwl->updateHIToolBarStatus(); + // We do this down below for wasCreated, so avoid doing this twice + // (only for performance, it gets called a lot anyway). + if (!wasCreated) { + if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) { + mwl->updateHIToolBarStatus(); + } } #else + // Simply transfer our toolbar over. Everything should stay put, unlike in Carbon. if (oldToolbar && !(f & Qt::FramelessWindowHint)) { OSWindowRef newWindow = qt_mac_window_for(q); [newWindow setToolbar:oldToolbar]; @@ -2708,6 +2721,16 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) if (wasCreated) { transferChildren(); +#ifndef QT_MAC_USE_COCOA + // If we were a unified window, We just transfered our toolbars out of the unified toolbar. + // So redo the status one more time. It apparently is not an issue with Cocoa. + if (q->isWindow()) { + if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) { + mwl->updateHIToolBarStatus(); + } + } +#endif + if (topData && (!topData->caption.isEmpty() || !topData->filePath.isEmpty())) setWindowTitle_helper(q->windowTitle()); @@ -3690,7 +3713,7 @@ static void qt_mac_update_widget_posisiton(QWidget *q, QRect oldRect, QRect newR // Perform a normal (complete repaint) update in some cases: if ( // move-by-scroll requires QWidgetPrivate::isOpaque set - (isMove && qd->isOpaque == false) || + (isMove && q->testAttribute(Qt::WA_OpaquePaintEvent) == false) || // limited update on resize requires WA_StaticContents. (isResize && q->testAttribute(Qt::WA_StaticContents) == false) || @@ -3800,7 +3823,6 @@ void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect) Qt coordinate system for parent X coordinate system for parent (relative to parent's wrect). */ - QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX); QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX); QRect wrect; //xrect is the X geometry of my X widget. (starts out in parent's Qt coord sys, and ends up in parent's X coord sys) @@ -3878,7 +3900,7 @@ void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect) } } - if (!validRange.contains(xrect)) { + if (xrect.height() > XCOORD_MAX || xrect.width() > XCOORD_MAX) { // we are too big, and must clip xrect &=wrectRange; wrect = xrect; @@ -3926,10 +3948,9 @@ void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect) qt_mac_update_widget_posisiton(q, oldRect, xrect); - if (jump) { - updateSystemBackground(); + if (jump) q->update(); - } + if (mapWindow && !dontShow) { q->setAttribute(Qt::WA_Mapped); #ifndef QT_MAC_USE_COCOA @@ -4011,6 +4032,8 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) setGeometry_sys_helper(x, y, w, h, isMove); } #else + QSize olds = q->size(); + const bool isResize = (olds != QSize(w, h)); NSWindow *window = qt_mac_window_for(q); const QRect &fStrut = frameStrut(); const QRect frameRect(QPoint(x - fStrut.left(), y - fStrut.top()), @@ -4018,7 +4041,10 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) fStrut.top() + fStrut.bottom() + h)); NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1), frameRect.width(), frameRect.height()); - + // The setFrame call will trigger a 'windowDidResize' notification for the corresponding + // NSWindow. The pending flag is set, so that the resize event can be send as non-spontaneous. + if (isResize) + q->setAttribute(Qt::WA_PendingResizeEvent); QPoint currTopLeft = data.crect.topLeft(); if (currTopLeft.x() == x && currTopLeft.y() == y && cocoaFrameRect.size.width != 0 @@ -4214,7 +4240,7 @@ void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r) HIRect bounds = CGRectMake(w->data->crect.x(), w->data->crect.y(), w->data->crect.width(), w->data->crect.height()); HIViewRef hiview = qt_mac_nativeview_for(w); - const bool opaque = qt_widget_private(w)->isOpaque; + const bool opaque = q->testAttribute(Qt::WA_OpaquePaintEvent); if (opaque) HIViewSetDrawingEnabled(hiview, false); @@ -4413,6 +4439,23 @@ void QWidgetPrivate::registerDropSite(bool on) #endif } +void QWidgetPrivate::registerTouchWindow() +{ +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 + if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6) + return; + Q_Q(QWidget); + if (!q->testAttribute(Qt::WA_WState_Created)) + return; +#ifndef QT_MAC_USE_COCOA + // Needs implementation! +#else + NSView *view = qt_mac_nativeview_for(q); + [view setAcceptsTouchEvents:YES]; +#endif +#endif +} + void QWidgetPrivate::setMask_sys(const QRegion ®ion) { Q_UNUSED(region); diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h index c285866..626950e 100644 --- a/src/gui/kernel/qwidget_p.h +++ b/src/gui/kernel/qwidget_p.h @@ -57,6 +57,7 @@ #include "private/qobject_p.h" #include "QtCore/qrect.h" #include "QtCore/qlocale.h" +#include "QtCore/qset.h" #include "QtGui/qregion.h" #include "QtGui/qsizepolicy.h" #include "QtGui/qstyle.h" @@ -556,6 +557,7 @@ public: void unregisterOleDnd(QWidget *widget, QOleDropTarget *target); #endif void grabMouseWhileInWindow(); + void registerTouchWindow(); #elif defined(Q_WS_MAC) // <--------------------------------------------------------- MAC // This is new stuff uint needWindowChange : 1; @@ -621,6 +623,7 @@ public: static OSStatus qt_window_event(EventHandlerCallRef er, EventRef event, void *); static OSStatus qt_widget_event(EventHandlerCallRef er, EventRef event, void *); static bool qt_widget_rgn(QWidget *, short, RgnHandle, bool); + void registerTouchWindow(); #elif defined(Q_WS_QWS) // <--------------------------------------------------------- QWS void setMaxWindowState_helper(); void setFullScreenSize_helper(); diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp index 988ddf2..dcf541c 100644 --- a/src/gui/kernel/qwidget_win.cpp +++ b/src/gui/kernel/qwidget_win.cpp @@ -140,14 +140,8 @@ static void init_wintab_functions() if (!qt_is_gui_used) return; QLibrary library(QLatin1String("wintab32")); - QT_WA({ - ptrWTOpen = (PtrWTOpen)library.resolve("WTOpenW"); - ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW"); - } , { - ptrWTOpen = (PtrWTOpen)library.resolve("WTOpenA"); - ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoA"); - }); - + ptrWTOpen = (PtrWTOpen)library.resolve("WTOpenW"); + ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW"); ptrWTClose = (PtrWTClose)library.resolve("WTClose"); ptrWTQueueSizeGet = (PtrWTQueueSizeGet)library.resolve("WTQueueSizeGet"); ptrWTQueueSizeSet = (PtrWTQueueSizeSet)library.resolve("WTQueueSizeSet"); @@ -287,25 +281,18 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO if (desktop && !q->testAttribute(Qt::WA_DontShowOnScreen)) { // desktop widget popup = false; // force this flags off - if (QSysInfo::WindowsVersion != QSysInfo::WV_NT && QSysInfo::WindowsVersion != QSysInfo::WV_95) - data.crect.setRect(GetSystemMetrics(76 /* SM_XVIRTUALSCREEN */), GetSystemMetrics(77 /* SM_YVIRTUALSCREEN */), + data.crect.setRect(GetSystemMetrics(76 /* SM_XVIRTUALSCREEN */), GetSystemMetrics(77 /* SM_YVIRTUALSCREEN */), GetSystemMetrics(78 /* SM_CXVIRTUALSCREEN */), GetSystemMetrics(79 /* SM_CYVIRTUALSCREEN */)); - else - data.crect.setRect(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); } parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0; -#ifdef UNICODE QString title; - const TCHAR *ttitle = 0; -#endif - QByteArray title95; int style = WS_CHILD; int exsty = 0; if (window) { - style = GetWindowLongA(window, GWL_STYLE); + style = GetWindowLong(window, GWL_STYLE); if (!style) qErrnoWarning("QWidget::create: GetWindowLong failed"); topLevel = false; // #### needed for some IE plugins?? @@ -361,12 +348,7 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO } if (flags & Qt::WindowTitleHint) { - QT_WA({ - title = q->isWindow() ? qAppName() : q->objectName(); - ttitle = (TCHAR*)title.utf16(); - } , { - title95 = q->isWindow() ? qAppName().toLocal8Bit() : q->objectName().toLatin1(); - }); + title = q->isWindow() ? qAppName() : q->objectName(); } // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in @@ -379,13 +361,13 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO destroyw = data.winid; id = window; setWinId(window); - LONG res = SetWindowLongA(window, GWL_STYLE, style); + LONG res = SetWindowLong(window, GWL_STYLE, style); if (!res) qErrnoWarning("QWidget::create: Failed to set window style"); #ifdef _WIN64 - res = SetWindowLongPtrA( window, GWLP_WNDPROC, (LONG_PTR)QtWndProc ); + res = SetWindowLongPtr( window, GWLP_WNDPROC, (LONG_PTR)QtWndProc ); #else - res = SetWindowLongA( window, GWL_WNDPROC, (LONG)QtWndProc ); + res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc ); #endif if (!res) qErrnoWarning("QWidget::create: Failed to set window procedure"); @@ -436,16 +418,10 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO } } - QT_WA({ - const TCHAR *cname = (TCHAR*)windowClassName.utf16(); - id = CreateWindowEx(exsty, cname, ttitle, style, - x, y, w, h, - parentw, 0, appinst, 0); - } , { - id = CreateWindowExA(exsty, windowClassName.toLatin1(), title95, style, - x, y, w, h, - parentw, 0, appinst, 0); - }); + id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()), + reinterpret_cast<const wchar_t *>(title.utf16()), style, + x, y, w, h, + parentw, NULL, appinst, NULL); if (!id) qErrnoWarning("QWidget::create: Failed to create window"); setWinId(id); @@ -457,16 +433,10 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO SetWindowPos(id, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); winUpdateIsOpaque(); } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget - QT_WA({ - const TCHAR *cname = (TCHAR*)windowClassName.utf16(); - id = CreateWindowEx(exsty, cname, ttitle, style, - data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), - parentw, NULL, appinst, NULL); - } , { - id = CreateWindowExA(exsty, windowClassName.toLatin1(), title95, style, - data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), + id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()), + reinterpret_cast<const wchar_t *>(title.utf16()), style, + data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), parentw, NULL, appinst, NULL); - }); if (!id) qErrnoWarning("QWidget::create: Failed to create window"); SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); @@ -500,6 +470,9 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO q->setAttribute(Qt::WA_WState_Created); // accept move/resize events hd = 0; // no display context + if (q->testAttribute(Qt::WA_AcceptTouchEvents)) + registerTouchWindow(); + if (window) { // got window from outside if (IsWindowVisible(window)) q->setAttribute(Qt::WA_WState_Visible); @@ -679,7 +652,7 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) // Show borderless toplevel windows in tasklist & NavBar if (!parent) { QString txt = q->windowTitle().isEmpty()?qAppName():q->windowTitle(); - SetWindowText(q->internalWinId(), (TCHAR*)txt.utf16()); + SetWindowText(q->internalWinId(), (wchar_t*)txt.utf16()); } #endif invalidateBuffer(q->rect()); @@ -764,11 +737,7 @@ void QWidgetPrivate::setWindowTitle_sys(const QString &caption) return; Q_ASSERT(q->testAttribute(Qt::WA_WState_Created)); - QT_WA({ - SetWindowText(q->internalWinId(), (TCHAR*)caption.utf16()); - } , { - SetWindowTextA(q->internalWinId(), caption.toLocal8Bit()); - }); + SetWindowText(q->internalWinId(), (wchar_t*)caption.utf16()); } /* @@ -850,11 +819,11 @@ void QWidgetPrivate::setWindowIcon_sys(bool forceReset) GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), &(x->iconPixmap)); if (x->winIconBig) { - SendMessageA(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall); - SendMessageA(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconBig); + SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall); + SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconBig); } else { - SendMessageA(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall); - SendMessageA(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconSmall); + SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall); + SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconSmall); } } @@ -881,7 +850,7 @@ LRESULT CALLBACK qJournalRecordProc(int nCode, WPARAM wParam, LPARAM lParam) /* Works only as long as pointer is inside the application's window, which is good enough for QDockWidget. - Doesn't call SetWindowsHookExA() - this function causes a system-wide + Doesn't call SetWindowsHookEx() - this function causes a system-wide freeze if any other app on the system installs a hook and fails to process events. */ void QWidgetPrivate::grabMouseWhileInWindow() @@ -905,7 +874,7 @@ void QWidget::grabMouse() if (!qt_nograb()) { if (mouseGrb) mouseGrb->releaseMouse(); - journalRec = SetWindowsHookExA(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandleA(0), 0); + journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0); Q_ASSERT(testAttribute(Qt::WA_WState_Created)); SetCapture(effectiveWinId()); mouseGrb = this; @@ -918,7 +887,7 @@ void QWidget::grabMouse(const QCursor &cursor) if (!qt_nograb()) { if (mouseGrb) mouseGrb->releaseMouse(); - journalRec = SetWindowsHookExA(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandleA(0), 0); + journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0); Q_ASSERT(testAttribute(Qt::WA_WState_Created)); SetCapture(effectiveWinId()); mouseGrbCur = new QCursor(cursor); @@ -1025,7 +994,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) if (newstate & Qt::WindowFullScreen) { if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized)) d->topData()->normalGeometry = geometry(); - d->topData()->savedFlags = Qt::WindowFlags(GetWindowLongA(internalWinId(), GWL_STYLE)); + d->topData()->savedFlags = Qt::WindowFlags(GetWindowLong(internalWinId(), GWL_STYLE)); #ifndef Q_FLATTEN_EXPOSE UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP; #else @@ -1035,7 +1004,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) style |= WS_SYSMENU; if (isVisible()) style |= WS_VISIBLE; - SetWindowLongA(internalWinId(), GWL_STYLE, style); + SetWindowLong(internalWinId(), GWL_STYLE, style); QRect r = QApplication::desktop()->screenGeometry(this); UINT swpf = SWP_FRAMECHANGED; if (newstate & Qt::WindowActive) @@ -1047,7 +1016,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) UINT style = d->topData()->savedFlags; if (isVisible()) style |= WS_VISIBLE; - SetWindowLongA(internalWinId(), GWL_STYLE, style); + SetWindowLong(internalWinId(), GWL_STYLE, style); UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE; if (newstate & Qt::WindowActive) @@ -1392,7 +1361,7 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) UINT style = top->savedFlags; if (q->isVisible()) style |= WS_VISIBLE; - SetWindowLongA(q->internalWinId(), GWL_STYLE, style); + SetWindowLong(q->internalWinId(), GWL_STYLE, style); UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE; if (data.window_state & Qt::WindowActive) @@ -1407,7 +1376,7 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData(); const bool inTopLevelResize = tlwExtra ? tlwExtra->inTopLevelResize : false; const bool isTranslucentWindow = !isOpaque && ptrUpdateLayeredWindowIndirect && (data.window_flags & Qt::FramelessWindowHint) - && GetWindowLongA(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED; + && GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED; if (q->testAttribute(Qt::WA_WState_ConfigPending)) { // processing config event if (q->internalWinId()) @@ -1575,11 +1544,11 @@ void QWidgetPrivate::winUpdateIsOpaque() return; if (!isOpaque && ptrUpdateLayeredWindowIndirect) { - SetWindowLongA(q->internalWinId(), GWL_EXSTYLE, - GetWindowLongA(q->internalWinId(), GWL_EXSTYLE) | Q_WS_EX_LAYERED); + SetWindowLong(q->internalWinId(), GWL_EXSTYLE, + GetWindowLong(q->internalWinId(), GWL_EXSTYLE) | Q_WS_EX_LAYERED); } else { - SetWindowLongA(q->internalWinId(), GWL_EXSTYLE, - GetWindowLongA(q->internalWinId(), GWL_EXSTYLE) & ~Q_WS_EX_LAYERED); + SetWindowLong(q->internalWinId(), GWL_EXSTYLE, + GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & ~Q_WS_EX_LAYERED); } #endif } @@ -1589,12 +1558,12 @@ void QWidgetPrivate::setConstraints_sys() #ifndef Q_WS_WINCE_WM Q_Q(QWidget); if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) { - int style = GetWindowLongA(q->internalWinId(), GWL_STYLE); + int style = GetWindowLong(q->internalWinId(), GWL_STYLE); if (shouldShowMaximizeButton()) style |= WS_MAXIMIZEBOX; else style &= ~WS_MAXIMIZEBOX; - SetWindowLongA(q->internalWinId(), GWL_STYLE, style); + SetWindowLong(q->internalWinId(), GWL_STYLE, style); } #endif } @@ -1864,10 +1833,8 @@ void QWidgetPrivate::updateFrameStrut() RECT rect = {0,0,0,0}; QTLWExtra *top = topData(); - uint exstyle = QT_WA_INLINE(GetWindowLongW(q->internalWinId(), GWL_EXSTYLE), - GetWindowLongA(q->internalWinId(), GWL_EXSTYLE)); - uint style = QT_WA_INLINE(GetWindowLongW(q->internalWinId(), GWL_STYLE), - GetWindowLongA(q->internalWinId(), GWL_STYLE)); + uint exstyle = GetWindowLong(q->internalWinId(), GWL_EXSTYLE); + uint style = GetWindowLong(q->internalWinId(), GWL_STYLE); #ifndef Q_WS_WINCE if (AdjustWindowRectEx(&rect, style & ~(WS_OVERLAPPED), FALSE, exstyle)) { #else @@ -1883,11 +1850,10 @@ void QWidgetPrivate::setWindowOpacity_sys(qreal level) { Q_Q(QWidget); - if (!isOpaque && ptrUpdateLayeredWindowIndirect && (data.window_flags & Qt::FramelessWindowHint)) { - if (GetWindowLongA(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED) { - Q_BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * level), Q_AC_SRC_ALPHA}; - Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, NULL, NULL, NULL, NULL, 0, &blend, Q_ULW_ALPHA, NULL}; - (*ptrUpdateLayeredWindowIndirect)(q->internalWinId(), &info); + if (!isOpaque && ptrUpdateLayeredWindow && (data.window_flags & Qt::FramelessWindowHint)) { + if (GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED) { + BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * level), AC_SRC_ALPHA}; + ptrUpdateLayeredWindow(q->internalWinId(), NULL, NULL, NULL, NULL, NULL, 0, &blend, Q_ULW_ALPHA); } return; } @@ -1903,15 +1869,15 @@ void QWidgetPrivate::setWindowOpacity_sys(qreal level) if (!ptrSetLayeredWindowAttributes) return; - int wl = GetWindowLongA(q->internalWinId(), GWL_EXSTYLE); + int wl = GetWindowLong(q->internalWinId(), GWL_EXSTYLE); if (level != 1.0) { if ((wl&Q_WS_EX_LAYERED) == 0) - SetWindowLongA(q->internalWinId(), GWL_EXSTYLE, wl|Q_WS_EX_LAYERED); + SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl | Q_WS_EX_LAYERED); } else if (wl&Q_WS_EX_LAYERED) { - SetWindowLongA(q->internalWinId(), GWL_EXSTYLE, wl & ~Q_WS_EX_LAYERED); + SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl & ~Q_WS_EX_LAYERED); } - (*ptrSetLayeredWindowAttributes)(q->internalWinId(), 0, (int)(level * 255), Q_LWA_ALPHA); + ptrSetLayeredWindowAttributes(q->internalWinId(), 0, (int)(level * 255), Q_LWA_ALPHA); } #endif //Q_WS_WINCE @@ -2069,8 +2035,16 @@ void QWidgetPrivate::setModal_sys() { } +void QWidgetPrivate::registerTouchWindow() +{ + Q_Q(QWidget); - + // enable WM_TOUCH* messages on our window + if (q->testAttribute(Qt::WA_WState_Created) + && QApplicationPrivate::RegisterTouchWindow + && q->windowType() != Qt::Desktop) + QApplicationPrivate::RegisterTouchWindow(q->effectiveWinId(), 0); +} QT_END_NAMESPACE diff --git a/src/gui/kernel/qwidget_wince.cpp b/src/gui/kernel/qwidget_wince.cpp index 24d8156..b0eaa12 100644 --- a/src/gui/kernel/qwidget_wince.cpp +++ b/src/gui/kernel/qwidget_wince.cpp @@ -188,11 +188,7 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0; -#ifdef UNICODE QString title; - const TCHAR *ttitle = 0; -#endif - QByteArray title95; int style = WS_CHILD; int exsty = WS_EX_NOPARENTNOTIFY; @@ -236,12 +232,7 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO } if (flags & Qt::WindowTitleHint) { - QT_WA({ - title = q->isWindow() ? qAppName() : q->objectName(); - ttitle = (TCHAR*)title.utf16(); - } , { - title95 = q->isWindow() ? qAppName().toLocal8Bit() : q->objectName().toLatin1(); - }); + title = q->isWindow() ? qAppName() : q->objectName(); } // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in @@ -254,11 +245,11 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO destroyw = data.winid; id = window; setWinId(window); - LONG res = SetWindowLongA(window, GWL_STYLE, style); + LONG res = SetWindowLong(window, GWL_STYLE, style); if (!res) qErrnoWarning("QWidget::create: Failed to set window style"); - res = SetWindowLongA( window, GWL_WNDPROC, (LONG)QtWndProc ); + res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc ); if (!res) qErrnoWarning("QWidget::create: Failed to set window procedure"); @@ -267,10 +258,10 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO if (!id) { //Create a dummy desktop RECT r; SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0); - const TCHAR *cname = reinterpret_cast<const TCHAR *> (windowClassName.utf16()); - id = CreateWindow(cname, ttitle, style, - r.left, r.top, r.right - r.left, r.bottom - r.top, - 0, 0, appinst, 0); + id = CreateWindow(reinterpret_cast<const wchar_t *>(windowClassName.utf16()), + reinterpret_cast<const wchar_t *>(title.utf16()), style, + r.left, r.top, r.right - r.left, r.bottom - r.top, + 0, 0, appinst, 0); } setWinId(id); } else if (topLevel) { // create top-level widget @@ -303,8 +294,8 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO } } - const TCHAR *cname = reinterpret_cast<const TCHAR *> (windowClassName.utf16()); - id = CreateWindowEx(exsty, cname, ttitle, style, + id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()), + reinterpret_cast<const wchar_t *>(title.utf16()), style, x, y, w, h, 0, 0, appinst, 0); @@ -314,16 +305,9 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip)) SetWindowPos(id, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget - QT_WA({ - const TCHAR *cname = (TCHAR*)windowClassName.utf16(); - id = CreateWindowEx(exsty, cname, ttitle, style, - data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), - parentw, NULL, appinst, NULL); - } , { - id = CreateWindowExA(exsty, windowClassName.toLatin1(), title95, style, - data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), + id = CreateWindowEx(exsty, (wchar_t*)windowClassName.utf16(), (wchar_t*)title.utf16(), style, + data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(), parentw, NULL, appinst, NULL); - }); if (!id) qErrnoWarning("QWidget::create: Failed to create window"); SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); @@ -510,7 +494,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) } if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) { if (!(newstate & Qt::WindowMaximized)) { - int style = GetWindowLongW(internalWinId(), GWL_STYLE) | WS_BORDER | WS_POPUP | WS_CAPTION; + int style = GetWindowLong(internalWinId(), GWL_STYLE) | WS_BORDER | WS_POPUP | WS_CAPTION; SetWindowLong(internalWinId(), GWL_STYLE, style); SetWindowLong(internalWinId(), GWL_EXSTYLE, GetWindowLong (internalWinId(), GWL_EXSTYLE) & ~ WS_EX_NODRAG); } @@ -535,11 +519,11 @@ void QWidget::setWindowState(Qt::WindowStates newstate) if (newstate & Qt::WindowFullScreen) { if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized)) d->topData()->normalGeometry = geometry(); - d->topData()->savedFlags = (Qt::WindowFlags) GetWindowLongA(internalWinId(), GWL_STYLE); + d->topData()->savedFlags = (Qt::WindowFlags)GetWindowLong(internalWinId(), GWL_STYLE); UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP; if (isVisible()) style |= WS_VISIBLE; - SetWindowLongA(internalWinId(), GWL_STYLE, style); + SetWindowLong(internalWinId(), GWL_STYLE, style); QRect r = qApp->desktop()->screenGeometry(this); UINT swpf = SWP_FRAMECHANGED; if (newstate & Qt::WindowActive) @@ -550,7 +534,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) UINT style = d->topData()->savedFlags; if (isVisible()) style |= WS_VISIBLE; - SetWindowLongA(internalWinId(), GWL_STYLE, style); + SetWindowLong(internalWinId(), GWL_STYLE, style); UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE; if (newstate & Qt::WindowActive) swpf |= SWP_NOACTIVATE; diff --git a/src/gui/kernel/qx11embed_x11.cpp b/src/gui/kernel/qx11embed_x11.cpp index 3ddde1b..659331f 100644 --- a/src/gui/kernel/qx11embed_x11.cpp +++ b/src/gui/kernel/qx11embed_x11.cpp @@ -826,7 +826,7 @@ bool QX11EmbedWidget::x11Event(XEvent *event) &actual_format_return, &nitems_return, &bytes_after_return, &prop_return) == Success) { if (nitems_return > 1) { - if (((int * )prop_return)[1] & XEMBED_MAPPED) { + if (((long * )prop_return)[1] & XEMBED_MAPPED) { XMapWindow(x11Info().display(), internalWinId()); } else { XUnmapWindow(x11Info().display(), internalWinId()); @@ -1670,9 +1670,9 @@ void QX11EmbedContainerPrivate::acceptClient(WId window) // Clients with the _XEMBED_INFO property are XEMBED clients. clientIsXEmbed = true; - unsigned int *p = (unsigned int *)prop_return; + long *p = (long *)prop_return; if (nitems_return >= 2) - clientversion = p[0]; + clientversion = (unsigned int)p[0]; } XFree(prop_return); diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp index 85fc0b9..831d389 100644 --- a/src/gui/painting/qblendfunctions.cpp +++ b/src/gui/painting/qblendfunctions.cpp @@ -374,9 +374,9 @@ template <typename T> void qt_blend_argb24_on_rgb16(uchar *destPixels, int dbpl, const uchar *src = srcPixels + y * sbpl; const uchar *srcEnd = src + srcOffset; while (src < srcEnd) { -#if defined(QT_ARCH_ARM) || defined(QT_ARCH_POWERPC) || (defined(QT_ARCH_WINDOWSCE) && !defined(_X86_)) - // non-16-bit aligned memory access is not possible on PowerPC & - // ARM <v6 (QT_ARCH_ARMV6) +#if defined(QT_ARCH_ARM) || defined(QT_ARCH_POWERPC) || defined(QT_ARCH_SH) || (defined(QT_ARCH_WINDOWSCE) && !defined(_X86_)) + // non-16-bit aligned memory access is not possible on PowerPC, + // ARM <v6 (QT_ARCH_ARMV6) & SH quint16 spix = (quint16(src[2])<<8) + src[1]; #else quint16 spix = *(quint16 *) (src + 1); diff --git a/src/gui/painting/qpaintengine_mac.cpp b/src/gui/painting/qpaintengine_mac.cpp index 793460f..f5f1bba 100644 --- a/src/gui/painting/qpaintengine_mac.cpp +++ b/src/gui/painting/qpaintengine_mac.cpp @@ -1381,8 +1381,13 @@ QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints) { Q_D(QCoreGraphicsPaintEngine); CGContextSetShouldAntialias(d->hd, hints & QPainter::Antialiasing); - CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ? - kCGInterpolationHigh : kCGInterpolationNone); + static const CGFloat ScaleFactor = qt_mac_get_scalefactor(); + if (ScaleFactor > 1.) { + CGContextSetInterpolationQuality(d->hd, kCGInterpolationHigh); + } else { + CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ? + kCGInterpolationHigh : kCGInterpolationNone); + } CGContextSetShouldSmoothFonts(d->hd, hints & QPainter::TextAntialiasing); } diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 37a88a3..4c35004 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -3353,6 +3353,7 @@ void QRasterPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textIte break; default: Q_ASSERT(false); + depth = 0; }; for(int i = 0; i < glyphs.size(); i++) { @@ -3380,6 +3381,7 @@ void QRasterPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textIte break; default: Q_ASSERT(false); + pitch = 0; }; alphaPenBlt(glyph->data, pitch, depth, diff --git a/src/gui/painting/qpdf.cpp b/src/gui/painting/qpdf.cpp index 664751a..178d519 100644 --- a/src/gui/painting/qpdf.cpp +++ b/src/gui/painting/qpdf.cpp @@ -48,6 +48,10 @@ #include "qprinterinfo.h" #include <qnumeric.h> +#ifdef Q_OS_UNIX +#include "private/qcore_unix_p.h" // overrides QT_OPEN +#endif + QT_BEGIN_NAMESPACE extern int qt_defaultDpi(); @@ -1647,7 +1651,7 @@ static void closeAllOpenFds() #endif // leave stdin/out/err untouched while(--i > 2) - ::close(i); + QT_CLOSE(i); } #endif @@ -1681,7 +1685,7 @@ bool QPdfBaseEnginePrivate::openPrintDevice() if (!printerName.isEmpty()) pr = printerName; int fds[2]; - if (pipe(fds) != 0) { + if (qt_safe_pipe(fds) != 0) { qWarning("QPdfPrinter: Could not open pipe to print"); return false; } @@ -1700,9 +1704,9 @@ bool QPdfBaseEnginePrivate::openPrintDevice() (void)execlp("true", "true", (char *)0); (void)execl("/bin/true", "true", (char *)0); (void)execl("/usr/bin/true", "true", (char *)0); - ::exit(0); + ::_exit(0); } - dup2(fds[0], 0); + qt_safe_dup2(fds[0], 0, 0); closeAllOpenFds(); @@ -1769,14 +1773,14 @@ bool QPdfBaseEnginePrivate::openPrintDevice() // wait for a second so the parent process (the // child of the GUI process) has exited. then // exit. - ::close(0); + QT_CLOSE(0); (void)::sleep(1); - ::exit(0); + ::_exit(0); } // parent process - ::close(fds[0]); + QT_CLOSE(fds[0]); fd = fds[1]; - (void)::waitpid(pid, 0, 0); + (void)qt_safe_waitpid(pid, 0, 0); if (fd < 0) return false; @@ -1923,7 +1927,7 @@ void QPdfBaseEnginePrivate::drawTextItem(const QPointF &p, const QTextItemInt &t #ifdef Q_WS_WIN if (ti.fontEngine->type() == QFontEngine::Win) { QFontEngineWin *fe = static_cast<QFontEngineWin *>(ti.fontEngine); - size = fe->tm.w.tmHeight; + size = fe->tm.tmHeight; } #endif diff --git a/src/gui/painting/qprintengine_pdf.cpp b/src/gui/painting/qprintengine_pdf.cpp index c1edcb3..b267860 100644 --- a/src/gui/painting/qprintengine_pdf.cpp +++ b/src/gui/painting/qprintengine_pdf.cpp @@ -655,7 +655,7 @@ void QPdfEnginePrivate::drawTextItem(const QPointF &p, const QTextItemInt &ti) #ifdef Q_WS_WIN if (ti.fontEngine->type() == QFontEngine::Win) { QFontEngineWin *fe = static_cast<QFontEngineWin *>(ti.fontEngine); - size = fe->tm.w.tmHeight; + size = fe->tm.tmHeight; } #endif int synthesized = ti.fontEngine->synthesized(); diff --git a/src/gui/painting/qprintengine_win.cpp b/src/gui/painting/qprintengine_win.cpp index 72faf7c..7b99e2f 100644 --- a/src/gui/painting/qprintengine_win.cpp +++ b/src/gui/painting/qprintengine_win.cpp @@ -199,33 +199,18 @@ bool QWin32PrintEngine::begin(QPaintDevice *pdev) if (d->printToFile && d->fileName.isEmpty()) d->fileName = d->port; - QT_WA({ - d->devModeW()->dmCopies = d->num_copies; - DOCINFO di; - memset(&di, 0, sizeof(DOCINFO)); - di.cbSize = sizeof(DOCINFO); - di.lpszDocName = reinterpret_cast<const wchar_t *>(d->docName.utf16()); - if (d->printToFile && !d->fileName.isEmpty()) - di.lpszOutput = reinterpret_cast<const wchar_t *>(d->fileName.utf16()); - if (ok && StartDoc(d->hdc, &di) == SP_ERROR) { - qErrnoWarning("QWin32PrintEngine::begin: StartDoc failed"); - ok = false; - } - } , { - d->devModeA()->dmCopies = d->num_copies; - DOCINFOA di; - memset(&di, 0, sizeof(DOCINFOA)); - di.cbSize = sizeof(DOCINFOA); - QByteArray docNameA = d->docName.toLocal8Bit(); - di.lpszDocName = docNameA.data(); - QByteArray outfileA = d->fileName.toLocal8Bit(); - if (d->printToFile && !d->fileName.isEmpty()) - di.lpszOutput = outfileA; - if (ok && StartDocA(d->hdc, &di) == SP_ERROR) { - qErrnoWarning("QWin32PrintEngine::begin: StartDoc failed"); - ok = false; - } - }); + d->devMode->dmCopies = d->num_copies; + + DOCINFO di; + memset(&di, 0, sizeof(DOCINFO)); + di.cbSize = sizeof(DOCINFO); + di.lpszDocName = reinterpret_cast<const wchar_t *>(d->docName.utf16()); + if (d->printToFile && !d->fileName.isEmpty()) + di.lpszOutput = reinterpret_cast<const wchar_t *>(d->fileName.utf16()); + if (ok && StartDoc(d->hdc, &di) == SP_ERROR) { + qErrnoWarning("QWin32PrintEngine::begin: StartDoc failed"); + ok = false; + } if (StartPage(d->hdc) <= 0) { qErrnoWarning("QWin32PrintEngine::begin: StartPage failed"); @@ -317,11 +302,6 @@ bool QWin32PrintEngine::newPage() bool success = false; if (d->hdc && d->state == QPrinter::Active) { -// bool restorePainter = false; -// if ((qWinVersion()& Qt::WV_DOS_based) && painter && painter->isActive()) { -// painter->save(); // EndPage/StartPage ruins the DC -// restorePainter = true; -// } if (EndPage(d->hdc) != SP_ERROR) { // reinitialize the DC before StartPage if needed, // because resetdc is disabled between calls to the StartPage and EndPage functions @@ -337,16 +317,10 @@ bool QWin32PrintEngine::newPage() } success = (StartPage(d->hdc) != SP_ERROR); } - if (!success) + if (!success) { d->state = QPrinter::Aborted; - -// if (qWinVersion() & Qt::WV_DOS_based) -// if (restorePainter) { -// painter->restore(); -// } - - if (!success) return false; + } } return true; } @@ -369,7 +343,7 @@ void QWin32PrintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem QRgb brushColor = state->pen().brush().color().rgb(); bool fallBack = state->pen().brush().style() != Qt::SolidPattern || qAlpha(brushColor) != 0xff - || QT_WA_INLINE(d->txop >= QTransform::TxProject, d->txop >= QTransform::TxScale) + || d->txop >= QTransform::TxProject || ti.fontEngine->type() != QFontEngine::Win; @@ -380,17 +354,10 @@ void QWin32PrintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem SelectObject(d->hdc, fe->hfont); if (GetDeviceCaps(d->hdc, TECHNOLOGY) != DT_CHARSTREAM) { - QT_WA({ - TCHAR n[64]; - GetTextFaceW(d->hdc, 64, n); - fallBack = QString::fromUtf16((ushort *)n) - != QString::fromUtf16((ushort *)fe->logfont.lfFaceName); - } , { - char an[64]; - GetTextFaceA(d->hdc, 64, an); - fallBack = QString::fromLocal8Bit(an) - != QString::fromLocal8Bit(((LOGFONTA*)(&fe->logfont))->lfFaceName); - }); + wchar_t n[64]; + GetTextFace(d->hdc, 64, n); + fallBack = QString::fromWCharArray(n) + != QString::fromWCharArray(fe->logfont.lfFaceName); } } @@ -861,7 +828,25 @@ void QWin32PrintEnginePrivate::fillPath_dev(const QPainterPath &path, const QCol void QWin32PrintEnginePrivate::strokePath_dev(const QPainterPath &path, const QColor &color, qreal penWidth) { composeGdiPath(path); - HPEN pen = CreatePen(PS_SOLID, qRound(penWidth), RGB(color.red(), color.green(), color.blue())); + LOGBRUSH brush; + brush.lbStyle = BS_SOLID; + brush.lbColor = RGB(color.red(), color.green(), color.blue()); + DWORD capStyle = PS_ENDCAP_SQUARE; + DWORD joinStyle = PS_JOIN_BEVEL; + if (pen.capStyle() == Qt::FlatCap) + capStyle = PS_ENDCAP_FLAT; + else if (pen.capStyle() == Qt::RoundCap) + capStyle = PS_ENDCAP_ROUND; + + if (pen.joinStyle() == Qt::MiterJoin) + joinStyle = PS_JOIN_MITER; + else if (pen.joinStyle() == Qt::RoundJoin) + joinStyle = PS_JOIN_ROUND; + + HPEN pen = ExtCreatePen(((penWidth == 0) ? PS_COSMETIC : PS_GEOMETRIC) + | PS_SOLID | capStyle | joinStyle, + penWidth, &brush, 0, 0); + HGDIOBJ old_pen = SelectObject(hdc, pen); StrokePath(hdc); DeleteObject(SelectObject(hdc, old_pen)); @@ -965,22 +950,14 @@ void QWin32PrintEnginePrivate::queryDefault() * Strings "windows" and "device" are specified in the MSDN under EnumPrinters() */ QString noPrinters(QLatin1String("qt_no_printers")); - QString output; - QT_WA({ - ushort buffer[256]; - GetProfileStringW(L"windows", L"device", - reinterpret_cast<const wchar_t *>(noPrinters.utf16()), - reinterpret_cast<wchar_t *>(buffer), 256); - output = QString::fromUtf16(buffer); - if (output.isEmpty() || output == noPrinters) // no printers - return; - }, { - char buffer[256]; - GetProfileStringA("windows", "device", noPrinters.toLatin1(), buffer, 256); - output = QString::fromLocal8Bit(buffer); - if (output.isEmpty() || output == noPrinters) // no printers - return; - }); + wchar_t buffer[256]; + GetProfileString(L"windows", L"device", + reinterpret_cast<const wchar_t *>(noPrinters.utf16()), + buffer, 256); + QString output = QString::fromWCharArray(buffer); + if (output.isEmpty() || output == noPrinters) // no printers + return; + QStringList info = output.split(QLatin1Char(',')); if (info.size() > 0) { if (name.isEmpty()) @@ -1012,13 +989,7 @@ void QWin32PrintEnginePrivate::initialize() txop = QTransform::TxNone; - bool ok; - QT_WA( { - ok = OpenPrinterW((LPWSTR)name.utf16(), (LPHANDLE)&hPrinter, 0); - }, { - ok = OpenPrinterA((LPSTR)name.toLatin1().data(), (LPHANDLE)&hPrinter, 0); - } ); - + bool ok = OpenPrinter((LPWSTR)name.utf16(), (LPHANDLE)&hPrinter, 0); if (!ok) { qErrnoWarning("QWin32PrintEngine::initialize: OpenPrinter failed"); return; @@ -1027,22 +998,10 @@ void QWin32PrintEnginePrivate::initialize() // Fetch the PRINTER_INFO_2 with DEVMODE data containing the // printer settings. DWORD infoSize, numBytes; - ok = true; - QT_WA( { - GetPrinterW(hPrinter, 2, NULL, 0, &infoSize); - hMem = GlobalAlloc(GHND, infoSize); - pInfo = GlobalLock(hMem); - if (!GetPrinterW(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes)) { - ok = false; - } - }, { - GetPrinterA(hPrinter, 2, NULL, 0, &infoSize); - hMem = GlobalAlloc(GHND, infoSize); - pInfo = GlobalLock(hMem); - if (!GetPrinterA(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes)) { - ok = false; - } - }); + GetPrinter(hPrinter, 2, NULL, 0, &infoSize); + hMem = GlobalAlloc(GHND, infoSize); + pInfo = (PRINTER_INFO_2*) GlobalLock(hMem); + ok = GetPrinter(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes); if (!ok) { qErrnoWarning("QWin32PrintEngine::initialize: GetPrinter failed"); @@ -1055,28 +1014,15 @@ void QWin32PrintEnginePrivate::initialize() return; } - QT_WA( { - devMode = pInfoW()->pDevMode; - }, { - devMode = pInfoA()->pDevMode; - } ); - - QT_WA( { - hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()), - reinterpret_cast<const wchar_t *>(name.utf16()), 0, devModeW()); - }, { - hdc = CreateDCA(program.toLatin1(), name.toLatin1(), 0, devModeA()); - } ); + devMode = pInfo->pDevMode; + hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()), + reinterpret_cast<const wchar_t *>(name.utf16()), 0, devMode); Q_ASSERT(hPrinter); Q_ASSERT(pInfo); if (devMode) { - QT_WA( { - num_copies = devModeW()->dmCopies; - }, { - num_copies = devModeA()->dmCopies; - } ); + num_copies = devMode->dmCopies; } initHDC(); @@ -1194,28 +1140,18 @@ void QWin32PrintEnginePrivate::release() QList<QVariant> QWin32PrintEnginePrivate::queryResolutions() const { // Read the supported resolutions of the printer. - DWORD numRes; - LONG *enumRes; - DWORD errRes; QList<QVariant> list; - QT_WA({ - numRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()), - reinterpret_cast<const wchar_t *>(port.utf16()), - DC_ENUMRESOLUTIONS, 0, 0); - if (numRes == (DWORD)-1) - return list; - enumRes = (LONG*)malloc(numRes * 2 * sizeof(LONG)); - errRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()), - reinterpret_cast<const wchar_t *>(port.utf16()), - DC_ENUMRESOLUTIONS, (LPWSTR)enumRes, 0); - }, { - numRes = DeviceCapabilitiesA(name.toLocal8Bit(), port.toLocal8Bit(), DC_ENUMRESOLUTIONS, 0, 0); - if (numRes == (DWORD)-1) - return list; - enumRes = (LONG*)malloc(numRes * 2 * sizeof(LONG)); - errRes = DeviceCapabilitiesA(name.toLocal8Bit(), port.toLocal8Bit(), DC_ENUMRESOLUTIONS, (LPSTR)enumRes, 0); - }); + DWORD numRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()), + reinterpret_cast<const wchar_t *>(port.utf16()), + DC_ENUMRESOLUTIONS, 0, 0); + if (numRes == (DWORD)-1) + return list; + + LONG *enumRes = (LONG*)malloc(numRes * 2 * sizeof(LONG)); + DWORD errRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()), + reinterpret_cast<const wchar_t *>(port.utf16()), + DC_ENUMRESOLUTIONS, (LPWSTR)enumRes, 0); if (errRes == (DWORD)-1) { qErrnoWarning("QWin32PrintEngine::queryResolutions: DeviceCapabilities failed"); @@ -1223,7 +1159,8 @@ QList<QVariant> QWin32PrintEnginePrivate::queryResolutions() const } for (uint i=0; i<numRes; ++i) - list.append(int(enumRes[i*2])); + list.append(int(enumRes[i * 2])); + return list; } @@ -1267,9 +1204,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & { if (!d->devMode) break; - short collate = value.toBool() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE; - QT_WA( { d->devModeW()->dmCollate = collate; }, - { d->devModeA()->dmCollate = collate; } ); + d->devMode->dmCollate = value.toBool() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE; d->doReinit(); } break; @@ -1278,8 +1213,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & { if (!d->devMode) break; - int cm = value.toInt() == QPrinter::Color ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME; - QT_WA( { d->devModeW()->dmColor = cm; }, { d->devModeA()->dmColor = cm; } ); + d->devMode->dmColor = (value.toInt() == QPrinter::Color) ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME; d->doReinit(); } break; @@ -1305,8 +1239,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & if (!d->devMode) break; d->num_copies = value.toInt(); - QT_WA( { d->devModeW()->dmCopies = d->num_copies; }, - { d->devModeA()->dmCopies = d->num_copies; }); + d->devMode->dmCopies = d->num_copies; d->doReinit(); break; @@ -1315,14 +1248,8 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & if (!d->devMode) break; int orientation = value.toInt() == QPrinter::Landscape ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT; - int old_orientation; - QT_WA( { - old_orientation = d->devModeW()->dmOrientation; - d->devModeW()->dmOrientation = orientation; - }, { - old_orientation = d->devModeA()->dmOrientation; - d->devModeA()->dmOrientation = orientation; - } ); + int old_orientation = d->devMode->dmOrientation; + d->devMode->dmOrientation = orientation; if (d->has_custom_paper_size && old_orientation != orientation) d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width()); d->doReinit(); @@ -1341,11 +1268,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & case PPK_PaperSize: if (!d->devMode) break; - QT_WA( { - d->devModeW()->dmPaperSize = mapPaperSizeDevmode(QPrinter::PaperSize(value.toInt())); - }, { - d->devModeA()->dmPaperSize = mapPaperSizeDevmode(QPrinter::PaperSize(value.toInt())); - } ); + d->devMode->dmPaperSize = mapPaperSizeDevmode(QPrinter::PaperSize(value.toInt())); d->has_custom_paper_size = (QPrinter::PaperSize(value.toInt()) == QPrinter::Custom); d->doReinit(); break; @@ -1360,11 +1283,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & if (v.contains(value)) dmMapped = mapPaperSourceDevmode(QPrinter::PaperSource(value.toInt())); - QT_WA( { - d->devModeW()->dmDefaultSource = dmMapped; - }, { - d->devModeA()->dmDefaultSource = dmMapped; - } ); + d->devMode->dmDefaultSource = dmMapped; d->doReinit(); } break; @@ -1398,11 +1317,7 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & if (!d->devMode) break; d->has_custom_paper_size = false; - QT_WA( { - d->devModeW()->dmPaperSize = value.toInt(); - }, { - d->devModeA()->dmPaperSize = value.toInt(); - } ); + d->devMode->dmPaperSize = value.toInt(); d->doReinit(); break; @@ -1412,33 +1327,28 @@ void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant & d->paper_size = value.toSizeF(); if (!d->devMode) break; - int orientation; - QT_WA( { - orientation = d->devModeW()->dmOrientation; - DWORD needed = 0; - DWORD returned = 0; - if (!EnumForms(d->hPrinter, 1, 0, 0, &needed, &returned)) { - BYTE *forms = (BYTE *) malloc(needed); - if (EnumForms(d->hPrinter, 1, forms, needed, &needed, &returned)) { - for (DWORD i=0; i< returned; ++i) { - FORM_INFO_1 *formArray = reinterpret_cast<FORM_INFO_1 *>(forms); - // the form sizes are specified in 1000th of a mm, - // convert the size to Points - QSizeF size((formArray[i].Size.cx * 72/25.4)/1000.0, - (formArray[i].Size.cy * 72/25.4)/1000.0); - if (qAbs(d->paper_size.width() - size.width()) <= 2 - && qAbs(d->paper_size.height() - size.height()) <= 2) - { - d->devModeW()->dmPaperSize = i+1; - break; - } + int orientation = d->devMode->dmOrientation; + DWORD needed = 0; + DWORD returned = 0; + if (!EnumForms(d->hPrinter, 1, 0, 0, &needed, &returned)) { + BYTE *forms = (BYTE *) malloc(needed); + if (EnumForms(d->hPrinter, 1, forms, needed, &needed, &returned)) { + for (DWORD i=0; i< returned; ++i) { + FORM_INFO_1 *formArray = reinterpret_cast<FORM_INFO_1 *>(forms); + // the form sizes are specified in 1000th of a mm, + // convert the size to Points + QSizeF size((formArray[i].Size.cx * 72/25.4)/1000.0, + (formArray[i].Size.cy * 72/25.4)/1000.0); + if (qAbs(d->paper_size.width() - size.width()) <= 2 + && qAbs(d->paper_size.height() - size.height()) <= 2) + { + d->devMode->dmPaperSize = i + 1; + break; } } - free(forms); } - }, { - orientation = d->devModeA()->dmOrientation; - } ); + free(forms); + } if (orientation != DMORIENT_PORTRAIT) d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width()); break; @@ -1478,13 +1388,7 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const if (!d->devMode) { value = QPrinter::Color; } else { - int mode; - QT_WA( { - mode = d->devModeW()->dmColor; - }, { - mode = d->devModeA()->dmColor; - } ); - value = mode == DMCOLOR_COLOR ? QPrinter::Color : QPrinter::GrayScale; + value = (d->devMode->dmColor == DMCOLOR_COLOR) ? QPrinter::Color : QPrinter::GrayScale; } } break; @@ -1506,9 +1410,7 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const if (!d->devMode) { value = QPrinter::Portrait; } else { - int o; - QT_WA( { o = d->devModeW()->dmOrientation; }, { o = d->devModeA()->dmOrientation; } ); - value = o == DMORIENT_LANDSCAPE ? QPrinter::Landscape : QPrinter::Portrait; + value = (d->devMode->dmOrientation == DMORIENT_LANDSCAPE) ? QPrinter::Landscape : QPrinter::Portrait; } } break; @@ -1542,11 +1444,7 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const if (!d->devMode) { value = QPrinter::A4; } else { - QT_WA( { - value = mapDevmodePaperSize(d->devModeW()->dmPaperSize); - }, { - value = mapDevmodePaperSize(d->devModeA()->dmPaperSize); - } ); + value = mapDevmodePaperSize(d->devMode->dmPaperSize); } } break; @@ -1565,11 +1463,7 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const if (!d->devMode) { value = QPrinter::Auto; } else { - QT_WA( { - value = mapDevmodePaperSource(d->devModeW()->dmDefaultSource); - }, { - value = mapDevmodePaperSource(d->devModeA()->dmDefaultSource); - } ); + value = mapDevmodePaperSource(d->devMode->dmDefaultSource); } break; @@ -1590,38 +1484,21 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const if (!d->devMode) { value = -1; } else { - QT_WA( { - value = d->devModeW()->dmPaperSize; - }, { - value = d->devModeA()->dmPaperSize; - } ); + value = d->devMode->dmPaperSize; } break; case PPK_PaperSources: { - int available, count; - WORD *data; - - QT_WA({ - available = DeviceCapabilitiesW((const WCHAR *)d->name.utf16(), (const WCHAR *)d->port.utf16(), DC_BINS, 0, - d->devModeW()); - }, { - available = DeviceCapabilitiesA(d->name.toLatin1(), d->port.toLatin1(), DC_BINS, 0, - d->devModeA()); - }); + int available = DeviceCapabilities((const wchar_t *)d->name.utf16(), + (const wchar_t *)d->port.utf16(), DC_BINS, 0, d->devMode); if (available <= 0) break; - data = (WORD *) malloc(available * sizeof(WORD)); - QT_WA({ - count = DeviceCapabilitiesW((const WCHAR *)d->name.utf16(), (const WCHAR *)d->port.utf16(), DC_BINS, (WCHAR *)data, - d->devModeW()); - }, { - count = DeviceCapabilitiesA(d->name.toLatin1(), d->port.toLatin1(), DC_BINS, - (char *) data, d->devModeA()); - }); + wchar_t *data = new wchar_t[available]; + int count = DeviceCapabilities((const wchar_t *)d->name.utf16(), + (const wchar_t *)d->port.utf16(), DC_BINS, data, d->devMode); QList<QVariant> out; for (int i=0; i<count; ++i) { @@ -1630,7 +1507,8 @@ QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const out << (int) src; } value = out; - free(data); + + delete [] data; } break; @@ -1675,24 +1553,23 @@ void QWin32PrintEngine::releaseDC(HDC) const HGLOBAL *QWin32PrintEnginePrivate::createDevNames() { - QT_WA( { - int size = sizeof(DEVNAMES) - + program.length() * 2 + 2 - + name.length() * 2 + 2 - + port.length() * 2 + 2; - HGLOBAL *hGlobal = (HGLOBAL *) GlobalAlloc(GMEM_MOVEABLE, size); - DEVNAMES *dn = (DEVNAMES*) GlobalLock(hGlobal); + int size = sizeof(DEVNAMES) + + program.length() * 2 + 2 + + name.length() * 2 + 2 + + port.length() * 2 + 2; + HGLOBAL *hGlobal = (HGLOBAL *) GlobalAlloc(GMEM_MOVEABLE, size); + DEVNAMES *dn = (DEVNAMES*) GlobalLock(hGlobal); - dn->wDriverOffset = sizeof(DEVNAMES) / sizeof(TCHAR); - dn->wDeviceOffset = dn->wDriverOffset + program.length() + 1; - dn->wOutputOffset = dn->wDeviceOffset + name.length() + 1; + dn->wDriverOffset = sizeof(DEVNAMES) / sizeof(wchar_t); + dn->wDeviceOffset = dn->wDriverOffset + program.length() + 1; + dn->wOutputOffset = dn->wDeviceOffset + name.length() + 1; - memcpy((ushort*)dn + dn->wDriverOffset, program.utf16(), program.length() * 2 + 2); - memcpy((ushort*)dn + dn->wDeviceOffset, name.utf16(), name.length() * 2 + 2); - memcpy((ushort*)dn + dn->wOutputOffset, port.utf16(), port.length() * 2 + 2); - dn->wDefault = 0; + memcpy((ushort*)dn + dn->wDriverOffset, program.utf16(), program.length() * 2 + 2); + memcpy((ushort*)dn + dn->wDeviceOffset, name.utf16(), name.length() * 2 + 2); + memcpy((ushort*)dn + dn->wOutputOffset, port.utf16(), port.length() * 2 + 2); + dn->wDefault = 0; - GlobalUnlock(hGlobal); + GlobalUnlock(hGlobal); // printf("QPrintDialogWinPrivate::createDevNames()\n" // " -> wDriverOffset: %d\n" @@ -1703,89 +1580,46 @@ HGLOBAL *QWin32PrintEnginePrivate::createDevNames() // dn->wOutputOffset); // printf("QPrintDialogWinPrivate::createDevNames(): %s, %s, %s\n", -// QString::fromUtf16((ushort*)(dn) + dn->wDriverOffset).latin1(), -// QString::fromUtf16((ushort*)(dn) + dn->wDeviceOffset).latin1(), -// QString::fromUtf16((ushort*)(dn) + dn->wOutputOffset).latin1()); - - return hGlobal; - }, { - int size = sizeof(DEVNAMES) - + program.length() + 2 - + name.length() + 2 - + port.length() + 2; - HGLOBAL *hGlobal = (HGLOBAL *) GlobalAlloc(GMEM_MOVEABLE, size); - DEVNAMES *dn = (DEVNAMES*) GlobalLock(hGlobal); - - dn->wDriverOffset = sizeof(DEVNAMES); - dn->wDeviceOffset = dn->wDriverOffset + program.length() + 1; - dn->wOutputOffset = dn->wDeviceOffset + name.length() + 1; - - memcpy((char*)dn + dn->wDriverOffset, program.toLatin1(), program.length() + 2); - memcpy((char*)dn + dn->wDeviceOffset, name.toLatin1(), name.length() + 2); - memcpy((char*)dn + dn->wOutputOffset, port.toLatin1(), port.length() + 2); - dn->wDefault = 0; - - GlobalUnlock(hGlobal); - return hGlobal; - } ); +// QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset).latin1(), +// QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset).latin1(), +// QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset).latin1()); + + return hGlobal; } void QWin32PrintEnginePrivate::readDevnames(HGLOBAL globalDevnames) { if (globalDevnames) { - QT_WA( { - DEVNAMES *dn = (DEVNAMES*) GlobalLock(globalDevnames); - name = QString::fromUtf16((ushort*)(dn) + dn->wDeviceOffset); - port = QString::fromUtf16((ushort*)(dn) + dn->wOutputOffset); - program = QString::fromUtf16((ushort*)(dn) + dn->wDriverOffset); - GlobalUnlock(globalDevnames); - }, { - DEVNAMES *dn = (DEVNAMES*) GlobalLock(globalDevnames); - name = QString::fromLatin1((char*)(dn) + dn->wDeviceOffset); - port = QString::fromLatin1((char*)(dn) + dn->wOutputOffset); - program = QString::fromLatin1((char*)(dn) + dn->wDriverOffset); - GlobalUnlock(globalDevnames); - } ); + DEVNAMES *dn = (DEVNAMES*) GlobalLock(globalDevnames); + name = QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset); + port = QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset); + program = QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset); + GlobalUnlock(globalDevnames); } } void QWin32PrintEnginePrivate::readDevmode(HGLOBAL globalDevmode) { if (globalDevmode) { - QT_WA( { - DEVMODE *dm = (DEVMODE*) GlobalLock(globalDevmode); - release(); - globalDevMode = globalDevmode; - devMode = dm; - hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()), - reinterpret_cast<const wchar_t *>(name.utf16()), 0, dm); - - num_copies = devModeW()->dmCopies; - if (!OpenPrinterW((LPWSTR)name.utf16(), (LPHANDLE)&hPrinter, 0)) - qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE."); - }, { - DEVMODEA *dm = (DEVMODEA*) GlobalLock(globalDevmode); - release(); - globalDevMode = globalDevmode; - devMode = dm; - hdc = CreateDCA(program.toLatin1(), name.toLatin1(), 0, dm); - - num_copies = devModeA()->dmCopies; - if (!OpenPrinterA((LPSTR)name.toLatin1().data(), (LPHANDLE)&hPrinter, 0)) - qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE."); - } ); + DEVMODE *dm = (DEVMODE*) GlobalLock(globalDevmode); + release(); + globalDevMode = globalDevmode; + devMode = dm; + hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()), + reinterpret_cast<const wchar_t *>(name.utf16()), 0, dm); + + num_copies = devMode->dmCopies; + if (!OpenPrinter((wchar_t*)name.utf16(), &hPrinter, 0)) + qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE."); } if (hdc) initHDC(); } -static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC hdc, +static void draw_text_item_win(const QPointF &pos, const QTextItemInt &ti, HDC hdc, bool convertToText, const QTransform &xform, const QPointF &topLeft) { - - // Make sure we translate for systems that can't handle world transforms - QPointF pos(QT_WA_INLINE(_pos, _pos + QPointF(xform.dx(), xform.dy()))); QFontEngine *fe = ti.fontEngine; QPointF baseline_pos = xform.inverted().map(xform.map(pos) - topLeft); @@ -1797,12 +1631,10 @@ static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC HFONT hfont; bool ttf = false; - bool useTextOutA = false; if (winfe) { hfont = winfe->hfont; ttf = winfe->ttf; - useTextOutA = winfe->useTextOutA; } else { hfont = (HFONT)GetStockObject(ANSI_VAR_FONT); } @@ -1812,153 +1644,115 @@ static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC wchar_t *convertedGlyphs = (wchar_t *)ti.chars; QGlyphLayout glyphs = ti.glyphs; - if (!(ti.flags & QTextItem::RightToLeft) && useTextOutA) { - qreal x = pos.x(); - qreal y = pos.y(); - - // hack to get symbol fonts working on Win95. See also QFontEngine constructor - // can only happen if !ttf - for(int i = 0; i < glyphs.numGlyphs; i++) { - QString str(QChar(glyphs.glyphs[i])); - QT_WA({ - TextOutW(hdc, qRound(x + glyphs.offsets[i].x.toReal()), - qRound(y + glyphs.offsets[i].y.toReal()), - (LPWSTR)str.utf16(), str.length()); - } , { - QByteArray cstr = str.toLocal8Bit(); - TextOutA(hdc, qRound(x + glyphs.offsets[i].x.toReal()), - qRound(y + glyphs.offsets[i].y.toReal()), - cstr.data(), cstr.length()); - }); - x += glyphs.effectiveAdvance(i).toReal(); - } - } else { - bool fast = !has_kerning && !(ti.flags & QTextItem::RightToLeft); - for(int i = 0; fast && i < glyphs.numGlyphs; i++) { - if (glyphs.offsets[i].x != 0 || glyphs.offsets[i].y != 0 || glyphs.justifications[i].space_18d6 != 0 - || glyphs.attributes[i].dontPrint) { - fast = false; - break; - } + bool fast = !has_kerning && !(ti.flags & QTextItem::RightToLeft); + for (int i = 0; fast && i < glyphs.numGlyphs; i++) { + if (glyphs.offsets[i].x != 0 || glyphs.offsets[i].y != 0 || glyphs.justifications[i].space_18d6 != 0 + || glyphs.attributes[i].dontPrint) { + fast = false; + break; } + } #if !defined(Q_OS_WINCE) - // Scale, rotate and translate here. This is only valid for systems > Windows Me. - // We should never get here on Windows Me or lower if the transformation specifies - // scaling or rotation. - QT_WA({ - XFORM win_xform; - win_xform.eM11 = xform.m11(); - win_xform.eM12 = xform.m12(); - win_xform.eM21 = xform.m21(); - win_xform.eM22 = xform.m22(); - win_xform.eDx = xform.dx(); - win_xform.eDy = xform.dy(); - SetGraphicsMode(hdc, GM_ADVANCED); - SetWorldTransform(hdc, &win_xform); - }, { - // nothing - }); + // Scale, rotate and translate here. + XFORM win_xform; + win_xform.eM11 = xform.m11(); + win_xform.eM12 = xform.m12(); + win_xform.eM21 = xform.m21(); + win_xform.eM22 = xform.m22(); + win_xform.eDx = xform.dx(); + win_xform.eDy = xform.dy(); + + SetGraphicsMode(hdc, GM_ADVANCED); + SetWorldTransform(hdc, &win_xform); #endif - if (fast) { - // fast path - QVarLengthArray<wchar_t> g(glyphs.numGlyphs); - for (int i = 0; i < glyphs.numGlyphs; ++i) - g[i] = glyphs.glyphs[i]; - ExtTextOutW(hdc, - qRound(baseline_pos.x() + glyphs.offsets[0].x.toReal()), - qRound(baseline_pos.y() + glyphs.offsets[0].y.toReal()), - options, 0, convertToText ? convertedGlyphs : g.data(), glyphs.numGlyphs, 0); - } else { - QVarLengthArray<QFixedPoint> positions; - QVarLengthArray<glyph_t> _glyphs; - - QTransform matrix = QTransform::fromTranslate(baseline_pos.x(), baseline_pos.y()); - ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, - _glyphs, positions); - if (_glyphs.size() == 0) { - SelectObject(hdc, old_font); - return; - } - - convertToText = convertToText && glyphs.numGlyphs == _glyphs.size(); - - bool outputEntireItem = (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) - && QSysInfo::WindowsVersion != QSysInfo::WV_NT - && _glyphs.size() > 0; + if (fast) { + // fast path + QVarLengthArray<wchar_t> g(glyphs.numGlyphs); + for (int i = 0; i < glyphs.numGlyphs; ++i) + g[i] = glyphs.glyphs[i]; + ExtTextOut(hdc, + qRound(baseline_pos.x() + glyphs.offsets[0].x.toReal()), + qRound(baseline_pos.y() + glyphs.offsets[0].y.toReal()), + options, 0, convertToText ? convertedGlyphs : g.data(), glyphs.numGlyphs, 0); + } else { + QVarLengthArray<QFixedPoint> positions; + QVarLengthArray<glyph_t> _glyphs; + + QTransform matrix = QTransform::fromTranslate(baseline_pos.x(), baseline_pos.y()); + ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, + _glyphs, positions); + if (_glyphs.size() == 0) { + SelectObject(hdc, old_font); + return; + } - if (outputEntireItem) { - options |= ETO_PDY; - QVarLengthArray<INT> glyphDistances(_glyphs.size() * 2); - QVarLengthArray<wchar_t> g(_glyphs.size()); - for (int i=0; i<_glyphs.size() - 1; ++i) { - glyphDistances[i * 2] = qRound(positions[i + 1].x) - qRound(positions[i].x); - glyphDistances[i * 2 + 1] = qRound(positions[i + 1].y) - qRound(positions[i].y); - g[i] = _glyphs[i]; - } - glyphDistances[(_glyphs.size() - 1) * 2] = 0; - glyphDistances[(_glyphs.size() - 1) * 2 + 1] = 0; - g[_glyphs.size() - 1] = _glyphs[_glyphs.size() - 1]; - ExtTextOutW(hdc, qRound(positions[0].x), qRound(positions[0].y), options, 0, - convertToText ? convertedGlyphs : g.data(), _glyphs.size(), - glyphDistances.data()); - } else { - int i = 0; - while(i < _glyphs.size()) { - wchar_t g = _glyphs[i]; - - ExtTextOutW(hdc, qRound(positions[i].x), - qRound(positions[i].y), options, 0, - convertToText ? convertedGlyphs + i : &g, 1, 0); - ++i; - } + convertToText = convertToText && glyphs.numGlyphs == _glyphs.size(); + bool outputEntireItem = _glyphs.size() > 0; + + if (outputEntireItem) { + options |= ETO_PDY; + QVarLengthArray<INT> glyphDistances(_glyphs.size() * 2); + QVarLengthArray<wchar_t> g(_glyphs.size()); + for (int i=0; i<_glyphs.size() - 1; ++i) { + glyphDistances[i * 2] = qRound(positions[i + 1].x) - qRound(positions[i].x); + glyphDistances[i * 2 + 1] = qRound(positions[i + 1].y) - qRound(positions[i].y); + g[i] = _glyphs[i]; + } + glyphDistances[(_glyphs.size() - 1) * 2] = 0; + glyphDistances[(_glyphs.size() - 1) * 2 + 1] = 0; + g[_glyphs.size() - 1] = _glyphs[_glyphs.size() - 1]; + ExtTextOut(hdc, qRound(positions[0].x), qRound(positions[0].y), options, 0, + convertToText ? convertedGlyphs : g.data(), _glyphs.size(), + glyphDistances.data()); + } else { + int i = 0; + while(i < _glyphs.size()) { + wchar_t g = _glyphs[i]; + + ExtTextOut(hdc, qRound(positions[i].x), + qRound(positions[i].y), options, 0, + convertToText ? convertedGlyphs + i : &g, 1, 0); + ++i; } } + } #if !defined(Q_OS_WINCE) - QT_WA({ - XFORM win_xform; - win_xform.eM11 = win_xform.eM22 = 1.0; - win_xform.eM12 = win_xform.eM21 = win_xform.eDx = win_xform.eDy = 0.0; - SetWorldTransform(hdc, &win_xform); - }, { - // nothing - }); + win_xform.eM11 = win_xform.eM22 = 1.0; + win_xform.eM12 = win_xform.eM21 = win_xform.eDx = win_xform.eDy = 0.0; + SetWorldTransform(hdc, &win_xform); #endif - } + SelectObject(hdc, old_font); } void QWin32PrintEnginePrivate::updateCustomPaperSize() { - QT_WA( { - uint paperSize = devModeW()->dmPaperSize; - if (paperSize > 0 && mapDevmodePaperSize(paperSize) == QPrinter::Custom) { - has_custom_paper_size = true; - DWORD needed = 0; - DWORD returned = 0; - if (!EnumForms(hPrinter, 1, 0, 0, &needed, &returned)) { - BYTE *forms = (BYTE *) malloc(needed); - if (EnumForms(hPrinter, 1, forms, needed, &needed, &returned)) { - if (paperSize <= returned) { - FORM_INFO_1 *formArray = (FORM_INFO_1 *) forms; - int width = formArray[paperSize-1].Size.cx; // 1/1000 of a mm - int height = formArray[paperSize-1].Size.cy; // 1/1000 of a mm - paper_size = QSizeF((width*72/25.4)/1000.0, (height*72/25.4)/1000.0); - } else { - has_custom_paper_size = false; - } + uint paperSize = devMode->dmPaperSize; + if (paperSize > 0 && mapDevmodePaperSize(paperSize) == QPrinter::Custom) { + has_custom_paper_size = true; + DWORD needed = 0; + DWORD returned = 0; + if (!EnumForms(hPrinter, 1, 0, 0, &needed, &returned)) { + BYTE *forms = (BYTE *) malloc(needed); + if (EnumForms(hPrinter, 1, forms, needed, &needed, &returned)) { + if (paperSize <= returned) { + FORM_INFO_1 *formArray = (FORM_INFO_1 *) forms; + int width = formArray[paperSize - 1].Size.cx; // 1/1000 of a mm + int height = formArray[paperSize - 1].Size.cy; // 1/1000 of a mm + paper_size = QSizeF((width * 72 /25.4) / 1000.0, (height * 72 / 25.4) / 1000.0); + } else { + has_custom_paper_size = false; } - free(forms); } - } else { - has_custom_paper_size = false; + free(forms); } - }, { - // Not supported under Win98 - } ); + } else { + has_custom_paper_size = false; + } } QT_END_NAMESPACE diff --git a/src/gui/painting/qprintengine_win_p.h b/src/gui/painting/qprintengine_win_p.h index 9eb0b69..36a32e8 100644 --- a/src/gui/painting/qprintengine_win_p.h +++ b/src/gui/painting/qprintengine_win_p.h @@ -169,18 +169,8 @@ public: void readDevmode(HGLOBAL globalDevmode); void readDevnames(HGLOBAL globalDevnames); - inline DEVMODEW *devModeW() const { return (DEVMODEW*) devMode; } - inline DEVMODEA *devModeA() const { return (DEVMODEA*) devMode; } - - inline PRINTER_INFO_2W *pInfoW() { return (PRINTER_INFO_2W*) pInfo; }; - inline PRINTER_INFO_2A *pInfoA() { return (PRINTER_INFO_2A*) pInfo; }; - inline bool resetDC() { - QT_WA( { - hdc = ResetDCW(hdc, devModeW()); - }, { - hdc = ResetDCA(hdc, devModeA()); - } ); + hdc = ResetDC(hdc, devMode); return hdc != 0; } @@ -202,8 +192,8 @@ public: HANDLE hPrinter; HGLOBAL globalDevMode; - void *devMode; - void *pInfo; + DEVMODE *devMode; + PRINTER_INFO_2 *pInfo; HGLOBAL hMem; HDC hdc; diff --git a/src/gui/painting/qprinterinfo_win.cpp b/src/gui/painting/qprinterinfo_win.cpp index f0352e6..a10cf3f 100644 --- a/src/gui/painting/qprinterinfo_win.cpp +++ b/src/gui/painting/qprinterinfo_win.cpp @@ -79,45 +79,24 @@ QList<QPrinterInfo> QPrinterInfo::availablePrinters() DWORD needed = 0; DWORD returned = 0; - QT_WA({ - if (!EnumPrintersW(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, - 4, 0, 0, &needed, &returned)) - { - buffer = new BYTE[needed]; - if (!EnumPrintersW(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, - 4, buffer, needed, &needed, &returned)) - { - delete [] buffer; - return printers; - } - PPRINTER_INFO_4 infoList = reinterpret_cast<PPRINTER_INFO_4>(buffer); - QPrinterInfo defPrn = defaultPrinter(); - for (uint i = 0; i < returned; ++i) { - printers.append(QPrinterInfo(QString::fromUtf16(reinterpret_cast<const ushort*>(infoList[i].pPrinterName)))); - if (printers.at(i).printerName() == defPrn.printerName()) - printers[i].d_ptr->m_default = true; - } - delete [] buffer; - } - }, { - // In Windows 98 networked printers are served through the local connection - if (!EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 5, 0, 0, &needed, &returned)) { - buffer = new BYTE[needed]; - if (!EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 5, buffer, needed, &needed, &returned)) { - delete [] buffer; - return printers; - } - - PPRINTER_INFO_5 infoList = reinterpret_cast<PPRINTER_INFO_5>(buffer); - QPrinterInfo defPrn = defaultPrinter(); - for (uint i = 0; i < returned; ++i) { - printers.append(QPrinterInfo(QString::fromLocal8Bit(reinterpret_cast<const char*>(infoList[i].pPrinterName)))); - if (printers.at(i).printerName() == defPrn.printerName()) - printers[i].d_ptr->m_default = true; - } - delete [] buffer; - } - }); + if ( !EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, 4, 0, 0, &needed, &returned)) + { + buffer = new BYTE[needed]; + if (!EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, + 4, buffer, needed, &needed, &returned)) + { + delete [] buffer; + return printers; + } + PPRINTER_INFO_4 infoList = reinterpret_cast<PPRINTER_INFO_4>(buffer); + QPrinterInfo defPrn = defaultPrinter(); + for (uint i = 0; i < returned; ++i) { + printers.append(QPrinterInfo(QString::fromWCharArray(infoList[i].pPrinterName))); + if (printers.at(i).printerName() == defPrn.printerName()) + printers[i].d_ptr->m_default = true; + } + delete [] buffer; + } return printers; } @@ -125,18 +104,9 @@ QList<QPrinterInfo> QPrinterInfo::availablePrinters() QPrinterInfo QPrinterInfo::defaultPrinter() { QString noPrinters(QLatin1String("qt_no_printers")); - QString output; - QT_WA({ - ushort buffer[256]; - GetProfileStringW(L"windows", L"device", - reinterpret_cast<const wchar_t *>(noPrinters.utf16()), - reinterpret_cast<wchar_t *>(buffer), 256); - output = QString::fromUtf16(buffer); - }, { - char buffer[256]; - GetProfileStringA("windows", "device", noPrinters.toLatin1(), buffer, 256); - output = QString::fromLocal8Bit(buffer); - }); + wchar_t buffer[256]; + GetProfileString(L"windows", L"device", (wchar_t*)noPrinters.utf16(), buffer, 256); + QString output = QString::fromWCharArray(buffer); // Filter out the name of the printer, which should be everything // before a comma. @@ -222,26 +192,16 @@ bool QPrinterInfo::isDefault() const QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const { const Q_D(QPrinterInfo); - DWORD size; - WORD* papers; QList<QPrinter::PaperSize> paperList; - QT_WA({ - size = DeviceCapabilitiesW(reinterpret_cast<const WCHAR*>(d->m_name.utf16()), - NULL, DC_PAPERS, NULL, NULL); - if ((int)size == -1) - return paperList; - papers = new WORD[size]; - size = DeviceCapabilitiesW(reinterpret_cast<const WCHAR*>(d->m_name.utf16()), - NULL, DC_PAPERS, reinterpret_cast<WCHAR*>(papers), NULL); - }, { - size = DeviceCapabilitiesA(d->m_name.toLatin1().data(), NULL, DC_PAPERS, NULL, NULL); - if ((int)size == -1) - return paperList; - papers = new WORD[size]; - size = DeviceCapabilitiesA(d->m_name.toLatin1().data(), NULL, DC_PAPERS, - reinterpret_cast<char*>(papers), NULL); - }); + DWORD size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->m_name.utf16()), + NULL, DC_PAPERS, NULL, NULL); + if ((int)size == -1) + return paperList; + + wchar_t *papers = new wchar_t[size]; + size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->m_name.utf16()), + NULL, DC_PAPERS, papers, NULL); for (int c = 0; c < (int)size; ++c) { paperList.append(mapDevmodePaperSize(papers[c])); diff --git a/src/gui/painting/qregion.cpp b/src/gui/painting/qregion.cpp index 1b7dc1b..762e9e0 100644 --- a/src/gui/painting/qregion.cpp +++ b/src/gui/painting/qregion.cpp @@ -92,10 +92,6 @@ QT_BEGIN_NAMESPACE Example of using complex regions: \snippet doc/src/snippets/code/src_gui_painting_qregion.cpp 0 - \warning Due to window system limitations, the whole coordinate space for a - region is limited to the points between -32767 and 32767 on Windows - 95/98/ME. You can circumvent this limitation by using a QPainterPath. - \section1 Additional License Information On Embedded Linux, Windows CE and X11 platforms, parts of this class rely on diff --git a/src/gui/painting/qwindowsurface_raster.cpp b/src/gui/painting/qwindowsurface_raster.cpp index c163d79..22433dd 100644 --- a/src/gui/painting/qwindowsurface_raster.cpp +++ b/src/gui/painting/qwindowsurface_raster.cpp @@ -43,6 +43,7 @@ #include <qglobal.h> // for Q_WS_WIN define (non-PCH) #ifdef Q_WS_WIN +#include <qlibrary.h> #include <qt_windows.h> #endif @@ -67,10 +68,6 @@ QT_BEGIN_NAMESPACE -#ifdef Q_WS_WIN -PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect; -#endif - class QRasterWindowSurfacePrivate { public: @@ -82,9 +79,6 @@ public: uint translucentBackground : 1; #endif #endif -#if defined(Q_WS_WIN) && !defined(Q_WS_WINCE) - uint canUseLayeredWindow : 1; -#endif uint inSetGeometry : 1; }; @@ -98,10 +92,6 @@ QRasterWindowSurface::QRasterWindowSurface(QWidget *window) && window->x11Info().depth() == 32; #endif #endif -#if defined(Q_WS_WIN) && !defined(Q_WS_WINCE) - d_ptr->canUseLayeredWindow = ptrUpdateLayeredWindowIndirect - && (qt_widget_private(window)->data.window_flags & Qt::FramelessWindowHint); -#endif d_ptr->image = 0; d_ptr->inSetGeometry = false; setStaticContentsSupport(true); @@ -130,8 +120,7 @@ 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 defined(Q_WS_WIN) && !defined(Q_WS_WINCE) - if (d_ptr->image->image.format() != QImage::Format_ARGB32_Premultiplied - && d_ptr->canUseLayeredWindow) + if (d_ptr->image->image.format() != QImage::Format_ARGB32_Premultiplied) prepareBuffer(QImage::Format_ARGB32_Premultiplied, window()); #endif QPainter p(&d_ptr->image->image); @@ -160,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 && d->canUseLayeredWindow) { + if (!qt_widget_private(window())->isOpaque) { QRect r = window()->frameGeometry(); QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft(); QRect dirtyRect = br.translated(offset + frameOffset); @@ -168,12 +157,11 @@ void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoi SIZE size = {r.width(), r.height()}; POINT ptDst = {r.x(), r.y()}; POINT ptSrc = {0, 0}; - Q_BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA}; + BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA}; RECT dirty = {dirtyRect.x(), dirtyRect.y(), dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()}; Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, d->image->hdc, &ptSrc, 0, &blend, Q_ULW_ALPHA, &dirty}; - - (*ptrUpdateLayeredWindowIndirect)(window()->internalWinId(), &info); + ptrUpdateLayeredWindowIndirect(window()->internalWinId(), &info); } else #endif { @@ -308,7 +296,7 @@ void QRasterWindowSurface::setGeometry(const QRect &rect) #ifndef Q_WS_WIN if (d_ptr->translucentBackground) #else - if (!qt_widget_private(window())->isOpaque && d->canUseLayeredWindow) + if (!qt_widget_private(window())->isOpaque) #endif prepareBuffer(QImage::Format_ARGB32_Premultiplied, window()); else diff --git a/src/gui/painting/qwindowsurface_raster_p.h b/src/gui/painting/qwindowsurface_raster_p.h index 897ed8d..996aaef 100644 --- a/src/gui/painting/qwindowsurface_raster_p.h +++ b/src/gui/painting/qwindowsurface_raster_p.h @@ -64,13 +64,6 @@ QT_BEGIN_NAMESPACE #define Q_ULW_ALPHA 0x00000002 // copied from ULW_ALPHA in winuser.h #define Q_AC_SRC_ALPHA 0x00000001 // copied from AC_SRC_ALPHA in winuser.h -struct Q_BLENDFUNCTION { - BYTE BlendOp; - BYTE BlendFlags; - BYTE SourceConstantAlpha; - BYTE AlphaFormat; -}; - struct Q_UPDATELAYEREDWINDOWINFO { DWORD cbSize; HDC hdcDst; @@ -79,12 +72,16 @@ struct Q_UPDATELAYEREDWINDOWINFO { HDC hdcSrc; const POINT *pptSrc; COLORREF crKey; - const Q_BLENDFUNCTION *pblend; + const BLENDFUNCTION *pblend; DWORD dwFlags; const RECT *prcDirty; }; +typedef BOOL (WINAPI *PtrUpdateLayeredWindow)(HWND hwnd, HDC hdcDst, const POINT *pptDst, + const SIZE *psize, HDC hdcSrc, const POINT *pptSrc, COLORREF crKey, + const BLENDFUNCTION *pblend, DWORD dwflags); typedef BOOL (WINAPI *PtrUpdateLayeredWindowIndirect)(HWND hwnd, const Q_UPDATELAYEREDWINDOWINFO *pULWInfo); +extern PtrUpdateLayeredWindow ptrUpdateLayeredWindow; extern PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect; #endif diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index ed3bdb5..7b8b75e 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -4535,17 +4535,17 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid ret = 0; break; case PM_DialogButtonsSeparator: - ret = 5; + ret = int(QStyleHelper::dpiScaled(5.)); break; case PM_DialogButtonsButtonWidth: - ret = 70; + ret = int(QStyleHelper::dpiScaled(70.)); break; case PM_DialogButtonsButtonHeight: - ret = 30; + ret = int(QStyleHelper::dpiScaled(30.)); break; case PM_CheckListControllerSize: case PM_CheckListButtonSize: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_TitleBarHeight: { if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) { @@ -4553,26 +4553,26 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid ret = qMax(widget ? widget->fontMetrics().lineSpacing() : opt->fontMetrics.lineSpacing(), 16); #ifndef QT_NO_DOCKWIDGET } else if (qobject_cast<const QDockWidget*>(widget)) { - ret = qMax(widget->fontMetrics().lineSpacing(), 13); + ret = qMax(widget->fontMetrics().lineSpacing(), int(QStyleHelper::dpiScaled(13))); #endif } else { ret = qMax(widget ? widget->fontMetrics().lineSpacing() : opt->fontMetrics.lineSpacing(), 18); } } else { - ret = 18; + ret = int(QStyleHelper::dpiScaled(18.)); } break; } case PM_ScrollBarSliderMin: - ret = 9; + ret = int(QStyleHelper::dpiScaled(9.)); break; case PM_ButtonMargin: - ret = 6; + ret = int(QStyleHelper::dpiScaled(6.)); break; case PM_DockWidgetTitleBarButtonMargin: - ret = 2; + ret = int(QStyleHelper::dpiScaled(2.)); break; case PM_ButtonDefaultIndicator: @@ -4580,7 +4580,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_MenuButtonIndicator: - ret = 12; + ret = int(QStyleHelper::dpiScaled(12.)); break; case PM_ButtonShiftHorizontal: @@ -4599,11 +4599,11 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_MdiSubWindowFrameWidth: - ret = 4; + ret = int(QStyleHelper::dpiScaled(4.)); break; case PM_MdiSubWindowMinimizedWidth: - ret = 196; + ret = int(QStyleHelper::dpiScaled(196.)); break; #ifndef QT_NO_SCROLLBAR @@ -4614,7 +4614,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid : QApplication::globalStrut().width(); ret = qMax(16, s); } else { - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); } break; #endif @@ -4624,7 +4624,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid #ifndef QT_NO_SLIDER case PM_SliderThickness: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_SliderTickmarkOffset: @@ -4658,11 +4658,11 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid #endif // QT_NO_SLIDER #ifndef QT_NO_DOCKWIDGET case PM_DockWidgetSeparatorExtent: - ret = 6; + ret = int(QStyleHelper::dpiScaled(6.)); break; case PM_DockWidgetHandleExtent: - ret = 8; + ret = int(QStyleHelper::dpiScaled(8.)); break; case PM_DockWidgetTitleMargin: ret = 0; @@ -4691,19 +4691,19 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_ToolBarItemSpacing: - ret = 4; + ret = int(QStyleHelper::dpiScaled(4.)); break; case PM_ToolBarHandleExtent: - ret = 8; + ret = int(QStyleHelper::dpiScaled(8.)); break; case PM_ToolBarSeparatorExtent: - ret = 6; + ret = int(QStyleHelper::dpiScaled(6.)); break; case PM_ToolBarExtensionExtent: - ret = 12; + ret = int(QStyleHelper::dpiScaled(12.)); break; #endif // QT_NO_TOOLBAR @@ -4713,7 +4713,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_TabBarTabHSpace: - ret = 24; + ret = int(QStyleHelper::dpiScaled(24.)); break; case PM_TabBarTabShiftHorizontal: @@ -4742,27 +4742,27 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_IndicatorWidth: - ret = 13; + ret = int(QStyleHelper::dpiScaled(13.)); break; case PM_IndicatorHeight: - ret = 13; + ret = int(QStyleHelper::dpiScaled(13.)); break; case PM_ExclusiveIndicatorWidth: - ret = 12; + ret = int(QStyleHelper::dpiScaled(12.)); break; case PM_ExclusiveIndicatorHeight: - ret = 12; + ret = int(QStyleHelper::dpiScaled(12.)); break; case PM_MenuTearoffHeight: - ret = 10; + ret = int(QStyleHelper::dpiScaled(10.)); break; case PM_MenuScrollerHeight: - ret = 10; + ret = int(QStyleHelper::dpiScaled(10.)); break; case PM_MenuDesktopFrameWidth: @@ -4772,16 +4772,16 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_HeaderMargin: - ret = 4; + ret = int(QStyleHelper::dpiScaled(4.)); break; case PM_HeaderMarkSize: - ret = 32; + ret = int(QStyleHelper::dpiScaled(32.)); break; case PM_HeaderGripMargin: - ret = 4; + ret = int(QStyleHelper::dpiScaled(4.)); break; case PM_TabBarScrollButtonWidth: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_LayoutLeftMargin: case PM_LayoutTopMargin: @@ -4803,13 +4803,13 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_DefaultTopLevelMargin: - ret = 11; + ret = int(QStyleHelper::dpiScaled(11.)); break; case PM_DefaultChildMargin: - ret = 9; + ret = int(QStyleHelper::dpiScaled(9.)); break; case PM_DefaultLayoutSpacing: - ret = 6; + ret = int(QStyleHelper::dpiScaled(6.)); break; case PM_TabBarIconSize: @@ -4820,14 +4820,14 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid case PM_ButtonIconSize: case PM_SmallIconSize: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_IconViewIconSize: ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget); break; case PM_LargeIconSize: - ret = 32; + ret = int(QStyleHelper::dpiScaled(32.)); break; case PM_ToolTipLabelFrameWidth: @@ -4835,13 +4835,13 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_CheckBoxLabelSpacing: case PM_RadioButtonLabelSpacing: - ret = 6; + ret = int(QStyleHelper::dpiScaled(6.)); break; case PM_SizeGripSize: - ret = 13; + ret = int(QStyleHelper::dpiScaled(13.)); break; case PM_MessageBoxIconSize: - ret = 32; + ret = int(QStyleHelper::dpiScaled(32.)); break; case PM_TextCursorWidth: ret = 1; @@ -4851,7 +4851,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid break; case PM_TabCloseIndicatorWidth: case PM_TabCloseIndicatorHeight: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_ScrollView_ScrollBarSpacing: ret = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget); diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 852d3fd..67586ac 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -684,11 +684,10 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, const QString pmKey = QString(QLS("windowframe %0")).arg(option->state); QPixmap pixmap; - QPixmapCache::find(pmKey, pixmap); QRect pmRect(QPoint(0,0), QSize(pmSize, pmSize)); // Only draw through style once - if (pixmap.isNull()) { + if (!QPixmapCache::find(pmKey, pixmap)) { pixmap = QPixmap(pmSize, pmSize); pixmap.fill(Qt::transparent); QPainter pmPainter(&pixmap); diff --git a/src/gui/styles/qproxystyle.cpp b/src/gui/styles/qproxystyle.cpp index 589ca9c..7177bed 100644 --- a/src/gui/styles/qproxystyle.cpp +++ b/src/gui/styles/qproxystyle.cpp @@ -93,7 +93,7 @@ void QProxyStylePrivate::ensureBaseStyle() const baseStyle = 0; } } - } + } if (!baseStyle) // Use application desktop style baseStyle = QStyleFactory::create(QApplicationPrivate::desktopStyleKey()); @@ -368,7 +368,7 @@ bool QProxyStyle::event(QEvent *e) return d->baseStyle->event(e); } -/*! +/*! Returns an icon for the given \a standardIcon. Reimplement this slot to provide your own icons in a QStyle diff --git a/src/gui/styles/qstylehelper.cpp b/src/gui/styles/qstylehelper.cpp index 997bd68..f9010e8 100644 --- a/src/gui/styles/qstylehelper.cpp +++ b/src/gui/styles/qstylehelper.cpp @@ -48,6 +48,12 @@ #include <private/qstyle_p.h> #include <qmath.h> +#if defined(Q_WS_WIN) +#include "qt_windows.h" +#elif defined(Q_WS_MAC) +#include <private/qt_cocoa_helpers_mac_p.h> +#endif + QT_BEGIN_NAMESPACE namespace QStyleHelper { @@ -72,6 +78,26 @@ QString uniqueName(const QString &key, const QStyleOption *option, const QSize & return tmp; } +qreal dpiScaled(qreal value) +{ + static qreal scale = -1; + if (scale < 0) { + scale = 1.0; +#if defined(Q_WS_WIN) + { + HDC hdcScreen = GetDC(0); + int dpi = GetDeviceCaps(hdcScreen, LOGPIXELSX); + ReleaseDC(0, hdcScreen); + scale = dpi/96.0; + } +#elif defined(Q_WS_MAC) + scale = qt_mac_get_scalefactor(); +#endif + } + return value * scale; +} + + #ifndef QT_NO_DIAL int calcBigLineSize(int radius) @@ -178,7 +204,6 @@ QPolygonF calcLines(const QStyleOptionSlider *dial) return poly; } - // This will draw a nice and shiny QDial for us. We don't want // all the shinyness in QWindowsStyle, hence we place it here diff --git a/src/gui/styles/qstylehelper_p.h b/src/gui/styles/qstylehelper_p.h index 7099e87..cac88e2 100644 --- a/src/gui/styles/qstylehelper_p.h +++ b/src/gui/styles/qstylehelper_p.h @@ -67,6 +67,7 @@ class QStyleOption; namespace QStyleHelper { QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size); + qreal dpiScaled(qreal value); #ifndef QT_NO_DIAL qreal angle(const QPointF &p1, const QPointF &p2); QPolygonF calcLines(const QStyleOptionSlider *dial); diff --git a/src/gui/styles/qstyleoption.cpp b/src/gui/styles/qstyleoption.cpp index 704f8ba..e174370 100644 --- a/src/gui/styles/qstyleoption.cpp +++ b/src/gui/styles/qstyleoption.cpp @@ -3542,7 +3542,8 @@ QStyleOptionQ3DockWindow::QStyleOptionQ3DockWindow(int version) */ QStyleOptionDockWidget::QStyleOptionDockWidget() - : QStyleOption(Version, SO_DockWidget), movable(false) + : QStyleOption(Version, SO_DockWidget), closable(false), + movable(false), floatable(false) { } diff --git a/src/gui/styles/qwindowsstyle.cpp b/src/gui/styles/qwindowsstyle.cpp index 39743b0..4f25e68 100644 --- a/src/gui/styles/qwindowsstyle.cpp +++ b/src/gui/styles/qwindowsstyle.cpp @@ -42,6 +42,7 @@ #include "qwindowsstyle.h" #include "qwindowsstyle_p.h" #include <private/qpixmapdata_p.h> +#include <private/qstylehelper_p.h> #if !defined(QT_NO_STYLE_WINDOWS) || defined(QT_PLUGIN) @@ -125,8 +126,6 @@ static const int windowsCheckMarkHMargin = 2; // horiz. margins of check mark static const int windowsRightBorder = 15; // right border on windows static const int windowsCheckMarkWidth = 12; // checkmarks width on windows -static bool use2000style = true; - enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight }; /* @@ -268,9 +267,6 @@ bool QWindowsStyle::eventFilter(QObject *o, QEvent *e) */ QWindowsStyle::QWindowsStyle() : QCommonStyle(*new QWindowsStylePrivate) { -#if defined(Q_OS_WIN32) - use2000style = QSysInfo::WindowsVersion != QSysInfo::WV_NT && QSysInfo::WindowsVersion != QSysInfo::WV_95; -#endif } /*! @@ -280,9 +276,6 @@ QWindowsStyle::QWindowsStyle() : QCommonStyle(*new QWindowsStylePrivate) */ QWindowsStyle::QWindowsStyle(QWindowsStylePrivate &dd) : QCommonStyle(dd) { -#if defined(Q_OS_WIN32) - use2000style = QSysInfo::WindowsVersion != QSysInfo::WV_NT && QSysInfo::WindowsVersion != QSysInfo::WV_95; -#endif } @@ -405,7 +398,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW #ifndef QT_NO_SLIDER case PM_SliderLength: - ret = 11; + ret = int(QStyleHelper::dpiScaled(11.)); break; // Returns the number of pixels to use for the business part of the @@ -453,11 +446,11 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW break; case PM_SmallIconSize: - ret = 16; + ret = int(QStyleHelper::dpiScaled(16.)); break; case PM_LargeIconSize: - ret = 32; + ret = int(QStyleHelper::dpiScaled(32.)); break; case PM_IconViewIconSize: @@ -465,13 +458,13 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW break; case PM_ToolBarIconSize: - ret = 24; + ret = int(QStyleHelper::dpiScaled(24.)); break; case PM_DockWidgetTitleMargin: - ret = 2; + ret = int(QStyleHelper::dpiScaled(2.)); break; case PM_DockWidgetTitleBarButtonMargin: - ret = 4; + ret = int(QStyleHelper::dpiScaled(4.)); break; #if defined(Q_WS_WIN) case PM_DockWidgetFrameWidth: @@ -553,7 +546,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW ret = 0; break; case PM_ToolBarHandleExtent: - ret = 10; + ret = int(QStyleHelper::dpiScaled(10.)); break; default: ret = QCommonStyle::pixelMetric(pm, opt, widget); @@ -1136,12 +1129,7 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid #endif break; case SH_ItemView_ChangeHighlightOnFocus: -#if defined(Q_WS_WIN) - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) - ret = 1; - else -#endif - ret = 0; + ret = 1; break; case SH_ToolBox_SelectedPageTitleBold: ret = 0; @@ -1149,36 +1137,34 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid #if defined(Q_WS_WIN) case SH_UnderlineShortcut: + { ret = 1; - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 - && QSysInfo::WindowsVersion != QSysInfo::WV_98 - && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - BOOL cues; - SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &cues, 0); - ret = int(cues); - // Do nothing if we always paint underlines - Q_D(const QWindowsStyle); - if (!ret && widget && d) { + BOOL cues = false; + SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &cues, 0); + ret = int(cues); + // Do nothing if we always paint underlines + Q_D(const QWindowsStyle); + if (!ret && widget && d) { #ifndef QT_NO_MENUBAR - const QMenuBar *menuBar = qobject_cast<const QMenuBar *>(widget); - if (!menuBar && qobject_cast<const QMenu *>(widget)) { - QWidget *w = QApplication::activeWindow(); - if (w && w != widget) - menuBar = qFindChild<QMenuBar *>(w); - } - // If we paint a menu bar draw underlines if is in the keyboardState - if (menuBar) { - if (menuBar->d_func()->keyboardState || d->altDown()) - ret = 1; - // Otherwise draw underlines if the toplevel widget has seen an alt-press - } else -#endif // QT_NO_MENUBAR - if (d->hasSeenAlt(widget)) { + const QMenuBar *menuBar = qobject_cast<const QMenuBar *>(widget); + if (!menuBar && qobject_cast<const QMenu *>(widget)) { + QWidget *w = QApplication::activeWindow(); + if (w && w != widget) + menuBar = qFindChild<QMenuBar *>(w); + } + // If we paint a menu bar draw underlines if is in the keyboardState + if (menuBar) { + if (menuBar->d_func()->keyboardState || d->altDown()) ret = 1; - } + // Otherwise draw underlines if the toplevel widget has seen an alt-press + } else +#endif // QT_NO_MENUBAR + if (d->hasSeenAlt(widget)) { + ret = 1; } } break; + } #endif #ifndef QT_NO_RUBBERBAND case SH_RubberBand_Mask: @@ -1316,7 +1302,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, if ((!(opt->state & State_Sunken )) && (!(opt->state & State_Enabled) || !(opt->state & State_MouseOver && opt->state & State_AutoRaise)) - && (opt->state & State_On) && use2000style) { + && (opt->state & State_On)) { fill = QBrush(opt->palette.light().color(), Qt::Dense4Pattern); stippled = true; } else { @@ -1630,9 +1616,9 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, popupPal.setColor(QPalette::Light, frame->palette.background().color()); popupPal.setColor(QPalette::Midlight, frame->palette.light().color()); } - if (use2000style && pe == PE_Frame && (frame->state & State_Raised)) + if (pe == PE_Frame && (frame->state & State_Raised)) qDrawWinButton(p, frame->rect, popupPal, frame->state & State_Sunken); - else if (use2000style && pe == PE_Frame && (frame->state & State_Sunken)) + else if (pe == PE_Frame && (frame->state & State_Sunken)) { popupPal.setColor(QPalette::Midlight, frame->palette.background().color()); qDrawWinPanel(p, frame->rect, popupPal, frame->state & State_Sunken); @@ -1783,13 +1769,12 @@ case PE_FrameDockWidget: break; #endif // QT_NO_PROGRESSBAR - case PE_FrameTabWidget: - if (use2000style) { - QRect rect = opt->rect; - QPalette pal = opt->palette; - qDrawWinButton(p, opt->rect, opt->palette, false, 0); - break; - } + case PE_FrameTabWidget: { + QRect rect = opt->rect; + QPalette pal = opt->palette; + qDrawWinButton(p, opt->rect, opt->palette, false, 0); + break; + } default: QCommonStyle::drawPrimitive(pe, opt, p, w); } @@ -2065,10 +2050,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai p->setPen(light); p->drawLine(x1, y1 + 2, x1, y2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness)); p->drawPoint(x1 + 1, y1 + 1); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(x1 + 1, y1 + 2, x1 + 1, y2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness)); - } } // Top { @@ -2076,10 +2057,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai int end = x2 - (nextSelected ? 0 : 2); p->setPen(light); p->drawLine(beg, y1, end, y1); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(beg, y1 + 1, end, y1 + 1); - } } // Right if (lastTab || selected || onlyOne || !nextSelected) { @@ -2109,10 +2086,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai p->setPen(light); p->drawLine(x1, y2 - 2, x1, y1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness)); p->drawPoint(x1 + 1, y2 - 1); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(x1 + 1, y2 - 2, x1 + 1, y1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness)); - } } // Bottom { @@ -2151,10 +2124,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai p->setPen(light); p->drawLine(x1 + 2, y1, x2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1); p->drawPoint(x1 + 1, y1 + 1); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(x1 + 2, y1 + 1, x2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1 + 1); - } } // Left { @@ -2162,10 +2131,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai int end = y2 - (nextSelected ? 0 : 2); p->setPen(light); p->drawLine(x1, beg, x1, end); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(x1 + 1, beg, x1 + 1, end); - } } // Bottom if (lastTab || selected || onlyOne || !nextSelected) { @@ -2197,11 +2162,6 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai p->setPen(light); p->drawLine(x2 - 2, y1, x1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1); p->drawPoint(x2 - 1, y1 + 1); - if (!use2000style) { - p->setPen(midlight); - p->drawLine(x2 - 3, y1 + 1, x1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1 + 1); - p->drawPoint(x2 - 1, y1); - } } // Right { @@ -2238,7 +2198,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai #ifndef QT_NO_SCROLLBAR case CE_ScrollBarSubLine: case CE_ScrollBarAddLine: { - if (use2000style && (opt->state & State_Sunken)) { + if ((opt->state & State_Sunken)) { p->setPen(opt->palette.dark().color()); p->setBrush(opt->palette.brush(QPalette::Button)); p->drawRect(opt->rect.adjusted(0, 0, -1, -1)); @@ -3026,8 +2986,7 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp if ((cmb->subControls & SC_ComboBoxFrame)) { if (cmb->frame) { QPalette shadePal = opt->palette; - if (use2000style) - shadePal.setColor(QPalette::Midlight, shadePal.button().color()); + shadePal.setColor(QPalette::Midlight, shadePal.button().color()); qDrawWinPanel(p, opt->rect, shadePal, true, &editBrush); } else { @@ -3103,8 +3062,7 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp QBrush editBrush = sb->palette.brush(QPalette::Base); QRect r = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxFrame, widget); QPalette shadePal = sb->palette; - if (use2000style) - shadePal.setColor(QPalette::Midlight, shadePal.button().color()); + shadePal.setColor(QPalette::Midlight, shadePal.button().color()); qDrawWinPanel(p, r, shadePal, true, &editBrush); } @@ -3200,11 +3158,14 @@ QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt, int defwidth = 0; if (btn->features & QStyleOptionButton::AutoDefaultButton) defwidth = 2 * proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget); + int minwidth = int(QStyleHelper::dpiScaled(75.)); + int minheight = int(QStyleHelper::dpiScaled(23.)); + #ifndef QT_QWS_SMALL_PUSHBUTTON - if (w < 75 + defwidth && !btn->text.isEmpty()) - w = 75 + defwidth; - if (h < 23 + defwidth) - h = 23 + defwidth; + if (w < minwidth + defwidth && !btn->text.isEmpty()) + w = minwidth + defwidth; + if (h < minheight + defwidth) + h = minheight + defwidth; #endif sz = QSize(w, h); } @@ -3230,7 +3191,7 @@ QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt, + 2 * windowsItemFrame)); } int maxpmw = mi->maxIconWidth; - int tabSpacing = use2000style ? 20 :windowsTabSpacing; + int tabSpacing = 20; if (mi->text.contains(QLatin1Char('\t'))) w += tabSpacing; else if (mi->menuItemType == QStyleOptionMenuItem::SubMenu) diff --git a/src/gui/styles/qwindowsvistastyle.cpp b/src/gui/styles/qwindowsvistastyle.cpp index 7a75a7d..3e65eef 100644 --- a/src/gui/styles/qwindowsvistastyle.cpp +++ b/src/gui/styles/qwindowsvistastyle.cpp @@ -41,6 +41,7 @@ #include "qwindowsvistastyle.h" #include "qwindowsvistastyle_p.h" +#include <private/qstylehelper_p.h> #if !defined(QT_NO_STYLE_WINDOWSVISTA) || defined(QT_PLUGIN) @@ -195,17 +196,15 @@ void Animation::paint(QPainter *painter, const QStyleOption *option) Q_UNUSED(painter); } -/* -* ! \internal -* -* Helperfunction to paint the current transition state -* between two animation frames. -* -* The result is a blended image consisting of -* ((alpha)*_primaryImage) + ((1-alpha)*_secondaryImage) -* -*/ +/*! \internal + Helperfunction to paint the current transition state between two + animation frames. + + The result is a blended image consisting of ((alpha)*_primaryImage) + + ((1-alpha)*_secondaryImage) + +*/ void Animation::drawBlendedImage(QPainter *painter, QRect rect, float alpha) { if (_secondaryImage.isNull() || _primaryImage.isNull()) return; @@ -247,14 +246,11 @@ void Animation::drawBlendedImage(QPainter *painter, QRect rect, float alpha) { painter->drawImage(rect, _tempImage); } -/* -* ! \internal -* -* Paints a transition state. The result will be a mix between the -* initial and final state of the transition, depending on the -* time difference between _startTime and current time. +/*! \internal + Paints a transition state. The result will be a mix between the + initial and final state of the transition, depending on the time + difference between _startTime and current time. */ - void Transition::paint(QPainter *painter, const QStyleOption *option) { float alpha = 1.0; @@ -277,15 +273,11 @@ void Transition::paint(QPainter *painter, const QStyleOption *option) drawBlendedImage(painter, option->rect, alpha); } -/* -* ! \internal -* -* Paints a pulse. The result will be a mix between the -* primary and secondary pulse images depending on the -* time difference between _startTime and current time. +/*! \internal + Paints a pulse. The result will be a mix between the primary and + secondary pulse images depending on the time difference between + _startTime and current time. */ - - void Pulse::paint(QPainter *painter, const QStyleOption *option) { float alpha = 1.0; @@ -307,31 +299,37 @@ void Pulse::paint(QPainter *painter, const QStyleOption *option) /*! - \reimp - * - * Animations are used for some state transitions on specific widgets. - * - * Only one running animation can exist for a widget at any specific time. - * Animations can be added through QWindowsVistaStylePrivate::startAnimation(Animation *) - * and any existing animation on a widget can be retrieved with - * QWindowsVistaStylePrivate::widgetAnimation(Widget *). - * - * Once an animation has been started, QWindowsVistaStylePrivate::timerEvent(QTimerEvent *) - * will continuously call update() on the widget until it is stopped, meaning that drawPrimitive - * will be called many times until the transition has completed. During this time, the result - * will be retrieved by the Animation::paint(...) function and not by the style itself. - * - * To determine if a transition should occur, the style needs to know the previous state of the - * widget as well as the current one. This is solved by updating dynamic properties on the widget - * every time the function is called. - * - * Transitions interrupting existing transitions should always be smooth, so whenever a hover-transition - * is started on a pulsating button, it uses the current frame of the pulse-animation as the - * starting image for the hover transition. - * + \internal + + Animations are used for some state transitions on specific widgets. + + Only one running animation can exist for a widget at any specific + time. Animations can be added through + QWindowsVistaStylePrivate::startAnimation(Animation *) and any + existing animation on a widget can be retrieved with + QWindowsVistaStylePrivate::widgetAnimation(Widget *). + + Once an animation has been started, + QWindowsVistaStylePrivate::timerEvent(QTimerEvent *) will + continuously call update() on the widget until it is stopped, + meaning that drawPrimitive will be called many times until the + transition has completed. During this time, the result will be + retrieved by the Animation::paint(...) function and not by the style + itself. + + To determine if a transition should occur, the style needs to know + the previous state of the widget as well as the current one. This is + solved by updating dynamic properties on the widget every time the + function is called. + + Transitions interrupting existing transitions should always be + smooth, so whenever a hover-transition is started on a pulsating + button, it uses the current frame of the pulse-animation as the + starting image for the hover transition. + */ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const + QPainter *painter, const QWidget *widget) const { QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func()); @@ -487,7 +485,12 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt case PE_IndicatorBranch: { XPThemeData theme(d->treeViewHelper(), painter, QLatin1String("TREEVIEW")); - static const int decoration_size = 16; + static int decoration_size = 0; + if (theme.isValid() && !decoration_size) { + SIZE size; + pGetThemePartSize(theme.handle(), 0, TVP_HOTGLYPH, GLPS_OPENED, 0, TS_TRUE, &size); + decoration_size = qMax(size.cx, size.cy); + } int mid_h = option->rect.x() + option->rect.width() / 2; int mid_v = option->rect.y() + option->rect.height() / 2; int bef_h = mid_h; @@ -535,17 +538,6 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt } break; - case PE_IndicatorToolBarHandle: - { - XPThemeData theme; - if (option->state & State_Horizontal) - theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPER, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2)); - else - theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPERVERT, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2)); - d->drawBackground(theme); - } - break; - case PE_FrameMenu: { int stateId = option->state & State_Active ? MB_ACTIVE : MB_INACTIVE; @@ -694,6 +686,24 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt } break; + case PE_IndicatorToolBarHandle: + { + XPThemeData theme; + QRect rect; + if (option->state & State_Horizontal) { + theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPER, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2)); + rect = option->rect.adjusted(0, 1, 0, -2); + rect.setWidth(4); + } else { + theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPERVERT, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2)); + rect = option->rect.adjusted(1, 0, -1, 0); + rect.setHeight(4); + } + theme.rect = rect; + d->drawBackground(theme); + } + break; + case PE_IndicatorToolBarSeparator: { QPen pen = painter->pen(); @@ -864,11 +874,9 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt /*! - - \reimp + \internal see drawPrimitive for comments on the animation support - */ void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const @@ -1230,7 +1238,15 @@ void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption case CE_MenuItem: if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) { // windows always has a check column, regardless whether we have an icon or not - int checkcol = qMax(menuitem->maxIconWidth, 28); + int checkcol = 28; + { + SIZE size; + MARGINS margins; + XPThemeData theme(widget, 0, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND, MBI_HOT); + pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size); + pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0, TMT_CONTENTMARGINS, NULL, &margins); + checkcol = qMax(menuitem->maxIconWidth, int(6 + size.cx + margins.cxLeftWidth + margins.cxRightWidth)); + } QColor darkLine = option->palette.background().color().darker(108); QColor lightLine = option->palette.background().color().lighter(107); QRect rect = option->rect; @@ -1275,8 +1291,23 @@ void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption if (checked) { XPThemeData theme(widget, painter, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND, menuitem->icon.isNull() ? MBI_HOT : MBI_PUSHED, vCheckRect); + SIZE size; + MARGINS margins; + pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size); + pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0, + TMT_CONTENTMARGINS, NULL, &margins); + QRect checkRect(0, 0, size.cx + margins.cxLeftWidth + margins.cxRightWidth , + size.cy + margins.cyBottomHeight + margins.cyTopHeight); + checkRect.moveCenter(vCheckRect.center()); + theme.rect = checkRect; + d->drawBackground(theme); + if (menuitem->icon.isNull()) { + checkRect = QRect(0, 0, size.cx, size.cy); + checkRect.moveCenter(theme.rect.center()); + theme.rect = checkRect; + theme.partId = MENU_POPUPCHECK; bool bullet = menuitem->checkType & QStyleOptionMenuItem::Exclusive; if (dis) @@ -1505,7 +1536,7 @@ void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption } /*! - \reimp + \internal see drawPrimitive for comments on the animation support @@ -1891,7 +1922,7 @@ void QWindowsVistaStyle::drawComplexControl(ComplexControl control, const QStyle } /*! - \reimp + \internal */ QSize QWindowsVistaStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const @@ -1926,9 +1957,18 @@ QSize QWindowsVistaStyle::sizeFromContents(ContentsType type, const QStyleOption return sz; case CT_MenuItem: sz = QWindowsXPStyle::sizeFromContents(type, option, size, widget); - sz.rwidth() += 28; + int minimumHeight; + { + SIZE size; + MARGINS margins; + XPThemeData theme(widget, 0, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND, MBI_HOT); + pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size); + pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0, TMT_CONTENTMARGINS, NULL, &margins); + minimumHeight = qMax<qint32>(size.cy + margins.cyBottomHeight+ margins.cyTopHeight, sz.height()); + sz.rwidth() += size.cx + margins.cxLeftWidth + margins.cxRightWidth; + } + if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) { - int minimumHeight = qMax<qint32>(22, sz.height()); if (menuitem->menuItemType != QStyleOptionMenuItem::Separator) sz.setHeight(minimumHeight); } @@ -1959,7 +1999,7 @@ QSize QWindowsVistaStyle::sizeFromContents(ContentsType type, const QStyleOption } /*! - \reimp + \internal */ QRect QWindowsVistaStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const { @@ -2130,7 +2170,7 @@ static bool buttonVisible(const QStyle::SubControl sc, const QStyleOptionTitleBa } -/*! \reimp */ +/*! \internal */ int QWindowsVistaStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const { @@ -2164,7 +2204,7 @@ int QWindowsVistaStyle::styleHint(StyleHint hint, const QStyleOption *option, co /*! - \reimp + \internal */ QRect QWindowsVistaStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option, SubControl subControl, const QWidget *widget) const @@ -2273,7 +2313,7 @@ QRect QWindowsVistaStyle::subControlRect(ComplexControl control, const QStyleOpt } /*! - \reimp + \internal */ bool QWindowsVistaStyle::event(QEvent *e) { @@ -2296,7 +2336,7 @@ bool QWindowsVistaStyle::event(QEvent *e) } /*! - \reimp + \internal */ QStyle::SubControl QWindowsVistaStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget) const @@ -2308,7 +2348,7 @@ QStyle::SubControl QWindowsVistaStyle::hitTestComplexControl(ComplexControl cont } /*! - \reimp + \internal */ int QWindowsVistaStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const { @@ -2318,9 +2358,9 @@ int QWindowsVistaStyle::pixelMetric(PixelMetric metric, const QStyleOption *opti switch (metric) { case PM_DockWidgetTitleBarButtonMargin: - return 5; + return int(QStyleHelper::dpiScaled(5.)); case PM_ScrollBarSliderMin: - return 18; + return int(QStyleHelper::dpiScaled(18.)); case PM_MenuHMargin: case PM_MenuVMargin: return 0; @@ -2333,7 +2373,7 @@ int QWindowsVistaStyle::pixelMetric(PixelMetric metric, const QStyleOption *opti } /*! - \reimp + \internal */ QPalette QWindowsVistaStyle::standardPalette() const { @@ -2341,7 +2381,7 @@ QPalette QWindowsVistaStyle::standardPalette() const } /*! - \reimp + \internal */ void QWindowsVistaStyle::polish(QApplication *app) { @@ -2349,7 +2389,7 @@ void QWindowsVistaStyle::polish(QApplication *app) } /*! - \reimp + \internal */ void QWindowsVistaStyle::polish(QWidget *widget) { @@ -2403,7 +2443,7 @@ void QWindowsVistaStyle::polish(QWidget *widget) } /*! - \reimp + \internal */ void QWindowsVistaStyle::unpolish(QWidget *widget) { @@ -2445,7 +2485,7 @@ void QWindowsVistaStyle::unpolish(QWidget *widget) /*! - \reimp + \internal */ void QWindowsVistaStyle::unpolish(QApplication *app) { @@ -2453,7 +2493,7 @@ void QWindowsVistaStyle::unpolish(QApplication *app) } /*! - \reimp + \internal */ void QWindowsVistaStyle::polish(QPalette &pal) { @@ -2462,7 +2502,7 @@ void QWindowsVistaStyle::polish(QPalette &pal) } /*! - \reimp + \internal */ QPixmap QWindowsVistaStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option, const QWidget *widget) const @@ -2531,9 +2571,7 @@ void QWindowsVistaStylePrivate::startAnimation(Animation *t) bool QWindowsVistaStylePrivate::transitionsEnabled() const { BOOL animEnabled = false; - if (QT_WA_INLINE(SystemParametersInfo(SPI_GETCLIENTAREAANIMATION, 0, &animEnabled, 0), - SystemParametersInfoA(SPI_GETCLIENTAREAANIMATION, 0, &animEnabled, 0) - )) + if (SystemParametersInfo(SPI_GETCLIENTAREAANIMATION, 0, &animEnabled, 0)) { if (animEnabled) return true; diff --git a/src/gui/styles/qwindowsxpstyle.cpp b/src/gui/styles/qwindowsxpstyle.cpp index b0eae1f..9c4afee 100644 --- a/src/gui/styles/qwindowsxpstyle.cpp +++ b/src/gui/styles/qwindowsxpstyle.cpp @@ -161,8 +161,7 @@ HTHEME XPThemeData::handle() htheme = QWindowsXPStylePrivate::handleMap->operator[](name); if (!htheme) { - htheme = pOpenThemeData(QWindowsXPStylePrivate::winId(widget), - (TCHAR*)name.utf16()); + htheme = pOpenThemeData(QWindowsXPStylePrivate::winId(widget), (wchar_t*)name.utf16()); if (htheme) { if (!QWindowsXPStylePrivate::handleMap) QWindowsXPStylePrivate::handleMap = new QMap<QString, HTHEME>; @@ -1547,11 +1546,11 @@ case PE_Frame: if (widget) { bool useGradient = true; const int maxlength = 256; - WCHAR themeFileName[maxlength]; - WCHAR themeColor[maxlength]; + wchar_t themeFileName[maxlength]; + wchar_t themeColor[maxlength]; // Due to a a scaling issue with the XP Silver theme, tab gradients are not used with it if (pGetCurrentThemeName(themeFileName, maxlength, themeColor, maxlength, NULL, 0) == S_OK) { - WCHAR* offset; + wchar_t *offset = 0; if ((offset = wcsrchr(themeFileName, QChar(QLatin1Char('\\')).unicode())) != NULL) { offset++; if (!lstrcmp(offset, L"Luna.msstyles") && !lstrcmp(offset, L"Metallic")) { @@ -3235,7 +3234,7 @@ int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, con break; case PM_SplitterWidth: - res = qMax(5, QApplication::globalStrut().width()); + res = qMax(int(QStyleHelper::dpiScaled(5.)), QApplication::globalStrut().width()); break; case PM_IndicatorWidth: @@ -3245,7 +3244,7 @@ int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, con if (theme.isValid()) { SIZE size; pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size); - res = (pm == PM_IndicatorWidth ? size.cx+2 : res = size.cy+2); + res = (pm == PM_IndicatorWidth ? size.cx : res = size.cy); } } break; @@ -3257,7 +3256,7 @@ int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, con if (theme.isValid()) { SIZE size; pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size); - res = (pm == PM_ExclusiveIndicatorWidth ? size.cx+2 : res = size.cy+2); + res = (pm == PM_ExclusiveIndicatorWidth ? size.cx : res = size.cy); } } break; @@ -3329,7 +3328,7 @@ int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, con #ifndef QT_NO_TOOLBAR case PM_ToolBarHandleExtent: - res = 8; + res = int(QStyleHelper::dpiScaled(8.)); break; #endif // QT_NO_TOOLBAR @@ -3344,10 +3343,10 @@ int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, con } break; case PM_DockWidgetSeparatorExtent: - res = 4; + res = int(QStyleHelper::dpiScaled(4.)); break; case PM_DockWidgetTitleMargin: - res = 4; + res = int(QStyleHelper::dpiScaled(4.)); break; case PM_ButtonShiftHorizontal: diff --git a/src/gui/text/qfont_win.cpp b/src/gui/text/qfont_win.cpp index 2c27c9b..2293973 100644 --- a/src/gui/text/qfont_win.cpp +++ b/src/gui/text/qfont_win.cpp @@ -39,11 +39,6 @@ ** ****************************************************************************/ -// the miscrosoft platform SDK says that the Unicode versions of -// TextOut and GetTextExtentsPoint32 are supported on all platforms, so we use them -// exclusively to simplify code, save a lot of conversions into the local encoding -// and have generally better unicode support :) - #include "qfont.h" #include "qfont_p.h" #include "qfontengine_p.h" @@ -67,8 +62,7 @@ extern HDC shared_dc(); // common dc for all fonts // ### maybe move to qapplication_win QFont qt_LOGFONTtoQFont(LOGFONT& lf, bool /*scale*/) { - QString family = QT_WA_INLINE(QString::fromUtf16((ushort*)lf.lfFaceName), - QString::fromLocal8Bit((char*)lf.lfFaceName)); + QString family = QString::fromWCharArray(lf.lfFaceName); QFont qf(family); qf.setItalic(lf.lfItalic); if (lf.lfWeight != FW_DONTCARE) { diff --git a/src/gui/text/qfontdatabase_qws.cpp b/src/gui/text/qfontdatabase_qws.cpp index 2c359ba..d348e1b 100644 --- a/src/gui/text/qfontdatabase_qws.cpp +++ b/src/gui/text/qfontdatabase_qws.cpp @@ -55,6 +55,7 @@ #endif #include "qfontengine_qpf_p.h" #include "private/qfactoryloader_p.h" +#include "private/qcore_unix_p.h" // overrides QT_OPEN #include "qabstractfontengine_qws.h" #include "qabstractfontengine_p.h" #include <qdatetime.h> @@ -128,7 +129,7 @@ void QFontDatabasePrivate::addQPF2File(const QByteArray &file) struct stat st; if (stat(file.constData(), &st)) return; - int f = ::open(file, O_RDONLY, 0); + int f = QT_OPEN(file, O_RDONLY, 0); if (f < 0) return; const uchar *data = (const uchar *)mmap(0, st.st_size, PROT_READ, MAP_SHARED, f, 0); @@ -176,7 +177,7 @@ void QFontDatabasePrivate::addQPF2File(const QByteArray &file) #endif } #ifndef QT_FONTS_ARE_RESOURCES - ::close(f); + QT_CLOSE(f); #endif } #endif diff --git a/src/gui/text/qfontdatabase_win.cpp b/src/gui/text/qfontdatabase_win.cpp index 2c0223b..2e8e5e4 100644 --- a/src/gui/text/qfontdatabase_win.cpp +++ b/src/gui/text/qfontdatabase_win.cpp @@ -195,21 +195,12 @@ static QString getEnglishName(const QString &familyName) QString i18n_name; HDC hdc = GetDC( 0 ); - HFONT hfont; - QT_WA( { - LOGFONTW lf; - memset( &lf, 0, sizeof( LOGFONTW ) ); - memcpy( lf.lfFaceName, familyName.utf16(), qMin(LF_FACESIZE, familyName.length())*sizeof(QChar) ); - lf.lfCharSet = DEFAULT_CHARSET; - hfont = CreateFontIndirectW( &lf ); - }, { - LOGFONTA lf; - memset( &lf, 0, sizeof( LOGFONTA ) ); - QByteArray lfam = familyName.toLocal8Bit(); - memcpy( lf.lfFaceName, lfam, qMin(LF_FACESIZE, lfam.size()) ); - lf.lfCharSet = DEFAULT_CHARSET; - hfont = CreateFontIndirectA( &lf ); - } ); + LOGFONT lf; + memset(&lf, 0, sizeof(LOGFONT)); + memcpy(lf.lfFaceName, familyName.utf16(), qMin(LF_FACESIZE, familyName.length()) * sizeof(wchar_t)); + lf.lfCharSet = DEFAULT_CHARSET; + HFONT hfont = CreateFontIndirect(&lf); + if(!hfont) { ReleaseDC(0, hdc); return QString(); @@ -245,32 +236,6 @@ error: return i18n_name; } -static void getFontSignature(const QString &familyName, - NEWTEXTMETRICEX *textmetric, - FONTSIGNATURE *signature) -{ - QT_WA({ - Q_UNUSED(familyName); - *signature = textmetric->ntmFontSig; - }, { - // the textmetric structure we get from EnumFontFamiliesEx on Win9x has - // a FONTSIGNATURE, but that one is uninitialized and doesn't work. Have to go - // the hard way and load the font to find out. - HDC hdc = GetDC(0); - LOGFONTA lf; - memset(&lf, 0, sizeof(LOGFONTA)); - QByteArray lfam = familyName.toLocal8Bit(); - memcpy(lf.lfFaceName, lfam.data(), qMin(LF_FACESIZE, lfam.length())); - lf.lfCharSet = DEFAULT_CHARSET; - HFONT hfont = CreateFontIndirectA(&lf); - HGDIOBJ oldobj = SelectObject(hdc, hfont); - GetTextCharsetInfo(hdc, signature, 0); - SelectObject(hdc, oldobj); - DeleteObject(hfont); - ReleaseDC(0, hdc); - }); -} - static void addFontToDatabase(QString familyName, const QString &scriptName, TEXTMETRIC *textmetric, @@ -288,26 +253,17 @@ void addFontToDatabase(QString familyName, const QString &scriptName, bool scalable; int size; -// QString escript = QString::fromUtf16((ushort *)f->elfScript); +// QString escript = QString::fromWCharArray(f->elfScript); // qDebug("script=%s", escript.latin1()); - QT_WA({ - NEWTEXTMETRIC *tm = (NEWTEXTMETRIC *)textmetric; - fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH); - ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE); - scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE); - size = scalable ? SMOOTH_SCALABLE : tm->tmHeight; - italic = tm->tmItalic; - weight = tm->tmWeight; - } , { - NEWTEXTMETRICA *tm = (NEWTEXTMETRICA *)textmetric; - fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH); - ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE); - scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE); - size = scalable ? SMOOTH_SCALABLE : tm->tmHeight; - italic = tm->tmItalic; - weight = tm->tmWeight; - }); + NEWTEXTMETRIC *tm = (NEWTEXTMETRIC *)textmetric; + fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH); + ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE); + scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE); + size = scalable ? SMOOTH_SCALABLE : tm->tmHeight; + italic = tm->tmItalic; + weight = tm->tmWeight; + // the "@family" fonts are just the same as "family". Ignore them. if (familyName[0] != QLatin1Char('@') && !familyName.startsWith(QLatin1String("WST_"))) { QtFontStyle::Key styleKey; @@ -420,18 +376,10 @@ static int CALLBACK storeFont(ENUMLOGFONTEX* f, NEWTEXTMETRICEX *textmetric, int type, LPARAM /*p*/) { - QString familyName; - QT_WA({ - familyName = QString::fromUtf16((ushort*)f->elfLogFont.lfFaceName); - },{ - ENUMLOGFONTEXA *fa = (ENUMLOGFONTEXA *)f; - familyName = QString::fromLocal8Bit(fa->elfLogFont.lfFaceName); - }); - QString script = QT_WA_INLINE(QString::fromUtf16((const ushort *)f->elfScript), - QString::fromLocal8Bit((const char *)((ENUMLOGFONTEXA *)f)->elfScript)); - - FONTSIGNATURE signature; - getFontSignature(familyName, textmetric, &signature); + QString familyName = QString::fromWCharArray(f->elfLogFont.lfFaceName); + QString script = QString::fromWCharArray(f->elfScript); + + FONTSIGNATURE signature = textmetric->ntmFontSig; // NEWTEXTMETRICEX is a NEWTEXTMETRIC, which according to the documentation is // identical to a TEXTMETRIC except for the last four members, which we don't use @@ -459,33 +407,17 @@ void populate_database(const QString& fam) HDC dummy = GetDC(0); - QT_WA({ - LOGFONT lf; - lf.lfCharSet = DEFAULT_CHARSET; - if (fam.isNull()) { - lf.lfFaceName[0] = 0; - } else { - memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded - } - lf.lfPitchAndFamily = 0; - - EnumFontFamiliesEx(dummy, &lf, - (FONTENUMPROC)storeFont, (LPARAM)privateDb(), 0); - } , { - LOGFONTA lf; - lf.lfCharSet = DEFAULT_CHARSET; - if (fam.isNull()) { - lf.lfFaceName[0] = 0; - } else { - QByteArray lname = fam.toLocal8Bit(); - memcpy(lf.lfFaceName,lname.data(), - qMin(lname.length()+1,32)); // 32 = Windows hard-coded - } - lf.lfPitchAndFamily = 0; + LOGFONT lf; + lf.lfCharSet = DEFAULT_CHARSET; + if (fam.isNull()) { + lf.lfFaceName[0] = 0; + } else { + memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded + } + lf.lfPitchAndFamily = 0; - EnumFontFamiliesExA(dummy, &lf, - (FONTENUMPROCA)storeFont, (LPARAM)privateDb(), 0); - }); + EnumFontFamiliesEx(dummy, &lf, + (FONTENUMPROC)storeFont, (LPARAM)privateDb(), 0); ReleaseDC(0, dummy); @@ -496,21 +428,11 @@ void populate_database(const QString& fam) for (int j = 0; j < fnt.families.count(); ++j) { const QString familyName = fnt.families.at(j); HDC hdc = GetDC(0); - HFONT hfont; - QT_WA({ - LOGFONTW lf; - memset(&lf, 0, sizeof(LOGFONTW)); - memcpy(lf.lfFaceName, familyName.utf16(), qMin(LF_FACESIZE, familyName.size())); - lf.lfCharSet = DEFAULT_CHARSET; - hfont = CreateFontIndirectW(&lf); - } , { - LOGFONTA lf; - memset(&lf, 0, sizeof(LOGFONTA)); - QByteArray lfam = familyName.toLocal8Bit(); - memcpy(lf.lfFaceName, lfam.data(), qMin(LF_FACESIZE, lfam.length())); - lf.lfCharSet = DEFAULT_CHARSET; - hfont = CreateFontIndirectA(&lf); - }); + LOGFONT lf; + memset(&lf, 0, sizeof(LOGFONT)); + memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE, familyName.size())); + lf.lfCharSet = DEFAULT_CHARSET; + HFONT hfont = CreateFontIndirect(&lf); HGDIOBJ oldobj = SelectObject(hdc, hfont); TEXTMETRIC textMetrics; @@ -598,17 +520,10 @@ static void initFontInfo(QFontEngineWin *fe, const QFontDef &request, const QFon HDC dc = ((request.styleStrategy & QFont::PreferDevice) && fp->hdc) ? fp->hdc : shared_dc(); SelectObject(dc, fe->hfont); - QT_WA({ - TCHAR n[64]; - GetTextFaceW(dc, 64, n); - fe->fontDef.family = QString::fromUtf16((ushort*)n); - fe->fontDef.fixedPitch = !(fe->tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH); - } , { - char an[64]; - GetTextFaceA(dc, 64, an); - fe->fontDef.family = QString::fromLocal8Bit(an); - fe->fontDef.fixedPitch = !(fe->tm.a.tmPitchAndFamily & TMPF_FIXED_PITCH); - }); + wchar_t n[64]; + GetTextFace(dc, 64, n); + fe->fontDef.family = QString::fromWCharArray(n); + fe->fontDef.fixedPitch = !(fe->tm.tmPitchAndFamily & TMPF_FIXED_PITCH); if (fe->fontDef.pointSize < 0) { fe->fontDef.pointSize = fe->fontDef.pixelSize * 72. / fp->dpi; } else if (fe->fontDef.pixelSize == -1) { @@ -704,12 +619,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ HFONT hfont = 0; if (fp->rawMode) { // will choose a stock font - int f, deffnt; - // ### why different? - if ((QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) || QSysInfo::WindowsVersion == QSysInfo::WV_32s) - deffnt = SYSTEM_FONT; - else - deffnt = DEFAULT_GUI_FONT; + int f, deffnt = SYSTEM_FONT; QString fam = desc->family->name.toLower(); if (fam == QLatin1String("default")) f = deffnt; @@ -778,11 +688,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ } else if (request.styleStrategy & QFont::PreferDevice) { strat = OUT_DEVICE_PRECIS; } else if (request.styleStrategy & QFont::PreferOutline) { - QT_WA({ - strat = OUT_OUTLINE_PRECIS; - } , { - strat = OUT_TT_PRECIS; - }); + strat = OUT_OUTLINE_PRECIS; } else if (request.styleStrategy & QFont::ForceOutline) { strat = OUT_TT_ONLY_PRECIS; #endif @@ -801,7 +707,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ if (request.styleStrategy & QFont::PreferAntialias) { if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) { - qual = 5; // == CLEARTYPE_QUALITY; + qual = CLEARTYPE_QUALITY; preferClearTypeAA = true; } else { qual = ANTIALIASED_QUALITY; @@ -827,16 +733,8 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ if (fam == QLatin1String("Courier") && !(request.styleStrategy & QFont::PreferBitmap)) fam = QLatin1String("Courier New"); - QT_WA({ - memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded - hfont = CreateFontIndirect(&lf); - } , { - // LOGFONTA and LOGFONTW are binary compatible - QByteArray lname = fam.toLocal8Bit(); - memcpy(lf.lfFaceName,lname.data(), - qMin(lname.length()+1,32)); // 32 = Windows hard-coded - hfont = CreateFontIndirectA((LOGFONTA*)&lf); - }); + memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded + hfont = CreateFontIndirect(&lf); if (!hfont) qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect failed"); @@ -845,17 +743,12 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ int avWidth = 0; BOOL res; HGDIOBJ oldObj = SelectObject(hdc, hfont); - QT_WA({ - TEXTMETRICW tm; - res = GetTextMetricsW(hdc, &tm); - avWidth = tm.tmAveCharWidth; - ttf = tm.tmPitchAndFamily & TMPF_TRUETYPE; - } , { - TEXTMETRICA tm; - res = GetTextMetricsA(hdc, &tm); - avWidth = tm.tmAveCharWidth; - ttf = tm.tmPitchAndFamily & TMPF_TRUETYPE; - }); + + TEXTMETRIC tm; + res = GetTextMetrics(hdc, &tm); + avWidth = tm.tmAveCharWidth; + ttf = tm.tmPitchAndFamily & TMPF_TRUETYPE; + SelectObject(hdc, oldObj); if (hfont && (!ttf || request.stretch != 100)) { @@ -863,11 +756,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp, const QFontDef &requ if (!res) qErrnoWarning("QFontEngine::loadEngine: GetTextMetrics failed"); lf.lfWidth = avWidth * request.stretch/100; - QT_WA({ - hfont = CreateFontIndirect(&lf); - } , { - hfont = CreateFontIndirectA((LOGFONTA*)&lf); - }); + hfont = CreateFontIndirect(&lf); if (!hfont) qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect with stretch failed"); } @@ -969,12 +858,6 @@ static QFontEngine *loadWin(const QFontPrivate *d, int script, const QFontDef &r // list of families to try QStringList family_list = familyList(req); - if(QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based && req.family.toLower() == QLatin1String("ms sans serif")) { - // small hack for Dos based machines to get the right font for non - // latin text when using the default font. - family_list << QLatin1String("Arial"); - } - const char *stylehint = styleHint(d->request); if (stylehint) family_list << QLatin1String(stylehint); @@ -1165,21 +1048,21 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt) HANDLE handle = 0; { -#ifdef QT_NO_TEMPORARYFILE - TCHAR lpBuffer[MAX_PATH]; +#ifdef QT_NO_TEMPORARYFILE + wchar_t lpBuffer[MAX_PATH]; GetTempPath(MAX_PATH, lpBuffer); - QString s = QString::fromUtf16((const ushort *) lpBuffer); + QString s = QString::fromWCharArray(lpBuffer); QFile tempfile(s + QLatin1String("/font") + QString::number(GetTickCount()) + QLatin1String(".ttf")); if (!tempfile.open(QIODevice::ReadWrite)) #else QTemporaryFile tempfile(QLatin1String("XXXXXXXX.ttf")); if (!tempfile.open()) -#endif +#endif // QT_NO_TEMPORARYFILE return; if (tempfile.write(fnt->data) == -1) return; -#ifndef QT_NO_TEMPORARYFILE +#ifndef QT_NO_TEMPORARYFILE tempfile.setAutoRemove(false); #endif fnt->fileName = QFileInfo(tempfile.fileName()).absoluteFilePath(); @@ -1191,13 +1074,11 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt) } #else DWORD dummy = 0; - HANDLE handle = ptrAddFontMemResourceEx((void *)fnt->data.constData(), - fnt->data.size(), - 0, - &dummy); + HANDLE handle = ptrAddFontMemResourceEx((void *)fnt->data.constData(), fnt->data.size(), 0, + &dummy); if (handle == 0) return; -#endif +#endif // Q_OS_WINCE fnt->handle = handle; fnt->data = QByteArray(); @@ -1219,12 +1100,10 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt) // supported from 2000 on, so no need to deal with the *A variant PtrAddFontResourceExW ptrAddFontResourceExW = (PtrAddFontResourceExW)QLibrary::resolve(QLatin1String("gdi32"), "AddFontResourceExW"); - if (!ptrAddFontResourceExW) + if (!ptrAddFontResourceExW + || ptrAddFontResourceExW((wchar_t*)fnt->fileName.utf16(), FR_PRIVATE, 0) == 0) return; - - if (ptrAddFontResourceExW((LPCWSTR)fnt->fileName.utf16(), FR_PRIVATE, 0) == 0) - return; -#endif +#endif // Q_OS_WINCE fnt->memoryFont = false; } @@ -1250,12 +1129,10 @@ bool QFontDatabase::removeApplicationFont(int handle) #else PtrRemoveFontMemResourceEx ptrRemoveFontMemResourceEx = (PtrRemoveFontMemResourceEx)QLibrary::resolve(QLatin1String("gdi32"), "RemoveFontMemResourceEx"); - if (!ptrRemoveFontMemResourceEx) - return false; - - if (!ptrRemoveFontMemResourceEx(font.handle)) + if (!ptrRemoveFontMemResourceEx + || !ptrRemoveFontMemResourceEx(font.handle)) return false; -#endif +#endif // Q_OS_WINCE } else { #ifdef Q_OS_WINCE if (!RemoveFontResource((LPCWSTR)font.fileName.utf16())) @@ -1263,12 +1140,10 @@ bool QFontDatabase::removeApplicationFont(int handle) #else PtrRemoveFontResourceExW ptrRemoveFontResourceExW = (PtrRemoveFontResourceExW)QLibrary::resolve(QLatin1String("gdi32"), "RemoveFontResourceExW"); - if (!ptrRemoveFontResourceExW) - return false; - - if (!ptrRemoveFontResourceExW((LPCWSTR)font.fileName.utf16(), FR_PRIVATE, 0)) + if (!ptrRemoveFontResourceExW + || !ptrRemoveFontResourceExW((LPCWSTR)font.fileName.utf16(), FR_PRIVATE, 0)) return false; -#endif +#endif // Q_OS_WINCE } db->invalidate(); diff --git a/src/gui/text/qfontengine_qpf.cpp b/src/gui/text/qfontengine_qpf.cpp index 2df4095..b255694 100644 --- a/src/gui/text/qfontengine_qpf.cpp +++ b/src/gui/text/qfontengine_qpf.cpp @@ -51,6 +51,7 @@ #if !defined(QT_NO_FREETYPE) #include "private/qfontengine_ft_p.h" #endif +#include "private/qcore_unix_p.h" // overrides QT_OPEN // for mmap #include <stdlib.h> @@ -252,7 +253,7 @@ QList<QByteArray> QFontEngineQPF::cleanUpAfterClientCrash(const QList<int> &cras for (int i = 0; i < int(dir.count()); ++i) { const QByteArray fileName = QFile::encodeName(dir.absoluteFilePath(dir[i])); - int fd = ::open(fileName.constData(), O_RDONLY, 0); + int fd = QT_OPEN(fileName.constData(), O_RDONLY, 0); if (fd >= 0) { void *header = ::mmap(0, sizeof(QFontEngineQPF::Header), PROT_READ, MAP_SHARED, fd, 0); if (header && header != MAP_FAILED) { @@ -265,7 +266,7 @@ QList<QByteArray> QFontEngineQPF::cleanUpAfterClientCrash(const QList<int> &cras ::munmap(header, sizeof(QFontEngineQPF::Header)); } - ::close(fd); + QT_CLOSE(fd); } } if (!removedFonts.isEmpty()) @@ -331,15 +332,15 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng qDebug() << "found existing qpf:" << fileName; #endif if (::access(encodedName, W_OK | R_OK) == 0) - fd = ::open(encodedName, O_RDWR, 0); + fd = QT_OPEN(encodedName, O_RDWR, 0); else if (::access(encodedName, R_OK) == 0) - fd = ::open(encodedName, O_RDONLY, 0); + fd = QT_OPEN(encodedName, O_RDONLY, 0); } else { #if defined(DEBUG_FONTENGINE) qDebug() << "creating qpf on the fly:" << fileName; #endif if (::access(QFile::encodeName(qws_fontCacheDir()), W_OK) == 0) { - fd = ::open(encodedName, O_RDWR | O_EXCL | O_CREAT, 0644); + fd = QT_OPEN(encodedName, O_RDWR | O_EXCL | O_CREAT, 0644); QBuffer buffer; buffer.open(QIODevice::ReadWrite); diff --git a/src/gui/text/qfontengine_qws.cpp b/src/gui/text/qfontengine_qws.cpp index 6fb4f15..70ce8f9 100644 --- a/src/gui/text/qfontengine_qws.cpp +++ b/src/gui/text/qfontengine_qws.cpp @@ -47,6 +47,7 @@ #include <private/qpaintengine_raster_p.h> #include <private/qpdf_p.h> #include "qtextengine_p.h" +#include "private/qcore_unix_p.h" // overrides QT_OPEN #include <qdebug.h> @@ -387,7 +388,7 @@ QFontEngineQPF1::QFontEngineQPF1(const QFontDef&, const QString &fn) { cache_cost = 1; - int f = ::open( QFile::encodeName(fn), O_RDONLY, 0); + int f = QT_OPEN( QFile::encodeName(fn), O_RDONLY, 0); Q_ASSERT(f>=0); QT_STATBUF st; if ( QT_FSTAT( f, &st ) ) @@ -406,7 +407,7 @@ QFontEngineQPF1::QFontEngineQPF1(const QFontDef&, const QString &fn) #endif if ( !data || data == (uchar*)MAP_FAILED ) qFatal("Failed to mmap %s",QFile::encodeName(fn).data()); - ::close(f); + QT_CLOSE(f); d = new QFontEngineQPF1Data; memcpy(reinterpret_cast<char*>(&d->fm),data,sizeof(d->fm)); diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp index 9715aef..f4adc9a 100644 --- a/src/gui/text/qfontengine_win.cpp +++ b/src/gui/text/qfontengine_win.cpp @@ -48,7 +48,6 @@ #include <qlibrary.h> #include <qpaintdevice.h> #include <qpainter.h> -#include <qlibrary.h> #include <limits.h> #include <qendian.h> @@ -85,8 +84,6 @@ ((quint32)(ch1)) \ ) -typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT); - // common DC for all fonts QT_BEGIN_NAMESPACE @@ -130,6 +127,7 @@ HDC shared_dc() static HFONT stock_sysfont = 0; +typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT); static PtrGetCharWidthI ptrGetCharWidthI = 0; static bool resolvedGetCharWidthI = false; @@ -141,27 +139,6 @@ static void resolveGetCharWidthI() ptrGetCharWidthI = (PtrGetCharWidthI)QLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI"); } -// Copy a LOGFONTW struct into a LOGFONTA by converting the face name to an 8 bit value. -// This is needed when calling CreateFontIndirect on non-unicode windowses. -inline static void wa_copy_logfont(LOGFONTW *lfw, LOGFONTA *lfa) -{ - lfa->lfHeight = lfw->lfHeight; - lfa->lfWidth = lfw->lfWidth; - lfa->lfEscapement = lfw->lfEscapement; - lfa->lfOrientation = lfw->lfOrientation; - lfa->lfWeight = lfw->lfWeight; - lfa->lfItalic = lfw->lfItalic; - lfa->lfUnderline = lfw->lfUnderline; - lfa->lfCharSet = lfw->lfCharSet; - lfa->lfOutPrecision = lfw->lfOutPrecision; - lfa->lfClipPrecision = lfw->lfClipPrecision; - lfa->lfQuality = lfw->lfQuality; - lfa->lfPitchAndFamily = lfw->lfPitchAndFamily; - - QString fam = QString::fromUtf16((const ushort*)lfw->lfFaceName); - memcpy(lfa->lfFaceName, fam.toLocal8Bit().constData(), fam.length() + 1); -} - // defined in qtextengine_win.cpp typedef void *SCRIPT_CACHE; typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *); @@ -187,14 +164,6 @@ static inline quint16 getUShort(unsigned char *p) return val; } -static inline HFONT systemFont() -{ - if (stock_sysfont == 0) - stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT); - return stock_sysfont; -} - - // general font engine QFixed QFontEngineWin::lineThickness() const @@ -205,33 +174,18 @@ QFixed QFontEngineWin::lineThickness() const return QFontEngine::lineThickness(); } -#if defined(Q_WS_WINCE) -static OUTLINETEXTMETRICW *getOutlineTextMetric(HDC hdc) +static OUTLINETEXTMETRIC *getOutlineTextMetric(HDC hdc) { int size; - size = GetOutlineTextMetricsW(hdc, 0, 0); - OUTLINETEXTMETRICW *otm = (OUTLINETEXTMETRICW *)malloc(size); - GetOutlineTextMetricsW(hdc, size, otm); + size = GetOutlineTextMetrics(hdc, 0, 0); + OUTLINETEXTMETRIC *otm = (OUTLINETEXTMETRIC *)malloc(size); + GetOutlineTextMetrics(hdc, size, otm); return otm; } -#else -static OUTLINETEXTMETRICA *getOutlineTextMetric(HDC hdc) -{ - int size; - size = GetOutlineTextMetricsA(hdc, 0, 0); - OUTLINETEXTMETRICA *otm = (OUTLINETEXTMETRICA *)malloc(size); - GetOutlineTextMetricsA(hdc, size, otm); - return otm; -} -#endif void QFontEngineWin::getCMap() { - QT_WA({ - ttf = (bool)(tm.w.tmPitchAndFamily & TMPF_TRUETYPE); - } , { - ttf = (bool)(tm.a.tmPitchAndFamily & TMPF_TRUETYPE); - }); + ttf = (bool)(tm.tmPitchAndFamily & TMPF_TRUETYPE); HDC hdc = shared_dc(); SelectObject(hdc, hfont); bool symb = false; @@ -249,11 +203,7 @@ void QFontEngineWin::getCMap() designToDevice = 1; _faceId.index = 0; if(cmap) { -#if defined(Q_WS_WINCE) - OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc); -#else - OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc); -#endif + OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc); designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight); unitsPerEm = otm->otmEMSquare; x_height = (int)otm->otmsXHeight; @@ -263,7 +213,7 @@ void QFontEngineWin::getCMap() fsType = otm->otmfsType; free(otm); } else { - unitsPerEm = tm.w.tmHeight; + unitsPerEm = tm.tmHeight; } } @@ -303,19 +253,14 @@ int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout } } else { #endif - ushort first, last; - QT_WA({ - first = tm.w.tmFirstChar; - last = tm.w.tmLastChar; - }, { - first = tm.a.tmFirstChar; - last = tm.a.tmLastChar; - }); + wchar_t first = tm.tmFirstChar; + wchar_t last = tm.tmLastChar; + for (; i < numChars; ++i, ++glyph_pos) { uint ucs = QChar::mirroredChar(getChar(str, i, numChars)); if ( #ifdef Q_WS_WINCE - tm.w.tmFirstChar > 60000 || // see line 375 + tm.tmFirstChar > 60000 || // see line 375 #endif ucs >= first && ucs <= last) glyphs->glyphs[glyph_pos] = ucs; @@ -341,19 +286,14 @@ int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout } } else { #endif - ushort first, last; - QT_WA({ - first = tm.w.tmFirstChar; - last = tm.w.tmLastChar; - }, { - first = tm.a.tmFirstChar; - last = tm.a.tmLastChar; - }); + wchar_t first = tm.tmFirstChar; + wchar_t last = tm.tmLastChar; + for (; i < numChars; ++i, ++glyph_pos) { uint uc = getChar(str, i, numChars); if ( #ifdef Q_WS_WINCE - tm.w.tmFirstChar > 60000 || // see comment in QFontEngineWin + tm.tmFirstChar > 60000 || // see comment in QFontEngineWin #endif uc >= first && uc <= last) glyphs->glyphs[glyph_pos] = uc; @@ -387,28 +327,14 @@ QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont lineWidth = -1; x_height = -1; - BOOL res; - QT_WA({ - res = GetTextMetricsW(hdc, &tm.w); - } , { - res = GetTextMetricsA(hdc, &tm.a); - }); - fontDef.fixedPitch = !(tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH); + BOOL res = GetTextMetrics(hdc, &tm); + fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH); if (!res) qErrnoWarning("QFontEngineWin: GetTextMetrics failed"); - cache_cost = tm.w.tmHeight * tm.w.tmAveCharWidth * 2000; + cache_cost = tm.tmHeight * tm.tmAveCharWidth * 2000; getCMap(); - useTextOutA = false; -#ifndef Q_OS_WINCE - // TextOutW doesn't work for symbol fonts on Windows 95! - // since we're using glyph indices we don't care for ttfs about this! - if (QSysInfo::WindowsVersion == QSysInfo::WV_95 && !ttf && - (_name == QLatin1String("Marlett") || _name == QLatin1String("Symbol") || - _name == QLatin1String("Webdings") || _name == QLatin1String("Wingdings"))) - useTextOutA = true; -#endif widthCache = 0; widthCacheSize = 0; designAdvances = 0; @@ -427,7 +353,7 @@ QFontEngineWin::~QFontEngineWin() free(widthCache); // make sure we aren't by accident still selected - SelectObject(shared_dc(), systemFont()); + SelectObject(shared_dc(), (HFONT)GetStockObject(SYSTEM_FONT)); if (!stockFont) { if (!DeleteObject(hfont)) @@ -435,39 +361,12 @@ QFontEngineWin::~QFontEngineWin() } } -HGDIOBJ QFontEngineWin::selectDesignFont(QFixed *overhang) const +HGDIOBJ QFontEngineWin::selectDesignFont() const { LOGFONT f = logfont; f.lfHeight = unitsPerEm; - HFONT designFont; - QT_WA({ - designFont = CreateFontIndirectW(&f); - }, { - LOGFONTA fa; - wa_copy_logfont(&f, &fa); - designFont = CreateFontIndirectA(&fa); - }); - HGDIOBJ oldFont = SelectObject(shared_dc(), designFont); - - if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) { - BOOL res; - QT_WA({ - TEXTMETRICW tm; - res = GetTextMetricsW(shared_dc(), &tm); - if (!res) - qErrnoWarning("QFontEngineWin: GetTextMetrics failed"); - *overhang = QFixed((int)tm.tmOverhang) / designToDevice; - } , { - TEXTMETRICA tm; - res = GetTextMetricsA(shared_dc(), &tm); - if (!res) - qErrnoWarning("QFontEngineWin: GetTextMetrics failed"); - *overhang = QFixed((int)tm.tmOverhang) / designToDevice; - }); - } else { - *overhang = 0; - } - return oldFont; + HFONT designFont = CreateFontIndirect(&f); + return SelectObject(shared_dc(), designFont); } bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const @@ -486,8 +385,6 @@ bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyph HDC hdc = shared_dc(); if (flags & QTextEngine::DesignMetrics) { HGDIOBJ oldFont = 0; - QFixed overhang = 0; - int glyph_pos = 0; for(register int i = 0; i < len; i++) { bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1 @@ -502,9 +399,9 @@ bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyph } if(designAdvances[glyph] < -999999) { if(!oldFont) - oldFont = selectDesignFont(&overhang); + oldFont = selectDesignFont(); SIZE size = {0, 0}; - GetTextExtentPoint32W(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size); + GetTextExtentPoint32(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size); designAdvances[glyph] = QFixed((int)size.cx)/designToDevice; } glyphs->advances_x[glyph_pos] = designAdvances[glyph]; @@ -538,7 +435,7 @@ bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyph SIZE size = {0, 0}; if (!oldFont) oldFont = SelectObject(hdc, hfont); - GetTextExtentPoint32W(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size); + GetTextExtentPoint32(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size); glyphs->advances_x[glyph_pos] = size.cx; // if glyph's within cache range, store it for later if (size.cx > 0 && size.cx < 0x100) @@ -564,8 +461,6 @@ void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFla HGDIOBJ oldFont = 0; HDC hdc = shared_dc(); if (ttf && (flags & QTextEngine::DesignMetrics)) { - QFixed overhang = 0; - for(int i = 0; i < glyphs->numGlyphs; i++) { unsigned int glyph = glyphs->glyphs[i]; if(int(glyph) >= designAdvancesSize) { @@ -575,35 +470,14 @@ void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFla designAdvances[i] = -1000000; designAdvancesSize = newSize; } - if(designAdvances[glyph] < -999999) { - if(!oldFont) - oldFont = selectDesignFont(&overhang); + if (designAdvances[glyph] < -999999) { + if (!oldFont) + oldFont = selectDesignFont(); - if (ptrGetCharWidthI) { - int width = 0; + int width = 0; + if (ptrGetCharWidthI) ptrGetCharWidthI(hdc, glyph, 1, 0, &width); - - designAdvances[glyph] = QFixed(width) / designToDevice; - } else { -#ifndef Q_WS_WINCE - GLYPHMETRICS gm; - DWORD res = GDI_ERROR; - MAT2 mat; - mat.eM11.value = mat.eM22.value = 1; - mat.eM11.fract = mat.eM22.fract = 0; - mat.eM21.value = mat.eM12.value = 0; - mat.eM21.fract = mat.eM12.fract = 0; - QT_WA({ - res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat); - } , { - res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat); - }); - - if (res != GDI_ERROR) { - designAdvances[glyph] = QFixed(gm.gmCellIncX) / designToDevice; - } -#endif - } + designAdvances[glyph] = QFixed(width) / designToDevice; } glyphs->advances_x[i] = designAdvances[glyph]; glyphs->advances_y[i] = 0; @@ -611,8 +485,6 @@ void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFla if(oldFont) DeleteObject(SelectObject(hdc, oldFont)); } else { - int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0; - for(int i = 0; i < glyphs->numGlyphs; i++) { unsigned int glyph = glyphs->glyphs[i]; @@ -640,31 +512,10 @@ void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFla ++chrLen; } SIZE size = {0, 0}; - GetTextExtentPoint32W(hdc, (wchar_t *)ch, chrLen, &size); + GetTextExtentPoint32(hdc, (wchar_t *)ch, chrLen, &size); width = size.cx; } else if (ptrGetCharWidthI) { ptrGetCharWidthI(hdc, glyph, 1, 0, &width); - - width -= overhang; - } else { -#ifndef Q_WS_WINCE - GLYPHMETRICS gm; - DWORD res = GDI_ERROR; - MAT2 mat; - mat.eM11.value = mat.eM22.value = 1; - mat.eM11.fract = mat.eM22.fract = 0; - mat.eM21.value = mat.eM12.value = 0; - mat.eM21.fract = mat.eM12.fract = 0; - QT_WA({ - res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat); - } , { - res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat); - }); - - if (res != GDI_ERROR) { - width = gm.gmCellIncX; - } -#endif } glyphs->advances_x[i] = width; // if glyph's within cache range, store it for later @@ -687,7 +538,7 @@ glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout &glyphs) for (int i = 0; i < glyphs.numGlyphs; ++i) w += glyphs.effectiveAdvance(i); - return glyph_metrics_t(0, -tm.w.tmAscent, w, tm.w.tmHeight, w, 0); + return glyph_metrics_t(0, -tm.tmAscent, w, tm.tmHeight, w, 0); } @@ -705,30 +556,13 @@ glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph, const QTransform &t) HDC hdc = shared_dc(); SelectObject(hdc, hfont); - if(!ttf) { - SIZE s = {0, 0}; - WCHAR ch = glyph; - int width; - int overhang = 0; - static bool resolved = false; - if (!resolved) { - QLibrary lib(QLatin1String("gdi32")); - qt_GetCharABCWidthsFloat = (pGetCharABCWidthsFloat) lib.resolve("GetCharABCWidthsFloatW"); - resolved = true; - } - if (QT_WA_INLINE(true, false) && qt_GetCharABCWidthsFloat) { - ABCFLOAT abc; - qt_GetCharABCWidthsFloat(hdc, ch, ch, &abc); - width = qRound(abc.abcfB); - } else { - GetTextExtentPoint32W(hdc, &ch, 1, &s); - overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0; - width = s.cx; - } + if (!ttf) { + wchar_t ch = glyph; + ABCFLOAT abc; + GetCharABCWidthsFloat(hdc, ch, ch, &abc); + int width = qRound(abc.abcfB); - return glyph_metrics_t(0, -tm.a.tmAscent, - width, tm.a.tmHeight, - width-overhang, 0).transformed(t); + return glyph_metrics_t(0, -tm.tmAscent, width, tm.tmHeight, width, 0).transformed(t); } else { DWORD res = 0; MAT2 mat; @@ -753,11 +587,8 @@ glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph, const QTransform &t) SetWorldTransform(hdc, &xform); } - QT_WA({ - res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat); - } , { - res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat); - }); + res = GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, 0, &mat); + if (t.type() > QTransform::TxTranslate) { XFORM xform; xform.eM11 = xform.eM22 = 1; @@ -793,28 +624,28 @@ glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph, const QTransform &t) else #endif { // fallback - width = tm.w.tmMaxCharWidth; + width = tm.tmMaxCharWidth; advance = width; } SelectObject(hdc, oldFont); - return glyph_metrics_t(0, -tm.w.tmAscent, width, tm.w.tmHeight, advance, 0).transformed(t); + return glyph_metrics_t(0, -tm.tmAscent, width, tm.tmHeight, advance, 0).transformed(t); #endif } QFixed QFontEngineWin::ascent() const { - return tm.w.tmAscent; + return tm.tmAscent; } QFixed QFontEngineWin::descent() const { - return tm.w.tmDescent; + return tm.tmDescent; } QFixed QFontEngineWin::leading() const { - return tm.w.tmExternalLeading; + return tm.tmExternalLeading; } @@ -827,12 +658,12 @@ QFixed QFontEngineWin::xHeight() const QFixed QFontEngineWin::averageCharWidth() const { - return tm.w.tmAveCharWidth; + return tm.tmAveCharWidth; } qreal QFontEngineWin::maxCharWidth() const { - return tm.w.tmMaxCharWidth; + return tm.tmMaxCharWidth; } enum { max_font_count = 256 }; @@ -879,10 +710,10 @@ qreal QFontEngineWin::minRightBearing() const SelectObject(hdc, hfont); if (ttf) { ABC *abc = 0; - int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar); + int n = tm.tmLastChar - tm.tmFirstChar; if (n <= max_font_count) { abc = new ABC[n+1]; - GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc); + GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc); } else { abc = new ABC[char_table_entries+1]; for(int i = 0; i < char_table_entries; i++) @@ -898,9 +729,6 @@ qreal QFontEngineWin::minRightBearing() const } } delete [] abc; - } else { - ml = 0; - mr = -tm.a.tmOverhang; } lbearing = ml; rbearing = mr; @@ -915,28 +743,14 @@ qreal QFontEngineWin::minRightBearing() const SelectObject(hdc, hfont); if (ttf) { ABC *abc = 0; - int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar); + int n = tm.tmLastChar - tm.tmFirstChar; if (n <= max_font_count) { abc = new ABC[n+1]; - QT_WA({ - GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc); - }, { - GetCharABCWidthsA(hdc,tm.a.tmFirstChar,tm.a.tmLastChar,abc); - }); + GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc); } else { abc = new ABC[char_table_entries+1]; - QT_WA({ - for(int i = 0; i < char_table_entries; i++) - GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i); - }, { - for(int i = 0; i < char_table_entries; i++) { - QByteArray w = QString(QChar(char_table[i])).toLocal8Bit(); - if (w.length() == 1) { - uint ch8 = (uchar)w[0]; - GetCharABCWidthsA(hdc, ch8, ch8, abc+i); - } - } - }); + for(int i = 0; i < char_table_entries; i++) + GetCharABCWidths(hdc, char_table[i], char_table[i], abc + i); n = char_table_entries; } ml = abc[0].abcA; @@ -949,33 +763,28 @@ qreal QFontEngineWin::minRightBearing() const } delete [] abc; } else { - QT_WA({ - ABCFLOAT *abc = 0; - int n = tm.w.tmLastChar - tm.w.tmFirstChar+1; - if (n <= max_font_count) { - abc = new ABCFLOAT[n]; - GetCharABCWidthsFloat(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc); - } else { - abc = new ABCFLOAT[char_table_entries]; - for(int i = 0; i < char_table_entries; i++) - GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i); - n = char_table_entries; - } - float fml = abc[0].abcfA; - float fmr = abc[0].abcfC; - for (int i=1; i<n; i++) { - if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) { - fml = qMin(fml,abc[i].abcfA); - fmr = qMin(fmr,abc[i].abcfC); - } + ABCFLOAT *abc = 0; + int n = tm.tmLastChar - tm.tmFirstChar+1; + if (n <= max_font_count) { + abc = new ABCFLOAT[n]; + GetCharABCWidthsFloat(hdc, tm.tmFirstChar, tm.tmLastChar, abc); + } else { + abc = new ABCFLOAT[char_table_entries]; + for(int i = 0; i < char_table_entries; i++) + GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i); + n = char_table_entries; + } + float fml = abc[0].abcfA; + float fmr = abc[0].abcfC; + for (int i=1; i<n; i++) { + if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) { + fml = qMin(fml,abc[i].abcfA); + fmr = qMin(fmr,abc[i].abcfC); } - ml = int(fml-0.9999); - mr = int(fmr-0.9999); - delete [] abc; - } , { - ml = 0; - mr = -tm.a.tmOverhang; - }); + } + ml = int(fml - 0.9999); + mr = int(fmr - 0.9999); + delete [] abc; } lbearing = ml; rbearing = mr; @@ -1012,17 +821,10 @@ bool QFontEngineWin::canRender(const QChar *string, int len) return false; } } else { - QT_WA({ - while(len--) { - if (tm.w.tmFirstChar > string->unicode() || tm.w.tmLastChar < string->unicode()) - return false; - } - }, { - while(len--) { - if (tm.a.tmFirstChar > string->unicode() || tm.a.tmLastChar < string->unicode()) - return false; - } - }); + while(len--) { + if (tm.tmFirstChar > string->unicode() || tm.tmLastChar < string->unicode()) + return false; + } } return true; } @@ -1065,11 +867,7 @@ static bool addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc, memset(&gMetric, 0, sizeof(GLYPHMETRICS)); int bufferSize = GDI_ERROR; #if !defined(Q_WS_WINCE) - QT_WA( { - bufferSize = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat); - }, { - bufferSize = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat); - }); + bufferSize = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat); #endif if ((DWORD)bufferSize == GDI_ERROR) { return false; @@ -1078,13 +876,7 @@ static bool addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc, void *dataBuffer = new char[bufferSize]; DWORD ret = GDI_ERROR; #if !defined(Q_WS_WINCE) - QT_WA( { - ret = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, bufferSize, - dataBuffer, &mat); - }, { - ret = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, bufferSize, - dataBuffer, &mat); - } ); + ret = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, bufferSize, dataBuffer, &mat); #endif if (ret == GDI_ERROR) { delete [](char *)dataBuffer; @@ -1171,14 +963,7 @@ void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, in // font at the correct pixel size. lf.lfHeight = -unitsPerEm; lf.lfWidth = 0; - HFONT hf; - QT_WA({ - hf = CreateFontIndirectW(&lf); - }, { - LOGFONTA lfa; - wa_copy_logfont(&lf, &lfa); - hf = CreateFontIndirectA(&lfa); - }); + HFONT hf = CreateFontIndirect(&lf); HDC hdc = shared_dc(); HGDIOBJ oldfont = SelectObject(hdc, hf); @@ -1200,7 +985,7 @@ void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyp QPainterPath *path, QTextItem::RenderFlags flags) { #if !defined(Q_WS_WINCE) - if(tm.w.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) { + if(tm.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) { hasOutline = true; QFontEngine::addOutlineToPath(x, y, glyphs, path, flags); if (hasOutline) { @@ -1234,11 +1019,11 @@ int QFontEngineWin::synthesized() const uchar data[4]; GetFontData(hdc, HEAD, 44, &data, 4); USHORT macStyle = getUShort(data); - if (tm.w.tmItalic && !(macStyle & 2)) + if (tm.tmItalic && !(macStyle & 2)) synthesized_flags = SynthesizedItalic; if (fontDef.stretch != 100 && ttf) synthesized_flags |= SynthesizedStretch; - if (tm.w.tmWeight >= 500 && !(macStyle & 1)) + if (tm.tmWeight >= 500 && !(macStyle & 1)) synthesized_flags |= SynthesizedBold; //qDebug() << "font is" << _name << // "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags; @@ -1254,24 +1039,12 @@ QFixed QFontEngineWin::emSquareSize() const QFontEngine::Properties QFontEngineWin::properties() const { - LOGFONT lf = logfont; lf.lfHeight = unitsPerEm; - HFONT hf; - QT_WA({ - hf = CreateFontIndirectW(&lf); - }, { - LOGFONTA lfa; - wa_copy_logfont(&lf, &lfa); - hf = CreateFontIndirectA(&lfa); - }); + HFONT hf = CreateFontIndirect(&lf); HDC hdc = shared_dc(); HGDIOBJ oldfont = SelectObject(hdc, hf); -#if defined(Q_WS_WINCE) - OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc); -#else - OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc); -#endif + OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc); Properties p; p.emSquare = unitsPerEm; p.italicAngle = otm->otmItalicAngle; @@ -1301,14 +1074,7 @@ void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_m if(flags & SynthesizedItalic) lf.lfItalic = false; lf.lfWidth = 0; - HFONT hf; - QT_WA({ - hf = CreateFontIndirectW(&lf); - }, { - LOGFONTA lfa; - wa_copy_logfont(&lf, &lfa); - hf = CreateFontIndirectA(&lfa); - }); + HFONT hf = CreateFontIndirect(&lf); HDC hdc = shared_dc(); HGDIOBJ oldfont = SelectObject(hdc, hf); QFixedPoint p; @@ -1377,13 +1143,7 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin memset(&mat, 0, sizeof(mat)); mat.eM11.value = mat.eM22.value = 1; - int error = 0; - QT_WA( { - error = GetGlyphOutlineW(hdc, glyph, ggo_options, &tgm, 0, 0, &mat); - }, { - error = GetGlyphOutlineA(hdc, glyph, ggo_options, &tgm, 0, 0, &mat); - } ); - + int error = GetGlyphOutline(hdc, glyph, ggo_options, &tgm, 0, 0, &mat); if (error == GDI_ERROR) { qWarning("QWinFontEngine: unable to query transformed glyph metrics..."); return 0; @@ -1430,11 +1190,11 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin if (has_transformation) { SetGraphicsMode(hdc, GM_ADVANCED); SetWorldTransform(hdc, &xform); - ExtTextOutW(hdc, 0, 0, options, 0, (LPCWSTR) &glyph, 1, 0); + ExtTextOut(hdc, 0, 0, options, 0, (LPCWSTR) &glyph, 1, 0); } else #endif { - ExtTextOutW(hdc, -gx + margin, -gy + margin, options, 0, (LPCWSTR) &glyph, 1, 0); + ExtTextOut(hdc, -gx + margin, -gy + margin, options, 0, (LPCWSTR) &glyph, 1, 0); } SelectObject(hdc, old_font); @@ -1450,7 +1210,7 @@ QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) if (qt_cleartype_enabled) { LOGFONT lf = logfont; lf.lfQuality = ANTIALIASED_QUALITY; - font = CreateFontIndirectW(&lf); + font = CreateFontIndirect(&lf); } QImage::Format mask_format = QNativeImage::systemFormat(); #ifndef Q_OS_WINCE @@ -1557,17 +1317,9 @@ void QFontEngineMultiWin::loadEngine(int at) QString fam = fallbacks.at(at-1); LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont; - HFONT hfont; - QT_WA({ - memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded - hfont = CreateFontIndirectW(&lf); - } , { - // LOGFONTA and LOGFONTW are binary compatible - QByteArray lname = fam.toLocal8Bit(); - memcpy(lf.lfFaceName,lname.data(), - qMin(lname.length()+1,32)); // 32 = Windows hard-coded - hfont = CreateFontIndirectA((LOGFONTA*)&lf); - }); + memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded + HFONT hfont = CreateFontIndirect(&lf); + bool stockFont = false; if (hfont == 0) { hfont = (HFONT)GetStockObject(ANSI_VAR_FONT); diff --git a/src/gui/text/qfontengine_win_p.h b/src/gui/text/qfontengine_win_p.h index a8da78a..b86bd00 100644 --- a/src/gui/text/qfontengine_win_p.h +++ b/src/gui/text/qfontengine_win_p.h @@ -80,7 +80,7 @@ public: virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, QPainterPath *path, QTextItem::RenderFlags flags); - HGDIOBJ selectDesignFont(QFixed *) const; + HGDIOBJ selectDesignFont() const; virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t g) { return boundingBox(g, QTransform()); } @@ -109,18 +109,14 @@ public: int getGlyphIndexes(const QChar *ch, int numChars, QGlyphLayout *glyphs, bool mirrored) const; void getCMap(); - QString _name; - HFONT hfont; + QString _name; + HFONT hfont; LOGFONT logfont; - uint stockFont : 1; - uint useTextOutA : 1; - uint ttf : 1; + uint stockFont : 1; + uint ttf : 1; uint hasOutline : 1; - union { - TEXTMETRICW w; - TEXTMETRICA a; - } tm; - int lw; + TEXTMETRIC tm; + int lw; const unsigned char *cmap; QByteArray cmapTable; mutable qreal lbearing; diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index b2ad686..2a590fd 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -1245,7 +1245,8 @@ void QTextControlPrivate::keyPressEvent(QKeyEvent *e) process: { QString text = e->text(); - if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t'))) { + if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t')) && + ((e->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) == Qt::NoModifier)) { if (overwriteMode // no need to call deleteChar() if we have a selection, insertText // does it already diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp index 2cc478d..e872617 100644 --- a/src/gui/util/qdesktopservices_win.cpp +++ b/src/gui/util/qdesktopservices_win.cpp @@ -62,33 +62,23 @@ QT_BEGIN_NAMESPACE -//#undef UNICODE - static bool openDocument(const QUrl &file) { if (!file.isValid()) return false; - quintptr returnValue; - QT_WA({ - returnValue = (quintptr)ShellExecute(0, 0, (TCHAR *)file.toString().utf16(), 0, 0, SW_SHOWNORMAL); - } , { - returnValue = (quintptr)ShellExecuteA(0, 0, file.toString().toLocal8Bit().constData(), 0, 0, SW_SHOWNORMAL); - }); + quintptr returnValue = (quintptr)ShellExecute(0, 0, (wchar_t*)file.toString().utf16(), 0, 0, SW_SHOWNORMAL); return (returnValue > 32); //ShellExecute returns a value greater than 32 if successful } static QString expandEnvStrings(const QString &command) { - #if defined(Q_OS_WINCE) return command; #else - QByteArray path = command.toLocal8Bit(); - char commandValue[2 * MAX_PATH] = {0}; - DWORD returnValue = ExpandEnvironmentStringsA(path.data(), commandValue, MAX_PATH); - if (returnValue) - return QString::fromLocal8Bit(commandValue); + wchar_t buffer[MAX_PATH]; + if (ExpandEnvironmentStrings((wchar_t*)command.utf16(), buffer, MAX_PATH)) + return QString::fromWCharArray(buffer); else return command; #endif @@ -129,8 +119,9 @@ static bool launchWebBrowser(const QUrl &url) command = QString::fromRawData((QChar*)keyValue, bufferSize); RegCloseKey(handle); - if(returnValue) + if (returnValue) return false; + command = expandEnvStrings(command); command = command.trimmed(); //Make sure the path for the process is in quotes @@ -152,7 +143,7 @@ static bool launchWebBrowser(const QUrl &url) ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); - returnValue = CreateProcess(NULL, (TCHAR*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); + returnValue = CreateProcess(NULL, (wchar_t*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (!returnValue) return false; @@ -168,9 +159,8 @@ static bool launchWebBrowser(const QUrl &url) if (url.scheme().isEmpty()) return openDocument(url); - quintptr returnValue; - returnValue = (quintptr)ShellExecute(0, 0, (TCHAR *) QString::fromUtf8(url.toEncoded().constData()).utf16(), - 0, 0, SW_SHOWNORMAL); + quintptr returnValue = (quintptr)ShellExecute(0, 0, (wchar_t *)QString::fromUtf8(url.toEncoded().constData()).utf16(), + 0, 0, SW_SHOWNORMAL); return (returnValue > 32); } diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp index d2ce1be..c1b7e7f 100644 --- a/src/gui/util/qsystemtrayicon_win.cpp +++ b/src/gui/util/qsystemtrayicon_win.cpp @@ -41,8 +41,7 @@ #include "qsystemtrayicon_p.h" #ifndef QT_NO_SYSTEMTRAYICON -//#define _WIN32_IE 0x0500 -#define _WIN32_IE 0x0600 //required for NOTIFYICONDATAW_V2_SIZE +#define _WIN32_IE 0x0600 //required for NOTIFYICONDATA_V2_SIZE //missing defines for MINGW : #ifndef NIN_BALLOONTIMEOUT @@ -77,25 +76,14 @@ static const UINT q_uNOTIFYICONID = 0; static uint MYWM_TASKBARCREATED = 0; #define MYWM_NOTIFYICON (WM_APP+101) -typedef BOOL (WINAPI *PtrShell_NotifyIcon)(DWORD,PNOTIFYICONDATA); -static PtrShell_NotifyIcon ptrShell_NotifyIcon = 0; +struct Q_NOTIFYICONIDENTIFIER { + DWORD cbSize; + HWND hWnd; + UINT uID; + GUID guidItem; +}; -static void resolveLibs() -{ - static bool triedResolve = false; -#if defined Q_OS_WINCE - QString libName(QLatin1String("coredll")); - const char* funcName = "Shell_NotifyIcon"; -#else - QString libName(QLatin1String("shell32")); - const char* funcName = "Shell_NotifyIconW"; -#endif - if (!triedResolve) { - QLibrary lib(libName); - triedResolve = true; - ptrShell_NotifyIcon = (PtrShell_NotifyIcon) lib.resolve(funcName); - } -} +typedef HRESULT (WINAPI *PtrShell_NotifyIconGetRect)(const Q_NOTIFYICONIDENTIFIER* identifier, RECT* iconLocation); class QSystemTrayIconSys : QWidget { @@ -103,37 +91,26 @@ public: QSystemTrayIconSys(QSystemTrayIcon *object); ~QSystemTrayIconSys(); bool winEvent( MSG *m, long *result ); - bool trayMessageA(DWORD msg); - bool trayMessageW(DWORD msg); bool trayMessage(DWORD msg); bool iconDrawItem(LPDRAWITEMSTRUCT lpdi); - void setIconContentsW(NOTIFYICONDATAW &data); - void setIconContentsA(NOTIFYICONDATAA &data); - bool showMessageW(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs); - bool showMessageA(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs); + void setIconContents(NOTIFYICONDATA &data); + bool showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs); bool allowsMessages(); bool supportsMessages(); QRect findIconGeometry(const int a_iButtonID); - QRect findTrayGeometry(); HBITMAP createIconMask(const QBitmap &bitmap); void createIcon(); - int detectShellVersion() const; HICON hIcon; QPoint globalPos; QSystemTrayIcon *q; private: - uint notifyIconSizeW; - uint notifyIconSizeA; - int currentShellVersion; + uint notifyIconSize; int maxTipLength; }; -// Checks for the shell32 dll version number, since only version -// 5 or later of supports ballon messages bool QSystemTrayIconSys::allowsMessages() { #ifndef QT_NO_SETTINGS - QSettings settings(QLatin1String("HKEY_CURRENT_USER\\Software\\Microsoft" "\\Windows\\CurrentVersion\\Explorer\\Advanced"), QSettings::NativeFormat); return settings.value(QLatin1String("EnableBalloonTips"), true).toBool(); @@ -142,63 +119,28 @@ bool QSystemTrayIconSys::allowsMessages() #endif } -// Checks for the shell32 dll version number, since only version -// 5 or later of supports ballon messages bool QSystemTrayIconSys::supportsMessages() { -#if NOTIFYICON_VERSION >= 3 - if (currentShellVersion >= 5) - return allowsMessages(); - else -#endif - return false; -} - -//Returns the runtime major version of the shell32 dll -int QSystemTrayIconSys::detectShellVersion() const -{ #ifndef Q_OS_WINCE - int shellVersion = 4; //NT 4.0 and W95 - DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)QLibrary::resolve( - QLatin1String("shell32"), "DllGetVersion"); - if (pDllGetVersion) - { - DLLVERSIONINFO dvi; - HRESULT hr; - ZeroMemory(&dvi, sizeof(dvi)); - dvi.cbSize = sizeof(dvi); - hr = (*pDllGetVersion)(&dvi); - if (SUCCEEDED(hr)) { - if (dvi.dwMajorVersion >= 5) - { - shellVersion = dvi.dwMajorVersion; - } - } - } - return shellVersion; + return allowsMessages(); #endif - return 4; //No ballonMessages and MaxTipLength = 64 for WindowsCE + return false; } QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object) : hIcon(0), q(object) { - currentShellVersion = detectShellVersion(); - notifyIconSizeA = FIELD_OFFSET(NOTIFYICONDATAA, szTip[64]); // NOTIFYICONDATAA_V1_SIZE - notifyIconSizeW = FIELD_OFFSET(NOTIFYICONDATAW, szTip[64]); // NOTIFYICONDATAW_V1_SIZE; +#ifndef Q_OS_WINCE + notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, guidItem); // NOTIFYICONDATAW_V2_SIZE; + maxTipLength = 128; +#else + notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, szTip[64]); // NOTIFYICONDATAW_V1_SIZE; maxTipLength = 64; - -#if NOTIFYICON_VERSION >= 3 - if (currentShellVersion >=5) { - notifyIconSizeA = FIELD_OFFSET(NOTIFYICONDATAA, guidItem); // NOTIFYICONDATAA_V2_SIZE - notifyIconSizeW = FIELD_OFFSET(NOTIFYICONDATAW, guidItem); // NOTIFYICONDATAW_V2_SIZE; - maxTipLength = 128; - } #endif // For restoring the tray icon after explorer crashes if (!MYWM_TASKBARCREATED) { - MYWM_TASKBARCREATED = QT_WA_INLINE(RegisterWindowMessageW(L"TaskbarCreated"),RegisterWindowMessageA("TaskbarCreated")); + MYWM_TASKBARCREATED = RegisterWindowMessage(L"TaskbarCreated"); } } @@ -208,118 +150,60 @@ QSystemTrayIconSys::~QSystemTrayIconSys() DestroyIcon(hIcon); } -void QSystemTrayIconSys::setIconContentsW(NOTIFYICONDATAW &tnd) +void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd) { - tnd.uFlags = NIF_MESSAGE|NIF_ICON|NIF_TIP; + tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; tnd.uCallbackMessage = MYWM_NOTIFYICON; tnd.hIcon = hIcon; QString tip = q->toolTip(); if (!tip.isNull()) { - // Tip is limited to maxTipLength - NULL; lstrcpyn appends a NULL terminator. tip = tip.left(maxTipLength - 1) + QChar(); -#if defined(Q_OS_WINCE) - wcsncpy(tnd.szTip, reinterpret_cast<const wchar_t *> (tip.utf16()), qMin(tip.length()+1, maxTipLength)); -#else - lstrcpynW(tnd.szTip, (TCHAR*)tip.utf16(), qMin(tip.length()+1, maxTipLength)); -#endif - } -} - -void QSystemTrayIconSys::setIconContentsA(NOTIFYICONDATAA &tnd) -{ - tnd.uFlags = NIF_MESSAGE|NIF_ICON|NIF_TIP; - tnd.uCallbackMessage = MYWM_NOTIFYICON; - tnd.hIcon = hIcon; - QString tip = q->toolTip(); - - if (!tip.isNull()) { - // Tip is limited to maxTipLength - NULL; lstrcpyn appends a NULL terminator. - tip = tip.left(maxTipLength - 1) + QChar(); -#if defined(Q_OS_WINCE) - strncpy(tnd.szTip, tip.toLocal8Bit().constData(), qMin(tip.length()+1, maxTipLength)); -#else - lstrcpynA(tnd.szTip, tip.toLocal8Bit().constData(), qMin(tip.length()+1, maxTipLength)); -#endif + memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t)); } } int iconFlag( QSystemTrayIcon::MessageIcon icon ) { - int flag = 0; #if NOTIFYICON_VERSION >= 3 switch (icon) { - case QSystemTrayIcon::NoIcon: - break; - case QSystemTrayIcon::Critical: - flag = NIIF_ERROR; - break; - case QSystemTrayIcon::Warning: - flag = NIIF_WARNING; - break; case QSystemTrayIcon::Information: - default : // fall through - flag = NIIF_INFO; + return NIIF_INFO; + case QSystemTrayIcon::Warning: + return NIIF_WARNING; + case QSystemTrayIcon::Critical: + return NIIF_ERROR; + case QSystemTrayIcon::NoIcon: + return NIIF_NONE; + default: + Q_ASSERT("Invalid QSystemTrayIcon::MessageIcon value", false); + return NIIF_NONE; } #else Q_UNUSED(icon); + return 0; #endif - return flag; } -bool QSystemTrayIconSys::showMessageW(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs) +bool QSystemTrayIconSys::showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs) { -#if NOTIFYICON_VERSION>=3 +#if NOTIFYICON_VERSION >= 3 NOTIFYICONDATA tnd; - memset(&tnd, 0, notifyIconSizeW); + memset(&tnd, 0, notifyIconSize); Q_ASSERT(testAttribute(Qt::WA_WState_Created)); - setIconContentsW(tnd); -#if defined(Q_OS_WINCE) - wcsncpy(tnd.szInfo, message.utf16(), qMin(message.length() + 1, 256)); - wcsncpy(tnd.szInfoTitle, title.utf16(), qMin(title.length()+1, 64)); -#else - lstrcpynW(tnd.szInfo, (TCHAR*)message.utf16(), qMin(message.length() + 1, 256)); - lstrcpynW(tnd.szInfoTitle, (TCHAR*)title.utf16(), qMin(title.length() + 1, 64)); -#endif - tnd.uID = q_uNOTIFYICONID; - tnd.dwInfoFlags = iconFlag(type); - tnd.cbSize = notifyIconSizeW; - tnd.hWnd = winId(); - tnd.uTimeout = uSecs; - tnd.uFlags = NIF_INFO; - return ptrShell_NotifyIcon(NIM_MODIFY, &tnd); -#else - Q_UNUSED(title); - Q_UNUSED(message); - Q_UNUSED(type); - Q_UNUSED(uSecs); - return false; -#endif -} - -bool QSystemTrayIconSys::showMessageA(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs) -{ -#if NOTIFYICON_VERSION>=3 - NOTIFYICONDATAA tnd; - memset(&tnd, 0, notifyIconSizeA); - Q_ASSERT(testAttribute(Qt::WA_WState_Created)); + setIconContents(tnd); + memcpy(tnd.szInfo, message.utf16(), qMin(message.length() + 1, 256) * sizeof(wchar_t)); + memcpy(tnd.szInfoTitle, title.utf16(), qMin(title.length() + 1, 64) * sizeof(wchar_t)); - setIconContentsA(tnd); -#if defined(Q_OS_WINCE) - strncpy(tnd.szInfo, message.toLocal8Bit().constData(), qMin(message.length() + 1, 256)); - strncpy(tnd.szInfoTitle, title.toLocal8Bit().constData(), qMin(title.length()+1, 64)); -#else - lstrcpynA(tnd.szInfo, message.toLocal8Bit().constData(), qMin(message.length() + 1, 256)); - lstrcpynA(tnd.szInfoTitle, title.toLocal8Bit().constData(), qMin(title.length() + 1, 64)); -#endif tnd.uID = q_uNOTIFYICONID; tnd.dwInfoFlags = iconFlag(type); - tnd.cbSize = notifyIconSizeA; + tnd.cbSize = notifyIconSize; tnd.hWnd = winId(); tnd.uTimeout = uSecs; tnd.uFlags = NIF_INFO; - return Shell_NotifyIconA(NIM_MODIFY, &tnd); + + return Shell_NotifyIcon(NIM_MODIFY, &tnd); #else Q_UNUSED(title); Q_UNUSED(message); @@ -329,53 +213,21 @@ bool QSystemTrayIconSys::showMessageA(const QString &title, const QString &messa #endif } -bool QSystemTrayIconSys::trayMessageA(DWORD msg) +bool QSystemTrayIconSys::trayMessage(DWORD msg) { -#if !defined(Q_WS_WINCE) - NOTIFYICONDATAA tnd; - memset(&tnd, 0, notifyIconSizeA); + NOTIFYICONDATA tnd; + memset(&tnd, 0, notifyIconSize); tnd.uID = q_uNOTIFYICONID; - tnd.cbSize = notifyIconSizeA; + tnd.cbSize = notifyIconSize; tnd.hWnd = winId(); - Q_ASSERT(testAttribute(Qt::WA_WState_Created)); - if (msg != NIM_DELETE) { - setIconContentsA(tnd); - } - return Shell_NotifyIconA(msg, &tnd); -#else - Q_UNUSED(msg); - return false; -#endif -} - -bool QSystemTrayIconSys::trayMessageW(DWORD msg) -{ - NOTIFYICONDATAW tnd; - memset(&tnd, 0, notifyIconSizeW); - tnd.uID = q_uNOTIFYICONID; - tnd.cbSize = notifyIconSizeW; - tnd.hWnd = winId(); Q_ASSERT(testAttribute(Qt::WA_WState_Created)); if (msg != NIM_DELETE) { - setIconContentsW(tnd); + setIconContents(tnd); } - return ptrShell_NotifyIcon(msg, &tnd); -} -bool QSystemTrayIconSys::trayMessage(DWORD msg) -{ - resolveLibs(); - if (!(ptrShell_NotifyIcon)) - return false; - - QT_WA({ - return trayMessageW(msg); - }, - { - return trayMessageA(msg); - }); + return Shell_NotifyIcon(msg, &tnd); } bool QSystemTrayIconSys::iconDrawItem(LPDRAWITEMSTRUCT lpdi) @@ -514,33 +366,6 @@ void QSystemTrayIconPrivate::install_sys() } } -//fallback on win 95/98 -QRect QSystemTrayIconSys::findTrayGeometry() -{ - //Use lower right corner as fallback - QPoint brCorner = QApplication::desktop()->screenGeometry().bottomRight(); - QRect ret(brCorner.x() - 10, brCorner.y() - 10, 10, 10); -#if defined(Q_OS_WINCE) - HWND trayHandle = FindWindowW(L"Shell_TrayWnd", NULL); -#else - HWND trayHandle = FindWindowA("Shell_TrayWnd", NULL); -#endif - if (trayHandle) { -#if defined(Q_OS_WINCE) - trayHandle = FindWindowW(L"TrayNotifyWnd", NULL); -#else - trayHandle = FindWindowExA(trayHandle, NULL, "TrayNotifyWnd", NULL); -#endif - if (trayHandle) { - RECT r; - if (GetWindowRect(trayHandle, &r)) { - ret = QRect(r.left, r.top, r.right- r.left, r.bottom - r.top); - } - } - } - return ret; -} - /* * This function tries to determine the icon geometry from the tray * @@ -548,26 +373,39 @@ QRect QSystemTrayIconSys::findTrayGeometry() */ QRect QSystemTrayIconSys::findIconGeometry(const int iconId) { + static PtrShell_NotifyIconGetRect Shell_NotifyIconGetRect = + (PtrShell_NotifyIconGetRect)QLibrary::resolve(QLatin1String("shell32"), "Shell_NotifyIconGetRect"); + + if (Shell_NotifyIconGetRect) { + Q_NOTIFYICONIDENTIFIER nid; + memset(&nid, 0, sizeof(nid)); + nid.cbSize = sizeof(nid); + nid.hWnd = winId(); + nid.uID = iconId; + + RECT rect; + HRESULT hr = Shell_NotifyIconGetRect(&nid, &rect); + if (SUCCEEDED(hr)) { + return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); + } + } + QRect ret; TBBUTTON buttonData; DWORD processID = 0; -#if defined(Q_OS_WINCE) - HWND trayHandle = FindWindowW(L"Shell_TrayWnd", NULL); -#else - HWND trayHandle = FindWindowA("Shell_TrayWnd", NULL); -#endif + HWND trayHandle = FindWindow(L"Shell_TrayWnd", NULL); //find the toolbar used in the notification area if (trayHandle) { #if defined(Q_OS_WINCE) - trayHandle = FindWindowW(L"TrayNotifyWnd", NULL); + trayHandle = FindWindow(L"TrayNotifyWnd", NULL); #else - trayHandle = FindWindowExA(trayHandle, NULL, "TrayNotifyWnd", NULL); + trayHandle = FindWindowEx(trayHandle, NULL, L"TrayNotifyWnd", NULL); #endif if (trayHandle) { #if defined(Q_OS_WINCE) - HWND hwnd = FindWindowW(L"SysPager", NULL); + HWND hwnd = FindWindow(L"SysPager", NULL); #else HWND hwnd = FindWindowEx(trayHandle, NULL, L"SysPager", NULL); #endif @@ -612,10 +450,10 @@ QRect QSystemTrayIconSys::findIconGeometry(const int iconId) DWORD appData[2] = { 0, 0 }; SendMessage(trayHandle, TB_GETBUTTON, toolbarButton , (LPARAM)data); - if(!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes)) + if (!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes)) continue; - if(!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes)) + if (!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes)) continue; int currentIconId = appData[1]; @@ -646,7 +484,6 @@ QRect QSystemTrayIconSys::findIconGeometry(const int iconId) return ret; } - void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut) { if (!sys || !sys->allowsMessages()) @@ -657,8 +494,6 @@ void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString uSecs = 10000; //10 sec default else uSecs = (int)timeOut; - resolveLibs(); - //message is limited to 255 chars + NULL QString messageString; if (message.isEmpty() && !title.isEmpty()) @@ -670,20 +505,12 @@ void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString QString titleString = title.left(63) + QChar(); if (sys->supportsMessages()) { - QT_WA({ - sys->showMessageW(titleString, messageString, type, (unsigned int)uSecs); - }, { - sys->showMessageA(titleString, messageString, type, (unsigned int)uSecs); - }); + sys->showMessage(titleString, messageString, type, (unsigned int)uSecs); } else { - //use fallbacks - QRect iconPos = sys->findIconGeometry(0); + //use fallback + QRect iconPos = sys->findIconGeometry(q_uNOTIFYICONID); if (iconPos.isValid()) { QBalloonTip::showBalloon(type, title, message, sys->q, iconPos.center(), uSecs, true); - } else { - QRect trayRect = sys->findTrayGeometry(); - QBalloonTip::showBalloon(type, title, message, sys->q, QPoint(trayRect.left(), - trayRect.center().y()), uSecs, false); } } } @@ -692,7 +519,7 @@ QRect QSystemTrayIconPrivate::geometry_sys() const { if (!sys) return QRect(); - return sys->findIconGeometry(0); + return sys->findIconGeometry(q_uNOTIFYICONID); } void QSystemTrayIconPrivate::remove_sys() diff --git a/src/gui/widgets/qabstractscrollarea.cpp b/src/gui/widgets/qabstractscrollarea.cpp index 00be29b..66572b8 100644 --- a/src/gui/widgets/qabstractscrollarea.cpp +++ b/src/gui/widgets/qabstractscrollarea.cpp @@ -51,10 +51,13 @@ #include "qdebug.h" #include "qboxlayout.h" #include "qpainter.h" +#include "qstandardgestures.h" #include "qabstractscrollarea_p.h" #include <qwidget.h> +#include <private/qapplication_p.h> + #ifdef Q_WS_MAC #include <private/qt_mac_p.h> #include <private/qt_cocoa_helpers_mac_p.h> @@ -157,6 +160,9 @@ 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) +#ifdef Q_WS_WIN + , singleFingerPanEnabled(false) +#endif { } @@ -290,6 +296,31 @@ void QAbstractScrollAreaPrivate::init() layoutChildren(); } +void QAbstractScrollAreaPrivate::setupGestures() +{ +#ifdef Q_OS_WIN + if (!viewport) + return; + 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 +} + void QAbstractScrollAreaPrivate::layoutChildren() { Q_Q(QAbstractScrollArea); @@ -909,7 +940,6 @@ bool QAbstractScrollArea::event(QEvent *e) case QEvent::DragMove: case QEvent::DragLeave: #endif - return false; case QEvent::StyleChange: case QEvent::LayoutDirectionChange: case QEvent::ApplicationLayoutDirectionChange: @@ -1238,6 +1268,7 @@ void QAbstractScrollAreaPrivate::_q_vslide(int y) void QAbstractScrollAreaPrivate::_q_showOrHideScrollBars() { layoutChildren(); + setupGestures(); } QPoint QAbstractScrollAreaPrivate::contentsOffset() const diff --git a/src/gui/widgets/qabstractscrollarea_p.h b/src/gui/widgets/qabstractscrollarea_p.h index 71a83cc..5d3494b 100644 --- a/src/gui/widgets/qabstractscrollarea_p.h +++ b/src/gui/widgets/qabstractscrollarea_p.h @@ -99,6 +99,11 @@ public: inline bool viewportEvent(QEvent *event) { return q_func()->viewportEvent(event); } QObject *viewportFilter; + +#ifdef Q_WS_WIN + bool singleFingerPanEnabled; +#endif + void setupGestures(); }; class QAbstractScrollAreaFilter : public QObject diff --git a/src/gui/widgets/qabstractspinbox.cpp b/src/gui/widgets/qabstractspinbox.cpp index 25acd6e..da18d13 100644 --- a/src/gui/widgets/qabstractspinbox.cpp +++ b/src/gui/widgets/qabstractspinbox.cpp @@ -57,6 +57,9 @@ #include <qpalette.h> #include <qstylepainter.h> #include <qdebug.h> +#ifndef QT_NO_ACCESSIBILITY +# include <qaccessible.h> +#endif #if defined(Q_WS_X11) #include <limits.h> @@ -951,6 +954,9 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event) d->buttonState = (Keyboard | (up ? Up : Down)); } stepBy(steps); +#ifndef QT_NO_ACCESSIBILITY + QAccessible::updateAccessibility(this, 0, QAccessible::ValueChanged); +#endif return; } #ifdef QT_KEYPAD_NAVIGATION @@ -1548,6 +1554,9 @@ void QAbstractSpinBoxPrivate::updateState(bool up) spinClickThresholdTimerId = q->startTimer(spinClickThresholdTimerInterval); buttonState = (up ? (Mouse | Up) : (Mouse | Down)); q->stepBy(up ? 1 : -1); +#ifndef QT_NO_ACCESSIBILITY + QAccessible::updateAccessibility(q, 0, QAccessible::ValueChanged); +#endif } } diff --git a/src/gui/widgets/qabstractspinbox_p.h b/src/gui/widgets/qabstractspinbox_p.h index 15f5d97..0d00e04 100644 --- a/src/gui/widgets/qabstractspinbox_p.h +++ b/src/gui/widgets/qabstractspinbox_p.h @@ -135,8 +135,6 @@ public: mutable QValidator::State cachedState; mutable QSize cachedSizeHint, cachedMinimumSizeHint; uint pendingEmit : 1; - uint spindownEnabled : 1; - uint spinupEnabled : 1; uint readOnly : 1; uint wrapping : 1; uint ignoreCursorPositionChanged : 1; diff --git a/src/gui/widgets/qcheckbox.cpp b/src/gui/widgets/qcheckbox.cpp index 0fbc323..3108c7c 100644 --- a/src/gui/widgets/qcheckbox.cpp +++ b/src/gui/widgets/qcheckbox.cpp @@ -75,52 +75,60 @@ public: \ingroup basicwidgets \mainclass - A QCheckBox is an option button that can be switched on (checked) - or off (unchecked). Checkboxes are typically used to represent - features in an application that can be enabled or disabled without - affecting others, but different types of behavior can be - implemented. - - A QButtonGroup can be used to group check buttons visually. + A QCheckBox is an option button that can be switched on (checked) or off + (unchecked). Checkboxes are typically used to represent features in an + application that can be enabled or disabled without affecting others, but + different types of behavior can be implemented. For example, a + QButtonGroup can be used to group check buttons logically, allowing + exclusive checkboxes. However, QButtonGroup does not provide any visual + representation. + + The image below further illustrates the differences between exclusive and + non-exclusive checkboxes. + + \table + \row \o \inlineimage checkboxes-exclusive.png + \o \inlineimage checkboxes-non-exclusive.png + \endtable Whenever a checkbox is checked or cleared it emits the signal - stateChanged(). Connect to this signal if you want to trigger an - action each time the checkbox changes state. You can use - isChecked() to query whether or not a checkbox is checked. - - In addition to the usual checked and unchecked states, QCheckBox - optionally provides a third state to indicate "no change". This - is useful whenever you need to give the user the option of neither - checking nor unchecking a checkbox. If you need this third state, - enable it with setTristate(), and use checkState() to query the current - toggle state. - - Just like QPushButton, a checkbox displays text, and optionally a - small icon. The icon is set with setIcon(). The text can be set in - the constructor or with setText(). A shortcut key can be specified - by preceding the preferred character with an ampersand. For - example: + stateChanged(). Connect to this signal if you want to trigger an action + each time the checkbox changes state. You can use isChecked() to query + whether or not a checkbox is checked. + + In addition to the usual checked and unchecked states, QCheckBox optionally + provides a third state to indicate "no change". This is useful whenever you + need to give the user the option of neither checking nor unchecking a + checkbox. If you need this third state, enable it with setTristate(), and + use checkState() to query the current toggle state. + + Just like QPushButton, a checkbox displays text, and optionally a small + icon. The icon is set with setIcon(). The text can be set in the + constructor or with setText(). A shortcut key can be specified by preceding + the preferred character with an ampersand. For example: \snippet doc/src/snippets/code/src_gui_widgets_qcheckbox.cpp 0 - In this example the shortcut is \e{Alt+A}. See the \l - {QShortcut#mnemonic}{QShortcut} documentation for details (to - display an actual ampersand, use '&&'). + In this example the shortcut is \e{Alt+A}. See the \l{QShortcut#mnemonic} + {QShortcut} documentation for details (to display an actual ampersand, + use '&&'). - Important inherited functions: text(), setText(), text(), - pixmap(), setPixmap(), accel(), setAccel(), isToggleButton(), - setDown(), isDown(), isOn(), checkState(), autoRepeat(), - isExclusiveToggle(), group(), setAutoRepeat(), toggle(), - pressed(), released(), clicked(), toggled(), checkState(), and - stateChanged(). + Important inherited functions: text(), setText(), text(), pixmap(), + setPixmap(), accel(), setAccel(), isToggleButton(), setDown(), isDown(), + isOn(), checkState(), autoRepeat(), isExclusiveToggle(), group(), + setAutoRepeat(), toggle(), pressed(), released(), clicked(), toggled(), + checkState(), and stateChanged(). \table 100% - \row \o \inlineimage macintosh-checkbox.png Screenshot of a Macintosh style checkbox - \o A checkbox shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}. - \row \o \inlineimage windows-checkbox.png Screenshot of a Windows XP style checkbox - \o A checkbox shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}. - \row \o \inlineimage plastique-checkbox.png Screenshot of a Plastique style checkbox - \o A checkbox shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}. + \row + \o \inlineimage macintosh-checkbox.png Screenshot of a Macintosh style checkbox + \o A checkbox shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}. + \row + \o \inlineimage windows-checkbox.png Screenshot of a Windows XP style checkbox + \o A checkbox shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}. + \row + \o \inlineimage plastique-checkbox.png Screenshot of a Plastique style checkbox + \o A checkbox shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}. \endtable \sa QAbstractButton, QRadioButton, {fowler}{GUI Design Handbook: Check Box} @@ -138,8 +146,8 @@ public: /*! \fn void QCheckBox::stateChanged(int state) - This signal is emitted whenever the check box's state changes, - i.e. whenever the user checks or unchecks it. + This signal is emitted whenever the check box's state changes, i.e. + whenever the user checks or unchecks it. \a state contains the check box's new Qt::CheckState. */ @@ -161,9 +169,9 @@ void QCheckBoxPrivate::init() } /*! - Initialize \a option with the values from this QCheckBox. This method is useful - for subclasses when they need a QStyleOptionButton, but don't want to fill - in all the information themselves. + Initializes \a option with the values from this QCheckBox. This method is + useful for subclasses that require a QStyleOptionButton, but do not want + to fill in all the information themselves. \sa QStyleOption::initFrom() */ @@ -193,7 +201,7 @@ void QCheckBox::initStyleOption(QStyleOptionButton *option) const /*! Constructs a checkbox with the given \a parent, but with no text. - The \a parent argument is passed on to the QAbstractButton constructor. + \a parent is passed on to the QAbstractButton constructor. */ QCheckBox::QCheckBox(QWidget *parent) @@ -206,7 +214,7 @@ QCheckBox::QCheckBox(QWidget *parent) /*! Constructs a checkbox with the given \a parent and \a text. - The \a parent argument is passed on to the QAbstractButton constructor. + \a parent is passed on to the QAbstractButton constructor. */ QCheckBox::QCheckBox(const QString &text, QWidget *parent) @@ -231,10 +239,8 @@ bool QCheckBox::isTristate() const /*! - Returns the check box's check state. - If you do not need tristate support, you can also - use \l QAbstractButton::isChecked() which returns - a boolean. + Returns the check box's check state. If you do not need tristate support, + you can also use \l QAbstractButton::isChecked() which returns a boolean. \sa setCheckState() Qt::CheckState */ @@ -247,10 +253,9 @@ Qt::CheckState QCheckBox::checkState() const } /*! - Sets the check box's check state to \a state. - If you do not need tristate support, you can also - use \l QAbstractButton::setChecked() which takes - a boolean. + Sets the check box's check state to \a state. If you do not need tristate + support, you can also use \l QAbstractButton::setChecked() which takes a + boolean. \sa checkState() Qt::CheckState */ @@ -274,7 +279,8 @@ void QCheckBox::setCheckState(Qt::CheckState state) } -/*!\reimp +/*! + \reimp */ QSize QCheckBox::sizeHint() const { @@ -294,7 +300,8 @@ QSize QCheckBox::sizeHint() const return d->sizeHint; } -/*!\reimp +/*! + \reimp */ void QCheckBox::paintEvent(QPaintEvent *) { @@ -325,7 +332,9 @@ void QCheckBox::mouseMoveEvent(QMouseEvent *e) } -/*!\reimp*/ +/*! + \reimp +*/ bool QCheckBox::hitButton(const QPoint &pos) const { QStyleOptionButton opt; @@ -333,7 +342,9 @@ bool QCheckBox::hitButton(const QPoint &pos) const return style()->subElementRect(QStyle::SE_CheckBoxClickRect, &opt, this).contains(pos); } -/*!\reimp*/ +/*! + \reimp +*/ void QCheckBox::checkStateSet() { Q_D(QCheckBox); @@ -345,7 +356,9 @@ void QCheckBox::checkStateSet() } } -/*!\reimp*/ +/*! + \reimp +*/ void QCheckBox::nextCheckState() { Q_D(QCheckBox); diff --git a/src/gui/widgets/qdockarealayout.cpp b/src/gui/widgets/qdockarealayout.cpp index ea5e323..b905ccd 100644 --- a/src/gui/widgets/qdockarealayout.cpp +++ b/src/gui/widgets/qdockarealayout.cpp @@ -223,7 +223,7 @@ static quintptr tabId(const QDockAreaLayoutItem &item) QDockAreaLayoutInfo::QDockAreaLayoutInfo() : sep(0), dockPos(QInternal::LeftDock), o(Qt::Horizontal), mainWindow(0) #ifndef QT_NO_TABBAR - , tabbed(false), tabBar(0), tabBarShape(QTabBar::RoundedSouth) + , tabbed(false), tabBar(0), tabBarShape(QTabBar::RoundedSouth), tabBarVisible(false) #endif { } @@ -233,7 +233,7 @@ QDockAreaLayoutInfo::QDockAreaLayoutInfo(int _sep, QInternal::DockPosition _dock QMainWindow *window) : sep(_sep), dockPos(_dockPos), o(_o), mainWindow(window) #ifndef QT_NO_TABBAR - , tabbed(false), tabBar(0), tabBarShape(static_cast<QTabBar::Shape>(tbshape)) + , tabbed(false), tabBar(0), tabBarShape(static_cast<QTabBar::Shape>(tbshape)), tabBarVisible(false) #endif { #ifdef QT_NO_TABBAR @@ -1488,7 +1488,7 @@ bool QDockAreaLayoutInfo::hasFixedSize() const void QDockAreaLayoutInfo::apply(bool animate) { - QWidgetAnimator *widgetAnimator = mainWindowLayout()->widgetAnimator; + QWidgetAnimator &widgetAnimator = mainWindowLayout()->widgetAnimator; #ifndef QT_NO_TABBAR if (tabbed) { @@ -1521,7 +1521,7 @@ void QDockAreaLayoutInfo::apply(bool animate) } } - widgetAnimator->animate(tabBar, tab_rect, animate); + widgetAnimator.animate(tabBar, tab_rect, animate); } #endif // QT_NO_TABBAR @@ -1544,7 +1544,7 @@ void QDockAreaLayoutInfo::apply(bool animate) QWidget *w = item.widgetItem->widget(); QRect geo = w->geometry(); - widgetAnimator->animate(w, r, animate); + widgetAnimator.animate(w, r, animate); if (!w->isHidden()) { QDockWidget *dw = qobject_cast<QDockWidget*>(w); if (!r.isValid() && geo.right() >= 0 && geo.bottom() >= 0) { @@ -2074,7 +2074,7 @@ void QDockAreaLayoutInfo::updateTabBar() const QDockAreaLayoutInfo *that = const_cast<QDockAreaLayoutInfo*>(this); - if (tabBar == 0) { + if (that->tabBar == 0) { that->tabBar = mainWindowLayout()->getTabBar(); that->tabBar->setShape(static_cast<QTabBar::Shape>(tabBarShape)); that->tabBar->setDrawBase(true); @@ -3064,13 +3064,13 @@ void QDockAreaLayout::splitDockWidget(QDockWidget *after, void QDockAreaLayout::apply(bool animate) { - QWidgetAnimator *widgetAnimator + QWidgetAnimator &widgetAnimator = qobject_cast<QMainWindowLayout*>(mainWindow->layout())->widgetAnimator; for (int i = 0; i < QInternal::DockCount; ++i) docks[i].apply(animate); if (centralWidgetItem != 0 && !centralWidgetItem->isEmpty()) { - widgetAnimator->animate(centralWidgetItem->widget(), centralWidgetRect, + widgetAnimator.animate(centralWidgetItem->widget(), centralWidgetRect, animate); } diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp index 4350520..5810c81 100644 --- a/src/gui/widgets/qdockwidget.cpp +++ b/src/gui/widgets/qdockwidget.cpp @@ -1322,8 +1322,7 @@ void QDockWidget::changeEvent(QEvent *event) QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget()); if (QMainWindowLayout *winLayout = (win ? qobject_cast<QMainWindowLayout*>(win->layout()) : 0)) - if (QDockAreaLayoutInfo *info = - (winLayout ? winLayout->layoutState.dockAreaLayout.info(this) : 0)) + if (QDockAreaLayoutInfo *info = winLayout->layoutState.dockAreaLayout.info(this)) info->updateTabBar(); } #endif // QT_NO_TABBAR diff --git a/src/gui/widgets/qeffects.cpp b/src/gui/widgets/qeffects.cpp index 065a2e0..d6d0a16 100644 --- a/src/gui/widgets/qeffects.cpp +++ b/src/gui/widgets/qeffects.cpp @@ -126,10 +126,9 @@ QAlphaWidget::QAlphaWidget(QWidget* w, Qt::WindowFlags f) QAlphaWidget::~QAlphaWidget() { -#ifdef Q_WS_WIN +#if defined(Q_WS_WIN) && !defined(Q_WS_WINCE) // Restore user-defined opacity value - if (widget && QSysInfo::WindowsVersion >= QSysInfo::WV_2000 && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based) - widget->setWindowOpacity(windowOpacity); + widget->setWindowOpacity(windowOpacity); #endif } @@ -160,43 +159,40 @@ void QAlphaWidget::run(int time) checkTime.start(); showWidget = true; -#if defined(Q_OS_WIN) - if (QSysInfo::WindowsVersion >= QSysInfo::WV_2000 && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based) { - qApp->installEventFilter(this); - widget->setWindowOpacity(0.0); - widget->show(); +#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) + qApp->installEventFilter(this); + widget->setWindowOpacity(0.0); + widget->show(); + connect(&anim, SIGNAL(timeout()), this, SLOT(render())); + anim.start(1); +#else + //This is roughly equivalent to calling setVisible(true) without actually showing the widget + widget->setAttribute(Qt::WA_WState_ExplicitShowHide, true); + widget->setAttribute(Qt::WA_WState_Hidden, false); + + qApp->installEventFilter(this); + + move(widget->geometry().x(),widget->geometry().y()); + resize(widget->size().width(), widget->size().height()); + + frontImage = QPixmap::grabWidget(widget).toImage(); + backImage = QPixmap::grabWindow(QApplication::desktop()->winId(), + widget->geometry().x(), widget->geometry().y(), + widget->geometry().width(), widget->geometry().height()).toImage(); + + if (!backImage.isNull() && checkTime.elapsed() < duration / 2) { + mixedImage = backImage.copy(); + pm = QPixmap::fromImage(mixedImage); + show(); + setEnabled(false); + connect(&anim, SIGNAL(timeout()), this, SLOT(render())); anim.start(1); - } else -#endif - { - //This is roughly equivalent to calling setVisible(true) without actually showing the widget - widget->setAttribute(Qt::WA_WState_ExplicitShowHide, true); - widget->setAttribute(Qt::WA_WState_Hidden, false); - - qApp->installEventFilter(this); - - move(widget->geometry().x(),widget->geometry().y()); - resize(widget->size().width(), widget->size().height()); - - frontImage = QPixmap::grabWidget(widget).toImage(); - backImage = QPixmap::grabWindow(QApplication::desktop()->winId(), - widget->geometry().x(), widget->geometry().y(), - widget->geometry().width(), widget->geometry().height()).toImage(); - - if (!backImage.isNull() && checkTime.elapsed() < duration / 2) { - mixedImage = backImage.copy(); - pm = QPixmap::fromImage(mixedImage); - show(); - setEnabled(false); - - connect(&anim, SIGNAL(timeout()), this, SLOT(render())); - anim.start(1); - } else { - duration = 0; - render(); - } + } else { + duration = 0; + render(); } +#endif } /* @@ -270,19 +266,17 @@ void QAlphaWidget::render() else alpha = 1; -#if defined(Q_OS_WIN) - if (QSysInfo::WindowsVersion >= QSysInfo::WV_2000 && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based) { - if (alpha >= windowOpacity || !showWidget) { - anim.stop(); - qApp->removeEventFilter(this); - widget->setWindowOpacity(windowOpacity); - q_blend = 0; - deleteLater(); - } else { - widget->setWindowOpacity(alpha); - } - } else -#endif +#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) + if (alpha >= windowOpacity || !showWidget) { + anim.stop(); + qApp->removeEventFilter(this); + widget->setWindowOpacity(windowOpacity); + q_blend = 0; + deleteLater(); + } else { + widget->setWindowOpacity(alpha); + } +#else if (alpha >= 1 || !showWidget) { anim.stop(); qApp->removeEventFilter(this); @@ -292,7 +286,7 @@ void QAlphaWidget::render() #ifdef Q_WS_WIN setEnabled(true); setFocus(); -#endif +#endif // Q_WS_WIN widget->hide(); } else { //Since we are faking the visibility of the widget @@ -309,6 +303,7 @@ void QAlphaWidget::render() pm = QPixmap::fromImage(mixedImage); repaint(); } +#endif // defined(Q_OS_WIN) && !defined(Q_OS_WINCE) } /* diff --git a/src/gui/widgets/qfontcombobox.cpp b/src/gui/widgets/qfontcombobox.cpp index 9660399..f87ccd3 100644 --- a/src/gui/widgets/qfontcombobox.cpp +++ b/src/gui/widgets/qfontcombobox.cpp @@ -263,7 +263,7 @@ void QFontComboBoxPrivate::_q_currentChanged(const QString &text) { Q_Q(QFontComboBox); QFont newFont(text); - if (currentFont != newFont) { + if (currentFont.family() != newFont.family()) { currentFont = newFont; emit q->currentFontChanged(currentFont); } diff --git a/src/gui/widgets/qframe.cpp b/src/gui/widgets/qframe.cpp index b9e769d..a87ec85 100644 --- a/src/gui/widgets/qframe.cpp +++ b/src/gui/widgets/qframe.cpp @@ -135,7 +135,7 @@ inline void QFramePrivate::init() \value VLine QFrame draws a vertical line that frames nothing (useful as separator) \value WinPanel draws a rectangular panel that can be raised or - sunken like those in Windows 95. Specifying this shape sets + sunken like those in Windows 2000. Specifying this shape sets the line width to 2 pixels. WinPanel is provided for compatibility. For GUI style independence we recommend using StyledPanel instead. diff --git a/src/gui/widgets/qgroupbox.cpp b/src/gui/widgets/qgroupbox.cpp index 0bfa8c0..2380e78 100644 --- a/src/gui/widgets/qgroupbox.cpp +++ b/src/gui/widgets/qgroupbox.cpp @@ -431,7 +431,7 @@ void QGroupBoxPrivate::_q_fixFocus(Qt::FocusReason reason) { Q_Q(QGroupBox); QWidget *fw = q->focusWidget(); - if (!fw) { + if (!fw || fw == q) { QWidget * best = 0; QWidget * candidate = 0; QWidget * w = q; @@ -449,8 +449,7 @@ void QGroupBoxPrivate::_q_fixFocus(Qt::FocusReason reason) } if (best) fw = best; - else - if (candidate) + else if (candidate) fw = candidate; } if (fw) diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp index c7f3e97..d1067a8 100644 --- a/src/gui/widgets/qlineedit.cpp +++ b/src/gui/widgets/qlineedit.cpp @@ -2169,7 +2169,8 @@ void QLineEdit::keyPressEvent(QKeyEvent *event) if (unknown && !d->readOnly) { QString t = event->text(); - if (!t.isEmpty() && t.at(0).isPrint()) { + 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()); diff --git a/src/gui/widgets/qmainwindow.cpp b/src/gui/widgets/qmainwindow.cpp index 0a0faa0..0c841eb 100644 --- a/src/gui/widgets/qmainwindow.cpp +++ b/src/gui/widgets/qmainwindow.cpp @@ -1419,9 +1419,10 @@ bool QMainWindow::event(QEvent *event) \i Toolbar breaks are not respected or preserved \i Any custom widgets in the toolbar will not be shown if the toolbar becomes too small (only actions will be shown) - \i If you call showFullScreen() on the main window, the QToolbar will - disappear since it is considered to be part of the title bar. You can - work around this by turning off the unified toolbar before you call + \i Before Qt 4.5, if you called showFullScreen() on the main window, the QToolbar would + disappear since it is considered to be part of the title bar. Qt 4.5 and up will now work around this by pulling + the toolbars out and back into the regular toolbar and vice versa when you swap out. + However, a good practice would be that turning off the unified toolbar before you call showFullScreen() and restoring it after you call showNormal(). \endlist diff --git a/src/gui/widgets/qmainwindowlayout.cpp b/src/gui/widgets/qmainwindowlayout.cpp index 526e7a5..1057f5f 100644 --- a/src/gui/widgets/qmainwindowlayout.cpp +++ b/src/gui/widgets/qmainwindowlayout.cpp @@ -426,42 +426,42 @@ QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget, return result; } -bool QMainWindowLayoutState::insertGap(QList<int> path, QLayoutItem *item) +bool QMainWindowLayoutState::insertGap(const QList<int> &path, QLayoutItem *item) { if (path.isEmpty()) return false; - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) { Q_ASSERT(qobject_cast<QToolBar*>(item->widget()) != 0); - return toolBarAreaLayout.insertGap(path, item); + return toolBarAreaLayout.insertGap(path.mid(1), item); } #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) { Q_ASSERT(qobject_cast<QDockWidget*>(item->widget()) != 0); - return dockAreaLayout.insertGap(path, item); + return dockAreaLayout.insertGap(path.mid(1), item); } #endif //QT_NO_DOCKWIDGET return false; } -void QMainWindowLayoutState::remove(QList<int> path) +void QMainWindowLayoutState::remove(const QList<int> &path) { - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) - toolBarAreaLayout.remove(path); + toolBarAreaLayout.remove(path.mid(1)); #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - dockAreaLayout.remove(path); + dockAreaLayout.remove(path.mid(1)); #endif //QT_NO_DOCKWIDGET } @@ -501,88 +501,88 @@ bool QMainWindowLayoutState::isValid() const return rect.isValid(); } -QLayoutItem *QMainWindowLayoutState::item(QList<int> path) +QLayoutItem *QMainWindowLayoutState::item(const QList<int> &path) { - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) - return toolBarAreaLayout.item(path).widgetItem; + return toolBarAreaLayout.item(path.mid(1)).widgetItem; #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - return dockAreaLayout.item(path).widgetItem; + return dockAreaLayout.item(path.mid(1)).widgetItem; #endif //QT_NO_DOCKWIDGET return 0; } -QRect QMainWindowLayoutState::itemRect(QList<int> path) const +QRect QMainWindowLayoutState::itemRect(const QList<int> &path) const { - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) - return toolBarAreaLayout.itemRect(path); + return toolBarAreaLayout.itemRect(path.mid(1)); #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - return dockAreaLayout.itemRect(path); + return dockAreaLayout.itemRect(path.mid(1)); #endif //QT_NO_DOCKWIDGET return QRect(); } -QRect QMainWindowLayoutState::gapRect(QList<int> path) const +QRect QMainWindowLayoutState::gapRect(const QList<int> &path) const { - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) - return toolBarAreaLayout.itemRect(path); + return toolBarAreaLayout.itemRect(path.mid(1)); #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - return dockAreaLayout.gapRect(path); + return dockAreaLayout.gapRect(path.mid(1)); #endif //QT_NO_DOCKWIDGET return QRect(); } -QLayoutItem *QMainWindowLayoutState::plug(QList<int> path) +QLayoutItem *QMainWindowLayoutState::plug(const QList<int> &path) { - int i = path.takeFirst(); + int i = path.first(); #ifndef QT_NO_TOOLBAR if (i == 0) - return toolBarAreaLayout.plug(path); + return toolBarAreaLayout.plug(path.mid(1)); #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - return dockAreaLayout.plug(path); + return dockAreaLayout.plug(path.mid(1)); #endif //QT_NO_DOCKWIDGET return 0; } -QLayoutItem *QMainWindowLayoutState::unplug(QList<int> path, QMainWindowLayoutState *other) +QLayoutItem *QMainWindowLayoutState::unplug(const QList<int> &path, QMainWindowLayoutState *other) { - int i = path.takeFirst(); + int i = path.first(); #ifdef QT_NO_TOOLBAR Q_UNUSED(other); #else if (i == 0) - return toolBarAreaLayout.unplug(path, other ? &other->toolBarAreaLayout : 0); + return toolBarAreaLayout.unplug(path.mid(1), other ? &other->toolBarAreaLayout : 0); #endif #ifndef QT_NO_DOCKWIDGET if (i == 1) - return dockAreaLayout.unplug(path); + return dockAreaLayout.unplug(path.mid(1)); #endif //QT_NO_DOCKWIDGET return 0; @@ -1361,7 +1361,7 @@ QLayoutItem *QMainWindowLayout::takeAt(int index) if (QLayoutItem *ret = layoutState.takeAt(index, &x)) { // the widget might in fact have been destroyed by now if (QWidget *w = ret->widget()) { - widgetAnimator->abort(w); + widgetAnimator.abort(w); if (w == pluggingWidget) pluggingWidget = 0; } @@ -1542,25 +1542,9 @@ bool QMainWindowLayout::plug(QLayoutItem *widgetItem) } } #endif - widgetAnimator->animate(widget, globalRect, - dockOptions & QMainWindow::AnimatedDocks); + widgetAnimator.animate(widget, globalRect, true); } else { -#ifndef QT_NO_DOCKWIDGET - if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) - dw->d_func()->plug(currentGapRect); -#endif -#ifndef QT_NO_TOOLBAR - if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) - tb->d_func()->plug(currentGapRect); -#endif - applyState(layoutState); - savedState.clear(); -#ifndef QT_NO_DOCKWIDGET - parentWidget()->update(layoutState.dockAreaLayout.separatorRegion()); -#endif - currentGapPos.clear(); - updateGapIndicator(); - pluggingWidget = 0; + animationFinished(widget); } return true; @@ -1667,6 +1651,11 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow) #endif #endif #endif // QT_NO_DOCKWIDGET + , widgetAnimator(this) + , pluggingWidget(0) +#ifndef QT_NO_RUBBERBAND + , gapIndicator(QRubberBand::Rectangle, mainwindow) +#endif //QT_NO_RUBBERBAND { #ifndef QT_NO_DOCKWIDGET #ifndef QT_NO_TABBAR @@ -1680,20 +1669,13 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow) #endif // QT_NO_DOCKWIDGET #ifndef QT_NO_RUBBERBAND - gapIndicator = new QRubberBand(QRubberBand::Rectangle, mainwindow); // For accessibility to identify this special widget. - gapIndicator->setObjectName(QLatin1String("qt_rubberband")); - - gapIndicator->hide(); + gapIndicator.setObjectName(QLatin1String("qt_rubberband")); + gapIndicator.hide(); #endif pluggingWidget = 0; setObjectName(mainwindow->objectName() + QLatin1String("_layout")); - widgetAnimator = new QWidgetAnimator(this); - connect(widgetAnimator, SIGNAL(finished(QWidget*)), - this, SLOT(animationFinished(QWidget*)), Qt::QueuedConnection); - connect(widgetAnimator, SIGNAL(finishedAll()), - this, SLOT(allAnimationsFinished())); } QMainWindowLayout::~QMainWindowLayout() @@ -1795,13 +1777,13 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget) void QMainWindowLayout::updateGapIndicator() { #ifndef QT_NO_RUBBERBAND - if (widgetAnimator->animating() || currentGapPos.isEmpty()) { - gapIndicator->hide(); + if (widgetAnimator.animating() || currentGapPos.isEmpty()) { + gapIndicator.hide(); } else { - if (gapIndicator->geometry() != currentGapRect) - gapIndicator->setGeometry(currentGapRect); - if (!gapIndicator->isVisible()) - gapIndicator->show(); + if (gapIndicator.geometry() != currentGapRect) + gapIndicator.setGeometry(currentGapRect); + if (!gapIndicator.isVisible()) + gapIndicator.show(); } #endif } diff --git a/src/gui/widgets/qmainwindowlayout_p.h b/src/gui/widgets/qmainwindowlayout_p.h index 26f8633..759461b 100644 --- a/src/gui/widgets/qmainwindowlayout_p.h +++ b/src/gui/widgets/qmainwindowlayout_p.h @@ -59,10 +59,12 @@ #include "QtGui/qlayout.h" #include "QtGui/qtabbar.h" +#include "QtGui/qrubberband.h" #include "QtCore/qvector.h" #include "QtCore/qset.h" #include "QtCore/qbasictimer.h" #include "private/qlayoutengine_p.h" +#include "private/qwidgetanimator_p.h" #include "qdockarealayout_p.h" #include "qtoolbararealayout_p.h" @@ -89,7 +91,6 @@ typedef const struct __CFString * CFStringRef; QT_BEGIN_NAMESPACE class QToolBar; -class QWidgetAnimator; class QRubberBand; /* This data structure represents the state of all the tool-bars and dock-widgets. It's value based @@ -128,9 +129,9 @@ public: QLayoutItem *itemAt(int index, int *x) const; QLayoutItem *takeAt(int index, int *x); QList<int> indexOf(QWidget *widget) const; - QLayoutItem *item(QList<int> path); - QRect itemRect(QList<int> path) const; - QRect gapRect(QList<int> path) const; // ### get rid of this, use itemRect() instead + QLayoutItem *item(const QList<int> &path); + QRect itemRect(const QList<int> &path) const; + QRect gapRect(const QList<int> &path) const; // ### get rid of this, use itemRect() instead bool contains(QWidget *widget) const; @@ -138,14 +139,14 @@ public: QWidget *centralWidget() const; QList<int> gapIndex(QWidget *widget, const QPoint &pos) const; - bool insertGap(QList<int> path, QLayoutItem *item); - void remove(QList<int> path); + bool insertGap(const QList<int> &path, QLayoutItem *item); + void remove(const QList<int> &path); void remove(QLayoutItem *item); void clear(); bool isValid() const; - QLayoutItem *plug(QList<int> path); - QLayoutItem *unplug(QList<int> path, QMainWindowLayoutState *savedState = 0); + QLayoutItem *plug(const QList<int> &path); + QLayoutItem *unplug(const QList<int> &path, QMainWindowLayoutState *savedState = 0); void saveState(QDataStream &stream) const; bool checkFormat(QDataStream &stream, bool pre43); @@ -278,12 +279,12 @@ public: // animations - QWidgetAnimator *widgetAnimator; + QWidgetAnimator widgetAnimator; QList<int> currentGapPos; QRect currentGapRect; QWidget *pluggingWidget; #ifndef QT_NO_RUBBERBAND - QRubberBand *gapIndicator; + QRubberBand gapIndicator; #endif QList<int> hover(QLayoutItem *widgetItem, const QPoint &mousePos); @@ -295,10 +296,10 @@ public: void applyState(QMainWindowLayoutState &newState, bool animate = true); void restore(bool keepSavedState = false); void updateHIToolBarStatus(); - -private slots: void animationFinished(QWidget *widget); void allAnimationsFinished(); + +private slots: #ifndef QT_NO_DOCKWIDGET #ifndef QT_NO_TABBAR void tabChanged(); diff --git a/src/gui/widgets/qmdisubwindow.cpp b/src/gui/widgets/qmdisubwindow.cpp index 25bc724..24dea37 100644 --- a/src/gui/widgets/qmdisubwindow.cpp +++ b/src/gui/widgets/qmdisubwindow.cpp @@ -1946,26 +1946,21 @@ QPalette QMdiSubWindowPrivate::desktopPalette() const colorref2qrgb(GetSysColor(COLOR_CAPTIONTEXT))); newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText, colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTIONTEXT))); - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 - && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - colorsInitialized = true; - BOOL hasGradient; - QT_WA({ - SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &hasGradient, 0); - } , { - SystemParametersInfoA(SPI_GETGRADIENTCAPTIONS, 0, &hasGradient, 0); - }); - if (hasGradient) { - newPalette.setColor(QPalette::Active, QPalette::Base, - colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION))); - newPalette.setColor(QPalette::Inactive, QPalette::Base, - colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION))); - } else { - newPalette.setColor(QPalette::Active, QPalette::Base, - newPalette.color(QPalette::Active, QPalette::Highlight)); - newPalette.setColor(QPalette::Inactive, QPalette::Base, - newPalette.color(QPalette::Inactive, QPalette::Highlight)); - } + + colorsInitialized = true; + BOOL hasGradient = false; + SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &hasGradient, 0); + + if (hasGradient) { + newPalette.setColor(QPalette::Active, QPalette::Base, + colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION))); + newPalette.setColor(QPalette::Inactive, QPalette::Base, + colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION))); + } else { + newPalette.setColor(QPalette::Active, QPalette::Base, + newPalette.color(QPalette::Active, QPalette::Highlight)); + newPalette.setColor(QPalette::Inactive, QPalette::Base, + newPalette.color(QPalette::Inactive, QPalette::Highlight)); } } #endif // Q_WS_WIN diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index fc55a2c..35b68b4 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -150,7 +150,6 @@ private: void QMenuPrivate::init() { Q_Q(QMenu); - activationRecursionGuard = false; #ifndef QT_NO_WHATSTHIS q->setAttribute(Qt::WA_CustomWhatsThis); #endif @@ -164,6 +163,12 @@ void QMenuPrivate::init() } } +int QMenuPrivate::scrollerHeight() const +{ + Q_Q(const QMenu); + return qMax(QApplication::globalStrut().height(), q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q)); +} + //Windows and KDE allows menus to cover the taskbar, while GNOME and Mac don't QRect QMenuPrivate::popupGeometry(int screen) const { @@ -194,57 +199,75 @@ QList<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const return ret; } -void QMenuPrivate::calcActionRects(QMap<QAction*, QRect> &actionRects, QList<QAction*> &actionList) const +void QMenuPrivate::updateActionRects() const { Q_Q(const QMenu); - if (!itemsDirty) { - actionRects = this->actionRects; - actionList = this->actionList; + if (!itemsDirty) return; + + //let's reinitialize the buffer + actionRects.resize(actions.count()); + actionRects.fill(QRect()); + + //let's try to get the last visible action + int lastVisibleAction = actions.count() - 1; + for(;lastVisibleAction >= 0; --lastVisibleAction) { + const QAction *action = actions.at(lastVisibleAction); + if (action->isVisible()) { + //removing trailing separators + if (action->isSeparator() && collapsibleSeparators) + continue; + break; + } } - actionRects.clear(); - actionList.clear(); int max_column_width = 0, dh = popupGeometry(QApplication::desktop()->screenNumber(q)).height(), - ncols = 1, y = 0; - const int hmargin = q->style()->pixelMetric(QStyle::PM_MenuHMargin, 0, q), - vmargin = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q), - icone = q->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q); + 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); //for compatability now - will have to refactor this away.. tabWidth = 0; maxIconWidth = 0; hasCheckableItems = false; - QList<QAction*> items = filteredActions(); - for(int i = 0; i < items.count(); i++) { - QAction *action = items.at(i); - if (widgetItems.value(action)) + ncols = 1; + sloppyAction = 0; + + for (int i = 0; i < actions.count(); ++i) { + QAction *action = actions.at(i); + if (action->isSeparator() || !action->isVisible() || widgetItems.at(i)) continue; + //..and some members hasCheckableItems |= action->isCheckable(); QIcon is = action->icon(); if (!is.isNull()) { - uint miw = maxIconWidth; - maxIconWidth = qMax<uint>(miw, icone + 4); + maxIconWidth = qMax<uint>(maxIconWidth, icone + 4); } } //calculate size QFontMetrics qfm = q->fontMetrics(); - for(int i = 0; i < items.count(); i++) { - QAction *action = items.at(i); + bool previousWasSeparator = true; // this is true to allow removing the leading separators + for(int i = 0; i <= lastVisibleAction; i++) { + QAction *action = actions.at(i); - QFontMetrics fm(action->font().resolve(q->font())); - QSize sz; + if (!action->isVisible() || + (collapsibleSeparators && previousWasSeparator && action->isSeparator())) + continue; // we continue, this action will get an empty QRect + + previousWasSeparator = action->isSeparator(); //let the style modify the above size.. QStyleOptionMenuItem opt; q->initStyleOption(&opt, action); - opt.rect = q->rect(); + const QFontMetrics &fm = opt.fontMetrics; - if (QWidget *w = widgetItems.value(action)) { - sz=w->sizeHint().expandedTo(w->minimumSize()).expandedTo(w->minimumSizeHint()).boundedTo(w->maximumSize()); + QSize sz; + if (QWidget *w = widgetItems.at(i)) { + sz = w->sizeHint().expandedTo(w->minimumSize()).expandedTo(w->minimumSizeHint()).boundedTo(w->maximumSize()); } else { //calc what I think the size is.. if (action->isSeparator()) { @@ -275,7 +298,7 @@ void QMenuPrivate::calcActionRects(QMap<QAction*, QRect> &actionRects, QList<QAc sz.setHeight(is_sz.height()); } } - sz = q->style()->sizeFromContents(QStyle::CT_MenuItem, &opt, sz, q); + sz = style->sizeFromContents(QStyle::CT_MenuItem, &opt, sz, q); } @@ -283,119 +306,59 @@ void QMenuPrivate::calcActionRects(QMap<QAction*, QRect> &actionRects, QList<QAc max_column_width = qMax(max_column_width, sz.width()); //wrapping if (!scroll && - y+sz.height()+vmargin > dh - (q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { + y+sz.height()+vmargin > dh - (style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { ncols++; y = vmargin; } y += sz.height(); - //append item - actionRects.insert(action, QRect(0, 0, sz.width(), sz.height())); - actionList.append(action); + //update the item + actionRects[i] = QRect(0, 0, sz.width(), sz.height()); } } - if (tabWidth) - max_column_width += tabWidth; //finally add in the tab width + max_column_width += tabWidth; //finally add in the tab width //calculate position - int x = hmargin; - y = vmargin; - - for(int i = 0; i < actionList.count(); i++) { - QAction *action = actionList.at(i); - QRect &rect = actionRects[action]; + 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); + int x = hmargin + fw + leftmargin; + y = base_y; + + for(int i = 0; i < actions.count(); i++) { + QRect &rect = actionRects[i]; if (rect.isNull()) continue; if (!scroll && - y+rect.height() > dh - (q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { - ncols--; - if (ncols < 0) - qWarning("QMenu: Column calculation mismatch (%d)", ncols); + y+rect.height() > dh - (style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q) * 2)) { x += max_column_width + hmargin; - y = vmargin; + y = base_y; } rect.translate(x, y); //move rect.setWidth(max_column_width); //uniform width - y += rect.height(); - } -} -void QMenuPrivate::updateActions() -{ - Q_Q(const QMenu); - if (!itemsDirty) - return; - sloppyAction = 0; - calcActionRects(actionRects, actionList); - for (QHash<QAction *, QWidget *>::ConstIterator item = widgetItems.constBegin(), - end = widgetItems.constEnd(); item != end; ++item) { - QAction *action = item.key(); - QWidget *widget = item.value(); - widget->setGeometry(actionRect(action)); - widget->setVisible(action->isVisible()); - } - ncols = 1; - int last_left = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q); - if (!scroll) { - for(int i = 0; i < actionList.count(); i++) { - int left = actionRects.value(actionList.at(i)).left(); - if (left > last_left) { - last_left = left; - ncols++; - } + //we need to update the widgets geometry + if (QWidget *widget = widgetItems.at(i)) { + widget->setGeometry(rect); + widget->setVisible(actions.at(i)->isVisible()); } + + y += rect.height(); } itemsDirty = 0; } -QList<QAction *> QMenuPrivate::filteredActions() const +QRect QMenuPrivate::actionRect(QAction *act) const { - QList<QAction *> visibleActions; - int i = 0; - while (i < actions.count()) { - QAction *action = actions.at(i); - if (!action->isVisible()) { - ++i; - continue; - } - if (!action->isSeparator() || !collapsibleSeparators) { - visibleActions.append(action); - ++i; - continue; - } + int index = actions.indexOf(act); + if (index == -1) + return QRect(); - // no leading separators - if (!visibleActions.isEmpty()) - visibleActions.append(action); - - // skip double/tripple/etc. separators - while (i < actions.count() - && (!actions.at(i)->isVisible() || actions.at(i)->isSeparator())) - ++i; - } + updateActionRects(); - if (collapsibleSeparators) { - // remove trailing separators - while (!visibleActions.isEmpty() && visibleActions.last()->isSeparator()) - visibleActions.removeLast(); - } - - return visibleActions; -} - -QRect QMenuPrivate::actionRect(QAction *act) const -{ - Q_Q(const QMenu); - QRect ret = actionRects.value(act); - if (ret.isNull()) - return ret; - if (scroll) - ret.translate(0, scroll->scrollOffset); - if (tearoff) - ret.translate(0, q->style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, q)); - const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q); - ret.translate(fw+leftmargin, fw+topmargin); - return ret; + //we found the action + return actionRects.at(index); } static const qreal MenuFadeTimeInSec = 0.150; @@ -525,14 +488,17 @@ void QMenuPrivate::setSyncAction() void QMenuPrivate::setFirstActionActive() { Q_Q(QMenu); - const int scrollerHeight = q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q); - for(int i = 0, saccum = 0; i < actionList.count(); i++) { - QAction *act = actionList[i]; + updateActionRects(); + for(int i = 0, saccum = 0; i < actions.count(); i++) { + const QRect &rect = actionRects.at(i); + if (rect.isNull()) + continue; if (scroll && scroll->scrollFlags & QMenuScroller::ScrollUp) { - saccum -= actionRects.value(act).height(); - if (saccum > scroll->scrollOffset-scrollerHeight) + saccum -= rect.height(); + if (saccum > scroll->scrollOffset - scrollerHeight()) continue; } + QAction *act = actions.at(i); if (!act->isSeparator() && (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q) || act->isEnabled())) { @@ -582,9 +548,10 @@ void QMenuPrivate::setCurrentAction(QAction *action, int popup, SelectionReason popupAction(currentAction, popup, activateFirst); } q->update(actionRect(action)); - QWidget *widget = widgetItems.value(action); if (reason == SelectedFromKeyboard) { + const int actionIndex = actions.indexOf(action); + QWidget *widget = widgetItems.at(actionIndex); if (widget) { if (widget->focusPolicy() != Qt::NoFocus) widget->setFocus(Qt::TabFocusReason); @@ -628,10 +595,9 @@ QAction *QMenuPrivate::actionAt(QPoint p) const if (!q_func()->rect().contains(p)) //sanity check return 0; - for(int i = 0; i < actionList.count(); i++) { - QAction *act = actionList[i]; - if (actionRect(act).contains(p)) - return act; + for(int i = 0; i < actionRects.count(); i++) { + if (actionRects.at(i).contains(p)) + return actions.at(i); } return 0; } @@ -705,27 +671,25 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc Q_Q(QMenu); if (!scroll || !scroll->scrollFlags) return; + updateActionRects(); int newOffset = 0; - const int scrollHeight = q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q); - const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollHeight : 0; - const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollHeight : 0; + const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollerHeight() : 0; + const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollerHeight() : 0; const int vmargin = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q); const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q); if (location == QMenuScroller::ScrollTop) { - for(int i = 0, saccum = 0; i < actionList.count(); i++) { - QAction *act = actionList.at(i); - if (act == action) { + for(int i = 0, saccum = 0; i < actions.count(); i++) { + if (actions.at(i) == action) { newOffset = topScroll - saccum; break; } - saccum += actionRects.value(act).height(); + saccum += actionRects.at(i).height(); } } else { - for(int i = 0, saccum = 0; i < actionList.count(); i++) { - QAction *act = actionList.at(i); - saccum += actionRects.value(act).height(); - if (act == action) { + for(int i = 0, saccum = 0; i < actions.count(); i++) { + saccum += actionRects.at(i).height(); + if (actions.at(i) == action) { if (location == QMenuScroller::ScrollCenter) newOffset = ((q->height() / 2) - botScroll) - (saccum - topScroll); else @@ -734,7 +698,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc } } if(newOffset) - newOffset -= fw*2; + newOffset -= fw * 2; } //figure out which scroll flags @@ -742,8 +706,8 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc if (newOffset < 0) //easy and cheap one newScrollFlags |= QMenuScroller::ScrollUp; int saccum = newOffset; - for(int i = 0; i < actionList.count(); i++) { - saccum += actionRects.value(actionList.at(i)).height(); + for(int i = 0; i < actionRects.count(); i++) { + saccum += actionRects.at(i).height(); if (saccum > q->height()) { newScrollFlags |= QMenuScroller::ScrollDown; break; @@ -794,9 +758,19 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc } //actually update flags - scroll->scrollOffset = newOffset; - if (scroll->scrollOffset > 0) - scroll->scrollOffset = 0; + const int delta = qMin(0, newOffset) - scroll->scrollOffset; //make sure the new offset is always negative + if (!itemsDirty && delta) { + //we've scrolled so we need to update the action rects + for (int i = 0; i < actionRects.count(); ++i) { + QRect ¤t = actionRects[i]; + current.moveTop(current.top() + delta); + + //we need to update the widgets geometry + if (QWidget *w = widgetItems.at(i)) + w->setGeometry(current); + } + } + scroll->scrollOffset += delta; scroll->scrollFlags = newScrollFlags; if (active) setCurrentAction(action); @@ -807,9 +781,12 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool active) { Q_Q(QMenu); + updateActionRects(); if(location == QMenuScroller::ScrollBottom) { - for(int i = actionList.size()-1; i >= 0; --i) { - QAction *act = actionList.at(i); + for(int i = actions.size()-1; i >= 0; --i) { + QAction *act = actions.at(i); + if (actionRects.at(i).isNull()) + continue; if (!act->isSeparator() && (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q) || act->isEnabled())) { @@ -821,8 +798,10 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool activ } } } else if(location == QMenuScroller::ScrollTop) { - for(int i = 0; i < actionList.size(); ++i) { - QAction *act = actionList.at(i); + for(int i = 0; i < actions.size(); ++i) { + QAction *act = actions.at(i); + if (actionRects.at(i).isNull()) + continue; if (!act->isSeparator() && (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q) || act->isEnabled())) { @@ -842,38 +821,33 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag Q_Q(QMenu); if (!scroll || !(scroll->scrollFlags & direction)) //not really possible... return; - const int scrollHeight = q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q); - const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollHeight : 0; - const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollHeight : 0; + updateActionRects(); + const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollerHeight() : 0; + const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollerHeight() : 0; const int vmargin = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q); const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q); const int offset = topScroll ? topScroll-vmargin : 0; if (direction == QMenuScroller::ScrollUp) { - for(int i = 0, saccum = 0; i < actionList.count(); i++) { - QAction *act = actionList.at(i); - const int iHeight = actionRects.value(act).height(); - saccum -= iHeight; + for(int i = 0, saccum = 0; i < actions.count(); i++) { + saccum -= actionRects.at(i).height(); if (saccum <= scroll->scrollOffset-offset) { - scrollMenu(act, page ? QMenuScroller::ScrollBottom : QMenuScroller::ScrollTop, active); + scrollMenu(actions.at(i), page ? QMenuScroller::ScrollBottom : QMenuScroller::ScrollTop, active); break; } } } else if (direction == QMenuScroller::ScrollDown) { bool scrolled = false; - for(int i = 0, saccum = 0; i < actionList.count(); i++) { - QAction *act = actionList.at(i); - const int iHeight = actionRects.value(act).height(); + for(int i = 0, saccum = 0; i < actions.count(); i++) { + const int iHeight = actionRects.at(i).height(); saccum -= iHeight; if (saccum <= scroll->scrollOffset-offset) { const int scrollerArea = q->height() - botScroll - fw*2; int visible = (scroll->scrollOffset-offset) - saccum; - for(i++ ; i < actionList.count(); i++) { - act = actionList.at(i); - const int iHeight = actionRects.value(act).height(); - visible += iHeight; + for(i++ ; i < actions.count(); i++) { + visible += actionRects.at(i).height(); if (visible > scrollerArea - topScroll) { scrolled = true; - scrollMenu(act, page ? QMenuScroller::ScrollTop : QMenuScroller::ScrollBottom, active); + scrollMenu(actions.at(i), page ? QMenuScroller::ScrollTop : QMenuScroller::ScrollBottom, active); break; } } @@ -896,13 +870,12 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e) if (scroll && !activeMenu) { //let the scroller "steal" the event bool isScroll = false; if (pos.x() >= 0 && pos.x() < q->width()) { - const int scrollerHeight = q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q); for(int dir = QMenuScroller::ScrollUp; dir <= QMenuScroller::ScrollDown; dir = dir << 1) { if (scroll->scrollFlags & dir) { if (dir == QMenuScroller::ScrollUp) - isScroll = (pos.y() <= scrollerHeight); + isScroll = (pos.y() <= scrollerHeight()); else if (dir == QMenuScroller::ScrollDown) - isScroll = (pos.y() >= q->height()-scrollerHeight); + isScroll = (pos.y() >= q->height() - scrollerHeight()); if (isScroll) { scroll->scrollDirection = dir; break; @@ -911,19 +884,17 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e) } } if (isScroll) { - if (!scroll->scrollTimer) - scroll->scrollTimer = new QBasicTimer; - scroll->scrollTimer->start(50, q); + scroll->scrollTimer.start(50, q); return true; - } else if (scroll->scrollTimer && scroll->scrollTimer->isActive()) { - scroll->scrollTimer->stop(); + } else { + scroll->scrollTimer.stop(); } } if (tearoff) { //let the tear off thingie "steal" the event.. QRect tearRect(0, 0, q->width(), q->style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, q)); if (scroll && scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp) - tearRect.translate(0, q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q)); + tearRect.translate(0, scrollerHeight()); q->update(tearRect); if (tearRect.contains(pos) && hasMouseMoved(e->globalPos())) { setCurrentAction(0); @@ -1178,7 +1149,8 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action) else option->palette.setCurrentColorGroup(QPalette::Disabled); - option->font = action->font(); + option->font = action->font().resolve(font()); + option->fontMetrics = QFontMetrics(option->font); if (d->currentAction && d->currentAction == action && !d->currentAction->isSeparator()) { option->state |= QStyle::State_Selected @@ -1373,19 +1345,17 @@ QMenu::QMenu(QMenuPrivate &dd, QWidget *parent) QMenu::~QMenu() { Q_D(QMenu); - for (QHash<QAction *, QWidget *>::ConstIterator item = d->widgetItems.constBegin(), - end = d->widgetItems.constEnd(); item != end; ++item) { - QWidgetAction *action = static_cast<QWidgetAction *>(item.key()); - QWidget *widget = item.value(); - if (action && widget) + for (int i = 0; i < d->widgetItems.count(); ++i) { + if (QWidget *widget = d->widgetItems.at(i)) { + QWidgetAction *action = static_cast<QWidgetAction *>(d->actions.at(i)); action->releaseWidget(widget); + d->widgetItems[i] = 0; + } } - d->widgetItems.clear(); if (d->eventLoop) d->eventLoop->exit(); - if (d->tornPopup) - d->tornPopup->close(); + hideTearOffMenu(); } /*! @@ -1596,8 +1566,8 @@ void QMenu::setTearOffEnabled(bool b) Q_D(QMenu); if (d->tearoff == b) return; - if (!b && d->tornPopup) - d->tornPopup->close(); + if (!b) + hideTearOffMenu(); d->tearoff = b; d->itemsDirty = true; @@ -1632,8 +1602,8 @@ bool QMenu::isTearOffMenuVisible() const */ void QMenu::hideTearOffMenu() { - if (d_func()->tornPopup) - d_func()->tornPopup->close(); + if (QWidget *w = d_func()->tornPopup) + w->close(); } @@ -1732,35 +1702,34 @@ QSize QMenu::sizeHint() const { Q_D(const QMenu); ensurePolished(); - QMap<QAction*, QRect> actionRects; - QList<QAction*> actionList; - d->calcActionRects(actionRects, actionList); + d->updateActionRects(); QSize s; QStyleOption opt(0); opt.rect = rect(); opt.palette = palette(); opt.state = QStyle::State_None; - for (QMap<QAction*, QRect>::const_iterator i = actionRects.constBegin(); - i != actionRects.constEnd(); ++i) { - if (i.value().bottom() > s.height()) - s.setHeight(i.value().y()+i.value().height()); - if (i.value().right() > s.width()) - s.setWidth(i.value().right()); - } - if (d->tearoff) - s.rheight() += style()->pixelMetric(QStyle::PM_MenuTearoffHeight, &opt, this); - if (const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, this)) { - s.rwidth() += fw*2; - s.rheight() += fw*2; + for (int i = 0; i < d->actionRects.count(); ++i) { + const QRect &rect = d->actionRects.at(i); + if (rect.isNull()) + continue; + if (rect.bottom() >= s.height()) + s.setHeight(rect.y() + rect.height()); + if (rect.right() >= s.width()) + s.setWidth(rect.x() + rect.width()); } // 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->leftmargin + d->rightmargin, d->topmargin + d->bottommargin); + s += QSize(d->rightmargin, d->bottommargin); return style()->sizeFromContents(QStyle::CT_Menu, &opt, s.expandedTo(QApplication::globalStrut()), this); @@ -1802,7 +1771,7 @@ void QMenu::popup(const QPoint &p, QAction *atAction) ensurePolished(); // Get the right font emit aboutToShow(); - d->updateActions(); + d->updateActionRects(); QPoint pos = p; QSize size = sizeHint(); QRect screen = d->popupGeometry(QApplication::desktop()->screenNumber(p)); @@ -1811,10 +1780,10 @@ void QMenu::popup(const QPoint &p, QAction *atAction) if (d->ncols > 1) { pos.setY(screen.top()+desktopFrame); } else if (atAction) { - for(int i=0, above_height=0; i<(int)d->actionList.count(); i++) { - QAction *action = d->actionList.at(i); + for(int i = 0, above_height = 0; i < d->actions.count(); i++) { + QAction *action = d->actions.at(i); if (action == atAction) { - int newY = pos.y()-above_height; + int newY = pos.y() - above_height; if (d->scroll && newY < desktopFrame) { d->scroll->scrollFlags = d->scroll->scrollFlags | QMenuPrivate::QMenuScroller::ScrollUp; @@ -1826,13 +1795,13 @@ void QMenu::popup(const QPoint &p, QAction *atAction) if (d->scroll && d->scroll->scrollFlags != QMenuPrivate::QMenuScroller::ScrollNone && !style()->styleHint(QStyle::SH_Menu_FillScreenWithScroll, 0, this)) { int below_height = above_height + d->scroll->scrollOffset; - for(int i2 = i; i2 < d->actionList.count(); i2++) - below_height += d->actionRects.value(d->actionList.at(i2)).height(); + for(int i2 = i; i2 < d->actionRects.count(); i2++) + below_height += d->actionRects.at(i2).height(); size.setHeight(below_height); } break; } else { - above_height += d->actionRects.value(action).height(); + above_height += d->actionRects.at(i).height(); } } } @@ -2039,8 +2008,7 @@ QAction *QMenu::exec(const QPoint &p, QAction *action) QAction *QMenu::exec(QList<QAction*> actions, const QPoint &pos, QAction *at, QWidget *parent) { QMenu menu(parent); - for(QList<QAction*>::ConstIterator it = actions.constBegin(); it != actions.constEnd(); ++it) - menu.addAction((*it)); + menu.addActions(actions); return menu.exec(pos, at); } @@ -2090,6 +2058,8 @@ void QMenu::hideEvent(QHideEvent *) d->hasHadMouse = false; d->causedPopup.widget = 0; d->causedPopup.action = 0; + if (d->scroll) + d->scroll->scrollTimer.stop(); //make sure the timer stops } /*! @@ -2098,6 +2068,7 @@ void QMenu::hideEvent(QHideEvent *) void QMenu::paintEvent(QPaintEvent *e) { Q_D(QMenu); + d->updateActionRects(); QPainter p(this); QRegion emptyArea = QRegion(rect()); @@ -2110,11 +2081,11 @@ void QMenu::paintEvent(QPaintEvent *e) style()->drawPrimitive(QStyle::PE_PanelMenu, &menuOpt, &p, this); //draw the items that need updating.. - for (int i = 0; i < d->actionList.count(); ++i) { - QAction *action = d->actionList.at(i); - QRect adjustedActionRect = d->actionRect(action); + for (int i = 0; i < d->actions.count(); ++i) { + QAction *action = d->actions.at(i); + QRect adjustedActionRect = d->actionRects.at(i); if (!e->rect().intersects(adjustedActionRect) - || d->widgetItems.value(action)) + || d->widgetItems.at(i)) continue; //set the clip region to be extra safe (and adjust for the scrollers) QRegion adjustedActionReg(adjustedActionRect); @@ -2130,18 +2101,17 @@ void QMenu::paintEvent(QPaintEvent *e) const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, this); //draw the scroller regions.. if (d->scroll) { - const int scrollerHeight = style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, this); menuOpt.menuItemType = QStyleOptionMenuItem::Scroller; menuOpt.state |= QStyle::State_Enabled; if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp) { - menuOpt.rect.setRect(fw, fw, width() - (fw * 2), scrollerHeight); + menuOpt.rect.setRect(fw, fw, width() - (fw * 2), d->scrollerHeight()); emptyArea -= QRegion(menuOpt.rect); p.setClipRect(menuOpt.rect); style()->drawControl(QStyle::CE_MenuScroller, &menuOpt, &p, this); } if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown) { - menuOpt.rect.setRect(fw, height() - scrollerHeight - fw, width() - (fw * 2), - scrollerHeight); + menuOpt.rect.setRect(fw, height() - d->scrollerHeight() - fw, width() - (fw * 2), + d->scrollerHeight()); emptyArea -= QRegion(menuOpt.rect); menuOpt.state |= QStyle::State_DownArrow; p.setClipRect(menuOpt.rect); @@ -2154,7 +2124,7 @@ void QMenu::paintEvent(QPaintEvent *e) menuOpt.rect.setRect(fw, fw, width() - (fw * 2), style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this)); if (d->scroll && d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp) - menuOpt.rect.translate(0, style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, this)); + menuOpt.rect.translate(0, d->scrollerHeight()); emptyArea -= QRegion(menuOpt.rect); p.setClipRect(menuOpt.rect); menuOpt.state = QStyle::State_None; @@ -2263,7 +2233,7 @@ void QMenu::mouseReleaseEvent(QMouseEvent *e) break; } } - if (e->button() || isContextMenu) + if (e->button() == Qt::LeftButton || isContextMenu) #endif d->activateAction(action, QAction::Trigger); } @@ -2344,11 +2314,11 @@ QMenu::event(QEvent *e) setMask(menuMask.region); } d->itemsDirty = 1; - d->updateActions(); + d->updateActionRects(); break; } case QEvent::Show: d->mouseDown = 0; - d->updateActions(); + d->updateActionRects(); if (d->currentAction) d->popupAction(d->currentAction, 0, false); break; @@ -2384,6 +2354,7 @@ bool QMenu::focusNextPrevChild(bool next) void QMenu::keyPressEvent(QKeyEvent *e) { Q_D(QMenu); + d->updateActionRects(); int key = e->key(); if (isRightToLeft()) { // in reverse mode open/close key for submenues are reversed if (key == Qt::Key_Left) @@ -2435,8 +2406,10 @@ void QMenu::keyPressEvent(QKeyEvent *e) QMenuPrivate::QMenuScroller::ScrollLocation scroll_loc = QMenuPrivate::QMenuScroller::ScrollStay; if (!d->currentAction) { if(key == Qt::Key_Down) { - for(int i = 0; i < d->actionList.size(); ++i) { - QAction *act = d->actionList.at(i); + for(int i = 0; i < d->actions.count(); ++i) { + QAction *act = d->actions.at(i); + if (d->actionRects.at(i).isNull()) + continue; if (!act->isSeparator() && (style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this) || act->isEnabled())) { @@ -2445,8 +2418,10 @@ void QMenu::keyPressEvent(QKeyEvent *e) } } } else { - for(int i = d->actionList.size()-1; i >= 0; --i) { - QAction *act = d->actionList.at(i); + for(int i = d->actions.count()-1; i >= 0; --i) { + QAction *act = d->actions.at(i); + if (d->actionRects.at(i).isNull()) + continue; if (!act->isSeparator() && (style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this) || act->isEnabled())) { @@ -2456,8 +2431,8 @@ void QMenu::keyPressEvent(QKeyEvent *e) } } } else { - for(int i=0, y=0; !nextAction && i < (int)d->actionList.count(); i++) { - QAction *act = d->actionList.at(i); + for(int i = 0, y = 0; !nextAction && i < d->actions.count(); i++) { + QAction *act = d->actions.at(i); if (act == d->currentAction) { if (key == Qt::Key_Up) { for(int next_i = i-1; true; next_i--) { @@ -2466,21 +2441,23 @@ void QMenu::keyPressEvent(QKeyEvent *e) break; if (d->scroll) scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom; - next_i = d->actionList.count()-1; + next_i = d->actionRects.count()-1; } - QAction *next = d->actionList.at(next_i); + QAction *next = d->actions.at(next_i); if (next == d->currentAction) break; + if (d->actionRects.at(next_i).isNull()) + continue; if (next->isSeparator() || (!next->isEnabled() && !style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this))) continue; nextAction = next; if (d->scroll && (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)) { - int topVisible = style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, this); + int topVisible = d->scrollerHeight(); if (d->tearoff) topVisible += style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this); - if (((y + d->scroll->scrollOffset) - topVisible) <= d->actionRects.value(nextAction).height()) + if (((y + d->scroll->scrollOffset) - topVisible) <= d->actionRects.at(next_i).height()) scroll_loc = QMenuPrivate::QMenuScroller::ScrollTop; } break; @@ -2488,31 +2465,32 @@ void QMenu::keyPressEvent(QKeyEvent *e) if (!nextAction && d->tearoff) d->tearoffHighlighted = 1; } else { - y += d->actionRects.value(act).height(); + y += d->actionRects.at(i).height(); for(int next_i = i+1; true; next_i++) { - if (next_i == d->actionList.count()) { + if (next_i == d->actionRects.count()) { if(!style()->styleHint(QStyle::SH_Menu_SelectionWrap, 0, this)) break; if (d->scroll) scroll_loc = QMenuPrivate::QMenuScroller::ScrollTop; next_i = 0; } - QAction *next = d->actionList.at(next_i); + QAction *next = d->actions.at(next_i); if (next == d->currentAction) break; + if (d->actionRects.at(next_i).isNull()) + continue; if (next->isSeparator() || (!next->isEnabled() && !style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this))) continue; nextAction = next; if (d->scroll && (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)) { - const int scrollerHeight = style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, this); - int bottomVisible = height()-scrollerHeight; + int bottomVisible = height() - d->scrollerHeight(); if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp) - bottomVisible -= scrollerHeight; + bottomVisible -= d->scrollerHeight(); if (d->tearoff) bottomVisible -= style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this); - if ((y + d->scroll->scrollOffset + d->actionRects.value(nextAction).height()) > bottomVisible) + if ((y + d->scroll->scrollOffset + d->actionRects.at(next_i).height()) > bottomVisible) scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom; } break; @@ -2520,13 +2498,12 @@ void QMenu::keyPressEvent(QKeyEvent *e) } break; } - y += d->actionRects.value(act).height(); + y += d->actionRects.at(i).height(); } } if (nextAction) { if (d->scroll && scroll_loc != QMenuPrivate::QMenuScroller::ScrollStay) { - if (d->scroll->scrollTimer) - d->scroll->scrollTimer->stop(); + d->scroll->scrollTimer.stop(); d->scrollMenu(nextAction, scroll_loc); } d->setCurrentAction(nextAction, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard); @@ -2648,9 +2625,11 @@ void QMenu::keyPressEvent(QKeyEvent *e) int best_match_count = 0; d->searchBufferTimer.start(2000, this); d->searchBuffer += e->text(); - for(int i = 0; i < d->actionList.size(); ++i) { + for(int i = 0; i < d->actions.size(); ++i) { int match_count = 0; - register QAction *act = d->actionList.at(i); + if (d->actionRects.at(i).isNull()) + continue; + QAction *act = d->actions.at(i); const QString act_text = act->text(); for(int c = 0; c < d->searchBuffer.size(); ++c) { if(act_text.indexOf(d->searchBuffer.at(c), 0, Qt::CaseInsensitive) != -1) @@ -2667,8 +2646,10 @@ void QMenu::keyPressEvent(QKeyEvent *e) int clashCount = 0; QAction *first = 0, *currentSelected = 0, *firstAfterCurrent = 0; QChar c = e->text().at(0).toUpper(); - for(int i = 0; i < d->actionList.size(); ++i) { - register QAction *act = d->actionList.at(i); + for(int i = 0; i < d->actions.size(); ++i) { + if (d->actionRects.at(i).isNull()) + continue; + QAction *act = d->actions.at(i); QKeySequence sequence = QKeySequence::mnemonic(act->text()); int key = sequence[0] & 0xffff; if (key == c.unicode()) { @@ -2739,7 +2720,7 @@ void QMenu::mouseMoveEvent(QMouseEvent *e) d->motions++; if (d->motions == 0) // ignore first mouse move event (see enterEvent()) return; - d->hasHadMouse |= rect().contains(e->pos()); + d->hasHadMouse = d->hasHadMouse || rect().contains(e->pos()); QAction *action = d->actionAt(e->pos()); if (!action) { @@ -2783,10 +2764,10 @@ void QMenu::timerEvent(QTimerEvent *e) { Q_D(QMenu); - if (d->scroll && d->scroll->scrollTimer && d->scroll->scrollTimer->timerId() == e->timerId()) { + if (d->scroll && d->scroll->scrollTimer.timerId() == e->timerId()) { d->scrollMenu((QMenuPrivate::QMenuScroller::ScrollDirection)d->scroll->scrollDirection); if (d->scroll->scrollFlags == QMenuPrivate::QMenuScroller::ScrollNone) - d->scroll->scrollTimer->stop(); + d->scroll->scrollTimer.stop(); } else if(QMenuPrivate::menuDelayTimer.timerId() == e->timerId()) { QMenuPrivate::menuDelayTimer.stop(); internalDelayedPopup(); @@ -2813,31 +2794,25 @@ void QMenu::actionEvent(QActionEvent *e) connect(e->action(), SIGNAL(triggered()), this, SLOT(_q_actionTriggered())); connect(e->action(), SIGNAL(hovered()), this, SLOT(_q_actionHovered())); } + QWidget *widget = 0; + if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) + widget = wa->requestWidget(this); + + int index = d->actions.indexOf(e->action()); + Q_ASSERT(index != -1); + d->widgetItems.insert(index, widget); - if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) { - QWidget *widget = wa->requestWidget(this); - if (widget) - d->widgetItems.insert(wa, widget); - } } else if (e->type() == QEvent::ActionRemoved) { - d->actionRects.clear(); - d->actionList.clear(); e->action()->disconnect(this); if (e->action() == d->currentAction) d->currentAction = 0; + int index = d->actions.indexOf(e->before()) + 1; if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) { - QWidget *widget = d->widgetItems.take(wa); - if (widget) + if (QWidget *widget = d->widgetItems.at(index)) wa->releaseWidget(widget); - } else { - // If this is called from the QAction destructor, the - // previous call to qobject_cast will fail because the - // QWidgetAction has been destroyed already. We need to - // remove it from the hash anyway or it might crash later - // the widget itself has been already destroyed in - // ~QWidgetAction - d->widgetItems.remove(e->action()); } + Q_ASSERT(index != -1); + d->widgetItems.removeAt(index); } #ifdef Q_WS_MAC @@ -2863,7 +2838,7 @@ void QMenu::actionEvent(QActionEvent *e) #endif if (isVisible()) { - d->updateActions(); + d->updateActionRects(); resize(sizeHint()); update(); } @@ -3044,7 +3019,7 @@ void QMenu::setSeparatorsCollapsible(bool collapse) d->collapsibleSeparators = collapse; d->itemsDirty = 1; if (isVisible()) { - d->updateActions(); + d->updateActionRects(); update(); } } @@ -3103,9 +3078,9 @@ int QMenu::insertSeparator(int index) QAction *QMenu::findActionForId(int id) const { - QList<QAction *> list = actions(); - for (int i = 0; i < list.size(); ++i) { - QAction *act = list.at(i); + Q_D(const QMenu); + for (int i = 0; i < d->actions.size(); ++i) { + QAction *act = d->actions.at(i); if (findIdForAction(act)== id) return act; } diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm index 6056119..77e98c4 100644 --- a/src/gui/widgets/qmenu_mac.mm +++ b/src/gui/widgets/qmenu_mac.mm @@ -1180,7 +1180,7 @@ QMenuPrivate::QMacMenuPrivate::addAction(QMacMenuAction *action, QMacMenuAction #endif } - QWidget *widget = qmenu ? qmenu->widgetItems.value(action->action) : 0; + QWidget *widget = qmenu ? qmenu->widgetItems.value(qmenu->actions.indexOf(action->action)) : 0; if (widget) { #ifndef QT_MAC_USE_COCOA ChangeMenuAttributes(action->menu, kMenuAttrDoNotCacheImage, 0); diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h index 1ea8fe9..4e428fe 100644 --- a/src/gui/widgets/qmenu_p.h +++ b/src/gui/widgets/qmenu_p.h @@ -126,9 +126,9 @@ class QMenuPrivate : public QWidgetPrivate Q_DECLARE_PUBLIC(QMenu) public: QMenuPrivate() : itemsDirty(0), maxIconWidth(0), tabWidth(0), ncols(0), - collapsibleSeparators(true), hasHadMouse(0), aboutToHide(0), motions(0), + collapsibleSeparators(true), activationRecursionGuard(false), hasHadMouse(0), aboutToHide(0), motions(0), currentAction(0), scroll(0), eventLoop(0), tearoff(0), tornoff(0), tearoffHighlighted(0), - hasCheckableItems(0), sloppyAction(0) + hasCheckableItems(0), sloppyAction(0), doChildEffects(false) #ifdef Q_WS_MAC ,mac_menu(0) #endif @@ -151,18 +151,18 @@ public: } void init(); + int scrollerHeight() const; + //item calculations mutable uint itemsDirty : 1; mutable uint maxIconWidth, tabWidth; QRect actionRect(QAction *) const; - mutable QMap<QAction*, QRect> actionRects; - mutable QList<QAction*> actionList; - mutable QHash<QAction *, QWidget *> widgetItems; - void calcActionRects(QMap<QAction*, QRect> &actionRects, QList<QAction*> &actionList) const; - void updateActions(); + + mutable QVector<QRect> actionRects; + mutable QWidgetList widgetItems; + void updateActionRects() const; QRect popupGeometry(int screen=-1) const; - QList<QAction *> filteredActions() const; - uint ncols : 4; //4 bits is probably plenty + mutable uint ncols : 4; //4 bits is probably plenty uint collapsibleSeparators : 1; uint activationRecursionGuard : 1; @@ -191,10 +191,10 @@ public: enum ScrollDirection { ScrollNone=0, ScrollUp=0x01, ScrollDown=0x02 }; uint scrollFlags : 2, scrollDirection : 2; int scrollOffset; - QBasicTimer *scrollTimer; + QBasicTimer scrollTimer; - QMenuScroller() : scrollFlags(ScrollNone), scrollDirection(ScrollNone), scrollOffset(0), scrollTimer(0) { } - ~QMenuScroller() { delete scrollTimer; } + QMenuScroller() : scrollFlags(ScrollNone), scrollDirection(ScrollNone), scrollOffset(0) { } + ~QMenuScroller() { } } *scroll; void scrollMenu(QMenuScroller::ScrollLocation location, bool active=false); void scrollMenu(QMenuScroller::ScrollDirection direction, bool page=false, bool active=false); @@ -234,7 +234,7 @@ public: //sloppy selection static QBasicTimer sloppyDelayTimer; - QAction *sloppyAction; + mutable QAction *sloppyAction; QRegion sloppyRegion; //default action diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp index 34de252..caacc58 100644 --- a/src/gui/widgets/qmenubar.cpp +++ b/src/gui/widgets/qmenubar.cpp @@ -197,17 +197,15 @@ void QMenuBarPrivate::updateGeometries() return; } #endif - calcActionRects(q_width, q_start, actionRects, actionList); - itemsWidth = q_width; - itemsStart = q_start; + calcActionRects(q_width, q_start); currentAction = 0; #ifndef QT_NO_SHORTCUT if(itemsDirty) { for(int j = 0; j < shortcutIndexMap.size(); ++j) q->releaseShortcut(shortcutIndexMap.value(j)); shortcutIndexMap.resize(0); // faster than clear - for(int i = 0; i < actionList.count(); i++) - shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actionList.at(i)->text()))); + for(int i = 0; i < actions.count(); i++) + shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actions.at(i)->text()))); } #endif itemsDirty = false; @@ -218,9 +216,9 @@ void QMenuBarPrivate::updateGeometries() //we try to see if the actions will fit there bool hasHiddenActions = false; - for (int i = 0; i < actionList.count(); ++i) { - QAction *action = actionList.at(i); - if (!menuRect.contains(actionRect(action))) { + for (int i = 0; i < actions.count(); ++i) { + const QRect &rect = actionRects.at(i); + if (!menuRect.contains(rect)) { hasHiddenActions = true; break; } @@ -229,10 +227,10 @@ void QMenuBarPrivate::updateGeometries() //...and if not, determine the ones that fit on the menu with the extension visible if (hasHiddenActions) { menuRect = this->menuRect(true); - for (int i = 0; i < actionList.count(); ++i) { - QAction *action = actionList.at(i); - if (!menuRect.contains(actionRect(action))) { - hiddenActions.append(action); + for (int i = 0; i < actions.count(); ++i) { + const QRect &rect = actionRects.at(i); + if (!menuRect.contains(rect)) { + hiddenActions.append(actions.at(i)); } } } @@ -267,12 +265,28 @@ void QMenuBarPrivate::updateGeometries() QRect QMenuBarPrivate::actionRect(QAction *act) const { Q_Q(const QMenuBar); - QRect ret = actionRects.value(act); - const int fw = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q); - ret.translate(fw, fw); + const int index = actions.indexOf(act); + if (index == -1) + return QRect(); + + //makes sure the geometries are up-to-date + const_cast<QMenuBarPrivate*>(this)->updateGeometries(); + + QRect ret = actionRects.at(index); return QStyle::visualRect(q->layoutDirection(), q->rect(), ret); } +void QMenuBarPrivate::focusFirstAction() +{ + if(!currentAction) { + updateGeometries(); + int index = 0; + while (index < actions.count() && actionRects.at(index).isNull()) ++index; + if (index < actions.count()) + setCurrentAction(actions.at(index)); + } +} + void QMenuBarPrivate::setKeyboardMode(bool b) { Q_Q(QMenuBar); @@ -285,8 +299,7 @@ void QMenuBarPrivate::setKeyboardMode(bool b) QWidget *fw = QApplication::focusWidget(); if (fw != q) keyboardFocusWidget = fw; - if(!currentAction && !actionList.isEmpty()) - setCurrentAction(actionList.first()); + focusFirstAction(); q->setFocus(Qt::MenuBarFocusReason); } else { if(!popupState) @@ -398,25 +411,27 @@ void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activat fw->setFocus(Qt::NoFocusReason); } -void QMenuBarPrivate::calcActionRects(int max_width, int start, QMap<QAction*, QRect> &actionRects, QList<QAction*> &actionList) const +void QMenuBarPrivate::calcActionRects(int max_width, int start) const { Q_Q(const QMenuBar); - if(!itemsDirty && itemsWidth == max_width && itemsStart == start) { - actionRects = actionRects; - actionList = actionList; + if(!itemsDirty) return; - } - actionRects.clear(); - actionList.clear(); - const int itemSpacing = q->style()->pixelMetric(QStyle::PM_MenuBarItemSpacing, 0, q); + + //let's reinitialize the buffer + actionRects.resize(actions.count()); + actionRects.fill(QRect()); + + const QStyle *style = q->style(); + + const int itemSpacing = style->pixelMetric(QStyle::PM_MenuBarItemSpacing, 0, q); int max_item_height = 0, separator = -1, separator_start = 0, separator_len = 0; //calculate size const QFontMetrics fm = q->fontMetrics(); - const int hmargin = q->style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, q), - vmargin = q->style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q), - icone = q->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q); + const int hmargin = style->pixelMetric(QStyle::PM_MenuBarHMargin, 0, q), + vmargin = style->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q), + icone = style->pixelMetric(QStyle::PM_SmallIconSize, 0, q); for(int i = 0; i < actions.count(); i++) { QAction *action = actions.at(i); if(!action->isVisible()) @@ -426,26 +441,21 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start, QMap<QAction*, Q //calc what I think the size is.. if(action->isSeparator()) { - if (q->style()->styleHint(QStyle::SH_DrawMenuBarSeparator, 0, q)) - separator = actionRects.count(); + if (style->styleHint(QStyle::SH_DrawMenuBarSeparator, 0, q)) + separator = i; continue; //we don't really position these! } else { - QString s = action->text(); + const QString s = action->text(); if(!s.isEmpty()) { - int w = fm.width(s); - w -= s.count(QLatin1Char('&')) * fm.width(QLatin1Char('&')); - w += s.count(QLatin1String("&&")) * fm.width(QLatin1Char('&')); + const int w = fm.width(s) + - s.count(QLatin1Char('&')) * fm.width(QLatin1Char('&')) + + s.count(QLatin1String("&&")) * fm.width(QLatin1Char('&')); sz = QSize(w, fm.height()); } QIcon is = action->icon(); - if (!is.isNull()) { - QSize is_sz = QSize(icone, icone); - if (is_sz.height() > sz.height()) - sz.setHeight(is_sz.height()); - if (is_sz.width() > sz.width()) - sz.setWidth(is_sz.width()); - } + if (!is.isNull()) + sz = sz.expandedTo(QSize(icone, icone)); } //let the style modify the above size.. @@ -455,8 +465,7 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start, QMap<QAction*, Q if(!sz.isEmpty()) { { //update the separator state - int iWidth = sz.width(); - iWidth += itemSpacing; + int iWidth = sz.width() + itemSpacing; if(separator == -1) separator_start += iWidth; else @@ -465,17 +474,19 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start, QMap<QAction*, Q //maximum height max_item_height = qMax(max_item_height, sz.height()); //append - actionRects.insert(action, QRect(0, 0, sz.width(), sz.height())); - actionList.append(action); + actionRects[i] = QRect(0, 0, sz.width(), sz.height()); } } //calculate position - int x = ((start == -1) ? hmargin : start) + itemSpacing; - int y = vmargin; - for(int i = 0; i < actionList.count(); i++) { - QAction *action = actionList.at(i); - QRect &rect = actionRects[action]; + const int fw = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q); + int x = fw + ((start == -1) ? hmargin : start) + itemSpacing; + int y = fw + vmargin; + for(int i = 0; i < actions.count(); i++) { + QRect &rect = actionRects[i]; + if (rect.isNull()) + continue; + //resize rect.setHeight(max_item_height); @@ -659,8 +670,9 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti \header \i String matches \i Placement \i Notes \row \i about.* \i Application Menu | About <application name> - \i If this entry is not found no About item will appear in - the Application Menu + \i The application name is fetched from the \c {Info.plist} file + (see note below). If this entry is not found no About item + will appear in the Application Menu. \row \i config, options, setup, settings or preferences \i Application Menu | Preferences \i If this entry is not found the Settings item will be disabled @@ -743,6 +755,28 @@ void QMenuBarPrivate::init() extension->hide(); } +//Gets the next action for keyboard navigation +QAction *QMenuBarPrivate::getNextAction(const int _start, const int increment) const +{ + Q_Q(const QMenuBar); + const_cast<QMenuBarPrivate*>(this)->updateGeometries(); + bool allowActiveAndDisabled = q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q); + const int start = (_start == -1 && increment == -1) ? actions.count() : _start; + const int end = increment == -1 ? 0 : actions.count() - 1; + + for (int i = start; start != end;) { + i += increment; + QAction *current = actions.at(i); + if (!actionRects.at(i).isNull() && (allowActiveAndDisabled || current->isEnabled())) + return current; + } + + if (_start != -1) //let's try from the beginning or the end + return getNextAction(-1, increment); + + return 0; +} + /*! Constructs a menu bar with parent \a parent. */ @@ -922,6 +956,13 @@ void QMenuBar::setActiveAction(QAction *act) /*! Removes all the actions from the menu bar. + \note On Mac OS X, menu items that have been merged to the system + menu bar are not removed by this function. One way to handle this + would be to remove the extra actions yourself. You can set the + \l{QAction::MenuRole}{menu role} on the different menus, so that + you know ahead of time which menu items get merged and which do + not. Then decide what to recreate or remove yourself. + \sa removeAction() */ void QMenuBar::clear() @@ -975,8 +1016,8 @@ void QMenuBar::paintEvent(QPaintEvent *e) QRegion emptyArea(rect()); //draw the items - for (int i = 0; i < d->actionList.count(); ++i) { - QAction *action = d->actionList.at(i); + for (int i = 0; i < d->actions.count(); ++i) { + QAction *action = d->actions.at(i); QRect adjustedActionRect = d->actionRect(action); if (adjustedActionRect.isEmpty() || !d->isVisible(action)) continue; @@ -1092,6 +1133,7 @@ void QMenuBar::mouseReleaseEvent(QMouseEvent *e) void QMenuBar::keyPressEvent(QKeyEvent *e) { Q_D(QMenuBar); + d->updateGeometries(); int key = e->key(); if(isRightToLeft()) { // in reverse mode open/close key for submenues are reversed if(key == Qt::Key_Left) @@ -1126,54 +1168,8 @@ void QMenuBar::keyPressEvent(QKeyEvent *e) case Qt::Key_Right: case Qt::Key_Left: { if(d->currentAction) { - QAction *nextAction = 0; - bool allowActiveAndDisabled = - style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this); - - for(int i=0; i<(int)d->actionList.count(); i++) { - if(d->actionList.at(i) == (QAction*)d->currentAction) { - if (key == Qt::Key_Left) { - while (i > 0) { - i--; - if (allowActiveAndDisabled || d->actionList[i]->isEnabled()) { - nextAction = d->actionList.at(i); - break; - } - } - } else { - while (i < d->actionList.count()-1) { - i++; - if (allowActiveAndDisabled || d->actionList[i]->isEnabled()) { - nextAction = d->actionList.at(i); - break; - } - } - } - break; - - } - } - - if(!nextAction) { - if (key == Qt::Key_Left) { - for (int i = d->actionList.size() - 1 ; i >= 0 ; --i) { - if (allowActiveAndDisabled || d->actionList[i]->isEnabled()) { - nextAction = d->actionList.at(i); - i--; - break; - } - } - } else { - for (int i = 0 ; i < d->actionList.count() ; ++i) { - if (allowActiveAndDisabled || d->actionList[i]->isEnabled()) { - nextAction = d->actionList.at(i); - i++; - break; - } - } - } - } - if(nextAction) { + int index = d->actions.indexOf(d->currentAction); + if (QAction *nextAction = d->getNextAction(index, key == Qt::Key_Left ? -1 : +1)) { d->setCurrentAction(nextAction, d->popupState, true); key_consumed = true; } @@ -1197,8 +1193,10 @@ void QMenuBar::keyPressEvent(QKeyEvent *e) QAction *first = 0, *currentSelected = 0, *firstAfterCurrent = 0; { QChar c = e->text()[0].toUpper(); - for(int i = 0; i < d->actionList.size(); ++i) { - register QAction *act = d->actionList.at(i); + for(int i = 0; i < d->actions.size(); ++i) { + if (d->actionRects.at(i).isNull()) + continue; + QAction *act = d->actions.at(i); QString s = act->text(); if(!s.isEmpty()) { int ampersand = s.indexOf(QLatin1Char('&')); @@ -1300,8 +1298,8 @@ void QMenuBar::actionEvent(QActionEvent *e) void QMenuBar::focusInEvent(QFocusEvent *) { Q_D(QMenuBar); - if(d->keyboardState && !d->currentAction && !d->actionList.isEmpty()) - d->setCurrentAction(d->actionList.first()); + if(d->keyboardState) + d->focusFirstAction(); } /*! @@ -1610,20 +1608,18 @@ QSize QMenuBar::minimumSizeHint() const ensurePolished(); QSize ret(0, 0); + const_cast<QMenuBarPrivate*>(d)->updateGeometries(); const int hmargin = style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, this); const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, this); int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this); int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this); if(as_gui_menubar) { - QMap<QAction*, QRect> actionRects; - QList<QAction*> actionList; int w = parentWidget() ? parentWidget()->width() : QApplication::desktop()->width(); - d->calcActionRects(w - (2 * fw), 0, actionRects, actionList); - if (d->actionList.count() > 0) { - ret = d->actionRect(d->actionList.at(0)).size(); - if (!d->extension->isHidden()) - ret += QSize(d->extension->sizeHint().width(), 0); - } + d->calcActionRects(w - (2 * fw), 0); + for (int i = 0; ret.isNull() && i < d->actions.count(); ++i) + ret = d->actionRects.at(i).size(); + if (!d->extension->isHidden()) + ret += QSize(d->extension->sizeHint().width(), 0); ret += QSize(2*fw + hmargin, 2*fw + vmargin); } int margin = 2*vmargin + 2*fw + spaceBelowMenuBar; @@ -1674,19 +1670,15 @@ QSize QMenuBar::sizeHint() const int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this); int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this); if(as_gui_menubar) { - QMap<QAction*, QRect> actionRects; - QList<QAction*> actionList; const int w = parentWidget() ? parentWidget()->width() : QApplication::desktop()->width(); - d->calcActionRects(w - (2 * fw), 0, actionRects, actionList); - for (QMap<QAction*, QRect>::const_iterator i = actionRects.constBegin(); - i != actionRects.constEnd(); ++i) { - QRect actionRect(i.value()); - if(actionRect.x() + actionRect.width() > ret.width()) - ret.setWidth(actionRect.x() + actionRect.width()); - if(actionRect.y() + actionRect.height() > ret.height()) - ret.setHeight(actionRect.y() + actionRect.height()); + d->calcActionRects(w - (2 * fw), 0); + for (int i = 0; i < d->actionRects.count(); ++i) { + const QRect &actionRect = d->actionRects.at(i); + ret = ret.expandedTo(QSize(actionRect.x() + actionRect.width(), actionRect.y() + actionRect.height())); } - ret += QSize(2*fw + 2*hmargin, 2*fw + 2*vmargin); + //the action geometries already contain the top and left + //margins. So we only need to add those from right and bottom. + ret += QSize(fw + hmargin, fw + vmargin); } int margin = 2*vmargin + 2*fw + spaceBelowMenuBar; if(d->leftWidget) { @@ -1733,11 +1725,10 @@ int QMenuBar::heightForWidth(int) const int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this); int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this); if(as_gui_menubar) { - if (d->actionList.count()) { - // assume all actionrects have the same height - height = d->actionRect(d->actionList.first()).height(); + for (int i = 0; i < d->actionRects.count(); ++i) + height = qMax(height, d->actionRects.at(i).height()); + if (height) //there is at least one non-null item height += spaceBelowMenuBar; - } height += 2*fw; height += 2*vmargin; } @@ -1764,7 +1755,7 @@ int QMenuBar::heightForWidth(int) const void QMenuBarPrivate::_q_internalShortcutActivated(int id) { Q_Q(QMenuBar); - QAction *act = actionList.at(id); + QAction *act = actions.at(id); setCurrentAction(act, true, true); if (act && !act->menu()) { activateAction(act, QAction::Trigger); diff --git a/src/gui/widgets/qmenubar_p.h b/src/gui/widgets/qmenubar_p.h index 0a4fbfe..b890b7b 100644 --- a/src/gui/widgets/qmenubar_p.h +++ b/src/gui/widgets/qmenubar_p.h @@ -69,9 +69,12 @@ class QMenuBarPrivate : public QWidgetPrivate { Q_DECLARE_PUBLIC(QMenuBar) public: - QMenuBarPrivate() : itemsDirty(0), itemsWidth(0), itemsStart(-1), currentAction(0), mouseDown(0), + QMenuBarPrivate() : itemsDirty(0), currentAction(0), mouseDown(0), closePopupMode(0), defaultPopDown(1), popupState(0), keyboardState(0), altPressed(0), - nativeMenuBar(-1) + nativeMenuBar(-1), doChildEffects(false) +#ifdef QT3_SUPPORT + , doAutoResize(false) +#endif #ifdef Q_WS_MAC , mac_menubar(0) #endif @@ -91,16 +94,14 @@ public: } void init(); - QStyleOptionMenuItem getStyleOption(const QAction *action) const; + QAction *getNextAction(const int start, const int increment) const; //item calculations uint itemsDirty : 1; - int itemsWidth, itemsStart; QVector<int> shortcutIndexMap; - mutable QMap<QAction*, QRect> actionRects; - mutable QList<QAction*> actionList; - void calcActionRects(int max_width, int start, QMap<QAction*, QRect> &actionRects, QList<QAction*> &actionList) const; + mutable QVector<QRect> actionRects; + void calcActionRects(int max_width, int start) const; QRect actionRect(QAction *) const; void updateGeometries(); @@ -116,6 +117,7 @@ public: QPointer<QMenu> activeMenu; //keyboard mode for keyboard navigation + void focusFirstAction(); void setKeyboardMode(bool); uint keyboardState : 1, altPressed : 1; QPointer<QWidget> keyboardFocusWidget; diff --git a/src/gui/widgets/qplaintextedit.cpp b/src/gui/widgets/qplaintextedit.cpp index 4977b31..82026d4 100644 --- a/src/gui/widgets/qplaintextedit.cpp +++ b/src/gui/widgets/qplaintextedit.cpp @@ -66,6 +66,8 @@ #include <qtexttable.h> #include <qvariant.h> +#include <qstandardgestures.h> + #include <qinputcontext.h> #ifndef QT_NO_TEXTEDIT @@ -250,7 +252,7 @@ QPlainTextDocumentLayoutPrivate *QPlainTextDocumentLayout::priv() const */ void QPlainTextDocumentLayout::requestUpdate() { - emit update(QRectF(0., -4., 1000000000., 1000000000.)); + emit update(QRectF(0., -document()->documentMargin(), 1000000000., 1000000000.)); } @@ -345,8 +347,7 @@ void QPlainTextDocumentLayout::documentChanged(int from, int /*charsRemoved*/, i } if (!d->blockUpdate) - emit update(); // optimization potential - + emit update(QRectF(0., -doc->documentMargin(), 1000000000., 1000000000.)); // optimization potential } @@ -726,6 +727,9 @@ QPlainTextEditPrivate::QPlainTextEditPrivate() backgroundVisible = false; centerOnScroll = false; inDrag = false; +#ifdef Q_WS_WIN + singleFingerPanEnabled = true; +#endif } @@ -781,6 +785,9 @@ void QPlainTextEditPrivate::init(const QString &txt) #ifndef QT_NO_CURSOR viewport->setCursor(Qt::IBeamCursor); #endif + originalOffsetY = 0; + panGesture = new QPanGesture(q); + QObject::connect(panGesture, SIGNAL(triggered()), q, SLOT(_q_gestureTriggered())); } void QPlainTextEditPrivate::_q_repaintContents(const QRectF &contentsRect) @@ -1014,14 +1021,13 @@ void QPlainTextEditPrivate::ensureViewportLayouted() QPlainText uses very much the same technology and concepts as QTextEdit, but is optimized for plain text handling. - QPlainTextEdit works on paragraphs and characters. A paragraph is a - formatted string which is word-wrapped to fit into the width of + QPlainTextEdit works on paragraphs and characters. A paragraph is + a formatted string which is word-wrapped to fit into the width of the widget. By default when reading plain text, one newline signifies a paragraph. A document consists of zero or more - paragraphs. The words in the paragraph are aligned in accordance - with the paragraph's alignment. Paragraphs are separated by hard - line breaks. Each character within a paragraph has its own - attributes, for example, font and color. + paragraphs. Paragraphs are separated by hard line breaks. Each + character within a paragraph has its own attributes, for example, + font and color. The shape of the mouse cursor on a QPlainTextEdit is Qt::IBeamCursor by default. It can be changed through the @@ -1162,7 +1168,8 @@ void QPlainTextEditPrivate::ensureViewportLayouted() \sa QTextDocument, QTextCursor, {Application Example}, - {Syntax Highlighter Example}, {Rich Text Processing} + {Code Editor Example}, {Syntax Highlighter Example}, + {Rich Text Processing} */ @@ -2899,6 +2906,30 @@ QAbstractTextDocumentLayout::PaintContext QPlainTextEdit::getPaintContext() cons (\a available is true) or unavailable (\a available is false). */ +void QPlainTextEditPrivate::_q_gestureTriggered() +{ + Q_Q(QPlainTextEdit); + QPanGesture *g = qobject_cast<QPanGesture*>(q->sender()); + if (!g) + return; + QScrollBar *hBar = q->horizontalScrollBar(); + QScrollBar *vBar = q->verticalScrollBar(); + if (g->state() == Qt::GestureStarted) + originalOffsetY = vBar->value(); + QSize totalOffset = g->totalOffset(); + if (!totalOffset.isNull()) { + if (QApplication::isRightToLeft()) + totalOffset.rwidth() *= -1; + // QPlainTextEdit scrolls by lines only in vertical direction + QFontMetrics fm(q->document()->defaultFont()); + int lineHeight = fm.height(); + int newX = hBar->value() - g->lastOffset().width(); + int newY = originalOffsetY - totalOffset.height()/lineHeight; + hbar->setValue(newX); + vbar->setValue(newY); + } +} + QT_END_NAMESPACE #include "moc_qplaintextedit.cpp" diff --git a/src/gui/widgets/qplaintextedit.h b/src/gui/widgets/qplaintextedit.h index dc0851b..35bbc37 100644 --- a/src/gui/widgets/qplaintextedit.h +++ b/src/gui/widgets/qplaintextedit.h @@ -269,6 +269,7 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars()) Q_PRIVATE_SLOT(d_func(), void _q_verticalScrollbarActionTriggered(int)) Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged()) + Q_PRIVATE_SLOT(d_func(), void _q_gestureTriggered()) friend class QPlainTextEditControl; }; diff --git a/src/gui/widgets/qplaintextedit_p.h b/src/gui/widgets/qplaintextedit_p.h index 5075fc4..ae584e0 100644 --- a/src/gui/widgets/qplaintextedit_p.h +++ b/src/gui/widgets/qplaintextedit_p.h @@ -72,6 +72,7 @@ class QMimeData; class QPlainTextEdit; class ExtraArea; +class QPanGesture; class QPlainTextEditControl : public QTextControl { @@ -173,6 +174,10 @@ public: void _q_cursorPositionChanged(); void _q_modificationChanged(bool); + + void _q_gestureTriggered(); + int originalOffsetY; + QPanGesture *panGesture; }; QT_END_NAMESPACE diff --git a/src/gui/widgets/qpushbutton.cpp b/src/gui/widgets/qpushbutton.cpp index 7da5930..a1c0d74 100644 --- a/src/gui/widgets/qpushbutton.cpp +++ b/src/gui/widgets/qpushbutton.cpp @@ -387,8 +387,9 @@ bool QPushButton::isDefault() const QSize QPushButton::sizeHint() const { Q_D(const QPushButton); - if (d->sizeHint.isValid()) + if (d->sizeHint.isValid() && d->lastAutoDefault == autoDefault()) return d->sizeHint; + d->lastAutoDefault = autoDefault(); ensurePolished(); int w = 0, h = 0; @@ -657,6 +658,8 @@ bool QPushButton::event(QEvent *e) ) { d->resetLayoutItemMargins(); updateGeometry(); + } else if (e->type() == QEvent::PolishRequest) { + updateGeometry(); } return QAbstractButton::event(e); } diff --git a/src/gui/widgets/qpushbutton_p.h b/src/gui/widgets/qpushbutton_p.h index 0c5ac79..9d682d8 100644 --- a/src/gui/widgets/qpushbutton_p.h +++ b/src/gui/widgets/qpushbutton_p.h @@ -65,7 +65,7 @@ public: QPushButtonPrivate() : QAbstractButtonPrivate(QSizePolicy::PushButton), autoDefault(Auto), - defaultButton(false), flat(false), menuOpen(false) {} + defaultButton(false), flat(false), menuOpen(false), lastAutoDefault(false) {} inline void init() { resetLayoutItemMargins(); } void resetLayoutItemMargins(); @@ -77,6 +77,7 @@ public: uint defaultButton : 1; uint flat : 1; uint menuOpen : 1; + mutable uint lastAutoDefault : 1; }; QT_END_NAMESPACE diff --git a/src/gui/widgets/qsizegrip.cpp b/src/gui/widgets/qsizegrip.cpp index d263b9c..c6aae68 100644 --- a/src/gui/widgets/qsizegrip.cpp +++ b/src/gui/widgets/qsizegrip.cpp @@ -335,8 +335,7 @@ void QSizeGrip::mousePressEvent(QMouseEvent * e) orientation = d->atLeft() ? SZ_SIZETOPLEFT : SZ_SIZETOPRIGHT; ReleaseCapture(); - QT_WA_INLINE(PostMessageW(tlw->winId(), WM_SYSCOMMAND, orientation, 0), - PostMessageA(tlw->winId(), WM_SYSCOMMAND, orientation, 0)); + PostMessage(tlw->winId(), WM_SYSCOMMAND, orientation, 0); return; } #endif // Q_WS_WIN diff --git a/src/gui/widgets/qtextedit.cpp b/src/gui/widgets/qtextedit.cpp index c8d8d04..e80df92 100644 --- a/src/gui/widgets/qtextedit.cpp +++ b/src/gui/widgets/qtextedit.cpp @@ -67,6 +67,8 @@ #include <qtexttable.h> #include <qvariant.h> +#include <qstandardgestures.h> + #include <qinputcontext.h> #endif @@ -111,6 +113,9 @@ QTextEditPrivate::QTextEditPrivate() preferRichText = false; showCursorOnInitialShow = true; inDrag = false; +#ifdef Q_WS_WIN + singleFingerPanEnabled = true; +#endif } void QTextEditPrivate::createAutoBulletList() @@ -178,6 +183,8 @@ 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) @@ -2610,6 +2617,25 @@ 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 617822a..9e10e07 100644 --- a/src/gui/widgets/qtextedit.h +++ b/src/gui/widgets/qtextedit.h @@ -414,6 +414,7 @@ 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 e7609d6..249331e 100644 --- a/src/gui/widgets/qtextedit_p.h +++ b/src/gui/widgets/qtextedit_p.h @@ -70,7 +70,7 @@ QT_BEGIN_NAMESPACE #ifndef QT_NO_TEXTEDIT class QMimeData; - +class QPanGesture; class QTextEditPrivate : public QAbstractScrollAreaPrivate { Q_DECLARE_PUBLIC(QTextEdit) @@ -129,6 +129,9 @@ public: QString anchorToScrollToWhenVisible; + void _q_gestureTriggered(); + QPanGesture *panGesture; + #ifdef QT_KEYPAD_NAVIGATION QBasicTimer deleteAllTimer; #endif diff --git a/src/gui/widgets/qtoolbar.cpp b/src/gui/widgets/qtoolbar.cpp index b635628..b249915 100644 --- a/src/gui/widgets/qtoolbar.cpp +++ b/src/gui/widgets/qtoolbar.cpp @@ -70,6 +70,8 @@ #include "qdebug.h" +#define POPUP_TIMER_INTERVAL 500 + QT_BEGIN_NAMESPACE #ifdef Q_WS_MAC @@ -87,14 +89,6 @@ static void qt_mac_updateToolBarButtonHint(QWidget *parentWidget) void QToolBarPrivate::init() { Q_Q(QToolBar); - - waitForPopupTimer = new QTimer(q); - waitForPopupTimer->setSingleShot(false); - waitForPopupTimer->setInterval(500); - QObject::connect(waitForPopupTimer, SIGNAL(timeout()), q, SLOT(_q_waitForPopup())); - - floatable = true; - movable = true; q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); q->setBackgroundRole(QPalette::Button); q->setAttribute(Qt::WA_Hover); @@ -1086,6 +1080,16 @@ bool QToolBar::event(QEvent *event) Q_D(QToolBar); switch (event->type()) { + case QEvent::Timer: + if (d->waitForPopupTimer.timerId() == static_cast<QTimerEvent*>(event)->timerId()) { + QWidget *w = QApplication::activePopupWidget(); + if (!waitForPopup(this, w)) { + d->waitForPopupTimer.stop(); + if (!this->underMouse()) + d->layout->setExpanded(false); + } + } + break; case QEvent::Hide: if (!isHidden()) break; @@ -1141,6 +1145,10 @@ bool QToolBar::event(QEvent *event) if (d->mouseReleaseEvent(static_cast<QMouseEvent*>(event))) return true; break; + case QEvent::HoverEnter: + case QEvent::HoverLeave: + // there's nothing special to do here and we don't want to update the whole widget + return true; case QEvent::HoverMove: { #ifndef QT_NO_CURSOR QHoverEvent *e = static_cast<QHoverEvent*>(event); @@ -1183,11 +1191,11 @@ bool QToolBar::event(QEvent *event) QWidget *w = QApplication::activePopupWidget(); if (waitForPopup(this, w)) { - d->waitForPopupTimer->start(); + d->waitForPopupTimer.start(POPUP_TIMER_INTERVAL, this); break; } - d->waitForPopupTimer->stop(); + d->waitForPopupTimer.stop(); d->layout->setExpanded(false); break; } @@ -1197,18 +1205,6 @@ bool QToolBar::event(QEvent *event) return QWidget::event(event); } -void QToolBarPrivate::_q_waitForPopup() -{ - Q_Q(QToolBar); - - QWidget *w = QApplication::activePopupWidget(); - if (!waitForPopup(q, w)) { - waitForPopupTimer->stop(); - if (!q->underMouse()) - layout->setExpanded(false); - } -} - /*! Returns a checkable action that can be used to show or hide this toolbar. diff --git a/src/gui/widgets/qtoolbar.h b/src/gui/widgets/qtoolbar.h index 2ab4ffd..07502b3 100644 --- a/src/gui/widgets/qtoolbar.h +++ b/src/gui/widgets/qtoolbar.h @@ -167,7 +167,6 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool)) Q_PRIVATE_SLOT(d_func(), void _q_updateIconSize(const QSize &)) Q_PRIVATE_SLOT(d_func(), void _q_updateToolButtonStyle(Qt::ToolButtonStyle)) - Q_PRIVATE_SLOT(d_func(), void _q_waitForPopup()) friend class QMainWindow; friend class QMainWindowLayout; diff --git a/src/gui/widgets/qtoolbar_p.h b/src/gui/widgets/qtoolbar_p.h index b03c460..42ea97f 100644 --- a/src/gui/widgets/qtoolbar_p.h +++ b/src/gui/widgets/qtoolbar_p.h @@ -56,6 +56,7 @@ #include "qtoolbar.h" #include "QtGui/qaction.h" #include "private/qwidget_p.h" +#include <QtCore/qbasictimer.h> QT_BEGIN_NAMESPACE @@ -70,7 +71,7 @@ class QToolBarPrivate : public QWidgetPrivate public: inline QToolBarPrivate() - : explicitIconSize(false), explicitToolButtonStyle(false), movable(false), + : explicitIconSize(false), explicitToolButtonStyle(false), movable(true), floatable(true), allowedAreas(Qt::AllToolBarAreas), orientation(Qt::Horizontal), toolButtonStyle(Qt::ToolButtonIconOnly), layout(0), state(0) @@ -84,16 +85,15 @@ public: void _q_toggleView(bool b); void _q_updateIconSize(const QSize &sz); void _q_updateToolButtonStyle(Qt::ToolButtonStyle style); - void _q_waitForPopup(); bool explicitIconSize; bool explicitToolButtonStyle; bool movable; + bool floatable; Qt::ToolBarAreas allowedAreas; Qt::Orientation orientation; Qt::ToolButtonStyle toolButtonStyle; QSize iconSize; - bool floatable; QAction *toggleViewAction; @@ -125,7 +125,7 @@ public: void unplug(const QRect &r); void plug(const QRect &r); - QTimer *waitForPopupTimer; + QBasicTimer waitForPopupTimer; }; #endif // QT_NO_TOOLBAR diff --git a/src/gui/widgets/qtoolbararealayout.cpp b/src/gui/widgets/qtoolbararealayout.cpp index db2afd6..b4a0ef0 100644 --- a/src/gui/widgets/qtoolbararealayout.cpp +++ b/src/gui/widgets/qtoolbararealayout.cpp @@ -156,21 +156,15 @@ void QToolBarAreaLayoutLine::fitLayout() if (item.skip()) continue; - QToolBarLayout *tblayout = qobject_cast<QToolBarLayout*>(item.widgetItem->widget()->layout()); - if (tblayout) + if (QToolBarLayout *tblayout = qobject_cast<QToolBarLayout*>(item.widgetItem->widget()->layout())) tblayout->checkUsePopupMenu(); - int itemMin = pick(o, item.minimumSize()); - int itemHint = pick(o, item.sizeHint()); - //we ensure the extraspace is not too low - item.size = qMax(item.size, itemHint); - if (item.preferredSize > 0) { - //preferredSize would be the default size - item.size = item.preferredSize; - } + const int itemMin = pick(o, item.minimumSize()); + //preferredSize is the default if it is set, otherwise, we take the sizehint + item.size = item.preferredSize > 0 ? item.preferredSize : pick(o, item.sizeHint()); //the extraspace is the space above the item minimum sizehint - int extraSpace = qMin(item.size - itemMin, extra); + const int extraSpace = qMin(item.size - itemMin, extra); item.size = itemMin + extraSpace; //that is the real size extra -= extraSpace; @@ -932,7 +926,7 @@ void QToolBarAreaLayout::apply(bool animate) if (visible && dock.o == Qt::Horizontal) geo = QStyle::visualRect(dir, line.rect, geo); - layout->widgetAnimator->animate(widget, geo, animate); + layout->widgetAnimator.animate(widget, geo, animate); } } } diff --git a/src/gui/widgets/qwidgetanimator.cpp b/src/gui/widgets/qwidgetanimator.cpp index c67be4a..56b3f43 100644 --- a/src/gui/widgets/qwidgetanimator.cpp +++ b/src/gui/widgets/qwidgetanimator.cpp @@ -39,12 +39,8 @@ ** ****************************************************************************/ -#include <QtCore/qtimer.h> -#include <QtCore/qdatetime.h> #include <QtGui/qwidget.h> -#include <QtGui/qtextedit.h> -#include <QtGui/private/qwidget_p.h> -#include <qdebug.h> +#include <QtGui/private/qmainwindowlayout_p.h> #include "qwidgetanimator_p.h" @@ -75,18 +71,12 @@ static inline int animateHelper(int start, int stop, int step, int steps) return start + g_animate_function[x]*(stop - start)/1000; } -QWidgetAnimator::QWidgetAnimator(QObject *parent) - : QObject(parent) +QWidgetAnimator::QWidgetAnimator(QMainWindowLayout *layout) : m_mainWindowLayout(layout) { - m_time = new QTime(); - m_timer = new QTimer(this); - m_timer->setInterval(g_animation_interval); - connect(m_timer, SIGNAL(timeout()), this, SLOT(animationStep())); } QWidgetAnimator::~QWidgetAnimator() { - delete m_time; } void QWidgetAnimator::abort(QWidget *w) @@ -94,8 +84,8 @@ void QWidgetAnimator::abort(QWidget *w) if (m_animation_map.remove(w) == 0) return; if (m_animation_map.isEmpty()) { - m_timer->stop(); - emit finishedAll(); + m_timer.stop(); + m_mainWindowLayout->allAnimationsFinished(); } } @@ -107,32 +97,21 @@ void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, boo if (r.right() < 0 || r.bottom() < 0) r = QRect(); - if (r.isNull() || final_geometry.isNull()) + if (r.isNull() || final_geometry.isNull() || r == final_geometry) animate = false; AnimationMap::const_iterator it = m_animation_map.constFind(widget); - if (it == m_animation_map.constEnd()) { - if (r == final_geometry) { - emit finished(widget); - return; - } - } else { - if ((*it).r2 == final_geometry) - return; - } + if (it != m_animation_map.constEnd() && (*it).r2 == final_geometry) + return; if (animate) { AnimationItem item(widget, r, final_geometry); m_animation_map[widget] = item; - if (!m_timer->isActive()) { - m_timer->start(); - m_time->start(); + if (!m_timer.isActive()) { + m_timer.start(g_animation_interval, this); + m_time.start(); } } else { - m_animation_map.remove(widget); - if (m_animation_map.isEmpty()) - m_timer->stop(); - if (!final_geometry.isValid() && !widget->isWindow()) { // Make the wigdet go away by sending it to negative space QSize s = widget->size(); @@ -140,18 +119,19 @@ void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, boo } widget->setGeometry(final_geometry); - emit finished(widget); - - if (m_animation_map.isEmpty()) - emit finishedAll(); - - return; + if (m_animation_map.remove(widget)) { + m_mainWindowLayout->animationFinished(widget); + if (m_animation_map.isEmpty()) { + m_timer.stop(); + m_mainWindowLayout->allAnimationsFinished(); + } + } } } -void QWidgetAnimator::animationStep() +void QWidgetAnimator::timerEvent(QTimerEvent *) { - int steps = (1 + m_time->restart())/g_animation_interval; + int steps = (1 + m_time.restart())/g_animation_interval; AnimationMap::iterator it = m_animation_map.begin(); while (it != m_animation_map.end()) { AnimationItem &item = *it; @@ -159,35 +139,34 @@ void QWidgetAnimator::animationStep() item.step = qMin(item.step + steps, g_animation_steps); int x = animateHelper(item.r1.left(), item.r2.left(), - item.step, g_animation_steps); + item.step, g_animation_steps); int y = animateHelper(item.r1.top(), item.r2.top(), - item.step, g_animation_steps); + item.step, g_animation_steps); int w = animateHelper(item.r1.width(), item.r2.width(), - item.step, g_animation_steps); + item.step, g_animation_steps); int h = animateHelper(item.r1.height(), item.r2.height(), - item.step, g_animation_steps); + item.step, g_animation_steps); item.widget->setGeometry(x, y, w, h); if (item.step == g_animation_steps) { - emit finished(item.widget); - AnimationMap::iterator tmp = it; - ++it; - m_animation_map.erase(tmp); + QWidget *widget = item.widget; + it = m_animation_map.erase(it); + m_mainWindowLayout->animationFinished(widget); } else { ++it; } } if (m_animation_map.isEmpty()) { - m_timer->stop(); - emit finishedAll(); + m_timer.stop(); + m_mainWindowLayout->allAnimationsFinished(); } } bool QWidgetAnimator::animating() const { - return m_timer->isActive(); + return m_timer.isActive(); } bool QWidgetAnimator::animating(QWidget *widget) diff --git a/src/gui/widgets/qwidgetanimator_p.h b/src/gui/widgets/qwidgetanimator_p.h index 6ee150b..0c68e00 100644 --- a/src/gui/widgets/qwidgetanimator_p.h +++ b/src/gui/widgets/qwidgetanimator_p.h @@ -56,18 +56,18 @@ #include <qobject.h> #include <qrect.h> #include <qmap.h> +#include <qbasictimer.h> +#include <qdatetime.h> QT_BEGIN_NAMESPACE class QWidget; -class QTimer; -class QTime; +class QMainWindowLayout; class QWidgetAnimator : public QObject { - Q_OBJECT public: - QWidgetAnimator(QObject *parent = 0); + QWidgetAnimator(QMainWindowLayout *layout); ~QWidgetAnimator(); void animate(QWidget *widget, const QRect &final_geometry, bool animate); bool animating() const; @@ -75,12 +75,8 @@ public: void abort(QWidget *widget); -signals: - void finished(QWidget *widget); - void finishedAll(); - -private slots: - void animationStep(); +protected: + void timerEvent(QTimerEvent *e); private: struct AnimationItem { @@ -93,8 +89,9 @@ private: }; typedef QMap<QWidget*, AnimationItem> AnimationMap; AnimationMap m_animation_map; - QTimer *m_timer; - QTime *m_time; + QBasicTimer m_timer; + QTime m_time; + QMainWindowLayout *m_mainWindowLayout; }; QT_END_NAMESPACE diff --git a/src/gui/widgets/qworkspace.cpp b/src/gui/widgets/qworkspace.cpp index 58ef1e3..2833c08 100644 --- a/src/gui/widgets/qworkspace.cpp +++ b/src/gui/widgets/qworkspace.cpp @@ -397,21 +397,17 @@ void QWorkspaceTitleBarPrivate::readColors() pal.setColor(QPalette::Inactive, QPalette::Highlight, colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTION))); pal.setColor(QPalette::Active, QPalette::HighlightedText, colorref2qrgb(GetSysColor(COLOR_CAPTIONTEXT))); pal.setColor(QPalette::Inactive, QPalette::HighlightedText, colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTIONTEXT))); - if (QSysInfo::WindowsVersion != QSysInfo::WV_95 && QSysInfo::WindowsVersion != QSysInfo::WV_NT) { - colorsInitialized = true; - BOOL gradient; - QT_WA({ - SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &gradient, 0); - } , { - SystemParametersInfoA(SPI_GETGRADIENTCAPTIONS, 0, &gradient, 0); - }); - if (gradient) { - pal.setColor(QPalette::Active, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION))); - pal.setColor(QPalette::Inactive, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION))); - } else { - pal.setColor(QPalette::Active, QPalette::Base, pal.color(QPalette::Active, QPalette::Highlight)); - pal.setColor(QPalette::Inactive, QPalette::Base, pal.color(QPalette::Inactive, QPalette::Highlight)); - } + + colorsInitialized = true; + BOOL gradient = false; + SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &gradient, 0); + + if (gradient) { + pal.setColor(QPalette::Active, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION))); + pal.setColor(QPalette::Inactive, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION))); + } else { + pal.setColor(QPalette::Active, QPalette::Base, pal.color(QPalette::Active, QPalette::Highlight)); + pal.setColor(QPalette::Inactive, QPalette::Base, pal.color(QPalette::Inactive, QPalette::Highlight)); } } #endif // Q_WS_WIN diff --git a/src/gui/widgets/widgets.pri b/src/gui/widgets/widgets.pri index 86dc453..2d809a1 100644 --- a/src/gui/widgets/widgets.pri +++ b/src/gui/widgets/widgets.pri @@ -37,7 +37,9 @@ HEADERS += \ widgets/qmdisubwindow.h \ widgets/qmdisubwindow_p.h \ widgets/qmenu.h \ + widgets/qmenu_p.h \ widgets/qmenubar.h \ + widgets/qmenubar_p.h \ widgets/qmenudata.h \ widgets/qprogressbar.h \ widgets/qpushbutton.h \ |